Apply systemd-based dbus activation
[platform/upstream/at-spi2-core.git] / registryd / deviceeventcontroller-x11.c
1 /* AT-SPI - Assistive Technology Service Provider Interface
2  *
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2001, 2003 Sun Microsystems Inc.,
6  * Copyright 2001, 2002 Ximian, Inc.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /* deviceeventcontroller-x11.c: X-specific DeviceEventController support */
25
26 #include <config.h>
27
28 #undef  SPI_XKB_DEBUG
29 #undef  SPI_DEBUG
30 #undef  SPI_KEYEVENT_DEBUG
31
32 #include <string.h>
33 #include <ctype.h>
34 #include <stdio.h>
35 #include <sys/time.h>
36
37 #include <X11/Xlib.h>
38 #include <X11/Xutil.h>
39 #include <X11/extensions/XTest.h>
40 #include <X11/XKBlib.h>
41
42 #define XK_MISCELLANY
43 #define XK_LATIN1
44 #include <X11/keysymdef.h>
45
46 #include <glib.h>
47
48 #include <dbus/dbus.h>
49
50 #include "paths.h"
51 #include "keymasks.h"
52 #include "de-types.h"
53 #include "de-marshaller.h"
54 #include "display.h"
55 #include "event-source.h"
56
57 #include "deviceeventcontroller.h"
58 #include "reentrant-list.h"
59
60 #include "introspection.h"
61
62 static void spi_dec_x11_emit_modifier_event (SpiDEController *controller,
63                              guint prev_mask,
64                              guint current_mask);
65
66 #define CHECK_RELEASE_DELAY 20
67 #define BIT(c, x)       (c[x/8]&(1<<(x%8)))
68 static guint check_release_handler = 0;
69 static Accessibility_DeviceEvent pressed_event;
70 static void wait_for_release_event (XEvent *event, SpiDEController *controller);
71
72 static int spi_error_code = 0;
73 struct _SpiPoint {
74     gint x;
75     gint y;
76 };
77 typedef struct _SpiPoint SpiPoint;
78 static SpiPoint last_mouse_pos_static = {0, 0}; 
79 static SpiPoint *last_mouse_pos = &last_mouse_pos_static;
80 static unsigned int mouse_mask_state = 0;
81 static unsigned int mouse_button_mask =
82   Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask;
83 static unsigned int key_modifier_mask =
84   Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask | Mod5Mask | ShiftMask | LockMask | ControlMask | SPI_KEYMASK_NUMLOCK;
85 static unsigned int _numlock_physical_mask = Mod2Mask; /* a guess, will be reset */
86
87 static XModifierKeymap* xmkeymap = NULL;
88
89
90 static int (*x_default_error_handler) (Display *display, XErrorEvent *error_event);
91
92 typedef struct {
93   Display *xevie_display;
94   unsigned int last_press_keycode;
95   unsigned int last_release_keycode;
96   struct timeval last_press_time;
97   struct timeval last_release_time;
98   int have_xkb;
99   int xkb_major_extension_opcode;
100   int xkb_base_event_code;
101   int xkb_base_error_code;
102   unsigned int xkb_latch_mask;
103   unsigned int pending_xkb_mod_relatch_mask;
104   XkbDescPtr xkb_desc;
105   KeyCode reserved_keycode;
106   KeySym reserved_keysym;
107   guint  reserved_reset_timeout;
108 } DEControllerPrivateData;
109
110 static void     spi_controller_register_with_devices          (SpiDEController           *controller);
111 static gboolean spi_device_event_controller_forward_key_event (SpiDEController           *controller,
112                                                                const XEvent              *event);
113
114
115 static SpiDEController *saved_controller;
116
117 static unsigned int
118 keysym_mod_mask (KeySym keysym, KeyCode keycode)
119 {
120         /* we really should use XKB and look directly at the keymap */
121         /* this is very inelegant */
122         Display *display = spi_get_display ();
123         unsigned int mods_rtn = 0;
124         unsigned int retval = 0;
125         KeySym sym_rtn;
126
127         if (XkbLookupKeySym (display, keycode, 0, &mods_rtn, &sym_rtn) &&
128             (sym_rtn == keysym)) {
129                 retval = 0;
130         }
131         else if (XkbLookupKeySym (display, keycode, ShiftMask, &mods_rtn, &sym_rtn) &&
132                  (sym_rtn == keysym)) {
133                 retval = ShiftMask;
134         }
135         else if (XkbLookupKeySym (display, keycode, Mod2Mask, &mods_rtn, &sym_rtn) &&
136                  (sym_rtn == keysym)) {
137                 retval = Mod2Mask;
138         }
139         else if (XkbLookupKeySym (display, keycode, Mod3Mask, &mods_rtn, &sym_rtn) &&
140                  (sym_rtn == keysym)) {
141                 retval = Mod3Mask;
142         }
143         else if (XkbLookupKeySym (display, keycode, 
144                                   ShiftMask | Mod2Mask, &mods_rtn, &sym_rtn) &&
145                  (sym_rtn == keysym)) {
146                 retval = (Mod2Mask | ShiftMask);
147         }
148         else if (XkbLookupKeySym (display, keycode, 
149                                   ShiftMask | Mod3Mask, &mods_rtn, &sym_rtn) &&
150                  (sym_rtn == keysym)) {
151                 retval = (Mod3Mask | ShiftMask);
152         }
153         else if (XkbLookupKeySym (display, keycode, 
154                                   ShiftMask | Mod4Mask, &mods_rtn, &sym_rtn) &&
155                  (sym_rtn == keysym)) {
156                 retval = (Mod4Mask | ShiftMask);
157         }
158         else
159                 retval = 0xFFFF;
160         return retval;
161 }
162
163 static gboolean
164 replace_map_keysym (DEControllerPrivateData *priv, KeyCode keycode, KeySym keysym)
165 {
166 #ifdef HAVE_XKB
167   Display *dpy = spi_get_display ();
168   XkbDescPtr desc;
169   if (!(desc = XkbGetMap (dpy, XkbAllMapComponentsMask, XkbUseCoreKbd)))
170     {
171       fprintf (stderr, "ERROR getting map\n");
172     }
173   XFlush (dpy);
174   XSync (dpy, False);
175   if (desc && desc->map)
176     {
177       gint offset = desc->map->key_sym_map[keycode].offset;
178       desc->map->syms[offset] = keysym; 
179     }
180   else
181     {
182       fprintf (stderr, "Error changing key map: empty server structure\n");
183     }           
184   XkbSetMap (dpy, XkbAllMapComponentsMask, desc);
185   /**
186    *  FIXME: the use of XkbChangeMap, and the reuse of the priv->xkb_desc structure, 
187    * would be far preferable.
188    * HOWEVER it does not seem to work using XFree 4.3. 
189    **/
190   /*        XkbChangeMap (dpy, priv->xkb_desc, priv->changes); */
191   XFlush (dpy);
192   XSync (dpy, False);
193   XkbFreeKeyboard (desc, 0, TRUE);
194
195   return TRUE;
196 #else
197   return FALSE;
198 #endif
199 }
200
201 static gboolean
202 spi_dec_reset_reserved (gpointer data)
203 {
204   DEControllerPrivateData *priv = data;
205   replace_map_keysym (priv, priv->reserved_keycode, priv->reserved_keysym);
206   priv->reserved_reset_timeout = 0;
207   return FALSE;
208 }
209
210 static gint
211 spi_dec_x11_get_keycode (SpiDEController *controller,
212                           gint keysym,
213                           gchar *key_str,
214                           gboolean fix,
215                           guint *modmask)
216 {
217         KeyCode keycode = 0;
218   if (key_str && key_str[0])
219                 keysym = XStringToKeysym(key_str);
220         keycode = XKeysymToKeycode (spi_get_display (), (KeySym) keysym);
221         if (!keycode && fix)
222         {
223                 DEControllerPrivateData *priv = controller->priv;
224                 /* if there's no keycode available, fix it */
225                 if (replace_map_keysym (priv, priv->reserved_keycode, keysym))
226                 {
227                         keycode = priv->reserved_keycode;
228                         /* 
229                          * queue a timer to restore the old keycode.  Ugly, but required 
230                          * due to races / asynchronous X delivery.   
231                          * Long-term fix is to extend the X keymap here instead of replace entries.
232                          */
233                         priv->reserved_reset_timeout = g_timeout_add (500, spi_dec_reset_reserved, priv);
234                         g_source_set_name_by_id (priv->reserved_reset_timeout, "[at-spi2-core] spi_dec_reset_reserved");
235                 }               
236                 if (modmask)
237                         *modmask = 0;
238                 return keycode;
239         }
240         if (modmask) 
241                 *modmask = keysym_mod_mask (keysym, keycode);
242         return keycode;
243 }
244
245 static void
246 spi_dec_set_unlatch_pending (SpiDEController *controller, unsigned mask)
247 {
248   DEControllerPrivateData *priv = controller->priv;
249 #ifdef SPI_XKB_DEBUG
250   if (priv->xkb_latch_mask) fprintf (stderr, "unlatch pending! %x\n", 
251                                      priv->xkb_latch_mask);
252 #endif
253   priv->pending_xkb_mod_relatch_mask |= priv->xkb_latch_mask; 
254 }
255  
256 static gboolean
257 spi_dec_button_update_and_emit (SpiDEController *controller,
258                                 guint mask_return)
259 {
260   Accessibility_DeviceEvent mouse_e;
261   gchar event_detail[3];
262   gboolean is_consumed = FALSE;
263
264   if ((mask_return & mouse_button_mask) !=
265       (mouse_mask_state & mouse_button_mask)) 
266     {
267       int button_number = 0;
268       gboolean is_down = False;
269       
270       if (!(mask_return & Button1Mask) &&
271           (mouse_mask_state & Button1Mask)) 
272         {
273           mouse_mask_state &= ~Button1Mask;
274           button_number = 1;
275         } 
276       else if ((mask_return & Button1Mask) &&
277                !(mouse_mask_state & Button1Mask)) 
278         {
279           mouse_mask_state |= Button1Mask;
280           button_number = 1;
281           is_down = True;
282         } 
283       else if (!(mask_return & Button2Mask) &&
284                (mouse_mask_state & Button2Mask)) 
285         {
286           mouse_mask_state &= ~Button2Mask;
287           button_number = 2;
288         } 
289       else if ((mask_return & Button2Mask) &&
290                !(mouse_mask_state & Button2Mask)) 
291         {
292           mouse_mask_state |= Button2Mask;
293           button_number = 2;
294           is_down = True;
295         } 
296       else if (!(mask_return & Button3Mask) &&
297                (mouse_mask_state & Button3Mask)) 
298         {
299           mouse_mask_state &= ~Button3Mask;
300           button_number = 3;
301         } 
302       else if ((mask_return & Button3Mask) &&
303                !(mouse_mask_state & Button3Mask)) 
304         {
305           mouse_mask_state |= Button3Mask;
306           button_number = 3;
307           is_down = True;
308         } 
309       else if (!(mask_return & Button4Mask) &&
310                (mouse_mask_state & Button4Mask)) 
311         {
312           mouse_mask_state &= ~Button4Mask;
313           button_number = 4;
314         } 
315       else if ((mask_return & Button4Mask) &&
316                !(mouse_mask_state & Button4Mask)) 
317         {
318           mouse_mask_state |= Button4Mask;
319           button_number = 4;
320           is_down = True;
321         } 
322       else if (!(mask_return & Button5Mask) &&
323                (mouse_mask_state & Button5Mask)) 
324         {
325           mouse_mask_state &= ~Button5Mask;
326           button_number = 5;
327         }
328       else if ((mask_return & Button5Mask) &&
329                !(mouse_mask_state & Button5Mask)) 
330         {
331           mouse_mask_state |= Button5Mask;
332           button_number = 5;
333           is_down = True;
334         }
335       if (button_number) {
336 #ifdef SPI_DEBUG                  
337         fprintf (stderr, "Button %d %s\n",
338                  button_number, (is_down) ? "Pressed" : "Released");
339 #endif
340         snprintf (event_detail, 3, "%d%c", button_number,
341                   (is_down) ? 'p' : 'r');
342         /* TODO: FIXME distinguish between physical and 
343          * logical buttons 
344          */
345         mouse_e.type      = (is_down) ? 
346           Accessibility_BUTTON_PRESSED_EVENT :
347           Accessibility_BUTTON_RELEASED_EVENT;
348         mouse_e.id        = button_number;
349         mouse_e.hw_code   = button_number;
350         mouse_e.modifiers = (dbus_uint16_t) mouse_mask_state; 
351         mouse_e.timestamp = 0;
352         mouse_e.event_string = "";
353         mouse_e.is_text   = FALSE;
354         is_consumed = 
355           spi_controller_notify_mouselisteners (controller, 
356                                                 &mouse_e);
357         if (!is_consumed)
358           {
359             dbus_uint32_t x = last_mouse_pos->x, y = last_mouse_pos->y;
360             spi_dec_dbus_emit(controller, SPI_DBUS_INTERFACE_EVENT_MOUSE, "Button", event_detail, x, y);
361           }
362         else
363           spi_dec_set_unlatch_pending (controller, mask_return);
364       }
365       return TRUE;
366     }
367   else
368     {
369       return FALSE;
370     }
371 }
372
373 static guint
374 spi_dec_x11_mouse_check (SpiDEController *controller, 
375                      int *x, int *y, gboolean *moved)
376 {
377   int win_x_return,win_y_return;
378   unsigned int mask_return;
379   Window root_return, child_return;
380   Display *display = spi_get_display ();
381
382   if (display != NULL)
383     XQueryPointer(display, DefaultRootWindow (display),
384                   &root_return, &child_return,
385                   x, y,
386                   &win_x_return, &win_y_return, &mask_return);
387   /* 
388    * Since many clients grab the pointer, and X goes an automatic
389    * pointer grab on mouse-down, we often must detect mouse button events
390    * by polling rather than via a button grab. 
391    * The while loop (rather than if) is used since it's possible that 
392    * multiple buttons have changed state since we last checked.
393    */
394   if (mask_return != mouse_mask_state) 
395     {
396       while (spi_dec_button_update_and_emit (controller, mask_return));
397     }
398
399   if (*x != last_mouse_pos->x || *y != last_mouse_pos->y) 
400     {
401       // TODO: combine these two signals?
402       dbus_uint32_t ix = *x, iy = *y;
403       spi_dec_dbus_emit(controller, SPI_DBUS_INTERFACE_EVENT_MOUSE, "Abs", "", ix, iy);
404       ix -= last_mouse_pos->x;
405       iy -= last_mouse_pos->y;
406       spi_dec_dbus_emit(controller, SPI_DBUS_INTERFACE_EVENT_MOUSE, "Rel", "", ix, iy);
407       last_mouse_pos->x = *x;
408       last_mouse_pos->y = *y;
409       *moved = True;
410     }
411   else
412     {
413       *moved = False;
414     }
415
416   return mask_return;
417 }
418
419 #ifdef WE_NEED_UGRAB_MOUSE
420 static int
421 spi_dec_ungrab_mouse (gpointer data)
422 {
423         Display *display = spi_get_display ();
424         if (display)
425           {
426             XUngrabButton (spi_get_display (), AnyButton, AnyModifier,
427                            XDefaultRootWindow (spi_get_display ()));
428           }
429         return FALSE;
430 }
431 #endif
432
433 static void
434 spi_dec_init_mouse_listener (SpiDEController *dec)
435 {
436 #ifdef GRAB_BUTTON
437   Display *display = spi_get_display ();
438
439   if (display)
440     {
441       if (XGrabButton (display, AnyButton, AnyModifier,
442                        spi_get_root_window (),
443                        True, ButtonPressMask | ButtonReleaseMask,
444                        GrabModeSync, GrabModeAsync, None, None) != Success) {
445 #ifdef SPI_DEBUG
446         fprintf (stderr, "WARNING: could not grab mouse buttons!\n");
447 #endif
448         ;
449       }
450       XSync (display, False);
451 #ifdef SPI_DEBUG
452       fprintf (stderr, "mouse buttons grabbed\n");
453 #endif
454     }
455 #endif
456 }
457
458 static void
459 spi_dec_clear_unlatch_pending (SpiDEController *controller)
460 {
461   DEControllerPrivateData *priv = controller->priv;
462   priv->xkb_latch_mask = 0;
463 }
464
465 static void
466 spi_device_event_controller_forward_mouse_event (SpiDEController *controller,
467                                                  XEvent *xevent)
468 {
469   Accessibility_DeviceEvent mouse_e;
470   gchar event_detail[3];
471   gboolean is_consumed = FALSE;
472   gboolean xkb_mod_unlatch_occurred;
473   XButtonEvent *xbutton_event = (XButtonEvent *) xevent;
474   dbus_uint32_t ix, iy;
475
476   int button = xbutton_event->button;
477   
478   unsigned int mouse_button_state = xbutton_event->state;
479
480   switch (button)
481     {
482     case 1:
483             mouse_button_state |= Button1Mask;
484             break;
485     case 2:
486             mouse_button_state |= Button2Mask;
487             break;
488     case 3:
489             mouse_button_state |= Button3Mask;
490             break;
491     case 4:
492             mouse_button_state |= Button4Mask;
493             break;
494     case 5:
495             mouse_button_state |= Button5Mask;
496             break;
497     }
498
499   last_mouse_pos->x = ((XButtonEvent *) xevent)->x_root;
500   last_mouse_pos->y = ((XButtonEvent *) xevent)->y_root;
501
502 #ifdef SPI_DEBUG  
503   fprintf (stderr, "mouse button %d %s (%x)\n",
504            xbutton_event->button, 
505            (xevent->type == ButtonPress) ? "Press" : "Release",
506            mouse_button_state);
507 #endif
508   snprintf (event_detail, 3, "%d%c", button,
509             (xevent->type == ButtonPress) ? 'p' : 'r');
510
511   /* TODO: FIXME distinguish between physical and logical buttons */
512   mouse_e.type      = (xevent->type == ButtonPress) ? 
513                       Accessibility_BUTTON_PRESSED_EVENT :
514                       Accessibility_BUTTON_RELEASED_EVENT;
515   mouse_e.id        = button;
516   mouse_e.hw_code   = button;
517   mouse_e.modifiers = (dbus_uint16_t) xbutton_event->state;
518   mouse_e.timestamp = (dbus_uint32_t) xbutton_event->time;
519   mouse_e.event_string = "";
520   mouse_e.is_text   = FALSE;
521   if ((mouse_button_state & mouse_button_mask) != 
522        (mouse_mask_state & mouse_button_mask))
523     { 
524       if ((mouse_mask_state & key_modifier_mask) !=
525           (mouse_button_state & key_modifier_mask))
526         spi_dec_x11_emit_modifier_event (controller, 
527                                      mouse_mask_state, mouse_button_state);
528       mouse_mask_state = mouse_button_state;
529       is_consumed = 
530         spi_controller_notify_mouselisteners (controller, &mouse_e);
531       ix = last_mouse_pos->x;
532       iy = last_mouse_pos->y;
533       spi_dec_dbus_emit(controller, SPI_DBUS_INTERFACE_EVENT_MOUSE, "Button", event_detail, ix, iy);
534     }
535
536   xkb_mod_unlatch_occurred = (xevent->type == ButtonPress ||
537                               xevent->type == ButtonRelease);
538   
539   /* if client wants to consume this event, and XKB latch state was
540    *   unset by this button event, we reset it
541    */
542   if (is_consumed && xkb_mod_unlatch_occurred)
543     spi_dec_set_unlatch_pending (controller, mouse_mask_state);
544   
545   XAllowEvents (spi_get_display (),
546                 (is_consumed) ? SyncPointer : ReplayPointer,
547                 CurrentTime);
548 }
549
550 static void
551 global_filter_fn (XEvent *xevent, void *data)
552 {
553   SpiDEController *controller;
554   DEControllerPrivateData *priv;
555   Display *display = spi_get_display ();
556   controller = SPI_DEVICE_EVENT_CONTROLLER (data);
557   priv = controller->priv;
558
559   if (xevent->type == MappingNotify)
560     xmkeymap = NULL;
561
562   if (xevent->type == KeyPress || xevent->type == KeyRelease)
563     {
564       if (priv->xevie_display == NULL)
565         {
566           gboolean is_consumed;
567
568           is_consumed =
569             spi_device_event_controller_forward_key_event (controller, xevent);
570
571           if (is_consumed)
572             {
573               int n_events;
574               int i;
575               XEvent next_event;
576               n_events = XPending (display);
577
578 #ifdef SPI_KEYEVENT_DEBUG
579               g_print ("Number of events pending: %d\n", n_events);
580 #endif
581               for (i = 0; i < n_events; i++)
582                 {
583                   XNextEvent (display, &next_event);
584                   if (next_event.type != KeyPress &&
585                       next_event.type != KeyRelease)
586                         g_warning ("Unexpected event type %d in queue", next_event.type);
587                  }
588
589               XAllowEvents (display, AsyncKeyboard, CurrentTime);
590               if (n_events)
591                 XUngrabKeyboard (display, CurrentTime);
592             }
593           else
594             {
595               if (xevent->type == KeyPress)
596                 wait_for_release_event (xevent, controller);
597               XAllowEvents (display, ReplayKeyboard, CurrentTime);
598             }
599         }
600
601       return;
602     }
603   if (xevent->type == ButtonPress || xevent->type == ButtonRelease)
604     {
605       spi_device_event_controller_forward_mouse_event (controller, xevent);
606     }
607   if (xevent->type == priv->xkb_base_event_code)
608     {
609       XkbAnyEvent * xkb_ev = (XkbAnyEvent *) xevent;
610       /* ugly but probably necessary...*/
611       XSynchronize (display, TRUE);
612
613       if (xkb_ev->xkb_type == XkbStateNotify)
614         {
615           XkbStateNotifyEvent *xkb_snev =
616                   (XkbStateNotifyEvent *) xkb_ev;
617           /* check the mouse, to catch mouse events grabbed by
618            * another client; in case we should revert this XKB delatch 
619            */
620           if (!priv->pending_xkb_mod_relatch_mask)
621             {
622               int x, y;
623               gboolean moved;
624               spi_dec_x11_mouse_check (controller, &x, &y, &moved);
625             }
626           /* we check again, since the previous call may have 
627              changed this flag */
628           if (priv->pending_xkb_mod_relatch_mask)
629             {
630               unsigned int feedback_mask;
631 #ifdef SPI_XKB_DEBUG
632               fprintf (stderr, "relatching %x\n",
633                        priv->pending_xkb_mod_relatch_mask);
634 #endif
635               /* temporarily turn off the latch bell, if it's on */
636               XkbGetControls (display,
637                               XkbAccessXFeedbackMask,
638                               priv->xkb_desc);
639               feedback_mask = priv->xkb_desc->ctrls->ax_options;
640               if (feedback_mask & XkbAX_StickyKeysFBMask)
641               {
642                 XkbControlsChangesRec changes = {XkbAccessXFeedbackMask,
643                                                  0, False};      
644                 priv->xkb_desc->ctrls->ax_options
645                               &= ~(XkbAX_StickyKeysFBMask);
646                 XkbChangeControls (display, priv->xkb_desc, &changes);
647               }
648               /* TODO: account for lock as well as latch */
649               XkbLatchModifiers (display,
650                                  XkbUseCoreKbd,
651                                  priv->pending_xkb_mod_relatch_mask,
652                                  priv->pending_xkb_mod_relatch_mask);
653               if (feedback_mask & XkbAX_StickyKeysFBMask)
654               { 
655                 XkbControlsChangesRec changes = {XkbAccessXFeedbackMask,
656                                                  0, False};      
657                 priv->xkb_desc->ctrls->ax_options = feedback_mask;
658                 XkbChangeControls (display, priv->xkb_desc, &changes);
659               }
660 #ifdef SPI_XKB_DEBUG
661               fprintf (stderr, "relatched %x\n",
662                        priv->pending_xkb_mod_relatch_mask);
663 #endif
664               priv->pending_xkb_mod_relatch_mask = 0;
665             }
666           else
667             {
668               priv->xkb_latch_mask = xkb_snev->latched_mods;
669             }
670         }
671       XSynchronize (display, FALSE);
672     }
673   
674   return;
675 }
676
677 static int
678 _spi_controller_device_error_handler (Display *display, XErrorEvent *error)
679 {
680   if (error->error_code == BadAccess) 
681     {  
682       g_message ("Could not complete key grab: grab already in use.\n");
683       spi_error_code = BadAccess;
684       return 0;
685     }
686   else 
687     {
688       return (*x_default_error_handler) (display, error);
689     }
690 }
691
692 static void
693 spi_controller_register_with_devices (SpiDEController *controller)
694 {
695   DEControllerPrivateData *priv;
696   int event_base, error_base, major_version, minor_version;
697
698   priv = controller->priv;
699   if (XTestQueryExtension (spi_get_display(), &event_base, &error_base, &major_version, &minor_version))
700     {
701       XTestGrabControl (spi_get_display (), True);
702     }
703
704   /* calls to device-specific implementations and routines go here */
705   /* register with: keyboard hardware code handler */
706   /* register with: (translated) keystroke handler */
707
708   priv->have_xkb = XkbQueryExtension (spi_get_display (),
709                                       &priv->xkb_major_extension_opcode,
710                                       &priv->xkb_base_event_code,
711                                       &priv->xkb_base_error_code, NULL, NULL);
712   if (priv->have_xkb)
713     {
714       gint i;
715       guint64 reserved = 0;
716       priv->xkb_desc = XkbGetMap (spi_get_display (), XkbKeySymsMask, XkbUseCoreKbd);
717       XkbSelectEvents (spi_get_display (),
718                        XkbUseCoreKbd,
719                        XkbStateNotifyMask, XkbStateNotifyMask);     
720       _numlock_physical_mask = XkbKeysymToModifiers (spi_get_display (), 
721                                                      XK_Num_Lock);
722       for (i = priv->xkb_desc->max_key_code; i >= priv->xkb_desc->min_key_code; --i)
723       {
724           if (priv->xkb_desc->map->key_sym_map[i].kt_index[0] == XkbOneLevelIndex)
725           { 
726               if (XkbKeycodeToKeysym (spi_get_display (), i, 0, 0) != 0)
727               {
728                   /* don't use this one if there's a grab client! */
729
730                   /* Runtime errors are generated from these functions,
731                    * that are then quashed. Equivalent to:
732                    * try
733                    *   {Blah}
734                    * except
735                    *   {;}
736                    */
737
738                   spi_x_error_trap ();
739                   XGrabKey (spi_get_display (), i, 0, 
740                             spi_get_root_window (),
741                             TRUE,
742                             GrabModeSync, GrabModeSync);
743                   XSync (spi_get_display (), TRUE);
744                   XUngrabKey (spi_get_display (), i, 0, 
745                               spi_get_root_window ());
746                   if (!spi_x_error_release ())
747                   {
748                       reserved = i;
749                       break;
750                   }
751               }
752           }
753       }
754       if (reserved) 
755       {
756           priv->reserved_keycode = reserved;
757           priv->reserved_keysym = XkbKeycodeToKeysym (spi_get_display (), reserved, 0, 0);
758       }
759       else
760       { 
761           priv->reserved_keycode = XKeysymToKeycode (spi_get_display (), XK_numbersign);
762           priv->reserved_keysym = XK_numbersign;
763       }
764 #ifdef SPI_RESERVED_DEBUG
765       unsigned sym = 0;
766       sym = XKeycodeToKeysym (spi_get_display (), reserved, 0);
767       fprintf (stderr, "%x\n", sym);
768       fprintf (stderr, "setting the reserved keycode to %d (%s)\n", 
769                reserved, 
770                XKeysymToString (XKeycodeToKeysym (spi_get_display (),
771                                                             reserved, 0)));
772 #endif
773     }   
774
775   spi_set_filter (global_filter_fn, controller);
776   spi_set_events (KeyPressMask | KeyReleaseMask);
777
778   x_default_error_handler = XSetErrorHandler (_spi_controller_device_error_handler);
779 }
780
781 static Accessibility_DeviceEvent
782 spi_keystroke_from_x_key_event (XKeyEvent *x_key_event)
783 {
784   Accessibility_DeviceEvent key_event;
785   KeySym keysym;
786   const int cbuf_bytes = 20;
787   char cbuf [21];
788   int nbytes;
789
790   nbytes = XLookupString (x_key_event, cbuf, cbuf_bytes, &keysym, NULL);  
791   key_event.id = (dbus_int32_t)(keysym);
792   key_event.hw_code = (dbus_int16_t) x_key_event->keycode;
793   if (((XEvent *) x_key_event)->type == KeyPress)
794     {
795       key_event.type = Accessibility_KEY_PRESSED_EVENT;
796     }
797   else
798     {
799       key_event.type = Accessibility_KEY_RELEASED_EVENT;
800     } 
801   key_event.modifiers = (dbus_uint16_t)(x_key_event->state);
802   key_event.is_text = FALSE;
803   switch (keysym)
804     {
805       case ' ':
806         key_event.event_string = g_strdup ("space");
807         break;
808       case XK_Tab:
809         key_event.event_string = g_strdup ("Tab");
810         break;
811       case XK_BackSpace:
812         key_event.event_string = g_strdup ("Backspace");
813         break;
814       case XK_Return:
815         key_event.event_string = g_strdup ("Return");
816         break;
817       case XK_Home:
818         key_event.event_string = g_strdup ("Home");
819         break;
820       case XK_Page_Down:
821         key_event.event_string = g_strdup ("Page_Down");
822         break;
823       case XK_Page_Up:
824         key_event.event_string = g_strdup ("Page_Up");
825         break;
826       case XK_F1:
827         key_event.event_string = g_strdup ("F1");
828         break;
829       case XK_F2:
830         key_event.event_string = g_strdup ("F2");
831         break;
832       case XK_F3:
833         key_event.event_string = g_strdup ("F3");
834         break;
835       case XK_F4:
836         key_event.event_string = g_strdup ("F4");
837         break;
838       case XK_F5:
839         key_event.event_string = g_strdup ("F5");
840         break;
841       case XK_F6:
842         key_event.event_string = g_strdup ("F6");
843         break;
844       case XK_F7:
845         key_event.event_string = g_strdup ("F7");
846         break;
847       case XK_F8:
848         key_event.event_string = g_strdup ("F8");
849         break;
850       case XK_F9:
851         key_event.event_string = g_strdup ("F9");
852         break;
853       case XK_F10:
854         key_event.event_string = g_strdup ("F10");
855         break;
856       case XK_F11:
857         key_event.event_string = g_strdup ("F11");
858         break;
859       case XK_F12:
860         key_event.event_string = g_strdup ("F12");
861         break;
862       case XK_End:
863         key_event.event_string = g_strdup ("End");
864         break;
865       case XK_Escape:
866         key_event.event_string = g_strdup ("Escape");
867         break;
868       case XK_Up:
869         key_event.event_string = g_strdup ("Up");
870         break;
871       case XK_Down:
872         key_event.event_string = g_strdup ("Down");
873         break;
874       case XK_Left:
875         key_event.event_string = g_strdup ("Left");
876         break;
877       case XK_Right:
878         key_event.event_string = g_strdup ("Right");
879         break;
880       default:
881         if (nbytes > 0)
882           {
883             gunichar c;
884             cbuf[nbytes] = '\0'; /* OK since length is cbuf_bytes+1 */
885             key_event.event_string = g_strdup (cbuf);
886             c = keysym2ucs (keysym);
887             if (c > 0 && !g_unichar_iscntrl (c))
888               {
889                 key_event.is_text = TRUE; 
890                 /* incorrect for some composed chars? */
891               }
892           }
893         else
894           {
895             key_event.event_string = g_strdup ("");
896           }
897     }
898
899   key_event.timestamp = (dbus_uint32_t) x_key_event->time;
900 #ifdef SPI_KEYEVENT_DEBUG
901   {
902     char *pressed_str  = "pressed";
903     char *released_str = "released";
904     char *state_ptr;
905
906     if (key_event.type == Accessibility_KEY_PRESSED_EVENT)
907       state_ptr = pressed_str;
908     else
909       state_ptr = released_str;
910  
911     fprintf (stderr,
912              "Key %lu %s (%c), modifiers %d; string=%s [%x] %s\n",
913              (unsigned long) keysym,
914              state_ptr,
915              keysym ? (int) keysym : '*',
916              (int) x_key_event->state,
917              key_event.event_string,
918              key_event.event_string[0],
919              (key_event.is_text == TRUE) ? "(text)" : "(not text)");
920   }
921 #endif
922 #ifdef SPI_DEBUG
923   fprintf (stderr, "%s%c\n",
924      (x_key_event->state & Mod1Mask)?"Alt-":"",
925      ((x_key_event->state & ShiftMask)^(x_key_event->state & LockMask))?
926      g_ascii_toupper (keysym) : g_ascii_tolower (keysym));
927   fprintf (stderr, "serial: %x Time: %x\n", x_key_event->serial, x_key_event->time);
928 #endif /* SPI_DEBUG */
929   return key_event;     
930 }
931
932 static gboolean
933 spi_dec_x11_grab_key (SpiDEController *controller,
934                       guint key_val,
935                       Accessibility_ControllerEventMask mod_mask)
936 {
937   XGrabKey (spi_get_display (),
938             key_val,
939             mod_mask,
940             spi_get_root_window (),
941             True,
942             GrabModeSync,
943             GrabModeSync);
944   XSync (spi_get_display (), False);
945   return spi_clear_error_state ();
946 }
947
948 static void
949 spi_dec_x11_ungrab_key (SpiDEController *controller,
950                         guint key_val,
951                         Accessibility_ControllerEventMask mod_mask)
952 {
953   XUngrabKey (spi_get_display (),
954               key_val,
955               mod_mask,
956               spi_get_root_window ());
957 }
958
959 static unsigned int
960 xkb_get_slowkeys_delay (SpiDEController *controller)
961 {
962   unsigned int retval = 0;
963   DEControllerPrivateData *priv = controller->priv;
964 #ifdef HAVE_XKB
965 #ifdef XKB_HAS_GET_SLOW_KEYS_DELAY      
966   retval = XkbGetSlowKeysDelay (spi_get_display (),
967                                 XkbUseCoreKbd, &bounce_delay);
968 #else
969   if (!(priv->xkb_desc == (XkbDescPtr) BadAlloc || priv->xkb_desc == NULL))
970     {
971       Status s = XkbGetControls (spi_get_display (),
972                                  XkbAllControlsMask, priv->xkb_desc);
973       if (s == Success)
974         {
975          if (priv->xkb_desc->ctrls->enabled_ctrls & XkbSlowKeysMask)
976                  retval = priv->xkb_desc->ctrls->slow_keys_delay;
977         }
978     }
979 #endif
980 #endif
981 #ifdef SPI_XKB_DEBUG
982         fprintf (stderr, "SlowKeys delay: %d\n", (int) retval);
983 #endif
984         return retval;
985 }
986
987 static unsigned int
988 xkb_get_bouncekeys_delay (SpiDEController *controller)
989 {
990   unsigned int retval = 0;
991   DEControllerPrivateData *priv = controller->priv;
992 #ifdef HAVE_XKB
993 #ifdef XKB_HAS_GET_BOUNCE_KEYS_DELAY    
994   retval = XkbGetBounceKeysDelay (spi_get_display (),
995                                   XkbUseCoreKbd, &bounce_delay);
996 #else
997   if (!(priv->xkb_desc == (XkbDescPtr) BadAlloc || priv->xkb_desc == NULL))
998     {
999       Status s = XkbGetControls (spi_get_display (),
1000                                  XkbAllControlsMask, priv->xkb_desc);
1001       if (s == Success)
1002         {
1003           if (priv->xkb_desc->ctrls->enabled_ctrls & XkbBounceKeysMask)
1004                   retval = priv->xkb_desc->ctrls->debounce_delay;
1005         }
1006     }
1007 #endif
1008 #endif
1009 #ifdef SPI_XKB_DEBUG
1010   fprintf (stderr, "BounceKeys delay: %d\n", (int) retval);
1011 #endif
1012   return retval;
1013 }
1014
1015 static gboolean
1016 spi_dec_x11_synth_keycode_press (SpiDEController *controller,
1017                          unsigned int keycode)
1018 {
1019         unsigned int time = CurrentTime;
1020         unsigned int bounce_delay;
1021 #ifdef THIS_IS_BROKEN 
1022         unsigned int elapsed_msec;
1023         struct timeval tv;
1024 #endif
1025         DEControllerPrivateData *priv = controller->priv;
1026
1027         spi_x_error_trap ();
1028         if (keycode == priv->last_release_keycode)
1029         {
1030                 bounce_delay = xkb_get_bouncekeys_delay (controller); 
1031                 if (bounce_delay)
1032                 {
1033 #ifdef THIS_IS_BROKEN
1034                         gettimeofday (&tv, NULL);
1035                         elapsed_msec =
1036                                 (tv.tv_sec - priv->last_release_time.tv_sec) * 1000
1037                                 + (tv.tv_usec - priv->last_release_time.tv_usec) / 1000;
1038 # ifdef SPI_XKB_DEBUG
1039                         fprintf (stderr, "%d ms elapsed (%ld usec)\n", elapsed_msec,
1040                                  (long) (tv.tv_usec - priv->last_release_time.tv_usec));
1041 # endif
1042                         if (elapsed_msec < bounce_delay)
1043                                 time = bounce_delay - elapsed_msec + 1;
1044 #else
1045                         time = bounce_delay + 10;
1046                         /* fudge for broken XTest */
1047 #endif
1048 #ifdef SPI_XKB_DEBUG                    
1049                         fprintf (stderr, "waiting %d ms\n", time);
1050 #endif
1051                 }
1052         }
1053         XTestFakeKeyEvent (spi_get_display (), keycode, True, time);
1054         priv->last_press_keycode = keycode;
1055         XFlush (spi_get_display ());
1056         XSync (spi_get_display (), False);
1057         gettimeofday (&priv->last_press_time, NULL);
1058         return TRUE;
1059 }
1060
1061 static gboolean
1062 spi_dec_x11_synth_keycode_release (SpiDEController *controller,
1063                            unsigned int keycode)
1064 {
1065         unsigned int time = CurrentTime;
1066         unsigned int slow_delay;
1067 #ifdef THIS_IS_BROKEN_DUNNO_WHY
1068         unsigned int elapsed_msec;
1069         struct timeval tv;
1070 #endif
1071         DEControllerPrivateData *priv = controller->priv;
1072
1073         spi_x_error_trap ();
1074         if (keycode == priv->last_press_keycode)
1075         {
1076                 slow_delay = xkb_get_slowkeys_delay (controller);
1077                 if (slow_delay)
1078                 {
1079 #ifdef THIS_IS_BROKEN_DUNNO_WHY
1080                         gettimeofday (&tv, NULL);
1081                         elapsed_msec =
1082                                 (tv.tv_sec - priv->last_press_time.tv_sec) * 1000
1083                                 + (tv.tv_usec - priv->last_press_time.tv_usec) / 1000;
1084 # ifdef SPI_XKB_DEBUG
1085                         fprintf (stderr, "%d ms elapsed (%ld usec)\n", elapsed_msec,
1086                                  (long) (tv.tv_usec - priv->last_press_time.tv_usec));
1087 # endif
1088                         if (elapsed_msec < slow_delay)
1089                                 time = slow_delay - elapsed_msec + 1;
1090 #else
1091                         time = slow_delay + 10;
1092                         /* our XTest seems broken, we have to add slop as above */
1093 #endif
1094 #ifdef SPI_XKB_DEBUG                    
1095                         fprintf (stderr, "waiting %d ms\n", time);
1096 #endif
1097                 }
1098         }
1099         XTestFakeKeyEvent (spi_get_display (), keycode, False, time);
1100         priv->last_release_keycode = keycode;
1101         XSync (spi_get_display (), False);
1102         gettimeofday (&priv->last_release_time, NULL);
1103         return TRUE;
1104 }
1105
1106 static gboolean
1107 spi_dec_x11_lock_modifiers (SpiDEController *controller, unsigned modifiers)
1108 {
1109     DEControllerPrivateData *priv = controller->priv;
1110     
1111     if (priv->have_xkb) {
1112         return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
1113                                   modifiers, modifiers);
1114     } else {
1115         int mod_index;
1116         if (xmkeymap==NULL)
1117           xmkeymap = XGetModifierMapping(spi_get_display ());
1118         for (mod_index=0;mod_index<8;mod_index++)
1119             if (modifiers & (1<<mod_index))
1120                 spi_dec_x11_synth_keycode_press(controller, xmkeymap->modifiermap[mod_index]);
1121         return TRUE;
1122     }
1123 }
1124
1125 static gboolean
1126 spi_dec_x11_unlock_modifiers (SpiDEController *controller, unsigned modifiers)
1127 {
1128     DEControllerPrivateData *priv = controller->priv;
1129     
1130     if (priv->have_xkb) {
1131         return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
1132                                   modifiers, 0);
1133     } else {
1134         int mod_index;
1135         if (xmkeymap==NULL)
1136           xmkeymap = XGetModifierMapping(spi_get_display ());
1137
1138         for (mod_index=0;mod_index<8;mod_index++)
1139             if (modifiers & (1<<mod_index))
1140                 spi_dec_x11_synth_keycode_release(controller, xmkeymap->modifiermap[mod_index]);
1141         return TRUE;
1142     }
1143 }
1144
1145 static KeySym
1146 keysym_for_unichar (SpiDEController *controller, gunichar unichar)
1147 {
1148         return (KeySym) ucs2keysym ((long) unichar);
1149 }
1150
1151 static gboolean
1152 spi_dec_x11_synth_keystring (SpiDEController *controller, guint synth_type, gint keycode, const char *keystring)
1153 {
1154         /* probably we need to create and inject an XIM handler eventually. */
1155         /* for now, try to match the string to existing 
1156          * keycode+modifier states. 
1157          */
1158         KeySym *keysyms;
1159         gint maxlen = 0;
1160         gunichar unichar = 0;
1161         gint i = 0;
1162         gboolean retval = TRUE;
1163         const gchar *c;
1164         KeySym keysym;
1165
1166         if (!(keystring && *keystring && g_utf8_validate (keystring, -1, &c))) { 
1167                 retval = FALSE;
1168         } 
1169         else {
1170 #ifdef SPI_DEBUG
1171                 fprintf (stderr, "[keystring synthesis attempted on %s]\n", keystring);
1172 #endif
1173                 maxlen = strlen (keystring) + 1;
1174                 keysyms = g_new0 (KeySym, maxlen);
1175
1176                 while (keystring && (unichar = g_utf8_get_char (keystring))) {
1177                         char bytes[6];
1178                         gint mbytes;
1179                         
1180                         mbytes = g_unichar_to_utf8 (unichar, bytes);
1181                         bytes[mbytes] = '\0';
1182 #ifdef SPI_DEBUG
1183                         fprintf (stderr, "[unichar %s]", bytes);
1184 #endif
1185                         keysym = keysym_for_unichar (controller, unichar);
1186                         if (keysym == NoSymbol) {
1187 #ifdef SPI_DEBUG
1188                                 fprintf (stderr, "no keysym for %s", bytes);
1189 #endif
1190                                 retval = FALSE;
1191                                 break;
1192                         }
1193                         keysyms[i++] = keysym;
1194                         keystring = g_utf8_next_char (keystring); 
1195                 }
1196                 keysyms[i++] = 0;
1197                 XSynchronize (spi_get_display (), TRUE);
1198                 for (i = 0; keysyms[i]; ++i) {
1199                         if (!spi_dec_synth_keysym (controller, keysyms[i])) {
1200 #ifdef SPI_DEBUG
1201                                 fprintf (stderr, "could not synthesize %c\n",
1202                                          (int) keysyms[i]);
1203 #endif
1204                                 retval = FALSE;
1205                                 break;
1206                         }
1207                 }
1208                 XSynchronize (spi_get_display (), FALSE);
1209
1210                 g_free (keysyms);
1211         }
1212
1213         if (synth_type == Accessibility_KEY_SYM) {
1214                 keysym = keycode;
1215         }
1216         else {
1217                 keysym = XkbKeycodeToKeysym (spi_get_display (), keycode, 0, 0);
1218         }
1219         if (XkbKeysymToModifiers (spi_get_display (), keysym) == 0)  {
1220                 spi_dec_clear_unlatch_pending (controller);
1221         }
1222         return retval;
1223 }
1224
1225 static void
1226 spi_dec_x11_init (SpiDEController *controller)
1227 {
1228   DEControllerPrivateData *priv = controller->priv;     
1229
1230   spi_events_init (spi_get_display ());
1231
1232   gettimeofday (&priv->last_press_time, NULL);
1233   gettimeofday (&priv->last_release_time, NULL);
1234   spi_controller_register_with_devices (controller);
1235
1236   spi_dec_init_mouse_listener (controller);
1237
1238   saved_controller = controller;
1239 }
1240
1241 static void
1242 spi_dec_x11_finalize (SpiDEController *controller)
1243 {
1244   DEControllerPrivateData *priv = controller->priv;
1245
1246   /* disconnect any special listeners, get rid of outstanding keygrabs */
1247   XUngrabKey (spi_get_display (), AnyKey, AnyModifier, DefaultRootWindow (spi_get_display ()));
1248
1249   if (priv->xkb_desc)
1250     XkbFreeKeyboard (priv->xkb_desc, 0, True);
1251   /* TODO: Should free the keymap */
1252 }
1253
1254 static gboolean
1255 spi_device_event_controller_forward_key_event (SpiDEController *controller,
1256                                                const XEvent    *event)
1257 {
1258   DEControllerPrivateData *priv = controller->priv;
1259   Accessibility_DeviceEvent key_event;
1260   gboolean ret;
1261
1262   g_assert (event->type == KeyPress || event->type == KeyRelease);
1263
1264   key_event = spi_keystroke_from_x_key_event ((XKeyEvent *) event);
1265
1266   if (priv->xevie_display == NULL)
1267     spi_controller_update_key_grabs (controller, &key_event);
1268
1269   /* relay to listeners, and decide whether to consume it or not */
1270   ret = spi_controller_notify_keylisteners (controller, &key_event, TRUE);
1271   g_free(key_event.event_string);
1272   return ret;
1273 }
1274
1275
1276 static gboolean
1277 is_key_released (long code)
1278 {
1279   char keys[32];
1280   int down;
1281
1282   XQueryKeymap (spi_get_display (), keys);
1283   down = BIT (keys, code);
1284   return (down == 0);
1285 }
1286
1287 static gboolean
1288 check_release (gpointer data)
1289 {
1290   gboolean released;
1291   Accessibility_DeviceEvent *event = (Accessibility_DeviceEvent *)data;
1292   KeyCode code = event->hw_code;
1293
1294   released = is_key_released (code);
1295
1296   if (released)
1297     {
1298       check_release_handler = 0;
1299       event->type = Accessibility_KEY_RELEASED_EVENT;
1300       spi_controller_notify_keylisteners (saved_controller, event, TRUE);
1301     }
1302   return (released == 0);
1303 }
1304
1305 static void
1306 wait_for_release_event (XEvent          *event,
1307                                     SpiDEController *controller)
1308 {
1309   pressed_event = spi_keystroke_from_x_key_event ((XKeyEvent *) event);
1310   check_release_handler = g_timeout_add (CHECK_RELEASE_DELAY, check_release, &pressed_event);
1311   g_source_set_name_by_id (check_release_handler, "[at-spi2-core] check_release");
1312 }
1313
1314 static void
1315 spi_dec_x11_emit_modifier_event (SpiDEController *controller, guint prev_mask, 
1316                              guint current_mask)
1317 {
1318   dbus_uint32_t d1, d2;
1319
1320 #ifdef SPI_XKB_DEBUG
1321   fprintf (stderr, "MODIFIER CHANGE EVENT! %x to %x\n", 
1322            prev_mask, current_mask);
1323 #endif
1324
1325   /* set bits for the virtual modifiers like NUMLOCK */
1326   if (prev_mask & _numlock_physical_mask) 
1327     prev_mask |= SPI_KEYMASK_NUMLOCK;
1328   if (current_mask & _numlock_physical_mask) 
1329     current_mask |= SPI_KEYMASK_NUMLOCK;
1330
1331   d1 = prev_mask & key_modifier_mask;
1332   d2 = current_mask & key_modifier_mask;
1333       spi_dec_dbus_emit(controller, SPI_DBUS_INTERFACE_EVENT_KEYBOARD, "Modifiers", "", d1, d2);
1334 }
1335
1336 static void
1337 spi_dec_x11_generate_mouse_event (SpiDEController *controller,
1338                                   gint x,
1339                                   gint y,
1340                                   const char *eventName)
1341 {
1342   int button = 0;
1343   gboolean err = FALSE;
1344   Display *display = spi_get_display ();
1345
1346   switch (eventName[0])
1347     {
1348       case 'b':
1349         switch (eventName[1])
1350           {
1351           /* TODO: check number of buttons before parsing */
1352           case '1':
1353                     button = 1;
1354                     break;
1355           case '2':
1356                   button = 2;
1357                   break;
1358           case '3':
1359                   button = 3;
1360                   break;
1361           case '4':
1362                   button = 4;
1363                   break;
1364           case '5':
1365                   button = 5;
1366                   break;
1367           default:
1368                   err = TRUE;
1369           }
1370         if (!err)
1371           {
1372             if (x != -1 && y != -1)
1373               {
1374                 XTestFakeMotionEvent (display, DefaultScreen (display),
1375                                       x, y, 0);
1376               }
1377             XTestFakeButtonEvent (display, button, !(eventName[2] == 'r'), 0);
1378             if (eventName[2] == 'c')
1379               XTestFakeButtonEvent (display, button, FALSE, 1);
1380             else if (eventName[2] == 'd')
1381               {
1382               XTestFakeButtonEvent (display, button, FALSE, 1);
1383               XTestFakeButtonEvent (display, button, TRUE, 2);
1384               XTestFakeButtonEvent (display, button, FALSE, 3);
1385               }
1386           }
1387         break;
1388       case 'r': /* relative motion */ 
1389         XTestFakeRelativeMotionEvent (display, x, y, 0);
1390         break;
1391       case 'a': /* absolute motion */
1392         XTestFakeMotionEvent (display, DefaultScreen (display),
1393                               x, y, 0);
1394         break;
1395     }
1396 }
1397
1398 void
1399 spi_dec_setup_x11 (SpiDEControllerClass *klass)
1400 {
1401   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1402
1403   klass->plat.get_keycode = spi_dec_x11_get_keycode;
1404   klass->plat.mouse_check = spi_dec_x11_mouse_check;
1405   klass->plat.synth_keycode_press = spi_dec_x11_synth_keycode_press;
1406   klass->plat.synth_keycode_release = spi_dec_x11_synth_keycode_release;
1407   klass->plat.lock_modifiers = spi_dec_x11_lock_modifiers;
1408   klass->plat.unlock_modifiers = spi_dec_x11_unlock_modifiers;
1409   klass->plat.synth_keystring = spi_dec_x11_synth_keystring;
1410   klass->plat.grab_key = spi_dec_x11_grab_key;
1411   klass->plat.ungrab_key = spi_dec_x11_ungrab_key;
1412   klass->plat.emit_modifier_event = spi_dec_x11_emit_modifier_event;
1413   klass->plat.generate_mouse_event = spi_dec_x11_generate_mouse_event;
1414
1415   klass->plat.init = spi_dec_x11_init;
1416   klass->plat.finalize = spi_dec_x11_finalize;
1417
1418   g_type_class_add_private (object_class, sizeof (DEControllerPrivateData));
1419 }