Thursday, January 24, 2013

How to move a cursor

So you thought moving a pointer/cursor on-screen is simple? Well... no.

Having recently spent a day fixing up freedesktop Bug 31636, I figured maybe I should take you on a journey that starts with naïveté and ends in insanity. Just like Twilight.

What is actually needed to move a pointer on the screen? Move your mouse. The driver submits two relative coordinates to the server and expects the pointer to move. So we take the coordinates, add it to the last known coordinates and we're done.

A 1:1 movement of course only works for slow mouse movements. For larger deltas, we need to accelerate the pointer movement so we can easily cover larger distances on the screen. So we look at the timestamps of the events, their delta movements and use that to calculate some factor. This factor is applied to the latest deltas and then decides the actual movement.

Now we've pretty much covered traditional mice. Many devices however are absolute input devices. They don't use delta coordinates, they just give us the absolute position of the pointer. However, that position is not in pixels but some device coordinate system. So we need to remember the axis ranges and scale from the device coordinate system into the screen coordinate system.

Many users have more than one screen. Two or more screens, when not in mirrored mode, create a desktop that is larger than each single screen. For absolute devices, we map the device to the desktop coordinates so that each edge of the device maps to the corresponding edge on the desktop. Absolute events from such a device must be first mapped to desktop coordinates. From those coordinates we can gather the screen the pointer is to be on and clip the coordinates back to the per-screen coordinates to draw the visible cursor. For relative devices the process is somewhat similar, we add movement to the desktop coordinates, then clip back to per-screen for updates.

All of the above is pretty standard and doesn't require any X specifics. Let's get into what the X11 protocol requires.

evdev has a calibration feature that allows a device to be adjusted for differences in the actual vs. announced coordinates. This is needed when a device real axis ranges are actually different to what the device announces. For example, a device may claim that the axis starts at 0, but really the first value you get out of it is e.g. 50. For historical reasons we cannot change the device axes once they are set up though. So evdev's calibration scales from the calibrated device range (e.g. 50-950) into the actual announced device range (0-1000). That scaled coordinate is then posted to the server. The wacom driver has a similar feature (called Area).

The X Input Extensions (XI) provides so-called "valuators" (== axes) to the clients as part of the various input events. Valuators 0 and 1 are x and y. XI requires valuator data to be in absolute device coordinates, but those are per protocol screen. In old-style multi-monitor setups with two Section Device entries in the xorg.conf, you have more than one protocol screen. The device itself however is still mapped to the whole desktop. So we convert device coordinates to desktop coordinates, then to screen coordinates on the current screen, and then that position is converted back into device coordinates. Bonus points for considering what happens in a setup with three monitors but only two protocol screens

If you kept counting, you should be up to 5 coordinate systems now:

  1. device coordinate system
  2. adjusted device coordinate system after calibration is applied
  3. desktop-wide coordinate system
  4. per-screen coordinate system
  5. per-screen device coordinate system
Yep, that's right. A coordinate from an absolute input device passes through all 5 before the pointer position is defined and the data can be appended to the event. And that happens on every single pointer event. Compare this to a relative event, which has four steps:
  1. relative coordinates
  2. device-specific acceleration
  3. desktop-wide coordinate system
  4. per-screen coordinate system
The bug that triggered this blog post was an actual use-case. If an absolute device is used in relative mode, the coordinates were still applied according to the device coordinate range. Thus, relative motion on the device was dependent on the desktop dimensions and attaching a second monitor would increase movement in one axes but not the other. To avoid this, we have an extra layer of scaling, where we pre-scale the coordinates first. That scaling is then undone by the second conversion into desktop coordinates. Whoopee.

Proposed XI2.3 addition: XIGetSupportedVersion

Update March 7 2013: This addition was not merged into XI 2.3, largely because there is no real need for it. XI 1.x' XGetExtensionVersion() returns the server version without locking in a client version and at this point there was no perceived need for getting the already-requested client version back. I'll leave this here for archival purposes but again, this request was not merged into XI 2.3

Original post below

Posting this here too to get a bit more exposure.

XIQueryVersion(3) is the first XI2 request clients should send to the server. The client announces its supported version and in return receives the server version (which is always less or equal to the client, never higher).

