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