Imported version 2.7.91
[platform/core/uifw/at-spi2-core.git] / registryd / deviceeventcontroller.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.c: implement the DeviceEventController interface */
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 #define XK_MISCELLANY
42 #define XK_LATIN1
43 #include <X11/keysymdef.h>
44
45 #ifdef HAVE_XEVIE
46 #include <X11/Xproto.h>
47 #include <X11/X.h>
48 #include <X11/extensions/Xevie.h>
49 #endif /* HAVE_XEVIE */
50
51 #include <glib.h>
52
53 #include <dbus/dbus.h>
54
55 #include "paths.h"
56 #include "keymasks.h"
57 #include "de-types.h"
58 #include "de-marshaller.h"
59 #include "display.h"
60 #include "event-source.h"
61
62 #include "deviceeventcontroller.h"
63 #include "reentrant-list.h"
64
65 #include "introspection.h"
66
67 KeySym ucs2keysym (long ucs);
68 long keysym2ucs(KeySym keysym); 
69
70 #define CHECK_RELEASE_DELAY 20
71 #define BIT(c, x)       (c[x/8]&(1<<(x%8)))
72 static guint check_release_handler = 0;
73 static Accessibility_DeviceEvent pressed_event;
74 static SpiDEController *saved_controller; 
75 static void wait_for_release_event (XEvent *event, SpiDEController *controller);
76
77 /* Our parent Gtk object type */
78 #define PARENT_TYPE G_TYPE_OBJECT
79
80 /* A pointer to our parent object class */
81 static int spi_error_code = 0;
82 struct _SpiPoint {
83     gint x;
84     gint y;
85 };
86 typedef struct _SpiPoint SpiPoint;
87 static SpiPoint last_mouse_pos_static = {0, 0}; 
88 static SpiPoint *last_mouse_pos = &last_mouse_pos_static;
89 static unsigned int mouse_mask_state = 0;
90 static unsigned int mouse_button_mask =
91   Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask;
92 static unsigned int key_modifier_mask =
93   Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask | Mod5Mask | ShiftMask | LockMask | ControlMask | SPI_KEYMASK_NUMLOCK;
94 static unsigned int _numlock_physical_mask = Mod2Mask; /* a guess, will be reset */
95
96 static GQuark spi_dec_private_quark = 0;
97 static XModifierKeymap* xmkeymap = NULL;
98
99 static gboolean have_mouse_listener = FALSE;
100 static gboolean have_mouse_event_listener = FALSE;
101
102 static int (*x_default_error_handler) (Display *display, XErrorEvent *error_event);
103
104 typedef enum {
105   SPI_DEVICE_TYPE_KBD,
106   SPI_DEVICE_TYPE_MOUSE,
107   SPI_DEVICE_TYPE_LAST_DEFINED
108 } SpiDeviceTypeCategory;
109
110 typedef struct {
111   guint                             ref_count : 30;
112   guint                             pending_add : 1;
113   guint                             pending_remove : 1;
114
115   Accessibility_ControllerEventMask mod_mask;
116   dbus_uint32_t               key_val;  /* KeyCode */
117 } DEControllerGrabMask;
118
119 typedef struct {
120   char *bus_name;
121   char *path;
122   SpiDeviceTypeCategory type;
123   gulong types;
124 } DEControllerListener;
125
126 typedef struct {
127   DEControllerListener listener;
128
129  GSList *keys;
130   Accessibility_ControllerEventMask mask;
131   Accessibility_EventListenerMode  *mode;       
132 } DEControllerKeyListener;
133
134 typedef struct {
135   unsigned int last_press_keycode;
136   unsigned int last_release_keycode;
137   struct timeval last_press_time;
138   struct timeval last_release_time;
139   int have_xkb;
140   int xkb_major_extension_opcode;
141   int xkb_base_event_code;
142   int xkb_base_error_code;
143   unsigned int xkb_latch_mask;
144   unsigned int pending_xkb_mod_relatch_mask;
145   XkbDescPtr xkb_desc;
146   KeyCode reserved_keycode;
147   KeySym reserved_keysym;
148   guint  reserved_reset_timeout;
149 } DEControllerPrivateData;
150
151 static void     spi_controller_register_with_devices          (SpiDEController           *controller);
152 static gboolean spi_controller_update_key_grabs               (SpiDEController           *controller,
153                                                                Accessibility_DeviceEvent *recv);
154 static gboolean spi_controller_register_device_listener       (SpiDEController           *controller,
155                                                                DEControllerListener      *l);
156 static gboolean spi_device_event_controller_forward_key_event (SpiDEController           *controller,
157                                                                const XEvent              *event);
158 static void     spi_controller_deregister_device_listener (SpiDEController            *controller,
159                                                            DEControllerListener *listener);
160 static void     spi_deregister_controller_key_listener (SpiDEController         *controller,
161                                                         DEControllerKeyListener *key_listener);
162 static gboolean spi_controller_notify_mouselisteners (SpiDEController                 *controller,
163                                                       const Accessibility_DeviceEvent *event);
164
165 static gboolean spi_eventtype_seq_contains_event (dbus_uint32_t types,
166                                                   const Accessibility_DeviceEvent *event);
167 static gboolean spi_clear_error_state (void);
168 static gboolean spi_dec_poll_mouse_moved (gpointer data);
169 static gboolean spi_dec_poll_mouse_moving (gpointer data);
170 static gboolean spi_dec_poll_mouse_idle (gpointer data);
171
172 G_DEFINE_TYPE(SpiDEController, spi_device_event_controller, G_TYPE_OBJECT)
173
174 DBusMessage *
175 invalid_arguments_error (DBusMessage *message)
176 {
177     DBusMessage *reply;
178     gchar       *errmsg;
179
180     errmsg= g_strdup_printf (
181             "Method \"%s\" with signature \"%s\" on interface \"%s\" was supplied with invalid arguments\n",
182             dbus_message_get_member (message),
183             dbus_message_get_signature (message),
184             dbus_message_get_interface (message));
185     reply = dbus_message_new_error (message,
186                                     DBUS_ERROR_INVALID_ARGS,
187                                     errmsg);
188     g_free (errmsg);
189     return reply;
190 }
191
192 /* Private methods */
193 static dbus_bool_t
194 spi_dbus_add_disconnect_match (DBusConnection *bus, const char *name)
195 {
196   char *match = g_strdup_printf ("interface=%s,member=NameOwnerChanged,arg0=%s", DBUS_INTERFACE_DBUS, name);
197   if (match)
198   {
199     DBusError error;
200     dbus_error_init (&error);
201     dbus_bus_add_match (bus, match, &error);
202     g_free (match);
203     if (dbus_error_is_set (&error))
204       {
205         dbus_error_free (&error);
206         return FALSE;
207       }
208     else
209       {
210         return TRUE;
211       }
212   }
213   else return FALSE;
214 }
215
216 static dbus_bool_t
217 spi_dbus_remove_disconnect_match (DBusConnection *bus, const char *name)
218 {
219   char *match = g_strdup_printf ("interface=%s,member=NameOwnerChanged,arg0=%s", DBUS_INTERFACE_DBUS, name);
220   if (match)
221   {
222     DBusError error;
223     dbus_error_init (&error);
224     dbus_bus_remove_match (bus, match, &error);
225     g_free (match);
226     if (dbus_error_is_set (&error))
227       {
228         dbus_error_free (&error);
229         return FALSE;
230       }
231     else
232       {
233         return TRUE;
234       }
235   }
236   else return FALSE;
237 }
238
239 static unsigned int
240 keysym_mod_mask (KeySym keysym, KeyCode keycode)
241 {
242         /* we really should use XKB and look directly at the keymap */
243         /* this is very inelegant */
244         Display *display = spi_get_display ();
245         unsigned int mods_rtn = 0;
246         unsigned int retval = 0;
247         KeySym sym_rtn;
248
249         if (XkbLookupKeySym (display, keycode, 0, &mods_rtn, &sym_rtn) &&
250             (sym_rtn == keysym)) {
251                 retval = 0;
252         }
253         else if (XkbLookupKeySym (display, keycode, ShiftMask, &mods_rtn, &sym_rtn) &&
254                  (sym_rtn == keysym)) {
255                 retval = ShiftMask;
256         }
257         else if (XkbLookupKeySym (display, keycode, Mod2Mask, &mods_rtn, &sym_rtn) &&
258                  (sym_rtn == keysym)) {
259                 retval = Mod2Mask;
260         }
261         else if (XkbLookupKeySym (display, keycode, Mod3Mask, &mods_rtn, &sym_rtn) &&
262                  (sym_rtn == keysym)) {
263                 retval = Mod3Mask;
264         }
265         else if (XkbLookupKeySym (display, keycode, 
266                                   ShiftMask | Mod2Mask, &mods_rtn, &sym_rtn) &&
267                  (sym_rtn == keysym)) {
268                 retval = (Mod2Mask | ShiftMask);
269         }
270         else if (XkbLookupKeySym (display, keycode, 
271                                   ShiftMask | Mod3Mask, &mods_rtn, &sym_rtn) &&
272                  (sym_rtn == keysym)) {
273                 retval = (Mod3Mask | ShiftMask);
274         }
275         else if (XkbLookupKeySym (display, keycode, 
276                                   ShiftMask | Mod4Mask, &mods_rtn, &sym_rtn) &&
277                  (sym_rtn == keysym)) {
278                 retval = (Mod4Mask | ShiftMask);
279         }
280         else
281                 retval = 0xFFFF;
282         return retval;
283 }
284
285 static gboolean
286 spi_dec_replace_map_keysym (DEControllerPrivateData *priv, KeyCode keycode, KeySym keysym)
287 {
288 #ifdef HAVE_XKB
289   Display *dpy = spi_get_display ();
290   XkbDescPtr desc;
291   if (!(desc = XkbGetMap (dpy, XkbAllMapComponentsMask, XkbUseCoreKbd)))
292     {
293       fprintf (stderr, "ERROR getting map\n");
294     }
295   XFlush (dpy);
296   XSync (dpy, False);
297   if (desc && desc->map)
298     {
299       gint offset = desc->map->key_sym_map[keycode].offset;
300       desc->map->syms[offset] = keysym; 
301     }
302   else
303     {
304       fprintf (stderr, "Error changing key map: empty server structure\n");
305     }           
306   XkbSetMap (dpy, XkbAllMapComponentsMask, desc);
307   /**
308    *  FIXME: the use of XkbChangeMap, and the reuse of the priv->xkb_desc structure, 
309    * would be far preferable.
310    * HOWEVER it does not seem to work using XFree 4.3. 
311    **/
312   /*        XkbChangeMap (dpy, priv->xkb_desc, priv->changes); */
313   XFlush (dpy);
314   XSync (dpy, False);
315   XkbFreeKeyboard (desc, 0, TRUE);
316
317   return TRUE;
318 #else
319   return FALSE;
320 #endif
321 }
322
323 static gboolean
324 spi_dec_reset_reserved (gpointer data)
325 {
326   DEControllerPrivateData *priv = data;
327   spi_dec_replace_map_keysym (priv, priv->reserved_keycode, priv->reserved_keysym);
328   priv->reserved_reset_timeout = 0;
329   return FALSE;
330 }
331
332 static KeyCode
333 keycode_for_keysym (SpiDEController *controller, long keysym, unsigned int *modmask)
334 {
335         KeyCode keycode = 0;
336         keycode = XKeysymToKeycode (spi_get_display (), (KeySym) keysym);
337         if (!keycode) 
338         {
339                 DEControllerPrivateData *priv = (DEControllerPrivateData *)
340                         g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
341                 /* if there's no keycode available, fix it */
342                 if (spi_dec_replace_map_keysym (priv, priv->reserved_keycode, keysym))
343                 {
344                         keycode = priv->reserved_keycode;
345                         /* 
346                          * queue a timer to restore the old keycode.  Ugly, but required 
347                          * due to races / asynchronous X delivery.   
348                          * Long-term fix is to extend the X keymap here instead of replace entries.
349                          */
350                         priv->reserved_reset_timeout = g_timeout_add (500, spi_dec_reset_reserved, priv);
351                 }
352                 if (NULL != modmask)
353                 {
354                   *modmask = 0;
355                 }
356                 return keycode;
357         }
358         if (modmask)
359                 *modmask = keysym_mod_mask (keysym, keycode);
360         return keycode;
361 }
362
363 static DEControllerGrabMask *
364 spi_grab_mask_clone (DEControllerGrabMask *grab_mask)
365 {
366   DEControllerGrabMask *clone = g_new (DEControllerGrabMask, 1);
367
368   memcpy (clone, grab_mask, sizeof (DEControllerGrabMask));
369
370   clone->ref_count = 1;
371   clone->pending_add = TRUE;
372   clone->pending_remove = FALSE;
373
374   return clone;
375 }
376
377 static void
378 spi_grab_mask_free (DEControllerGrabMask *grab_mask)
379 {
380   g_free (grab_mask);
381 }
382
383 static gint
384 spi_grab_mask_compare_values (gconstpointer p1, gconstpointer p2)
385 {
386   DEControllerGrabMask *l1 = (DEControllerGrabMask *) p1;
387   DEControllerGrabMask *l2 = (DEControllerGrabMask *) p2;
388
389   if (p1 == p2)
390     {
391       return 0;
392     }
393   else
394     { 
395       return ((l1->mod_mask != l2->mod_mask) || (l1->key_val != l2->key_val));
396     }
397 }
398
399 static void
400 spi_dec_set_unlatch_pending (SpiDEController *controller, unsigned mask)
401 {
402   DEControllerPrivateData *priv = 
403     g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
404 #ifdef SPI_XKB_DEBUG
405   if (priv->xkb_latch_mask) fprintf (stderr, "unlatch pending! %x\n", 
406                                      priv->xkb_latch_mask);
407 #endif
408   priv->pending_xkb_mod_relatch_mask |= priv->xkb_latch_mask; 
409 }
410  
411 static void
412 spi_dec_clear_unlatch_pending (SpiDEController *controller)
413 {
414   DEControllerPrivateData *priv = 
415     g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
416   priv->xkb_latch_mask = 0;
417 }
418
419 static void emit(SpiDEController *controller, const char *interface, const char *name, const char *minor, int a1, int a2)
420 {
421   DBusMessage *signal = NULL;
422   DBusMessageIter iter, iter_struct, iter_variant;
423   int nil = 0;
424   const char *path = SPI_DBUS_PATH_ROOT;
425   const char *bus_name = dbus_bus_get_unique_name (controller->bus);
426
427   signal = dbus_message_new_signal (path, interface, name);
428
429   dbus_message_iter_init_append (signal, &iter);
430
431   dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &minor);
432   dbus_message_iter_append_basic (&iter, DBUS_TYPE_INT32, &a1);
433   dbus_message_iter_append_basic (&iter, DBUS_TYPE_INT32, &a2);
434   dbus_message_iter_open_container (&iter, DBUS_TYPE_VARIANT, "i", &iter_variant);
435       dbus_message_iter_append_basic (&iter_variant, DBUS_TYPE_INT32, &nil);
436   dbus_message_iter_close_container (&iter, &iter_variant);
437
438   dbus_message_iter_open_container (&iter, DBUS_TYPE_STRUCT, NULL,
439                                     &iter_struct);
440   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_STRING, &bus_name);
441   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_OBJECT_PATH, &path);
442   dbus_message_iter_close_container (&iter, &iter_struct);
443
444   dbus_connection_send (controller->bus, signal, NULL);
445   dbus_message_unref (signal);
446 }
447
448 static gboolean
449 spi_dec_button_update_and_emit (SpiDEController *controller,
450                                 guint mask_return)
451 {
452   Accessibility_DeviceEvent mouse_e;
453   gchar event_detail[3];
454   gboolean is_consumed = FALSE;
455
456   if ((mask_return & mouse_button_mask) !=
457       (mouse_mask_state & mouse_button_mask)) 
458     {
459       int button_number = 0;
460       gboolean is_down = False;
461       
462       if (!(mask_return & Button1Mask) &&
463           (mouse_mask_state & Button1Mask)) 
464         {
465           mouse_mask_state &= ~Button1Mask;
466           button_number = 1;
467         } 
468       else if ((mask_return & Button1Mask) &&
469                !(mouse_mask_state & Button1Mask)) 
470         {
471           mouse_mask_state |= Button1Mask;
472           button_number = 1;
473           is_down = True;
474         } 
475       else if (!(mask_return & Button2Mask) &&
476                (mouse_mask_state & Button2Mask)) 
477         {
478           mouse_mask_state &= ~Button2Mask;
479           button_number = 2;
480         } 
481       else if ((mask_return & Button2Mask) &&
482                !(mouse_mask_state & Button2Mask)) 
483         {
484           mouse_mask_state |= Button2Mask;
485           button_number = 2;
486           is_down = True;
487         } 
488       else if (!(mask_return & Button3Mask) &&
489                (mouse_mask_state & Button3Mask)) 
490         {
491           mouse_mask_state &= ~Button3Mask;
492           button_number = 3;
493         } 
494       else if ((mask_return & Button3Mask) &&
495                !(mouse_mask_state & Button3Mask)) 
496         {
497           mouse_mask_state |= Button3Mask;
498           button_number = 3;
499           is_down = True;
500         } 
501       else if (!(mask_return & Button4Mask) &&
502                (mouse_mask_state & Button4Mask)) 
503         {
504           mouse_mask_state &= ~Button4Mask;
505           button_number = 4;
506         } 
507       else if ((mask_return & Button4Mask) &&
508                !(mouse_mask_state & Button4Mask)) 
509         {
510           mouse_mask_state |= Button4Mask;
511           button_number = 4;
512           is_down = True;
513         } 
514       else if (!(mask_return & Button5Mask) &&
515                (mouse_mask_state & Button5Mask)) 
516         {
517           mouse_mask_state &= ~Button5Mask;
518           button_number = 5;
519         }
520       else if ((mask_return & Button5Mask) &&
521                !(mouse_mask_state & Button5Mask)) 
522         {
523           mouse_mask_state |= Button5Mask;
524           button_number = 5;
525           is_down = True;
526         }
527       if (button_number) {
528 #ifdef SPI_DEBUG                  
529         fprintf (stderr, "Button %d %s\n",
530                  button_number, (is_down) ? "Pressed" : "Released");
531 #endif
532         snprintf (event_detail, 3, "%d%c", button_number,
533                   (is_down) ? 'p' : 'r');
534         /* TODO: FIXME distinguish between physical and 
535          * logical buttons 
536          */
537         mouse_e.type      = (is_down) ? 
538           Accessibility_BUTTON_PRESSED_EVENT :
539           Accessibility_BUTTON_RELEASED_EVENT;
540         mouse_e.id        = button_number;
541         mouse_e.hw_code   = button_number;
542         mouse_e.modifiers = (dbus_uint16_t) mouse_mask_state; 
543         mouse_e.timestamp = 0;
544         mouse_e.event_string = "";
545         mouse_e.is_text   = FALSE;
546         is_consumed = 
547           spi_controller_notify_mouselisteners (controller, 
548                                                 &mouse_e);
549         if (!is_consumed)
550           {
551             dbus_uint32_t x = last_mouse_pos->x, y = last_mouse_pos->y;
552             emit(controller, SPI_DBUS_INTERFACE_EVENT_MOUSE, "Button", event_detail, x, y);
553           }
554         else
555           spi_dec_set_unlatch_pending (controller, mask_return);
556       }
557       return TRUE;
558     }
559   else
560     {
561       return FALSE;
562     }
563 }
564
565
566 static guint
567 spi_dec_mouse_check (SpiDEController *controller, 
568                      int *x, int *y, gboolean *moved)
569 {
570   int win_x_return,win_y_return;
571   unsigned int mask_return;
572   Window root_return, child_return;
573   Display *display = spi_get_display ();
574
575   if (display != NULL)
576     XQueryPointer(display, DefaultRootWindow (display),
577                   &root_return, &child_return,
578                   x, y,
579                   &win_x_return, &win_y_return, &mask_return);
580   /* 
581    * Since many clients grab the pointer, and X goes an automatic
582    * pointer grab on mouse-down, we often must detect mouse button events
583    * by polling rather than via a button grab. 
584    * The while loop (rather than if) is used since it's possible that 
585    * multiple buttons have changed state since we last checked.
586    */
587   if (mask_return != mouse_mask_state) 
588     {
589       while (spi_dec_button_update_and_emit (controller, mask_return));
590     }
591
592   if (*x != last_mouse_pos->x || *y != last_mouse_pos->y) 
593     {
594       // TODO: combine these two signals?
595       dbus_uint32_t ix = *x, iy = *y;
596       emit(controller, SPI_DBUS_INTERFACE_EVENT_MOUSE, "Abs", "", ix, iy);
597       ix -= last_mouse_pos->x;
598       iy -= last_mouse_pos->y;
599       emit(controller, SPI_DBUS_INTERFACE_EVENT_MOUSE, "Rel", "", ix, iy);
600       last_mouse_pos->x = *x;
601       last_mouse_pos->y = *y;
602       *moved = True;
603     }
604   else
605     {
606       *moved = False;
607     }
608
609   return mask_return;
610 }
611
612 static void
613 spi_dec_emit_modifier_event (SpiDEController *controller, guint prev_mask, 
614                              guint current_mask)
615 {
616   dbus_uint32_t d1, d2;
617
618 #ifdef SPI_XKB_DEBUG
619   fprintf (stderr, "MODIFIER CHANGE EVENT! %x to %x\n", 
620            prev_mask, current_mask);
621 #endif
622
623   /* set bits for the virtual modifiers like NUMLOCK */
624   if (prev_mask & _numlock_physical_mask) 
625     prev_mask |= SPI_KEYMASK_NUMLOCK;
626   if (current_mask & _numlock_physical_mask) 
627     current_mask |= SPI_KEYMASK_NUMLOCK;
628
629   d1 = prev_mask & key_modifier_mask;
630   d2 = current_mask & key_modifier_mask;
631       emit(controller, SPI_DBUS_INTERFACE_EVENT_KEYBOARD, "Modifiers", "", d1, d2);
632 }
633
634 static gboolean
635 spi_dec_poll_mouse_moved (gpointer data)
636 {
637   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(data);
638   int x, y;
639   gboolean moved;
640   guint mask_return;
641
642   mask_return = spi_dec_mouse_check (controller, &x, &y, &moved);
643
644   if ((mask_return & key_modifier_mask) !=
645       (mouse_mask_state & key_modifier_mask)) 
646     {
647       spi_dec_emit_modifier_event (controller, mouse_mask_state, mask_return);
648       mouse_mask_state = mask_return;
649     }
650
651   return moved;
652 }
653
654 static gboolean
655 spi_dec_poll_mouse_idle (gpointer data)
656 {
657   if (!have_mouse_event_listener && !have_mouse_listener)
658     return FALSE;
659   else if (!spi_dec_poll_mouse_moved (data))
660     return TRUE;
661   else
662     {
663       g_timeout_add (20, spi_dec_poll_mouse_moving, data);          
664       return FALSE;         
665     }
666 }
667
668 static gboolean
669 spi_dec_poll_mouse_moving (gpointer data)
670 {
671   if (!have_mouse_event_listener && !have_mouse_listener)
672     return FALSE;
673   else if (spi_dec_poll_mouse_moved (data))
674     return TRUE;
675   else
676     {
677       g_timeout_add (100, spi_dec_poll_mouse_idle, data);           
678       return FALSE;
679     }
680 }
681
682 #ifdef WE_NEED_UGRAB_MOUSE
683 static int
684 spi_dec_ungrab_mouse (gpointer data)
685 {
686         Display *display = spi_get_display ();
687         if (display)
688           {
689             XUngrabButton (spi_get_display (), AnyButton, AnyModifier,
690                            XDefaultRootWindow (spi_get_display ()));
691           }
692         return FALSE;
693 }
694 #endif
695
696 static void
697 spi_dec_init_mouse_listener (SpiDEController *dec)
698 {
699 #ifdef GRAB_BUTTON
700   Display *display = spi_get_display ();
701
702   if (display)
703     {
704       if (XGrabButton (display, AnyButton, AnyModifier,
705                        spi_get_root_window (),
706                        True, ButtonPressMask | ButtonReleaseMask,
707                        GrabModeSync, GrabModeAsync, None, None) != Success) {
708 #ifdef SPI_DEBUG
709         fprintf (stderr, "WARNING: could not grab mouse buttons!\n");
710 #endif
711         ;
712       }
713       XSync (display, False);
714 #ifdef SPI_DEBUG
715       fprintf (stderr, "mouse buttons grabbed\n");
716 #endif
717     }
718 #endif
719 }
720
721 /**
722  * Eventually we can use this to make the marshalling of mask types
723  * more sane, but for now we just use this to detect 
724  * the use of 'virtual' masks such as numlock and convert them to
725  * system-specific mask values (i.e. ModMask).
726  * 
727  **/
728 static Accessibility_ControllerEventMask
729 spi_dec_translate_mask (Accessibility_ControllerEventMask mask)
730 {
731   Accessibility_ControllerEventMask tmp_mask;
732   gboolean has_numlock;
733
734   has_numlock = (mask & SPI_KEYMASK_NUMLOCK);
735   tmp_mask = mask;
736   if (has_numlock)
737     {
738       tmp_mask = mask ^ SPI_KEYMASK_NUMLOCK;
739       tmp_mask |= _numlock_physical_mask;
740     }
741  
742   return tmp_mask;
743 }
744
745 static DEControllerKeyListener *
746 spi_dec_key_listener_new (const char *bus_name,
747                           const char *path,
748                           GSList *keys,
749                           const Accessibility_ControllerEventMask mask,
750                           const dbus_uint32_t types,
751                           const Accessibility_EventListenerMode  *mode)
752 {
753   DEControllerKeyListener *key_listener = g_new0 (DEControllerKeyListener, 1);
754   key_listener->listener.bus_name = g_strdup(bus_name);
755   key_listener->listener.path = g_strdup(path);
756   key_listener->listener.type = SPI_DEVICE_TYPE_KBD;
757   key_listener->keys = keys;
758   key_listener->mask = spi_dec_translate_mask (mask);
759   key_listener->listener.types = types;
760   if (mode)
761   {
762     key_listener->mode = (Accessibility_EventListenerMode *) g_malloc(sizeof(Accessibility_EventListenerMode));
763     memcpy(key_listener->mode, mode, sizeof(*mode));
764   }
765   else
766     key_listener->mode = NULL;
767
768 #ifdef SPI_DEBUG
769   g_print ("new listener, with mask %x, is_global %d, keys %p (%d)\n",
770            (unsigned int) key_listener->mask,
771            (int) (mode ? mode->global : 0),
772            (void *) key_listener->keys,
773            (int) (key_listener->keys ? g_slist_length(key_listener->keys) : 0));
774 #endif
775
776   return key_listener;  
777 }
778
779 static DEControllerListener *
780 spi_dec_listener_new (const char *bus_name,
781                       const char *path,
782                       dbus_uint32_t types)
783 {
784   DEControllerListener *listener = g_new0 (DEControllerListener, 1);
785   listener->bus_name = g_strdup(bus_name);
786   listener->path = g_strdup(path);
787   listener->type = SPI_DEVICE_TYPE_MOUSE;
788   listener->types = types;
789   return listener;      
790 }
791
792 static DEControllerListener *
793 spi_listener_clone (DEControllerListener *listener)
794 {
795   DEControllerListener *clone = g_new0 (DEControllerListener, 1);
796   clone->bus_name = g_strdup (listener->bus_name);
797   clone->path = g_strdup (listener->path);
798   clone->type = listener->type;
799   clone->types = listener->types;
800   return clone;
801 }
802
803 static GSList *keylist_clone (GSList *s)
804 {
805   GSList *d = NULL;
806   GSList *l;
807
808   for (l = s; l; l = g_slist_next(l))
809   {
810     Accessibility_KeyDefinition *kd = (Accessibility_KeyDefinition *)g_malloc(sizeof(Accessibility_KeyDefinition));
811     if (kd)
812     {
813       Accessibility_KeyDefinition *kds = (Accessibility_KeyDefinition *)l->data;
814       kd->keycode = kds->keycode;
815       kd->keysym = kds->keysym;
816       kd->keystring = g_strdup(kds->keystring);
817       d = g_slist_append(d, kd);
818     }
819   }
820   return d;
821 }
822
823 static DEControllerKeyListener *
824 spi_key_listener_clone (DEControllerKeyListener *key_listener)
825 {
826   DEControllerKeyListener *clone = g_new0 (DEControllerKeyListener, 1);
827   clone->listener.bus_name = g_strdup (key_listener->listener.bus_name);
828   clone->listener.path = g_strdup (key_listener->listener.path);
829   clone->listener.type = SPI_DEVICE_TYPE_KBD;
830   clone->keys = keylist_clone (key_listener->keys);
831   clone->mask = key_listener->mask;
832   clone->listener.types = key_listener->listener.types;
833   if (key_listener->mode)
834   {
835     clone->mode = (Accessibility_EventListenerMode *)g_malloc(sizeof(Accessibility_EventListenerMode));
836     if (clone->mode) memcpy(clone->mode, key_listener->mode, sizeof(Accessibility_EventListenerMode));
837   }
838   else
839     clone->mode = NULL;
840   return clone;
841 }
842
843 static void keylist_free(GSList *keys)
844 {
845   GSList *l;
846
847   for (l = keys; l; l = g_slist_next(l))
848   {
849     Accessibility_KeyDefinition *kd = (Accessibility_KeyDefinition *)l->data;
850     g_free(kd->keystring);
851     g_free(kd);
852   }
853   g_slist_free (keys);
854 }
855
856 static void
857 spi_key_listener_data_free (DEControllerKeyListener *key_listener)
858 {
859   keylist_free(key_listener->keys);
860   if (key_listener->mode) g_free(key_listener->mode);
861   g_free (key_listener->listener.bus_name);
862   g_free (key_listener->listener.path);
863   g_free (key_listener);
864 }
865
866 static void
867 spi_key_listener_clone_free (DEControllerKeyListener *clone)
868 {
869   spi_key_listener_data_free (clone);
870 }
871
872 static void
873 spi_listener_clone_free (DEControllerListener *clone)
874 {
875   g_free (clone->path);
876   g_free (clone->bus_name);
877   g_free (clone);
878 }
879
880 static void
881 spi_dec_listener_free (DEControllerListener    *listener)
882 {
883   if (listener->type == SPI_DEVICE_TYPE_KBD) 
884     spi_key_listener_data_free ((DEControllerKeyListener *) listener);
885   else
886   {
887     g_free (listener->bus_name);
888     g_free (listener->path);
889   }
890 }
891
892 static void
893 _register_keygrab (SpiDEController      *controller,
894                    DEControllerGrabMask *grab_mask)
895 {
896   GList *l;
897
898   l = g_list_find_custom (controller->keygrabs_list, grab_mask,
899                           spi_grab_mask_compare_values);
900   if (l)
901     {
902       DEControllerGrabMask *cur_mask = l->data;
903
904       cur_mask->ref_count++;
905       if (cur_mask->pending_remove)
906         {
907           cur_mask->pending_remove = FALSE;
908         }
909     }
910   else
911     {
912       controller->keygrabs_list =
913         g_list_prepend (controller->keygrabs_list,
914                         spi_grab_mask_clone (grab_mask));
915     }
916 }
917
918 static void
919 _deregister_keygrab (SpiDEController      *controller,
920                      DEControllerGrabMask *grab_mask)
921 {
922   GList *l;
923
924   l = g_list_find_custom (controller->keygrabs_list, grab_mask,
925                           spi_grab_mask_compare_values);
926
927   if (l)
928     {
929       DEControllerGrabMask *cur_mask = l->data;
930
931       cur_mask->ref_count--;
932       if (cur_mask->ref_count <= 0)
933         {
934           cur_mask->pending_remove = TRUE;
935         }
936     }
937 }
938
939 static void
940 handle_keygrab (SpiDEController         *controller,
941                 DEControllerKeyListener *key_listener,
942                 void                   (*process_cb) (SpiDEController *controller,
943                                                       DEControllerGrabMask *grab_mask))
944 {
945   DEControllerGrabMask grab_mask = { 0 };
946
947   grab_mask.mod_mask = key_listener->mask;
948   if (g_slist_length (key_listener->keys) == 0) /* special case means AnyKey/AllKeys */
949     {
950       grab_mask.key_val = AnyKey;
951 #ifdef SPI_DEBUG
952       fprintf (stderr, "AnyKey grab!");
953 #endif
954       process_cb (controller, &grab_mask);
955     }
956   else
957     {
958       GSList *l;
959
960       for (l = key_listener->keys; l; l = g_slist_next(l))
961         {
962           Accessibility_KeyDefinition *keydef = l->data;
963           long int key_val = keydef->keysym;
964           /* X Grabs require keycodes, not keysyms */
965           if (keydef->keystring && keydef->keystring[0])
966             {
967               key_val = XStringToKeysym(keydef->keystring);                 
968             }
969           if (key_val > 0)
970             {
971               key_val = XKeysymToKeycode (spi_get_display (), (KeySym) key_val);
972             }
973           else
974             {
975               key_val = keydef->keycode;
976             }
977           grab_mask.key_val = key_val;
978           process_cb (controller, &grab_mask);
979         }
980     }
981 }
982
983 static gboolean
984 spi_controller_register_global_keygrabs (SpiDEController         *controller,
985                                          DEControllerKeyListener *key_listener)
986 {
987   handle_keygrab (controller, key_listener, _register_keygrab);
988   if (controller->xevie_display == NULL)
989     return spi_controller_update_key_grabs (controller, NULL);
990   else
991     return TRUE;
992 }
993
994 static void
995 spi_controller_deregister_global_keygrabs (SpiDEController         *controller,
996                                            DEControllerKeyListener *key_listener)
997 {
998   handle_keygrab (controller, key_listener, _deregister_keygrab);
999   if (controller->xevie_display == NULL)
1000     spi_controller_update_key_grabs (controller, NULL);
1001 }
1002
1003 static void
1004 append_keystroke_listener (DBusMessageIter *iter, DEControllerKeyListener *listener)
1005 {
1006   dbus_uint32_t d_uint;
1007   DBusMessageIter iter_struct, iter_subarray, iter_substruct;
1008   GSList *kl;
1009
1010   if (!dbus_message_iter_open_container (iter, DBUS_TYPE_STRUCT, NULL,
1011                                          &iter_struct))
1012     return;
1013
1014   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_STRING,
1015                                   &listener->listener.bus_name);
1016   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_OBJECT_PATH,
1017                                   &listener->listener.path);
1018   d_uint = listener->listener.type;
1019   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_UINT32, &d_uint);
1020   d_uint = listener->listener.types;
1021   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_UINT32, &d_uint);
1022   if (!dbus_message_iter_open_container (&iter_struct, DBUS_TYPE_ARRAY,
1023                                          "(iisi)", &iter_subarray))
1024   {
1025     dbus_message_iter_close_container (iter, &iter_struct);
1026     return;
1027   }
1028   for (kl = listener->keys; kl; kl = kl->next)
1029   {
1030     Accessibility_KeyDefinition *kd = kl->data;
1031     if (!dbus_message_iter_open_container (&iter_subarray, DBUS_TYPE_STRUCT,
1032                                          NULL, &iter_substruct))
1033       break;
1034     dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_INT32, &kd->keycode);
1035     dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_INT32, &kd->keysym);
1036     dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_STRING, &kd->keystring);
1037     dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_INT32, &kd->unused);
1038     dbus_message_iter_close_container (&iter_subarray, &iter_substruct);
1039   }
1040   dbus_message_iter_close_container (&iter_struct, &iter_subarray);
1041   d_uint = listener->mask;
1042   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_UINT32, &d_uint);
1043   if (dbus_message_iter_open_container (&iter_struct, DBUS_TYPE_STRUCT,
1044                                          NULL, &iter_substruct))
1045   {
1046     if (listener->mode)
1047     {
1048       dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_BOOLEAN,
1049                                       &listener->mode->synchronous);
1050       dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_BOOLEAN,
1051                                       &listener->mode->preemptive);
1052       dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_BOOLEAN,
1053                                       &listener->mode->global);
1054     }
1055     else
1056     {
1057       dbus_bool_t dummy_val = FALSE;
1058       dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_BOOLEAN,
1059                                       &dummy_val);
1060       dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_BOOLEAN,
1061                                       &dummy_val);
1062       dbus_message_iter_append_basic (&iter_substruct, DBUS_TYPE_BOOLEAN,
1063                                       &dummy_val);
1064     }
1065     dbus_message_iter_close_container (&iter_struct, &iter_substruct);
1066   }
1067   dbus_message_iter_close_container (iter, &iter_struct);
1068 }
1069
1070 static void
1071 notify_keystroke_listener (SpiDEController *controller,
1072                            DEControllerKeyListener *listener,
1073                            gboolean enable)
1074 {
1075   const char *path = SPI_DBUS_PATH_DEC;
1076   const char *interface = SPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER;
1077   const char *name = (enable
1078                       ? "KeystrokeListenerRegistered"
1079                       : "KeystrokeListenerDeregistered");
1080   DBusMessage *signal;
1081   DBusMessageIter iter;
1082
1083   signal = dbus_message_new_signal (path, interface, name);
1084   if (!signal)
1085     return;
1086   dbus_message_iter_init_append (signal, &iter);
1087   append_keystroke_listener (&iter, listener);
1088   dbus_connection_send (controller->bus, signal, NULL);
1089   dbus_message_unref (signal);
1090 }
1091
1092 static void
1093 append_mouse_listener (DBusMessageIter *iter, DEControllerListener *listener)
1094 {
1095   DBusMessageIter iter_struct;
1096   dbus_uint32_t d_uint;
1097
1098   if (!dbus_message_iter_open_container (iter, DBUS_TYPE_STRUCT, NULL,
1099                                          &iter_struct))
1100     return;
1101   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_STRING,
1102                                   &listener->bus_name);
1103   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_OBJECT_PATH,
1104                                   &listener->path);
1105   d_uint = listener->types;
1106   dbus_message_iter_append_basic (&iter_struct, DBUS_TYPE_UINT32, &d_uint);
1107   dbus_message_iter_close_container (iter, &iter_struct);
1108 }
1109
1110 static void
1111 notify_mouse_listener (SpiDEController *controller,
1112                        DEControllerListener *listener,
1113                        gboolean enable)
1114 {
1115   const char *path = SPI_DBUS_PATH_DEC;
1116   const char *interface = SPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER;
1117   const char *name = (enable
1118                       ? "DeviceListenerRegistered"
1119                       : "DeviceListenerDeregistered");
1120   DBusMessage *signal;
1121   DBusMessageIter iter;
1122
1123   signal = dbus_message_new_signal (path, interface, name);
1124   if (!signal)
1125     return;
1126   dbus_message_iter_init_append (signal, &iter);
1127   append_mouse_listener (&iter, listener);
1128   dbus_connection_send (controller->bus, signal, NULL);
1129   dbus_message_unref (signal);
1130 }
1131
1132 static gboolean
1133 spi_controller_register_device_listener (SpiDEController      *controller,
1134                                          DEControllerListener *listener)
1135 {
1136   DEControllerKeyListener *key_listener;
1137   gboolean retval;
1138   
1139   switch (listener->type) {
1140   case SPI_DEVICE_TYPE_KBD:
1141       key_listener = (DEControllerKeyListener *) listener;
1142
1143       controller->key_listeners = g_list_prepend (controller->key_listeners,
1144                                                   key_listener);
1145       spi_dbus_add_disconnect_match (controller->bus, key_listener->listener.bus_name);
1146       if (key_listener->mode->global)
1147         {
1148           retval = spi_controller_register_global_keygrabs (controller, key_listener);
1149         }
1150       else
1151           retval = TRUE;
1152       if (retval)
1153         notify_keystroke_listener (controller, key_listener, TRUE);
1154       break;
1155   case SPI_DEVICE_TYPE_MOUSE:
1156       controller->mouse_listeners = g_list_prepend (controller->mouse_listeners, listener);
1157       if (!have_mouse_listener)
1158         {
1159           have_mouse_listener = TRUE;
1160           if (!have_mouse_event_listener)
1161             g_timeout_add (100, spi_dec_poll_mouse_idle, controller);
1162         }
1163       spi_dbus_add_disconnect_match (controller->bus, listener->bus_name);
1164       notify_mouse_listener (controller, listener, TRUE);
1165       break;
1166   default:
1167       break;
1168   }
1169   return FALSE;
1170 }
1171
1172 static void
1173 set_reply (DBusPendingCall *pending, void *user_data)
1174 {
1175     void **replyptr = (void **)user_data;
1176
1177     *replyptr = dbus_pending_call_steal_reply (pending);
1178 }
1179
1180 static GSList *hung_processes = NULL;
1181
1182 static void
1183 reset_hung_process (DBusPendingCall *pending, void *data)
1184 {
1185   DBusMessage *message = data;
1186   const char *dest = dbus_message_get_destination (message);
1187   GSList *l;
1188
1189   /* At this point we don't care about the result */
1190   dbus_pending_call_unref (pending);
1191
1192   for (l = hung_processes; l; l = l->next)
1193   {
1194     if (!strcmp (l->data, dest))
1195     {
1196       g_free (l->data);
1197       hung_processes = g_slist_remove (hung_processes, l->data);
1198       break;
1199     }
1200   }
1201 }
1202
1203 static gint
1204 time_elapsed (struct timeval *origin)
1205 {
1206   struct timeval tv;
1207
1208   gettimeofday (&tv, NULL);
1209   return (tv.tv_sec - origin->tv_sec) * 1000 + (tv.tv_usec - origin->tv_usec) / 1000;
1210 }
1211
1212 static void
1213 reset_hung_process_from_ping (DBusPendingCall *pending, void *data)
1214 {
1215   GSList *l;
1216
1217   for (l = hung_processes; l; l = l->next)
1218   {
1219     if (!strcmp (l->data, data))
1220     {
1221       g_free (l->data);
1222       hung_processes = g_slist_remove (hung_processes, l->data);
1223       break;
1224     }
1225   }
1226   g_free (data);
1227   dbus_pending_call_unref (pending);
1228 }
1229
1230 static DBusMessage *
1231 send_and_allow_reentry (DBusConnection *bus, DBusMessage *message, int timeout, DBusError *error)
1232 {
1233     DBusPendingCall *pending;
1234     DBusMessage *reply = NULL;
1235   struct timeval tv;
1236
1237     if (!dbus_connection_send_with_reply (bus, message, &pending, -1))
1238     {
1239         return NULL;
1240     }
1241     dbus_pending_call_set_notify (pending, set_reply, (void *)&reply, NULL);
1242     gettimeofday (&tv, NULL);
1243     while (!reply)
1244     {
1245       if (!dbus_connection_read_write_dispatch (bus, timeout) ||
1246           time_elapsed (&tv) > timeout)
1247       {
1248         const char *dest = dbus_message_get_destination (message);
1249         GSList *l;
1250         gchar *bus_name_dup;
1251         dbus_message_ref (message);
1252         dbus_pending_call_set_notify (pending, reset_hung_process, message,
1253                                       (DBusFreeFunction) dbus_message_unref);
1254         message = dbus_message_new_method_call (dest, "/",
1255                                                 "org.freedesktop.DBus.Peer",
1256                                                 "Ping");
1257         if (!message)
1258           return NULL;
1259         dbus_connection_send_with_reply (bus, message, &pending, -1);
1260         dbus_message_unref (message);
1261         if (!pending)
1262           return NULL;
1263         bus_name_dup = g_strdup (dest);
1264         dbus_pending_call_set_notify (pending, reset_hung_process_from_ping,
1265                                       bus_name_dup, NULL);
1266         for (l = hung_processes; l; l = l->next)
1267           if (!strcmp (l->data, dest))
1268             return NULL;
1269         hung_processes = g_slist_prepend (hung_processes, g_strdup (dest));
1270         return NULL;
1271       }
1272     }
1273     dbus_pending_call_unref (pending);
1274     return reply;
1275 }
1276 static gboolean
1277 Accessibility_DeviceEventListener_NotifyEvent(SpiDEController *controller,
1278                                               SpiRegistry *registry,
1279                                               DEControllerListener *listener,
1280                                               const Accessibility_DeviceEvent *key_event)
1281 {
1282   DBusMessage *message = dbus_message_new_method_call(listener->bus_name,
1283                                                       listener->path,
1284                                                       SPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER,
1285                                                       "NotifyEvent");
1286   dbus_bool_t consumed = FALSE;
1287   GSList *l;
1288   gboolean hung = FALSE;
1289
1290   for (l = hung_processes; l; l = l->next)
1291   {
1292     if (!strcmp (l->data, listener->bus_name))
1293     {
1294       dbus_message_set_no_reply (message, TRUE);
1295       hung = TRUE;
1296       break;
1297     }
1298   }
1299
1300   if (spi_dbus_marshal_deviceEvent(message, key_event))
1301   {
1302     DBusMessage *reply;
1303
1304     if (hung)
1305     {
1306       dbus_connection_send (controller->bus, message, NULL);
1307       dbus_message_unref (message);
1308       return FALSE;
1309     }
1310
1311     reply = send_and_allow_reentry (controller->bus, message, 3000, NULL);
1312     if (reply)
1313     {
1314       dbus_message_get_args(reply, NULL, DBUS_TYPE_BOOLEAN, &consumed, DBUS_TYPE_INVALID);
1315       dbus_message_unref(reply);
1316     }
1317   }
1318   dbus_message_unref(message);
1319   return consumed;
1320 }
1321
1322 static gboolean
1323 spi_controller_notify_mouselisteners (SpiDEController                 *controller,
1324                                       const Accessibility_DeviceEvent *event)
1325 {
1326   GList   *l;
1327   GSList  *notify = NULL, *l2;
1328   GList  **listeners = &controller->mouse_listeners;
1329   gboolean is_consumed;
1330 #ifdef SPI_KEYEVENT_DEBUG
1331   gboolean found = FALSE;
1332 #endif
1333   if (!listeners)
1334     {
1335       return FALSE;
1336     }
1337
1338   for (l = *listeners; l; l = l->next)
1339     {
1340        DEControllerListener *listener = l->data;
1341
1342        if (spi_eventtype_seq_contains_event (listener->types, event))
1343          {
1344            /* we clone (don't dup) the listener, to avoid refcount inc. */
1345            notify = g_slist_prepend (notify,
1346                                      spi_listener_clone (listener));
1347 #ifdef SPI_KEYEVENT_DEBUG
1348            found = TRUE;
1349 #endif
1350          }
1351     }
1352
1353 #ifdef SPI_KEYEVENT_DEBUG
1354   if (!found)
1355     {
1356       g_print ("no match for event\n");
1357     }
1358 #endif
1359
1360   is_consumed = FALSE;
1361   for (l2 = notify; l2 && !is_consumed; l2 = l2->next)
1362     {
1363       DEControllerListener *listener = l2->data;
1364
1365       is_consumed = Accessibility_DeviceEventListener_NotifyEvent (controller, controller->registry, listener, event);
1366
1367       spi_listener_clone_free ((DEControllerListener *) l2->data);
1368     }
1369
1370   for (; l2; l2 = l2->next)
1371     {
1372       DEControllerListener *listener = l2->data;
1373       spi_listener_clone_free (listener);
1374       /* clone doesn't have its own ref, so don't use spi_device_listener_free */
1375     }
1376
1377   g_slist_free (notify);
1378
1379 #ifdef SPI_DEBUG
1380   if (is_consumed) g_message ("consumed\n");
1381 #endif
1382   return is_consumed;
1383 }
1384
1385 static void
1386 spi_device_event_controller_forward_mouse_event (SpiDEController *controller,
1387                                                  XEvent *xevent)
1388 {
1389   Accessibility_DeviceEvent mouse_e;
1390   gchar event_detail[3];
1391   gboolean is_consumed = FALSE;
1392   gboolean xkb_mod_unlatch_occurred;
1393   XButtonEvent *xbutton_event = (XButtonEvent *) xevent;
1394   dbus_uint32_t ix, iy;
1395
1396   int button = xbutton_event->button;
1397   
1398   unsigned int mouse_button_state = xbutton_event->state;
1399
1400   switch (button)
1401     {
1402     case 1:
1403             mouse_button_state |= Button1Mask;
1404             break;
1405     case 2:
1406             mouse_button_state |= Button2Mask;
1407             break;
1408     case 3:
1409             mouse_button_state |= Button3Mask;
1410             break;
1411     case 4:
1412             mouse_button_state |= Button4Mask;
1413             break;
1414     case 5:
1415             mouse_button_state |= Button5Mask;
1416             break;
1417     }
1418
1419   last_mouse_pos->x = ((XButtonEvent *) xevent)->x_root;
1420   last_mouse_pos->y = ((XButtonEvent *) xevent)->y_root;
1421
1422 #ifdef SPI_DEBUG  
1423   fprintf (stderr, "mouse button %d %s (%x)\n",
1424            xbutton_event->button, 
1425            (xevent->type == ButtonPress) ? "Press" : "Release",
1426            mouse_button_state);
1427 #endif
1428   snprintf (event_detail, 3, "%d%c", button,
1429             (xevent->type == ButtonPress) ? 'p' : 'r');
1430
1431   /* TODO: FIXME distinguish between physical and logical buttons */
1432   mouse_e.type      = (xevent->type == ButtonPress) ? 
1433                       Accessibility_BUTTON_PRESSED_EVENT :
1434                       Accessibility_BUTTON_RELEASED_EVENT;
1435   mouse_e.id        = button;
1436   mouse_e.hw_code   = button;
1437   mouse_e.modifiers = (dbus_uint16_t) xbutton_event->state;
1438   mouse_e.timestamp = (dbus_uint32_t) xbutton_event->time;
1439   mouse_e.event_string = "";
1440   mouse_e.is_text   = FALSE;
1441   if ((mouse_button_state & mouse_button_mask) != 
1442        (mouse_mask_state & mouse_button_mask))
1443     { 
1444       if ((mouse_mask_state & key_modifier_mask) !=
1445           (mouse_button_state & key_modifier_mask))
1446         spi_dec_emit_modifier_event (controller, 
1447                                      mouse_mask_state, mouse_button_state);
1448       mouse_mask_state = mouse_button_state;
1449       is_consumed = 
1450         spi_controller_notify_mouselisteners (controller, &mouse_e);
1451       ix = last_mouse_pos->x;
1452       iy = last_mouse_pos->y;
1453       emit(controller, SPI_DBUS_INTERFACE_EVENT_MOUSE, "Button", event_detail, ix, iy);
1454     }
1455
1456   xkb_mod_unlatch_occurred = (xevent->type == ButtonPress ||
1457                               xevent->type == ButtonRelease);
1458   
1459   /* if client wants to consume this event, and XKB latch state was
1460    *   unset by this button event, we reset it
1461    */
1462   if (is_consumed && xkb_mod_unlatch_occurred)
1463     spi_dec_set_unlatch_pending (controller, mouse_mask_state);
1464   
1465   XAllowEvents (spi_get_display (),
1466                 (is_consumed) ? SyncPointer : ReplayPointer,
1467                 CurrentTime);
1468 }
1469
1470 static void
1471 global_filter_fn (XEvent *xevent, void *data)
1472 {
1473   SpiDEController *controller;
1474   DEControllerPrivateData *priv;
1475   Display *display = spi_get_display ();
1476   controller = SPI_DEVICE_EVENT_CONTROLLER (data);
1477   priv = (DEControllerPrivateData *)
1478           g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);  
1479
1480   if (xevent->type == MappingNotify)
1481     xmkeymap = NULL;
1482
1483   if (xevent->type == KeyPress || xevent->type == KeyRelease)
1484     {
1485       if (controller->xevie_display == NULL)
1486         {
1487           gboolean is_consumed;
1488
1489           is_consumed =
1490             spi_device_event_controller_forward_key_event (controller, xevent);
1491
1492           if (is_consumed)
1493             {
1494               int n_events;
1495               int i;
1496               XEvent next_event;
1497               n_events = XPending (display);
1498
1499 #ifdef SPI_KEYEVENT_DEBUG
1500               g_print ("Number of events pending: %d\n", n_events);
1501 #endif
1502               for (i = 0; i < n_events; i++)
1503                 {
1504                   XNextEvent (display, &next_event);
1505                   if (next_event.type != KeyPress &&
1506                       next_event.type != KeyRelease)
1507                         g_warning ("Unexpected event type %d in queue", next_event.type);
1508                  }
1509
1510               XAllowEvents (display, AsyncKeyboard, CurrentTime);
1511               if (n_events)
1512                 XUngrabKeyboard (display, CurrentTime);
1513             }
1514           else
1515             {
1516               if (xevent->type == KeyPress)
1517                 wait_for_release_event (xevent, controller);
1518               XAllowEvents (display, ReplayKeyboard, CurrentTime);
1519             }
1520         }
1521
1522       return;
1523     }
1524   if (xevent->type == ButtonPress || xevent->type == ButtonRelease)
1525     {
1526       spi_device_event_controller_forward_mouse_event (controller, xevent);
1527     }
1528   if (xevent->type == priv->xkb_base_event_code)
1529     {
1530       XkbAnyEvent * xkb_ev = (XkbAnyEvent *) xevent;
1531       /* ugly but probably necessary...*/
1532       XSynchronize (display, TRUE);
1533
1534       if (xkb_ev->xkb_type == XkbStateNotify)
1535         {
1536           XkbStateNotifyEvent *xkb_snev =
1537                   (XkbStateNotifyEvent *) xkb_ev;
1538           /* check the mouse, to catch mouse events grabbed by
1539            * another client; in case we should revert this XKB delatch 
1540            */
1541           if (!priv->pending_xkb_mod_relatch_mask)
1542             {
1543               int x, y;
1544               gboolean moved;
1545               spi_dec_mouse_check (controller, &x, &y, &moved);
1546             }
1547           /* we check again, since the previous call may have 
1548              changed this flag */
1549           if (priv->pending_xkb_mod_relatch_mask)
1550             {
1551               unsigned int feedback_mask;
1552 #ifdef SPI_XKB_DEBUG
1553               fprintf (stderr, "relatching %x\n",
1554                        priv->pending_xkb_mod_relatch_mask);
1555 #endif
1556               /* temporarily turn off the latch bell, if it's on */
1557               XkbGetControls (display,
1558                               XkbAccessXFeedbackMask,
1559                               priv->xkb_desc);
1560               feedback_mask = priv->xkb_desc->ctrls->ax_options;
1561               if (feedback_mask & XkbAX_StickyKeysFBMask)
1562               {
1563                 XkbControlsChangesRec changes = {XkbAccessXFeedbackMask,
1564                                                  0, False};      
1565                 priv->xkb_desc->ctrls->ax_options
1566                               &= ~(XkbAX_StickyKeysFBMask);
1567                 XkbChangeControls (display, priv->xkb_desc, &changes);
1568               }
1569               /* TODO: account for lock as well as latch */
1570               XkbLatchModifiers (display,
1571                                  XkbUseCoreKbd,
1572                                  priv->pending_xkb_mod_relatch_mask,
1573                                  priv->pending_xkb_mod_relatch_mask);
1574               if (feedback_mask & XkbAX_StickyKeysFBMask)
1575               { 
1576                 XkbControlsChangesRec changes = {XkbAccessXFeedbackMask,
1577                                                  0, False};      
1578                 priv->xkb_desc->ctrls->ax_options = feedback_mask;
1579                 XkbChangeControls (display, priv->xkb_desc, &changes);
1580               }
1581 #ifdef SPI_XKB_DEBUG
1582               fprintf (stderr, "relatched %x\n",
1583                        priv->pending_xkb_mod_relatch_mask);
1584 #endif
1585               priv->pending_xkb_mod_relatch_mask = 0;
1586             }
1587           else
1588             {
1589               priv->xkb_latch_mask = xkb_snev->latched_mods;
1590             }
1591         }
1592       XSynchronize (display, FALSE);
1593     }
1594   
1595   return;
1596 }
1597
1598 static int
1599 _spi_controller_device_error_handler (Display *display, XErrorEvent *error)
1600 {
1601   if (error->error_code == BadAccess) 
1602     {  
1603       g_message ("Could not complete key grab: grab already in use.\n");
1604       spi_error_code = BadAccess;
1605       return 0;
1606     }
1607   else 
1608     {
1609       return (*x_default_error_handler) (display, error);
1610     }
1611 }
1612
1613 static void
1614 spi_controller_register_with_devices (SpiDEController *controller)
1615 {
1616   DEControllerPrivateData *priv;
1617   int event_base, error_base, major_version, minor_version;
1618
1619   priv = (DEControllerPrivateData *) g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
1620   if (XTestQueryExtension (spi_get_display(), &event_base, &error_base, &major_version, &minor_version))
1621     {
1622       XTestGrabControl (spi_get_display (), True);
1623     }
1624
1625   /* calls to device-specific implementations and routines go here */
1626   /* register with: keyboard hardware code handler */
1627   /* register with: (translated) keystroke handler */
1628
1629   priv->have_xkb = XkbQueryExtension (spi_get_display (),
1630                                       &priv->xkb_major_extension_opcode,
1631                                       &priv->xkb_base_event_code,
1632                                       &priv->xkb_base_error_code, NULL, NULL);
1633   if (priv->have_xkb)
1634     {
1635       gint i;
1636       guint64 reserved = 0;
1637       priv->xkb_desc = XkbGetMap (spi_get_display (), XkbKeySymsMask, XkbUseCoreKbd);
1638       XkbSelectEvents (spi_get_display (),
1639                        XkbUseCoreKbd,
1640                        XkbStateNotifyMask, XkbStateNotifyMask);     
1641       _numlock_physical_mask = XkbKeysymToModifiers (spi_get_display (), 
1642                                                      XK_Num_Lock);
1643       for (i = priv->xkb_desc->max_key_code; i >= priv->xkb_desc->min_key_code; --i)
1644       {
1645           if (priv->xkb_desc->map->key_sym_map[i].kt_index[0] == XkbOneLevelIndex)
1646           { 
1647               if (XKeycodeToKeysym (spi_get_display (), i, 0) != 0)
1648               {
1649                   /* don't use this one if there's a grab client! */
1650
1651                   /* Runtime errors are generated from these functions,
1652                    * that are then quashed. Equivalent to:
1653                    * try
1654                    *   {Blah}
1655                    * except
1656                    *   {;}
1657                    */
1658
1659                   spi_x_error_trap ();
1660                   XGrabKey (spi_get_display (), i, 0, 
1661                             spi_get_root_window (),
1662                             TRUE,
1663                             GrabModeSync, GrabModeSync);
1664                   XSync (spi_get_display (), TRUE);
1665                   XUngrabKey (spi_get_display (), i, 0, 
1666                               spi_get_root_window ());
1667                   if (!spi_x_error_release ())
1668                   {
1669                       reserved = i;
1670                       break;
1671                   }
1672               }
1673           }
1674       }
1675       if (reserved) 
1676       {
1677           priv->reserved_keycode = reserved;
1678           priv->reserved_keysym = XKeycodeToKeysym (spi_get_display (), reserved, 0);
1679       }
1680       else
1681       { 
1682           priv->reserved_keycode = XKeysymToKeycode (spi_get_display (), XK_numbersign);
1683           priv->reserved_keysym = XK_numbersign;
1684       }
1685 #ifdef SPI_RESERVED_DEBUG
1686       unsigned sym = 0;
1687       sym = XKeycodeToKeysym (spi_get_display (), reserved, 0);
1688       fprintf (stderr, "%x\n", sym);
1689       fprintf (stderr, "setting the reserved keycode to %d (%s)\n", 
1690                reserved, 
1691                XKeysymToString (XKeycodeToKeysym (spi_get_display (),
1692                                                             reserved, 0)));
1693 #endif
1694     }   
1695
1696   spi_set_filter (global_filter_fn, controller);
1697   spi_set_events (KeyPressMask | KeyReleaseMask);
1698
1699   x_default_error_handler = XSetErrorHandler (_spi_controller_device_error_handler);
1700 }
1701
1702 static gboolean
1703 spi_key_set_contains_key (GSList                          *key_set,
1704                           const Accessibility_DeviceEvent *key_event)
1705 {
1706   gint i;
1707   gint len;
1708   GSList *l;
1709
1710   if (!key_set)
1711     {
1712 #ifdef SPI_DEBUG
1713       g_print ("null key set!\n");
1714 #endif
1715       return TRUE;
1716     }
1717
1718   len = g_slist_length (key_set);
1719   
1720   if (len == 0) /* special case, means "all keys/any key" */
1721     {
1722 #ifdef SPI_DEBUG
1723       g_print ("anykey\n");         
1724 #endif
1725       return TRUE;
1726     }
1727
1728   for (l = key_set,i = 0; l; l = g_slist_next(l),i++)
1729     {
1730       Accessibility_KeyDefinition *kd = l->data;
1731 #ifdef SPI_KEYEVENT_DEBUG           
1732       g_print ("key_set[%d] event = %d, code = %d; key_event %d, code %d, string %s\n",
1733                 i,
1734                 (int) kd->keysym,
1735                 (int) kd->keycode,
1736                 (int) key_event->id,
1737                 (int) key_event->hw_code,
1738                 key_event->event_string); 
1739 #endif
1740       if (kd->keysym == (dbus_uint32_t) key_event->id)
1741         {
1742           return TRUE;
1743         }
1744       if (kd->keycode == (dbus_uint32_t) key_event->hw_code)
1745         {
1746           return TRUE;
1747         }
1748       if (key_event->event_string && key_event->event_string[0] &&
1749           !strcmp (kd->keystring, key_event->event_string))
1750         {
1751           return TRUE;
1752         }
1753     }
1754
1755   return FALSE;
1756 }
1757
1758 static gboolean
1759 spi_eventtype_seq_contains_event (dbus_uint32_t types,
1760                                   const Accessibility_DeviceEvent *event)
1761 {
1762   if (types == 0) /* special case, means "all events/any event" */
1763     {
1764       return TRUE;
1765     }
1766
1767   return (types & (1 << event->type));
1768 }
1769
1770 static gboolean
1771 spi_key_event_matches_listener (const Accessibility_DeviceEvent *key_event,
1772                                 DEControllerKeyListener         *listener,
1773                                 dbus_bool_t                    is_system_global)
1774 {
1775   if (((key_event->modifiers & 0xFF) == (dbus_uint16_t) (listener->mask & 0xFF)) &&
1776        spi_key_set_contains_key (listener->keys, key_event) &&
1777        spi_eventtype_seq_contains_event (listener->listener.types, key_event) && 
1778       (is_system_global == listener->mode->global))
1779     {
1780       return TRUE;
1781     }
1782   else
1783     {
1784       return FALSE;
1785     }
1786 }
1787
1788 static gboolean
1789 spi_controller_notify_keylisteners (SpiDEController                 *controller,
1790                                     Accessibility_DeviceEvent       *key_event,
1791                                     dbus_bool_t                    is_system_global)
1792 {
1793   GList   *l;
1794   GSList  *notify = NULL, *l2;
1795   GList  **key_listeners = &controller->key_listeners;
1796   gboolean is_consumed;
1797
1798   if (!key_listeners)
1799     {
1800       return FALSE;
1801     }
1802
1803   /* set the NUMLOCK event mask bit if appropriate: see bug #143702 */
1804   if (key_event->modifiers & _numlock_physical_mask)
1805       key_event->modifiers |= SPI_KEYMASK_NUMLOCK;
1806
1807   for (l = *key_listeners; l; l = l->next)
1808     {
1809        DEControllerKeyListener *key_listener = l->data;
1810
1811        if (spi_key_event_matches_listener (key_event, key_listener, is_system_global))
1812          {
1813            /* we clone (don't dup) the listener, to avoid refcount inc. */
1814            notify = g_slist_prepend (notify,
1815                                      spi_key_listener_clone (key_listener));
1816          }
1817     }
1818
1819 #ifdef SPI_KEYEVENT_DEBUG
1820   if (!notify)
1821     {
1822       g_print ("no match for event\n");
1823     }
1824 #endif
1825
1826   is_consumed = FALSE;
1827   for (l2 = notify; l2 && !is_consumed; l2 = l2->next)
1828     {
1829       DEControllerKeyListener *key_listener = l2->data;     
1830
1831       is_consumed = Accessibility_DeviceEventListener_NotifyEvent (controller, controller->registry, &key_listener->listener, key_event) &&
1832                     key_listener->mode->preemptive;
1833
1834       spi_key_listener_clone_free (key_listener);
1835     }
1836
1837   for (; l2; l2 = l2->next)
1838     {
1839       DEControllerKeyListener *key_listener = l2->data;     
1840       spi_key_listener_clone_free (key_listener);
1841       /* clone doesn't have its own ref, so don't use spi_dec_listener_free */
1842     }
1843
1844   g_slist_free (notify);
1845
1846 #ifdef SPI_DEBUG
1847   if (is_consumed) g_message ("consumed\n");
1848 #endif
1849   return is_consumed;
1850 }
1851
1852 static gboolean
1853 spi_clear_error_state (void)
1854 {
1855         gboolean retval = spi_error_code != 0;
1856         spi_error_code = 0;
1857         return retval;
1858 }
1859
1860 static Accessibility_DeviceEvent
1861 spi_keystroke_from_x_key_event (XKeyEvent *x_key_event)
1862 {
1863   Accessibility_DeviceEvent key_event;
1864   KeySym keysym;
1865   const int cbuf_bytes = 20;
1866   char cbuf [21];
1867   int nbytes;
1868
1869   nbytes = XLookupString (x_key_event, cbuf, cbuf_bytes, &keysym, NULL);  
1870   key_event.id = (dbus_int32_t)(keysym);
1871   key_event.hw_code = (dbus_int16_t) x_key_event->keycode;
1872   if (((XEvent *) x_key_event)->type == KeyPress)
1873     {
1874       key_event.type = Accessibility_KEY_PRESSED_EVENT;
1875     }
1876   else
1877     {
1878       key_event.type = Accessibility_KEY_RELEASED_EVENT;
1879     } 
1880   key_event.modifiers = (dbus_uint16_t)(x_key_event->state);
1881   key_event.is_text = FALSE;
1882   switch (keysym)
1883     {
1884       case ' ':
1885         key_event.event_string = g_strdup ("space");
1886         break;
1887       case XK_Tab:
1888         key_event.event_string = g_strdup ("Tab");
1889         break;
1890       case XK_BackSpace:
1891         key_event.event_string = g_strdup ("Backspace");
1892         break;
1893       case XK_Return:
1894         key_event.event_string = g_strdup ("Return");
1895         break;
1896       case XK_Home:
1897         key_event.event_string = g_strdup ("Home");
1898         break;
1899       case XK_Page_Down:
1900         key_event.event_string = g_strdup ("Page_Down");
1901         break;
1902       case XK_Page_Up:
1903         key_event.event_string = g_strdup ("Page_Up");
1904         break;
1905       case XK_F1:
1906         key_event.event_string = g_strdup ("F1");
1907         break;
1908       case XK_F2:
1909         key_event.event_string = g_strdup ("F2");
1910         break;
1911       case XK_F3:
1912         key_event.event_string = g_strdup ("F3");
1913         break;
1914       case XK_F4:
1915         key_event.event_string = g_strdup ("F4");
1916         break;
1917       case XK_F5:
1918         key_event.event_string = g_strdup ("F5");
1919         break;
1920       case XK_F6:
1921         key_event.event_string = g_strdup ("F6");
1922         break;
1923       case XK_F7:
1924         key_event.event_string = g_strdup ("F7");
1925         break;
1926       case XK_F8:
1927         key_event.event_string = g_strdup ("F8");
1928         break;
1929       case XK_F9:
1930         key_event.event_string = g_strdup ("F9");
1931         break;
1932       case XK_F10:
1933         key_event.event_string = g_strdup ("F10");
1934         break;
1935       case XK_F11:
1936         key_event.event_string = g_strdup ("F11");
1937         break;
1938       case XK_F12:
1939         key_event.event_string = g_strdup ("F12");
1940         break;
1941       case XK_End:
1942         key_event.event_string = g_strdup ("End");
1943         break;
1944       case XK_Escape:
1945         key_event.event_string = g_strdup ("Escape");
1946         break;
1947       case XK_Up:
1948         key_event.event_string = g_strdup ("Up");
1949         break;
1950       case XK_Down:
1951         key_event.event_string = g_strdup ("Down");
1952         break;
1953       case XK_Left:
1954         key_event.event_string = g_strdup ("Left");
1955         break;
1956       case XK_Right:
1957         key_event.event_string = g_strdup ("Right");
1958         break;
1959       default:
1960         if (nbytes > 0)
1961           {
1962             gunichar c;
1963             cbuf[nbytes] = '\0'; /* OK since length is cbuf_bytes+1 */
1964             key_event.event_string = g_strdup (cbuf);
1965             c = keysym2ucs (keysym);
1966             if (c > 0 && !g_unichar_iscntrl (c))
1967               {
1968                 key_event.is_text = TRUE; 
1969                 /* incorrect for some composed chars? */
1970               }
1971           }
1972         else
1973           {
1974             key_event.event_string = g_strdup ("");
1975           }
1976     }
1977
1978   key_event.timestamp = (dbus_uint32_t) x_key_event->time;
1979 #ifdef SPI_KEYEVENT_DEBUG
1980   {
1981     char *pressed_str  = "pressed";
1982     char *released_str = "released";
1983     char *state_ptr;
1984
1985     if (key_event.type == Accessibility_KEY_PRESSED_EVENT)
1986       state_ptr = pressed_str;
1987     else
1988       state_ptr = released_str;
1989  
1990     fprintf (stderr,
1991              "Key %lu %s (%c), modifiers %d; string=%s [%x] %s\n",
1992              (unsigned long) keysym,
1993              state_ptr,
1994              keysym ? (int) keysym : '*',
1995              (int) x_key_event->state,
1996              key_event.event_string,
1997              key_event.event_string[0],
1998              (key_event.is_text == TRUE) ? "(text)" : "(not text)");
1999   }
2000 #endif
2001 #ifdef SPI_DEBUG
2002   fprintf (stderr, "%s%c\n",
2003      (x_key_event->state & Mod1Mask)?"Alt-":"",
2004      ((x_key_event->state & ShiftMask)^(x_key_event->state & LockMask))?
2005      g_ascii_toupper (keysym) : g_ascii_tolower (keysym));
2006   fprintf (stderr, "serial: %x Time: %x\n", x_key_event->serial, x_key_event->time);
2007 #endif /* SPI_DEBUG */
2008   return key_event;     
2009 }
2010
2011 static gboolean
2012 spi_controller_update_key_grabs (SpiDEController           *controller,
2013                                  Accessibility_DeviceEvent *recv)
2014 {
2015   GList *l, *next;
2016   gboolean   update_failed = FALSE;
2017   KeyCode keycode = 0;
2018   
2019   g_return_val_if_fail (controller != NULL, FALSE);
2020
2021   /*
2022    * masks known to work with default RH 7.1+:
2023    * 0 (no mods), LockMask, Mod1Mask, Mod2Mask, ShiftMask,
2024    * ShiftMask|LockMask, Mod1Mask|LockMask, Mod2Mask|LockMask,
2025    * ShiftMask|Mod1Mask, ShiftMask|Mod2Mask, Mod1Mask|Mod2Mask,
2026    * ShiftMask|LockMask|Mod1Mask, ShiftMask|LockMask|Mod2Mask,
2027    *
2028    * ControlMask grabs are broken, must be in use already
2029    */
2030   if (recv)
2031     keycode = keycode_for_keysym (controller, recv->id, NULL);
2032   for (l = controller->keygrabs_list; l; l = next)
2033     {
2034       gboolean do_remove;
2035       gboolean re_issue_grab;
2036       DEControllerGrabMask *grab_mask = l->data;
2037
2038       next = l->next;
2039
2040       re_issue_grab = recv &&
2041               (recv->modifiers & grab_mask->mod_mask) &&
2042               (grab_mask->key_val == keycode);
2043
2044 #ifdef SPI_DEBUG
2045       fprintf (stderr, "mask=%lx %lx (%c%c) %s\n",
2046                (long int) grab_mask->key_val,
2047                (long int) grab_mask->mod_mask,
2048                grab_mask->pending_add ? '+' : '.',
2049                grab_mask->pending_remove ? '-' : '.',
2050                re_issue_grab ? "re-issue": "");
2051 #endif
2052
2053       do_remove = FALSE;
2054
2055       if (grab_mask->pending_add && grab_mask->pending_remove)
2056         {
2057           do_remove = TRUE;
2058         }
2059       else if (grab_mask->pending_remove)
2060         {
2061 #ifdef SPI_DEBUG
2062       fprintf (stderr, "ungrabbing, mask=%x\n", grab_mask->mod_mask);
2063 #endif
2064           XUngrabKey (spi_get_display (),
2065                       grab_mask->key_val,
2066                       grab_mask->mod_mask,
2067                       spi_get_root_window ());
2068
2069           do_remove = TRUE;
2070         }
2071       else if (grab_mask->pending_add || re_issue_grab)
2072         {
2073
2074 #ifdef SPI_DEBUG
2075           fprintf (stderr, "grab %d with mask %x\n", grab_mask->key_val, grab_mask->mod_mask);
2076 #endif
2077           XGrabKey (spi_get_display (),
2078                     grab_mask->key_val,
2079                     grab_mask->mod_mask,
2080                     spi_get_root_window (),
2081                     True,
2082                     GrabModeSync,
2083                     GrabModeSync);
2084           XSync (spi_get_display (), False);
2085           update_failed = spi_clear_error_state ();
2086           if (update_failed) {
2087                   while (grab_mask->ref_count > 0) --grab_mask->ref_count;
2088                   do_remove = TRUE;
2089           }
2090         }
2091
2092       grab_mask->pending_add = FALSE;
2093       grab_mask->pending_remove = FALSE;
2094
2095       if (do_remove)
2096         {
2097           g_assert (grab_mask->ref_count <= 0);
2098
2099           controller->keygrabs_list = g_list_delete_link (
2100             controller->keygrabs_list, l);
2101
2102           spi_grab_mask_free (grab_mask);
2103         }
2104
2105     } 
2106
2107   return ! update_failed;
2108 }
2109
2110 /*
2111  * Implemented GObject::finalize
2112  */
2113 static void
2114 spi_device_event_controller_object_finalize (GObject *object)
2115 {
2116   SpiDEController *controller;
2117   DEControllerPrivateData *private;
2118   controller = SPI_DEVICE_EVENT_CONTROLLER (object);
2119   GObjectClass *parent_class = G_OBJECT_CLASS(spi_device_event_controller_parent_class);
2120 #ifdef SPI_DEBUG
2121   fprintf(stderr, "spi_device_event_controller_object_finalize called\n");
2122 #endif
2123   /* disconnect any special listeners, get rid of outstanding keygrabs */
2124   XUngrabKey (spi_get_display (), AnyKey, AnyModifier, DefaultRootWindow (spi_get_display ()));
2125
2126 #ifdef HAVE_XEVIE
2127   if (controller->xevie_display != NULL)
2128     {
2129       XevieEnd(controller->xevie_display);
2130 #ifdef SPI_KEYEVENT_DEBUG
2131       printf("XevieEnd(dpy) finished \n");
2132 #endif
2133     }
2134 #endif
2135
2136   private = g_object_get_data (G_OBJECT (controller), "spi-dec-private");
2137   if (private->xkb_desc)
2138           XkbFreeKeyboard (private->xkb_desc, 0, True);
2139   g_free (private);
2140   parent_class->finalize (object);
2141 }
2142
2143 /*
2144  * DBus Accessibility::DEController::RegisterKeystrokeListener
2145  *     method implementation
2146  */
2147 static DBusMessage *
2148 impl_register_keystroke_listener (DBusConnection *bus,
2149                                   DBusMessage *message,
2150                                   void *user_data)
2151 {
2152   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2153   DEControllerKeyListener *dec_listener;
2154   DBusMessageIter iter, iter_array;
2155   const char *path;
2156   GSList *keys = NULL;
2157   dbus_int32_t mask, type;
2158   Accessibility_EventListenerMode *mode;
2159  dbus_bool_t ret;
2160   DBusMessage *reply = NULL;
2161   char *keystring;
2162
2163   if (strcmp (dbus_message_get_signature (message), "oa(iisi)uu(bbb)") != 0)
2164     return invalid_arguments_error (message);
2165
2166   dbus_message_iter_init(message, &iter);
2167   dbus_message_iter_get_basic(&iter, &path);
2168   dbus_message_iter_next(&iter);
2169   dbus_message_iter_recurse(&iter, &iter_array);
2170   while (dbus_message_iter_get_arg_type(&iter_array) != DBUS_TYPE_INVALID)
2171   {
2172     Accessibility_KeyDefinition *kd = (Accessibility_KeyDefinition *)g_malloc(sizeof(Accessibility_KeyDefinition));
2173     if (!spi_dbus_message_iter_get_struct(&iter_array, DBUS_TYPE_INT32, &kd->keycode, DBUS_TYPE_INT32, &kd->keysym, DBUS_TYPE_STRING, &keystring, DBUS_TYPE_INVALID))
2174     {
2175       break;
2176     }
2177     kd->keystring = g_strdup (keystring);
2178     keys = g_slist_append(keys, kd);
2179   }
2180   dbus_message_iter_next(&iter);
2181   dbus_message_iter_get_basic(&iter, &mask);
2182   dbus_message_iter_next(&iter);
2183   dbus_message_iter_get_basic(&iter, &type);
2184   dbus_message_iter_next(&iter);
2185   mode = (Accessibility_EventListenerMode *)g_malloc(sizeof(Accessibility_EventListenerMode));
2186   if (mode)
2187   {
2188     spi_dbus_message_iter_get_struct(&iter, DBUS_TYPE_BOOLEAN, &mode->synchronous, DBUS_TYPE_BOOLEAN, &mode->preemptive, DBUS_TYPE_BOOLEAN, &mode->global, DBUS_TYPE_INVALID);
2189   }
2190 #ifdef SPI_DEBUG
2191   fprintf (stderr, "registering keystroke listener %s:%s with maskVal %lu\n",
2192            dbus_message_get_sender(message), path, (unsigned long) mask);
2193 #endif
2194   dec_listener = spi_dec_key_listener_new (dbus_message_get_sender(message), path, keys, mask, type, mode);
2195   g_free (mode);
2196   ret = spi_controller_register_device_listener (
2197           controller, (DEControllerListener *) dec_listener);
2198   reply = dbus_message_new_method_return (message);
2199   if (reply)
2200   {
2201     dbus_message_append_args (reply, DBUS_TYPE_BOOLEAN, &ret, DBUS_TYPE_INVALID);
2202   }
2203   return reply;
2204 }
2205
2206 /*
2207  * DBus Accessibility::DEController::RegisterDeviceEventListener
2208  *     method implementation
2209  */
2210 static DBusMessage *
2211 impl_register_device_event_listener (DBusConnection *bus,
2212                                   DBusMessage *message,
2213                                   void *user_data)
2214 {
2215   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2216   DEControllerListener *dec_listener;
2217   const char *path;
2218   dbus_int32_t event_types;
2219   dbus_bool_t ret;
2220   DBusMessage *reply = NULL;
2221
2222   if (!dbus_message_get_args(message, NULL, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_UINT32, &event_types, DBUS_TYPE_INVALID))
2223   {
2224     return invalid_arguments_error (message);
2225   }
2226   dec_listener = spi_dec_listener_new (dbus_message_get_sender(message), path, event_types);
2227   ret =  spi_controller_register_device_listener (
2228           controller, (DEControllerListener *) dec_listener);
2229   reply = dbus_message_new_method_return (message);
2230   if (reply)
2231   {
2232     dbus_message_append_args (reply, DBUS_TYPE_BOOLEAN, &ret, DBUS_TYPE_INVALID);
2233   }
2234   return reply;
2235 }
2236
2237 typedef struct {
2238         DBusConnection *bus;
2239         DEControllerListener    *listener;
2240 } RemoveListenerClosure;
2241
2242 static SpiReEntrantContinue
2243 remove_listener_cb (GList * const *list,
2244                     gpointer       user_data)
2245 {
2246   DEControllerListener  *listener = (*list)->data;
2247   RemoveListenerClosure *ctx = user_data;
2248
2249   if (!strcmp(ctx->listener->bus_name, listener->bus_name) &&
2250       !strcmp(ctx->listener->path, listener->path))
2251     {
2252       spi_re_entrant_list_delete_link (list);
2253       spi_dbus_remove_disconnect_match (ctx->bus, listener->bus_name);
2254       spi_dec_listener_free (listener);
2255     }
2256
2257   return SPI_RE_ENTRANT_CONTINUE;
2258 }
2259
2260 static SpiReEntrantContinue
2261 copy_key_listener_cb (GList * const *list,
2262                       gpointer       user_data)
2263 {
2264   DEControllerKeyListener  *key_listener = (*list)->data;
2265   RemoveListenerClosure    *ctx = user_data;
2266
2267   if (!strcmp(ctx->listener->bus_name, key_listener->listener.bus_name) &&
2268       !strcmp(ctx->listener->path, key_listener->listener.path))
2269     {
2270       /* TODO: FIXME aggregate keys in case the listener is registered twice */
2271       DEControllerKeyListener *ctx_key_listener = 
2272         (DEControllerKeyListener *) ctx->listener; 
2273       keylist_free (ctx_key_listener->keys);        
2274       ctx_key_listener->keys = keylist_clone(key_listener->keys);
2275     }
2276
2277   return SPI_RE_ENTRANT_CONTINUE;
2278 }
2279
2280 static void
2281 spi_controller_deregister_device_listener (SpiDEController            *controller,
2282                                            DEControllerListener *listener)
2283 {
2284   RemoveListenerClosure  ctx;
2285
2286   ctx.bus = controller->bus;
2287   ctx.listener = listener;
2288
2289   notify_mouse_listener (controller, listener, FALSE);
2290
2291   spi_re_entrant_list_foreach (&controller->mouse_listeners,
2292                                remove_listener_cb, &ctx);
2293   if (!controller->mouse_listeners)
2294     have_mouse_listener = FALSE;
2295 }
2296
2297 static void
2298 spi_deregister_controller_key_listener (SpiDEController            *controller,
2299                                         DEControllerKeyListener    *key_listener)
2300 {
2301   RemoveListenerClosure  ctx;
2302
2303   ctx.bus = controller->bus;
2304   ctx.listener = (DEControllerListener *) spi_key_listener_clone (key_listener);
2305
2306   notify_keystroke_listener (controller, key_listener, FALSE);
2307
2308   /* special case, copy keyset from existing controller list entry */
2309   if (g_slist_length(key_listener->keys) == 0)
2310     {
2311       spi_re_entrant_list_foreach (&controller->key_listeners,
2312                                   copy_key_listener_cb, &ctx);
2313     }
2314
2315   spi_controller_deregister_global_keygrabs (controller, key_listener);
2316
2317   spi_re_entrant_list_foreach (&controller->key_listeners,
2318                                 remove_listener_cb, &ctx);
2319
2320   spi_key_listener_clone_free ((DEControllerKeyListener *) ctx.listener);
2321 }
2322
2323 void
2324 spi_remove_device_listeners (SpiDEController *controller, const char *bus_name)
2325 {
2326   GList *l, *tmp;
2327
2328   for (l = controller->mouse_listeners; l; l = tmp)
2329   {
2330     DEControllerListener *listener = l->data;
2331     tmp = l->next;
2332     if (!strcmp (listener->bus_name, bus_name))
2333     {
2334       spi_controller_deregister_device_listener (controller, listener);
2335       tmp = controller->mouse_listeners;
2336     }
2337   }
2338   for (l = controller->key_listeners; l; l = tmp)
2339   {
2340     DEControllerKeyListener *key_listener = l->data;
2341     tmp = l->next;
2342     if (!strcmp (key_listener->listener.bus_name, bus_name))
2343     {
2344       /* TODO: untangle the below line(s) */
2345       spi_deregister_controller_key_listener (controller, key_listener);
2346       tmp = controller->key_listeners;
2347     }
2348   }
2349 }
2350
2351 /*
2352  * DBus Accessibility::DEController::DeregisterKeystrokeListener
2353  *     method implementation
2354  */
2355 static DBusMessage *
2356 impl_deregister_keystroke_listener (DBusConnection *bus,
2357                                   DBusMessage *message,
2358                                   void *user_data)
2359 {
2360   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2361   DEControllerKeyListener *key_listener;
2362   DBusMessageIter iter, iter_array;
2363   const char *path;
2364   GSList *keys = NULL;
2365   dbus_int32_t mask, type;
2366   DBusMessage *reply = NULL;
2367
2368   dbus_message_iter_init(message, &iter);
2369   if (strcmp (dbus_message_get_signature (message), "oa(iisi)uu") != 0)
2370   {
2371     g_warning ("Received DeregisterKeystrokeListener with strange signature '%s'", dbus_message_get_signature (message));
2372     return invalid_arguments_error (message);
2373   }
2374
2375   dbus_message_iter_get_basic(&iter, &path);
2376   dbus_message_iter_next(&iter);
2377   dbus_message_iter_recurse(&iter, &iter_array);
2378   while (dbus_message_iter_get_arg_type(&iter_array) != DBUS_TYPE_INVALID)
2379   {
2380     Accessibility_KeyDefinition *kd = (Accessibility_KeyDefinition *)g_malloc(sizeof(Accessibility_KeyDefinition));
2381   char *keystring;
2382
2383     if (!spi_dbus_message_iter_get_struct(&iter_array, DBUS_TYPE_INT32, &kd->keycode, DBUS_TYPE_INT32, &kd->keysym, DBUS_TYPE_STRING, &keystring, DBUS_TYPE_INVALID))
2384     {
2385       break;
2386     }
2387     kd->keystring = g_strdup (keystring);
2388     keys = g_slist_append(keys, kd);
2389   }
2390   dbus_message_iter_next(&iter);
2391   dbus_message_iter_get_basic(&iter, &mask);
2392   dbus_message_iter_next(&iter);
2393   dbus_message_iter_get_basic(&iter, &type);
2394   dbus_message_iter_next(&iter);
2395   key_listener = spi_dec_key_listener_new (dbus_message_get_sender(message), path, keys, mask, type, NULL);
2396 #ifdef SPI_DEREGISTER_DEBUG
2397   fprintf (stderr, "deregistering keystroke listener %p with maskVal %lu\n",
2398            (void *) l, (unsigned long) mask->value);
2399 #endif
2400
2401   spi_deregister_controller_key_listener (controller, key_listener);
2402
2403   spi_dec_listener_free ((DEControllerListener *) key_listener);
2404   reply = dbus_message_new_method_return (message);
2405   return reply;
2406 }
2407
2408 /*
2409  * DBus Accessibility::DEController::DeregisterDeviceEventListener
2410  *     method implementation
2411  */
2412 static DBusMessage *
2413 impl_deregister_device_event_listener (DBusConnection *bus,
2414                                   DBusMessage *message,
2415                                   void *user_data)
2416 {
2417   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2418   DEControllerListener *listener;
2419   const char *path;
2420   dbus_int32_t event_types;
2421   DBusMessage *reply = NULL;
2422
2423   if (!dbus_message_get_args(message, NULL, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_UINT32, &event_types, DBUS_TYPE_INVALID))
2424   {
2425     return invalid_arguments_error (message);
2426   }
2427   listener = spi_dec_listener_new (dbus_message_get_sender(message), path, event_types);
2428   spi_controller_deregister_device_listener (
2429           controller, listener);
2430   reply = dbus_message_new_method_return (message);
2431   return reply;
2432 }
2433
2434 static DBusMessage *
2435 impl_get_keystroke_listeners (DBusConnection *bus,
2436                                   DBusMessage *message,
2437                                   void *user_data)
2438 {
2439   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2440   DBusMessageIter iter, iter_array;
2441   DBusMessage *reply = dbus_message_new_method_return (message);
2442   GList *l;
2443
2444   if (!reply)
2445     return NULL;
2446
2447   dbus_message_iter_init_append (reply, &iter);
2448   dbus_message_iter_open_container (&iter, DBUS_TYPE_ARRAY,
2449                                     "(souua(iisi)u(bbb))", &iter_array);
2450   for (l = controller->key_listeners; l; l = l->next)
2451   {
2452     append_keystroke_listener (&iter_array, l->data);
2453   }
2454   dbus_message_iter_close_container (&iter, &iter_array);
2455   return reply;
2456 }
2457
2458 static DBusMessage *
2459 impl_get_device_event_listeners (DBusConnection *bus,
2460                                   DBusMessage *message,
2461                                   void *user_data)
2462 {
2463   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2464   DBusMessageIter iter, iter_array;
2465   GList *l;
2466   DBusMessage *reply = dbus_message_new_method_return (message);
2467
2468   if (!reply)
2469     return NULL;
2470
2471   dbus_message_iter_init_append (reply, &iter);
2472   dbus_message_iter_open_container (&iter, DBUS_TYPE_ARRAY,
2473                                     "(sou)", &iter_array);
2474   for (l = controller->key_listeners; l; l = l->next)
2475   {
2476     append_mouse_listener (&iter_array, l->data);
2477   }
2478   dbus_message_iter_close_container (&iter, &iter_array);
2479   return reply;
2480 }
2481
2482 static unsigned int dec_xkb_get_slowkeys_delay (SpiDEController *controller)
2483 {
2484   unsigned int retval = 0;
2485   DEControllerPrivateData *priv = (DEControllerPrivateData *)
2486           g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
2487 #ifdef HAVE_XKB
2488 #ifdef XKB_HAS_GET_SLOW_KEYS_DELAY      
2489   retval = XkbGetSlowKeysDelay (spi_get_display (),
2490                                 XkbUseCoreKbd, &bounce_delay);
2491 #else
2492   if (!(priv->xkb_desc == (XkbDescPtr) BadAlloc || priv->xkb_desc == NULL))
2493     {
2494       Status s = XkbGetControls (spi_get_display (),
2495                                  XkbAllControlsMask, priv->xkb_desc);
2496       if (s == Success)
2497         {
2498          if (priv->xkb_desc->ctrls->enabled_ctrls & XkbSlowKeysMask)
2499                  retval = priv->xkb_desc->ctrls->slow_keys_delay;
2500         }
2501     }
2502 #endif
2503 #endif
2504 #ifdef SPI_XKB_DEBUG
2505         fprintf (stderr, "SlowKeys delay: %d\n", (int) retval);
2506 #endif
2507         return retval;
2508 }
2509
2510 static unsigned int dec_xkb_get_bouncekeys_delay (SpiDEController *controller)
2511 {
2512   unsigned int retval = 0;
2513   DEControllerPrivateData *priv = (DEControllerPrivateData *)
2514           g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
2515 #ifdef HAVE_XKB
2516 #ifdef XKB_HAS_GET_BOUNCE_KEYS_DELAY    
2517   retval = XkbGetBounceKeysDelay (spi_get_display (),
2518                                   XkbUseCoreKbd, &bounce_delay);
2519 #else
2520   if (!(priv->xkb_desc == (XkbDescPtr) BadAlloc || priv->xkb_desc == NULL))
2521     {
2522       Status s = XkbGetControls (spi_get_display (),
2523                                  XkbAllControlsMask, priv->xkb_desc);
2524       if (s == Success)
2525         {
2526           if (priv->xkb_desc->ctrls->enabled_ctrls & XkbBounceKeysMask)
2527                   retval = priv->xkb_desc->ctrls->debounce_delay;
2528         }
2529     }
2530 #endif
2531 #endif
2532 #ifdef SPI_XKB_DEBUG
2533   fprintf (stderr, "BounceKeys delay: %d\n", (int) retval);
2534 #endif
2535   return retval;
2536 }
2537
2538 static gboolean
2539 dec_synth_keycode_press (SpiDEController *controller,
2540                          unsigned int keycode)
2541 {
2542         unsigned int time = CurrentTime;
2543         unsigned int bounce_delay;
2544         unsigned int elapsed_msec;
2545         struct timeval tv;
2546         DEControllerPrivateData *priv =
2547                 (DEControllerPrivateData *) g_object_get_qdata (G_OBJECT (controller),
2548                                                                 spi_dec_private_quark);
2549         if (keycode == priv->last_release_keycode)
2550         {
2551                 bounce_delay = dec_xkb_get_bouncekeys_delay (controller); 
2552                 if (bounce_delay)
2553                 {
2554                         gettimeofday (&tv, NULL);
2555                         elapsed_msec =
2556                                 (tv.tv_sec - priv->last_release_time.tv_sec) * 1000
2557                                 + (tv.tv_usec - priv->last_release_time.tv_usec) / 1000;
2558 #ifdef SPI_XKB_DEBUG                    
2559                         fprintf (stderr, "%d ms elapsed (%ld usec)\n", elapsed_msec,
2560                                  (long) (tv.tv_usec - priv->last_release_time.tv_usec));
2561 #endif
2562 #ifdef THIS_IS_BROKEN
2563                         if (elapsed_msec < bounce_delay)
2564                                 time = bounce_delay - elapsed_msec + 1;
2565 #else
2566                         time = bounce_delay + 10;
2567                         /* fudge for broken XTest */
2568 #endif
2569 #ifdef SPI_XKB_DEBUG                    
2570                         fprintf (stderr, "waiting %d ms\n", time);
2571 #endif
2572                 }
2573         }
2574         XTestFakeKeyEvent (spi_get_display (), keycode, True, time);
2575         priv->last_press_keycode = keycode;
2576         XFlush (spi_get_display ());
2577         XSync (spi_get_display (), False);
2578         gettimeofday (&priv->last_press_time, NULL);
2579         return TRUE;
2580 }
2581
2582 static gboolean
2583 dec_synth_keycode_release (SpiDEController *controller,
2584                            unsigned int keycode)
2585 {
2586         unsigned int time = CurrentTime;
2587         unsigned int slow_delay;
2588         unsigned int elapsed_msec;
2589         struct timeval tv;
2590         DEControllerPrivateData *priv =
2591                 (DEControllerPrivateData *) g_object_get_qdata (G_OBJECT (controller),
2592                                                                 spi_dec_private_quark);
2593         if (keycode == priv->last_press_keycode)
2594         {
2595                 slow_delay = dec_xkb_get_slowkeys_delay (controller);
2596                 if (slow_delay)
2597                 {
2598                         gettimeofday (&tv, NULL);
2599                         elapsed_msec =
2600                                 (tv.tv_sec - priv->last_press_time.tv_sec) * 1000
2601                                 + (tv.tv_usec - priv->last_press_time.tv_usec) / 1000;
2602 #ifdef SPI_XKB_DEBUG                    
2603                         fprintf (stderr, "%d ms elapsed (%ld usec)\n", elapsed_msec,
2604                                  (long) (tv.tv_usec - priv->last_press_time.tv_usec));
2605 #endif
2606 #ifdef THIS_IS_BROKEN_DUNNO_WHY
2607                         if (elapsed_msec < slow_delay)
2608                                 time = slow_delay - elapsed_msec + 1;
2609 #else
2610                         time = slow_delay + 10;
2611                         /* our XTest seems broken, we have to add slop as above */
2612 #endif
2613 #ifdef SPI_XKB_DEBUG                    
2614                         fprintf (stderr, "waiting %d ms\n", time);
2615 #endif
2616                 }
2617         }
2618         XTestFakeKeyEvent (spi_get_display (), keycode, False, time);
2619         priv->last_release_keycode = keycode;
2620         XSync (spi_get_display (), False);
2621         gettimeofday (&priv->last_release_time, NULL);
2622         return TRUE;
2623 }
2624
2625 static unsigned
2626 dec_get_modifier_state (SpiDEController *controller)
2627 {
2628         return mouse_mask_state;
2629 }
2630
2631 static gboolean
2632 dec_lock_modifiers (SpiDEController *controller, unsigned modifiers)
2633 {
2634     DEControllerPrivateData *priv = (DEControllerPrivateData *) 
2635     g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);   
2636     
2637     if (priv->have_xkb) {
2638         return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
2639                                   modifiers, modifiers);
2640     } else {
2641         int mod_index;
2642         for (mod_index=0;mod_index<8;mod_index++)
2643             if (modifiers & (1<<mod_index))
2644                 dec_synth_keycode_press(controller, xmkeymap->modifiermap[mod_index]);
2645         return TRUE;
2646     }
2647 }
2648
2649 static gboolean
2650 dec_unlock_modifiers (SpiDEController *controller, unsigned modifiers)
2651 {
2652     DEControllerPrivateData *priv = (DEControllerPrivateData *) 
2653     g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);   
2654     
2655     if (priv->have_xkb) {
2656         return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
2657                                   modifiers, 0);
2658     } else {
2659         int mod_index;
2660         for (mod_index=0;mod_index<8;mod_index++)
2661             if (modifiers & (1<<mod_index))
2662                 dec_synth_keycode_release(controller, xmkeymap->modifiermap[mod_index]);
2663         return TRUE;
2664     }
2665 }
2666
2667 static KeySym
2668 dec_keysym_for_unichar (SpiDEController *controller, gunichar unichar)
2669 {
2670         return ucs2keysym ((long) unichar);
2671 }
2672
2673 static gboolean
2674 dec_synth_keysym (SpiDEController *controller, KeySym keysym)
2675 {
2676         KeyCode key_synth_code;
2677         unsigned int modifiers, synth_mods, lock_mods;
2678
2679         key_synth_code = keycode_for_keysym (controller, keysym, &synth_mods);
2680
2681         if ((key_synth_code == 0) || (synth_mods == 0xFF)) return FALSE;
2682
2683         /* TODO: set the modifiers accordingly! */
2684         modifiers = dec_get_modifier_state (controller);
2685         /* side-effect; we may unset mousebutton modifiers here! */
2686
2687         lock_mods = 0;
2688         if (synth_mods != modifiers) {
2689                 lock_mods = synth_mods & ~modifiers;
2690                 dec_lock_modifiers (controller, lock_mods);
2691         }
2692         dec_synth_keycode_press (controller, key_synth_code);
2693         dec_synth_keycode_release (controller, key_synth_code);
2694
2695         if (synth_mods != modifiers) 
2696                 dec_unlock_modifiers (controller, lock_mods);
2697         return TRUE;
2698 }
2699
2700
2701 static gboolean
2702 dec_synth_keystring (SpiDEController *controller, const char *keystring)
2703 {
2704         /* probably we need to create and inject an XIM handler eventually. */
2705         /* for now, try to match the string to existing 
2706          * keycode+modifier states. 
2707          */
2708         KeySym *keysyms;
2709         gint maxlen = 0;
2710         gunichar unichar = 0;
2711         gint i = 0;
2712         gboolean retval = TRUE;
2713         const gchar *c;
2714
2715         maxlen = strlen (keystring) + 1;
2716         keysyms = g_new0 (KeySym, maxlen);
2717         if (!(keystring && *keystring && g_utf8_validate (keystring, -1, &c))) { 
2718                 retval = FALSE;
2719         } 
2720         else {
2721 #ifdef SPI_DEBUG
2722                 fprintf (stderr, "[keystring synthesis attempted on %s]\n", keystring);
2723 #endif
2724                 while (keystring && (unichar = g_utf8_get_char (keystring))) {
2725                         KeySym keysym;
2726                         char bytes[6];
2727                         gint mbytes;
2728                         
2729                         mbytes = g_unichar_to_utf8 (unichar, bytes);
2730                         bytes[mbytes] = '\0';
2731 #ifdef SPI_DEBUG
2732                         fprintf (stderr, "[unichar %s]", bytes);
2733 #endif
2734                         keysym = dec_keysym_for_unichar (controller, unichar);
2735                         if (keysym == NoSymbol) {
2736 #ifdef SPI_DEBUG
2737                                 fprintf (stderr, "no keysym for %s", bytes);
2738 #endif
2739                                 retval = FALSE;
2740                                 break;
2741                         }
2742                         keysyms[i++] = keysym;
2743                         keystring = g_utf8_next_char (keystring); 
2744                 }
2745                 keysyms[i++] = 0;
2746                 XSynchronize (spi_get_display (), TRUE);
2747                 for (i = 0; keysyms[i]; ++i) {
2748                         if (!dec_synth_keysym (controller, keysyms[i])) {
2749 #ifdef SPI_DEBUG
2750                                 fprintf (stderr, "could not synthesize %c\n",
2751                                          (int) keysyms[i]);
2752 #endif
2753                                 retval = FALSE;
2754                                 break;
2755                         }
2756                 }
2757                 XSynchronize (spi_get_display (), FALSE);
2758         }
2759         g_free (keysyms);
2760
2761         return retval;
2762 }
2763
2764
2765 /*
2766  * DBus Accessibility::DEController::RegisterKeystrokeListener
2767  *     method implementation
2768  */
2769 static DBusMessage * impl_generate_keyboard_event (DBusConnection *bus, DBusMessage *message, void *user_data)
2770 {
2771   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2772   dbus_int32_t keycode;
2773   char *keystring;
2774   dbus_uint32_t synth_type;
2775   KeySym keysym;
2776   DEControllerPrivateData *priv;
2777   DBusMessage *reply = NULL;
2778
2779   if (!dbus_message_get_args(message, NULL, DBUS_TYPE_INT32, &keycode, DBUS_TYPE_STRING, &keystring, DBUS_TYPE_UINT32, &synth_type, DBUS_TYPE_INVALID))
2780   {
2781     return invalid_arguments_error (message);
2782   }
2783
2784 #ifdef SPI_DEBUG
2785         fprintf (stderr, "synthesizing keystroke %ld, type %d\n",
2786                  (long) keycode, (int) synth_type);
2787 #endif
2788   /* TODO: hide/wrap/remove X dependency */
2789
2790   /*
2791    * TODO: when initializing, query for XTest extension before using,
2792    * and fall back to XSendEvent() if XTest is not available.
2793    */
2794   
2795   spi_x_error_trap ();
2796
2797   priv = (DEControllerPrivateData *) 
2798       g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
2799
2800   if (!priv->have_xkb && xmkeymap==NULL) {
2801     xmkeymap = XGetModifierMapping(spi_get_display ());
2802   }
2803
2804   switch (synth_type)
2805     {
2806       case Accessibility_KEY_PRESS:
2807               dec_synth_keycode_press (controller, keycode);
2808               break;
2809       case Accessibility_KEY_PRESSRELEASE:
2810               dec_synth_keycode_press (controller, keycode);
2811       case Accessibility_KEY_RELEASE:
2812               dec_synth_keycode_release (controller, keycode);
2813               break;
2814       case Accessibility_KEY_SYM:
2815 #ifdef SPI_XKB_DEBUG          
2816               fprintf (stderr, "KeySym synthesis\n");
2817 #endif
2818               /* 
2819                * note: we are using long for 'keycode'
2820                * in our arg list; it can contain either
2821                * a keycode or a keysym.
2822                */
2823               dec_synth_keysym (controller, (KeySym) keycode);
2824               break;
2825       case Accessibility_KEY_STRING:
2826               if (!dec_synth_keystring (controller, keystring))
2827                       fprintf (stderr, "Keystring synthesis failure, string=%s\n",
2828                                keystring);
2829               break;
2830     }
2831   if (synth_type == Accessibility_KEY_SYM) {
2832     keysym = keycode;
2833   }
2834   else {
2835     keysym = XkbKeycodeToKeysym (spi_get_display (), keycode, 0, 0);
2836   }
2837   if (XkbKeysymToModifiers (spi_get_display (), keysym) == 0) 
2838     {
2839       spi_dec_clear_unlatch_pending (controller);
2840     }
2841   reply = dbus_message_new_method_return (message);
2842   return reply;
2843 }
2844
2845 /* Accessibility::DEController::GenerateMouseEvent */
2846 static DBusMessage * impl_generate_mouse_event (DBusConnection *bus, DBusMessage *message, void *user_data)
2847 {
2848   dbus_int32_t       x;
2849   dbus_int32_t       y;
2850   char *eventName;
2851   DBusMessage *reply = NULL;
2852   int button = 0;
2853   gboolean err = FALSE;
2854   Display *display = spi_get_display ();
2855
2856   if (!dbus_message_get_args(message, NULL, DBUS_TYPE_INT32, &x, DBUS_TYPE_INT32, &y, DBUS_TYPE_STRING, &eventName, DBUS_TYPE_INVALID))
2857   {
2858     return invalid_arguments_error (message);
2859   }
2860
2861 #ifdef SPI_DEBUG
2862   fprintf (stderr, "generating mouse %s event at %ld, %ld\n",
2863            eventName, (long int) x, (long int) y);
2864 #endif
2865   switch (eventName[0])
2866     {
2867       case 'b':
2868         switch (eventName[1])
2869           {
2870           /* TODO: check number of buttons before parsing */
2871           case '1':
2872                     button = 1;
2873                     break;
2874           case '2':
2875                   button = 2;
2876                   break;
2877           case '3':
2878                   button = 3;
2879                   break;
2880           case '4':
2881                   button = 4;
2882                   break;
2883           case '5':
2884                   button = 5;
2885                   break;
2886           default:
2887                   err = TRUE;
2888           }
2889         if (!err)
2890           {
2891             if (x != -1 && y != -1)
2892               {
2893                 XTestFakeMotionEvent (display, DefaultScreen (display),
2894                                       x, y, 0);
2895               }
2896             XTestFakeButtonEvent (display, button, !(eventName[2] == 'r'), 0);
2897             if (eventName[2] == 'c')
2898               XTestFakeButtonEvent (display, button, FALSE, 1);
2899             else if (eventName[2] == 'd')
2900               {
2901               XTestFakeButtonEvent (display, button, FALSE, 1);
2902               XTestFakeButtonEvent (display, button, TRUE, 2);
2903               XTestFakeButtonEvent (display, button, FALSE, 3);
2904               }
2905           }
2906         break;
2907       case 'r': /* relative motion */ 
2908         XTestFakeRelativeMotionEvent (display, x, y, 0);
2909         break;
2910       case 'a': /* absolute motion */
2911         XTestFakeMotionEvent (display, DefaultScreen (display),
2912                               x, y, 0);
2913         break;
2914     }
2915   reply = dbus_message_new_method_return (message);
2916   return reply;
2917 }
2918
2919 /* Accessibility::DEController::NotifyListenersSync */
2920 static DBusMessage *
2921 impl_notify_listeners_sync (DBusConnection *bus, DBusMessage *message, void *user_data)
2922 {
2923   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2924   Accessibility_DeviceEvent event;
2925   dbus_bool_t ret;
2926   DBusMessage *reply = NULL;
2927
2928   if (!spi_dbus_demarshal_deviceEvent(message, &event))
2929   {
2930     return invalid_arguments_error (message);
2931   }
2932 #ifdef SPI_DEBUG
2933   g_print ("notifylistening listeners synchronously: controller %p, event id %d\n",
2934            controller, (int) event.id);
2935 #endif
2936   ret = spi_controller_notify_keylisteners (controller,
2937                                              (Accessibility_DeviceEvent *) 
2938                                              &event, FALSE) ?
2939           TRUE : FALSE; 
2940   reply = dbus_message_new_method_return (message);
2941   if (reply)
2942   {
2943     dbus_message_append_args (reply, DBUS_TYPE_BOOLEAN, &ret, DBUS_TYPE_INVALID);
2944   }
2945   return reply;
2946 }
2947
2948 static DBusMessage *
2949 impl_notify_listeners_async (DBusConnection *bus, DBusMessage *message, void *user_data)
2950 {
2951   SpiDEController *controller = SPI_DEVICE_EVENT_CONTROLLER(user_data);
2952   Accessibility_DeviceEvent event;
2953   DBusMessage *reply = NULL;
2954
2955   if (!spi_dbus_demarshal_deviceEvent(message, &event))
2956   {
2957     return invalid_arguments_error (message);
2958   }
2959 #ifdef SPI_DEBUG
2960   g_print ("notifylistening listeners asynchronously: controller %p, event id %d\n",
2961            controller, (int) event.id);
2962 #endif
2963   spi_controller_notify_keylisteners (controller, (Accessibility_DeviceEvent *)
2964                                       &event, FALSE); 
2965   reply = dbus_message_new_method_return (message);
2966   return reply;
2967 }
2968
2969 static void
2970 spi_device_event_controller_class_init (SpiDEControllerClass *klass)
2971 {
2972   GObjectClass * object_class = (GObjectClass *) klass;
2973
2974   spi_device_event_controller_parent_class = g_type_class_peek_parent (klass);
2975
2976   object_class->finalize = spi_device_event_controller_object_finalize;
2977
2978   if (!spi_dec_private_quark)
2979           spi_dec_private_quark = g_quark_from_static_string ("spi-dec-private");
2980 }
2981
2982 #ifdef HAVE_XEVIE
2983 static Bool isEvent(Display *dpy, XEvent *event, char *arg)
2984 {
2985    return TRUE;
2986 }
2987
2988 static gboolean
2989 handle_io (GIOChannel *source,
2990            GIOCondition condition,
2991            gpointer data) 
2992 {
2993   SpiDEController *controller = (SpiDEController *) data;
2994   gboolean is_consumed = FALSE;
2995   XEvent ev;
2996
2997   while (XCheckIfEvent(controller->xevie_display, &ev, isEvent, NULL))
2998     {
2999       if (ev.type == KeyPress || ev.type == KeyRelease)
3000         is_consumed = spi_device_event_controller_forward_key_event (controller, &ev);
3001
3002       if (! is_consumed)
3003         XevieSendEvent(controller->xevie_display, &ev, XEVIE_UNMODIFIED);
3004     }
3005
3006   return TRUE;
3007 }
3008 #endif /* HAVE_XEVIE */
3009
3010 static void
3011 spi_device_event_controller_init (SpiDEController *device_event_controller)
3012 {
3013   spi_events_init (spi_get_display());
3014 #ifdef HAVE_XEVIE
3015   GIOChannel *ioc;
3016   int fd;
3017 #endif /* HAVE_XEVIE */
3018
3019   DEControllerPrivateData *private;     
3020   device_event_controller->key_listeners   = NULL;
3021   device_event_controller->mouse_listeners = NULL;
3022   device_event_controller->keygrabs_list   = NULL;
3023   device_event_controller->xevie_display   = NULL;
3024
3025 #ifdef HAVE_XEVIE
3026   device_event_controller->xevie_display = XOpenDisplay(NULL);
3027
3028   if (XevieStart(device_event_controller->xevie_display) == TRUE)
3029     {
3030 #ifdef SPI_KEYEVENT_DEBUG
3031       fprintf (stderr, "XevieStart() success \n");
3032 #endif
3033       XevieSelectInput(device_event_controller->xevie_display, KeyPressMask | KeyReleaseMask);
3034
3035       fd = ConnectionNumber(device_event_controller->xevie_display);
3036       ioc = g_io_channel_unix_new (fd);
3037       g_io_add_watch (ioc, G_IO_IN | G_IO_HUP, handle_io, device_event_controller);
3038       g_io_channel_unref (ioc);
3039     }
3040   else
3041     {
3042       device_event_controller->xevie_display = NULL;
3043 #ifdef SPI_KEYEVENT_DEBUG
3044       fprintf (stderr, "XevieStart() failed, only one client is allowed to do event int exception\n");
3045 #endif
3046     }
3047 #endif /* HAVE_XEVIE */
3048
3049   private = g_new0 (DEControllerPrivateData, 1);
3050   gettimeofday (&private->last_press_time, NULL);
3051   gettimeofday (&private->last_release_time, NULL);
3052   g_object_set_qdata (G_OBJECT (device_event_controller),
3053                       spi_dec_private_quark,
3054                       private);
3055   spi_controller_register_with_devices (device_event_controller);
3056   device_event_controller->message_queue = g_queue_new ();
3057   saved_controller = device_event_controller;
3058 }
3059
3060 static gboolean
3061 spi_device_event_controller_forward_key_event (SpiDEController *controller,
3062                                                const XEvent    *event)
3063 {
3064   Accessibility_DeviceEvent key_event;
3065   gboolean ret;
3066
3067   g_assert (event->type == KeyPress || event->type == KeyRelease);
3068
3069   key_event = spi_keystroke_from_x_key_event ((XKeyEvent *) event);
3070
3071   if (controller->xevie_display == NULL)
3072     spi_controller_update_key_grabs (controller, &key_event);
3073
3074   /* relay to listeners, and decide whether to consume it or not */
3075   ret = spi_controller_notify_keylisteners (controller, &key_event, TRUE);
3076   g_free(key_event.event_string);
3077   return ret;
3078 }
3079
3080
3081 static gboolean
3082 is_key_released (KeyCode code)
3083 {
3084   char keys[32];
3085   int down;
3086
3087   XQueryKeymap (spi_get_display (), keys);
3088   down = BIT (keys, code);
3089   return (down == 0);
3090 }
3091
3092 static gboolean
3093 check_release (gpointer data)
3094 {
3095   gboolean released;
3096   Accessibility_DeviceEvent *event = (Accessibility_DeviceEvent *)data;
3097   KeyCode code = event->hw_code;
3098
3099   released = is_key_released (code);
3100
3101   if (released)
3102     {
3103       check_release_handler = 0;
3104       event->type = Accessibility_KEY_RELEASED_EVENT;
3105       spi_controller_notify_keylisteners (saved_controller, event, TRUE);
3106     }
3107   return (released == 0);
3108 }
3109
3110 static void wait_for_release_event (XEvent          *event,
3111                                     SpiDEController *controller)
3112 {
3113   pressed_event = spi_keystroke_from_x_key_event ((XKeyEvent *) event);
3114   check_release_handler = g_timeout_add (CHECK_RELEASE_DELAY, check_release, &pressed_event);
3115 }
3116
3117 /*---------------------------------------------------------------------------*/
3118
3119 static const char *introspection_header =
3120 "<?xml version=\"1.0\"?>\n";
3121
3122 static const char *introspection_node_element =
3123 "<node name=\"%s\">\n";
3124
3125 static const char *introspection_footer =
3126 "</node>";
3127
3128 static DBusMessage *
3129 impl_Introspect (DBusConnection * bus,
3130                  DBusMessage * message, void *user_data)
3131 {
3132   GString *output;
3133   gchar *final;
3134
3135   const gchar *pathstr = SPI_DBUS_PATH_DEC;
3136
3137   DBusMessage *reply;
3138
3139   output = g_string_new(introspection_header);
3140
3141   g_string_append_printf(output, introspection_node_element, pathstr);
3142
3143   g_string_append (output, spi_org_a11y_atspi_DeviceEventController);
3144
3145   g_string_append(output, introspection_footer);
3146   final = g_string_free(output, FALSE);
3147
3148   reply = dbus_message_new_method_return (message);
3149   dbus_message_append_args(reply, DBUS_TYPE_STRING, &final, DBUS_TYPE_INVALID);
3150
3151   g_free(final);
3152   return reply;
3153 }
3154
3155 /*---------------------------------------------------------------------------*/
3156
3157 static void
3158 handle_dec_method_from_idle (DBusConnection *bus, DBusMessage *message, void *user_data)
3159 {
3160   const gchar *iface   = dbus_message_get_interface (message);
3161   const gchar *member  = dbus_message_get_member (message);
3162   DBusHandlerResult result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3163   DBusMessage *reply = NULL;
3164
3165   if (!strcmp (iface, SPI_DBUS_INTERFACE_DEC))
3166     {
3167       result = DBUS_HANDLER_RESULT_HANDLED;
3168       if      (!strcmp (member, "RegisterKeystrokeListener"))
3169           reply = impl_register_keystroke_listener (bus, message, user_data);
3170       else if (!strcmp (member, "RegisterDeviceEventListener"))
3171           reply = impl_register_device_event_listener (bus, message, user_data);
3172       else if (!strcmp (member, "DeregisterKeystrokeListener"))
3173           reply = impl_deregister_keystroke_listener (bus, message, user_data);
3174       else if (!strcmp (member, "DeregisterDeviceEventListener"))
3175           reply = impl_deregister_device_event_listener (bus, message, user_data);
3176       else if (!strcmp (member, "GetKeystrokeListeners"))
3177           reply = impl_get_keystroke_listeners (bus, message, user_data);
3178       else if (!strcmp (member, "GetDeviceEventListeners"))
3179           reply = impl_get_device_event_listeners (bus, message, user_data);
3180       else if (!strcmp (member, "GenerateKeyboardEvent"))
3181           reply = impl_generate_keyboard_event (bus, message, user_data);
3182       else if (!strcmp (member, "GenerateMouseEvent"))
3183           reply = impl_generate_mouse_event (bus, message, user_data);
3184       else if (!strcmp (member, "NotifyListenersSync"))
3185           reply = impl_notify_listeners_sync (bus, message, user_data);
3186       else if (!strcmp (member, "NotifyListenersAsync"))
3187           reply = impl_notify_listeners_async (bus, message, user_data);
3188       else
3189           result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3190     }
3191
3192   if (!strcmp (iface, "org.freedesktop.DBus.Introspectable"))
3193     {
3194       result = DBUS_HANDLER_RESULT_HANDLED;
3195       if      (!strcmp (member, "Introspect"))
3196           reply = impl_Introspect (bus, message, user_data);
3197       else
3198           result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3199     }
3200
3201   if (result == DBUS_HANDLER_RESULT_HANDLED)
3202     {
3203       if (!reply)
3204         {
3205           reply = dbus_message_new_method_return (message);
3206         }
3207
3208       dbus_connection_send (bus, reply, NULL);
3209       dbus_message_unref (reply);
3210     }
3211 }
3212
3213 static gboolean
3214 message_queue_dispatch (gpointer data)
3215 {
3216   saved_controller->message_queue_idle = 0;
3217   while (!g_queue_is_empty (saved_controller->message_queue))
3218     {
3219       DBusMessage *message = g_queue_pop_head (saved_controller->message_queue);
3220       data = g_queue_pop_head (saved_controller->message_queue);
3221       handle_dec_method_from_idle (saved_controller->bus, message, data);
3222       dbus_message_unref (message);
3223     }
3224   return FALSE;
3225 }
3226
3227 static DBusHandlerResult
3228 handle_dec_method (DBusConnection *bus, DBusMessage *message, void *user_data)
3229 {
3230   const gchar *iface   = dbus_message_get_interface (message);
3231   const gchar *member  = dbus_message_get_member (message);
3232   const gint   type    = dbus_message_get_type (message);
3233
3234   /* Check for basic reasons not to handle */
3235   if (type   != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3236       member == NULL ||
3237       iface  == NULL)
3238       return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3239
3240   dbus_message_ref (message);
3241   g_queue_push_tail (saved_controller->message_queue, message);
3242   g_queue_push_tail (saved_controller->message_queue, user_data);
3243   if (!saved_controller->message_queue_idle)
3244     saved_controller->message_queue_idle = g_idle_add (message_queue_dispatch, NULL);
3245   return DBUS_HANDLER_RESULT_HANDLED;
3246 }
3247
3248 static DBusObjectPathVTable dec_vtable =
3249 {
3250   NULL,
3251   &handle_dec_method,
3252   NULL, NULL, NULL, NULL
3253 };
3254
3255 SpiDEController *
3256 spi_registry_dec_new (SpiRegistry *reg, DBusConnection *bus)
3257 {
3258   SpiDEController *dec = g_object_new (SPI_DEVICE_EVENT_CONTROLLER_TYPE, NULL);
3259
3260   dec->registry = g_object_ref (reg);
3261   reg->dec = g_object_ref (dec);
3262   dec->bus = bus;
3263
3264   dbus_connection_register_object_path (bus, SPI_DBUS_PATH_DEC, &dec_vtable, dec);
3265
3266   spi_dec_init_mouse_listener (dec);
3267
3268   return dec;
3269 }
3270
3271 void
3272 spi_device_event_controller_start_poll_mouse (SpiRegistry *registry)
3273 {
3274   if (!have_mouse_event_listener)
3275     {
3276       have_mouse_event_listener = TRUE;
3277       if (!have_mouse_listener)
3278       g_timeout_add (100, spi_dec_poll_mouse_idle, registry->dec);
3279     }
3280 }
3281
3282 void
3283 spi_device_event_controller_stop_poll_mouse (void)
3284 {
3285   have_mouse_event_listener = FALSE;
3286 }