As XI 2.1 - 2.3 progressed, we started using this information in the server. Clients are treated slightly differently depending on their announced version. The current differences are:

  • XIQueryPointer will not set the button 1 mask for pointer-emulated events if the client supports XI 2.2 or newer.
  • XIAllowEvents will allow XIRejectTouch and XIAcceptTouch for clients supporting XI 2.2 or newer.
  • Raw event delivery changes if a client supports XI 2.1 or newer.
The client can issue multiple XIQueryVersion requests, but they need to have the same version numbers to provide for consistent server behaviour.

So far, so good. This works fine as long as the client supports one specific version. However, as toolkits like GTK have come to support XI2, the requirements changed a bit. An application and its toolkit usually look like a single client to the server. However, the client may support XI 2.0, but the toolkit may support XI 2.3. And neither knows of the other's version support. If the client requests XIQueryVersion before the toolkit, the toolkit is locked into the client version. But if the toolkit first requests XIQueryVersion, the client is locked into the version supported by the toolkit. Worst case the client may get a BadValue and quit because it may not be built for this case.

Jasper St. Pierre and Owen Taylor brought this up on #xorg-devel today, and I've send a proposed solution to the mailing list.

A new XIGetSupportedVersion request simply returns the server's major/minor version number. Uncapped, so really what the server supports. And the same request also returns the client version previously announced with XIQueryVersion. Or zero, if the client hasn't called it yet.

This request enables toolkits to query what the client has already set, and of course what the server supports without modifying the client state. The request is currently an RFC, but I do hope we may get this into XI 2.3.

If you're working on XI2-aware clients or toolkits and you have a use-case that requires this or would break by this addition, please speak up now.

Wednesday, January 2, 2013

Getting rid of the GNOME "Oh No! Something has gone wrong." dialog

In some error cases, GNOME will display a full-screen window with only a single button. The window claims that "Oh no! Something has gone wrong." and "A problem has occurred and the system can't recover. Please log out and try again." The button merely allows a user to log-out and thus quit the current session. Killing that window with xkill also quits the session.

Most of the crashes I get is from experimental code crashing gnome-settings-daemon. Certainly not something fatal, certainly not something that should prevent me from continuing to work in my current session. After all, the menu key still works, the hot corner works, everything works, but closing the dialog will throw me out of my session. And because that pesky dialog is always on-top, I'm down to one monitor. Luckily, the dialog can be disabled.

Update Jan 3: As Jasper points out in the comments, Alt+F4 will close the window. Though I tried Ctrl+W and Ctrl+Q, I haven't used Alt+F4 in ages. Sometimes the right solution is so much simpler :)

The dialog is displayed by gnome-session and it's named the fail whale (code). It's triggered only for required apps and those can be configured.

$ cat /usr/share/gnome-session/sessions/gnome.session | grep Required
RequiredComponents=gnome-shell;gnome-settings-daemon;
Drop g-s-d from the required components, restart the session, and you won't see the error anymore. Try it by sending SIGABRT to g-s-d.
$ kill -ABRT `pidof gnome-settings-daemon`
Doing so twice (g-s-d restarts once) will trigger the error unless g-s-d is dropped from the required components.

It should go without saying, but the above will only display the error message, it won't fix the actual error that causes the message to be displayed.

Monday, December 10, 2012

What's new in XI 2.3 - Pointer Barrier events and barrier releases

Update 7 March 2013: XI 2.3 is released, amend accordingly

The main feature making up XI 2.3 is Pointer Barrier events. This feature was initiated by Chris Halse-Rogers and then taken up by Jasper St. Pierre and me, until it became part of XI 2.3.

The usual conditions apply: a client must announce XI2.3 support with the XIQueryVersion() request to utilise any of the below.

Pointer barriers

Pointer Barriers are an XFixes v5.0 additions to restrict pointer movement. They were first available in server 1.11 (released Aug 2011). A pointer barrier is created by a client along a specific horizontal or vertical line of pixels. Relative input devices such as mice or touchpads will be constrained by this barrier, preventing the cursor from moving across the barrier.

For example, GNOME3 creates a vertical barrier on the top-left screen edge. In a multi-monitor screen, flicking the pointer up to the Activities menu will constrain the pointer there even if there is a screen to the left of the menu. This makes the menu much easier to hit.

The client can choose for the barrier to be transparent in specific directions. GNOME3's pointer barrier is permissive in the direction of positive X (i.e. left-to-right). Thus, moving from the left screen to the right is unrestricted, even though the pointer is constrained when moving in the other direction.

A simple client that creates a vertical pointer barrier looks like this:

Display *dpy = XOpenDisplay(NULL);
int fixes_opcode, fixes_event_base, fixes_error_base;
PointerBarrier barrier;

if (!XQueryExtension(dpy, "XFIXES",
                     &fixes_opcode,
                     &fixes_event_base,
                     &fixes_error_base))
    return EXIT_FAILURE;

/* vertical barrier from 20/20 to 20/100 */
barrier = XFixesCreatePointerBarrier(dpy, DefaultRootWindow(dpy),
                                     20, 20,
                                     20, 100,
                                     0, /* block in all directions */
                                     0, NULL); /* no per-device barriers */

mainloop();

The above code will set up a barrier for all devices, blocking in all directions.

Pointer barrier events

As of XI 2.3, pointer barrier events are sent to clients when pointer movement is constrained by a barrier, provided that client created pointer barriers, the clients have the matching event mask set. Two new event types were added, XI_BarrierHit and XI_BarrierLeave. Both events are only sent to clients owning a barrier and are only sent to the window used to create the barrier (the root window in the example above).

unsigned char m[XIMaskLen(XI_BarrierLeave)] = {0};
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_BarrierLeave);
mask.mask = m;

XISetMask(mask.mask, XI_BarrierHit);
XISetMask(mask.mask, XI_BarrierLeave);
XISelectEvents(dpy, DefaultRootWindow(dpy), &mask, 1);
XSync(dpy, False);

while (1) {
    XEvent ev;
    XNextEvent(dpy, &ev);
    if (ev.type != GenericEvent || ev.xcookie.extension != xi2_opcode)
       continue;

    XGetEventData(dpy, &ev.xcookie);
    XIBarrierEvent *b = ev.xcookie.data;
    if (b->evtype == XI_BarrierHit)
       printf("Pointer hit the barrier\n");
    else if (b->evtype == XI_BarrierLeave)
       printf("Pointer left the barrier\n");
    
    XFreeEventData(dpy, &ev.xcookie);
}

An XI_BarrierHit event is first sent when the pointer movement is first constrained by a barrier. It includes some information such as the device, the barrier and the window. It also includes coordinate data.

XI_BarrierHit events are sent for each movement of the pointer against this barrier, or along it, until the pointer finally moves away from the barrier again. "Moving away" means a move to different position that is not blocked by the barrier.

  • if the barrier is vertical, the pointer moves to a different X axis value, or
  • if the barrier is horizontal, the pointer moves to a different Y axis value, or
  • the pointer moves past the barrier's end point
Once the pointer does move away, a XI_BarrierLeave event is sent. A pointer that moves against a barrier, pushes against it for 3 more events and then pulls back will thus generate 4 XI_BarrierHit events and one XI_BarrierLeave event.

Who gets events? Always the client that created the barrier, and only if the window has the event mask set. If the client has a grab on the device with the grab_window being the barrier window, the barrier events follow the usual grab event mask behaviour:

  • if the grab event mask has XI_BarrierHit set, the event is delivered
  • if the grab event mask does not have XI_BarrierHit set but the window mask does and owner_events is True, the event is delivered
  • if owner_events is False and the grab mask does not have XI_BarrierHit set, no event is sent
The above applies to XI_BarrierLeave events as well.

If the client's grab has a grab_window different to the barrier window, or the device is grabbed by another client, event delivery is as usual. In all cases, if the device is grabbed, the XIBarrierDeviceIsGrabbed flag is set. Clients should use this flag to determine what to do. For example, the barrier that is used to trigger the GNOME overlay should probably not trigger if another client has a grab as it may interfere with drag-and-drop.

Coordinates and time in pointer barrier events

Barrier events contain two sets of x/y coordinates. First, the root coordinates which represent the position of the pointer after being confined by barrier (and screen extents, where applicable). This coordinate is the same you would get from a subsequent XIQueryPointer request.

The second set are the delta coordinates (dx/dy), in screen coordinates, from the last pointer position, had the barrier not constrained it. So you can calculate how much the pointer would have moved and thus derive speed. The dtime field in the event helps you to calculate speed, it provides the time in milliseconds since the last pointer event. The deltas are calculated after taking pointer acceleration into account.

    XIBarrierEvent *b = ev.xcookie.data;
    double dx, dy;
    double speed;
    unsigned int millis;

    dx = b->dx;
    dy = b->dy;
    millis = b->dtime;

    speed = sqrt(dx * dx + dy * dy) / millis * 1000;

    printf("Barrier was hit at %.2f/%.2f at %.2f pixels/sec\n",
           b->root_x, b->root_y,  speed);

Releasing a pointer from barrier constraints

By default, a pointer barrier blocks all movement of relative input devices across a barrier. However, a client can opt to temporarily release the pointer from the barrier constraints with the XIBarrierReleasePointer request.

To do so, the client needs the event ID of the barrier event. Since a pointer may bump against the same barrier multiple times before the client reacts (X is asynchronous, after all), the event ID serves to identify a set of movements against or along the pointer barrier.

An event ID is assigned to the first XI_BarrierHit event, and then it remains the same until the XI_BarrierLeave event. This event is the last event with the current event ID, any future barrier events will have a new event ID. This approach may be familiar to you from dealing with touch events, that use a similar approach (touch IDs start at TouchBegin and are tracked through to the TouchEnd).

To release a pointer and let it pass through the barrier, call XIBarrierReleasePointer().

    XIBarrierEvent *b = ev.xcookie.data;
    ...
    if (speed > 200) {
        printf("Movement exceeds speed limit, allowing pointer to go through\n")
        XIBarrierReleasePointer(dpy, b->deviceid, b->barrier, b->eventid);
        XFlush(dpy);
    }
If, when the request arrives at the server, the pointer is still trapped by the barrier, the barrier is now transparent and the pointer can move through it with the next movement. If the pointer moves away from the barrier after releasing it and later moves against this barrier again, it will be constrained once more (albeit with a different eventid). Likewise, if the pointer has already moved away and against the barrier again before the client reacted, the release request has no effect.

If the release does succeed and the pointer moves through the barrier, the client gets a XI_BarrierLeave event with the XIBarrierPointerReleased flag.

The pointer barrier hit-box

As mentioned above, a XI_BarrierLeave event is sent when the pointer moves away from the barrier. This would usually require a 1 pixel movement (let's ignore subpixel-movement, our hand's aren't that precise). However, during testing we found that 1 px pointer-movement can still happen even when a user tries hart to move along the barrier, or even when pushing against the barrier. Thus, we implemented a hit-box of 2 pixels. Thus, a 1 px movement along the barrier still counts as hitting the barrier, and the pointer is not treated as having left the barrier until it leaves the hit-box.

Testing the current state

The current code is available in the barriers branch of the following repositories:

git://people.freedesktop.org/~whot/inputproto.git 
git://people.freedesktop.org/~whot/libXi.git 
git://people.freedesktop.org/~whot/xserver.git 
An example program to test the feature is available here

Tuesday, December 4, 2012

Two magic words - "I think"

We live in a world of absolutes. Water is wet, taxes are annoying, death is certain, it's always beer o'clock somewhere and the world is going to end somewhen later this year (which makes this post doubly futile, but what the hell). Hard to dispute any of those.

We also live in a world of non-absolutes. You may be freezing when someone right next to you is hot. You may be enjoying a movie when the person you dragged into the theatre is wishing for stronger teeth to gnaw through that wrist. Saying "it's cold" or "this movie is awesome" is going to be met with disagreement

What does that have to do with software development? We tend to be so convinced of ourselves that we take our personal opinion or experience as absolutes. It's acceptable to say "it's broken" when the application crashes once you start typing. But to say "it's broken" because it doesn't work as you expected is bad.

Such a statement kills the climate of any conversation. If you tell me that something "is broken", "is completely borked", "is idiotic", or any of those you're achieving one thing: You're putting me on the defence, and quite offensively so. After all, how could I have possibly written, approved, applied something that's so clearly wrong? That makes me uncomfortable. So I'll likely attack back because all I need to do now is find one example that proves you wrong. And that's usually quite easy. But at that point it's unlikely a decent conversation will ensue.

Worse, if you keep doing that at some point I'll stop listening because someone who makes false statements all the time should be in politics or advertising, but not involved with FOSS.

So now let's try the same again with those magic words: "I think this is completely broken". Well, now you've changed it from an absolute statement to an expression of your opinion. So my task is now to convince you to reconsider your opinion. I'm not on the defence, and the result is that in the worst case we'll agree to disagree - without that awkward absolute statement in the room.

A few examples:

  • "Nobody needs this" vs. "I don't think anybody needs this"
  • "The application must not do this" vs "I think the application must not do this"
  • "Wearing underpants is wrong" vs "I think wearing underpants is wrong"
  • "Bananas must be peeled from the bottom" vs "I think bananas must be peeled from the bottom"
Did you notice any differences? Any of the "I think" can be quite simply countered with "I don't think so" (especially the third one, please) and all you'd have is a discussion of two people with differing viewpoints. Even re-reading these examples my reaction to the first is automatically "WTF?", but the reaction to the "I think" alternatives is a conversational "nah, mate".

So next time you're not happy about something: just prefix your criticism with "I think". You may be surprised what difference it makes to the conversation.

Oh, two other magic words: "for me". Compare "This workflow is completely broken" vs "This workflow is completely broken for me". Amazing what difference those two words make...

Thursday, November 29, 2012

X.Org integration test suite - part 2, the registry

Back in August, I wrote about the X.Org Integration Test suite, in short XIT. Since then I've been quite busy adding tests to it, expanding it and fixing the odd bug. Jasper St. Pierre has been writing tests against it for the new pointer barrier features, making that feature probably the first to get full, repeatable testing before merging.

Aside from general cleanup so that tests are even easier to write, one of the features I've pushed today is a bug registry. One of the issues with the test suite (especially one that is not integrated with the repository directly) is that tests don't just fail or succeed, they can also be known to fail, or known to succeed.

For example, a test may succeed on git master, but fail on the 1.13 branch - either because the fix has not yet been backported, or because the fix will not be backported anyway.

Keeping track of those failures is quite a task, especially when you have multiple server versions to worry about.

This is what the bug-registry is supposed to address. It's in its early stages, but has already been quite helpful. At it's very base is the commandline client xit-bug-registry, and the matching data file (xml) that keeps track of the various test cases.

This is a simple introduction on how to use it.

To get started, run the tests, then create a new registry from the test output

$> sudo ./tests/server/server --gtest_output="xml:server-results.xml"
$> xit-bug-registry create server-results.xml > registry.xml
Information about the tests can now be queried:
$> xit-bug-registry -f registry.xml list

TestSuite                     TestCase                               Success
---------                     --------                               -------
BarrierConflictingDirections  InvalidConflictingDirectionsBarrier/0     True
BarrierConflictingDirections  InvalidConflictingDirectionsBarrier/1     True
EventQueueTest                mieqOverflow                              True
MiscServerTest                DoubleSegfault                            True
PointerGrabTest               GrabDisabledDevices                       True
PointerGrabTest               ImplicitGrabRawEvents                     False
ScreenSaverTest               ScreenSaverActivateDeactivate             False
...
The above shows a bunch of tests that are expected to succeed, and two that are expected to fail. Ideally, these tests will be annotated, so that looking up info will look like this:
$> xit-bug-registry -f registry.xml info XTest DisabledDevicesProperty
XTest DisabledDevicesProperty:  Expected result: Success
Known bugs: 
0: https://bugs.freedesktop.org/show_bug.cgi?id=56380
Known fixes: 
0: aad65415bff12c6860c19beac42e4165e598a40f
To get there, some manual interaction is required:
$> xit-bug-registry -f registry.xml edit \
 XTest DisabledDevicesProperty \
 add-bug http://bugs.freedesktop.org/56380
$> xit-bug-registry -f registry.xml edit \
 XTest DisabledDevicesProperty \
add-commit aad65415bff12c6860c19beac42e4165e598a40f

There are other bits one can add, but bugs and commits are likely the interesting bits. Right now, that's all it does, but in the future I hope to expand the script to query the bug database for the bug status, and query repositories to check if the fix is on the branch yet.

That's all nice, but the real important bit is to verify that after fixing a bug, one hasn't broken anything.

$> sudo ./tests/server/server --gtest_output="xml:server-results.xml"
$> xit-bug-registry -f registry.xml verify server-results.xml
Code TestSuite                    TestCase                                Result  Expected
---- ---------                    --------                                ------  --------
++   BarrierConflictingDirections InvalidConflictingDirectionsBarrier/0   true      true
++   BarrierConflictingDirections InvalidConflictingDirectionsBarrier/1   true      true
++   BarrierConflictingDirections InvalidConflictingDirectionsBarrier/2   true      true
++   BarrierConflictingDirections InvalidConflictingDirectionsBarrier/3   true      true
++   BarrierConflictingDirections InvalidConflictingDirectionsBarrier/4   true      true
++   BarrierConflictingDirections InvalidConflictingDirectionsBarrier/5   true      true
--   PointerGrabTest              ImplicitGrabRawEvents                  false     false
XX   ScreenSaverTest              ScreenSaverActivateDeactivate           true     false
++   TouchDeviceChangeTest        DeviceChangedEventPointerToTouchSwitch  true      true
++   TouchDeviceChangeTest        DeviceChangedEventTouchToPointerSwitch  true      true
XX   TouchDeviceChangeTest        NoCursorJumpsOnTouchToPointerSwitch     true     false
++   TouchDeviceTest              DisableDeviceEndTouches                 true      true
--   TouchEventHistoryTest        EventHistoryReplay/0                   false     false
--   TouchEventHistoryTest        EventHistoryReplay/1                   false     false
--   TouchEventHistoryTest        EventHistoryReplay/10                  false     false
...

This simply shows us which tests had which result. Cases with code ++ succeeded when they were expected to, -- failed when they were expected to. XX is what you need to look for, it indicates that the test outcome differs to the status in the registry. In this case, two tests now succeed when before they didn't - usually a good outcome.

Once a fix is merged, you can update the status of the bug:

$> xit-bug-registry -f registry.xml edit \
 XTest DisabledDevicesProperty \
 set-status success
If this test fails in the future, you'll now be able to spot it.

The information is all in the registry file and though I admit the interface is still clumsy, it's quite simple to keep a set of registries (e.g. upstream, Fedora, RHEL, etc.) and thus a known set of test outcomes for each.

Finally, as test cases are being added, it's important to update the registry. This is as simple as:

$> xit-bug-registry create results-with-new-testcases.xml > new-registry.xml
$> xit-bug-registry merge registry.xml new-registry.xml
This command will merge any new test cases into our original registry, but won't update the status on any existing ones.

Friday, October 19, 2012

Lenovo x220t Tablet and the broken Wacom 0xE6 tablet

I noticed that my tablet didn't work anymore. In fact, the tablet itself didn't even show up in /proc/bus/input/devices. At first I suspected a kernel bug and rebooted into a variety of different Fedora kernels, but to no avail.

Looking at various logs, I discovered:
:: whot@yabbi:~> dmesg | grep 56a
[    2.291841] usb 2-1.5: New USB device found, idVendor=056a, idProduct=0094
Wacom's vendor ID is 056a, but the tablet in the x220 is a 0xE6, not a 0x94 (the latter of which doesn't exist). With that info, googling for a solution was a bit easier. As suggested in the thread on linuxwacom-devel a power off did indeed fix the issue for me.
:: whot@yabbi:~> dmesg | grep 56a
[    2.291841] usb 2-1.5: New USB device found, idVendor=056a, idProduct=00e6
It turns out this is an issue with kernel 3.5.3 and 3.5.4, but it is fixed in 3.5.5. kernel bug. As Ping states:
The root cause is somewhere in the kernel tablet is set to a wrong mode. Once it is in that mode, a reboot won't reset it to normal. We have to power it off and wait a few seconds for all bits to reset. That's why I tell people to even unplug the power cable since bits may stay as long as they get power.

update 20/10/12: list kernel versions affected, add Ping's quote