2007-09-08 Li Yuan <li.yuan@sun.com>
[platform/core/uifw/at-spi2-atk.git] / registryd / deviceeventcontroller.c
index c51fff3..e9ee33a 100644 (file)
@@ -2,7 +2,7 @@
  *
  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
  *
- * Copyright 2001, 2002 Sun Microsystems Inc.,
+ * Copyright 2001, 2003 Sun Microsystems Inc.,
  * Copyright 2001, 2002 Ximian, Inc.
  *
  * This library is free software; you can redistribute it and/or
 #include <string.h>
 #include <ctype.h>
 #include <stdio.h>
+#include <sys/time.h>
 #include <bonobo/bonobo-exception.h>
 
 #include <X11/Xlib.h>
 #include <X11/extensions/XTest.h>
 #include <X11/XKBlib.h>
 #define XK_MISCELLANY
+#define XK_LATIN1
 #include <X11/keysymdef.h>
+
+#ifdef HAVE_XEVIE
+#include <X11/Xproto.h>
+#include <X11/X.h>
+#include <X11/extensions/Xevie.h>
+#endif /* HAVE_XEVIE */
+
 #include <gdk/gdk.h>
 #include <gdk/gdkx.h> /* TODO: hide dependency (wrap in single porting file) */
 #include <gdk/gdkkeysyms.h>
 #include "../libspi/spi-private.h"
 #include "deviceeventcontroller.h"
 
+KeySym ucs2keysym (long ucs);
+long keysym2ucs(KeySym keysym); 
+
+#define CHECK_RELEASE_DELAY 20
+#define BIT(c, x)       (c[x/8]&(1<<(x%8)))
+static guint check_release_handler = 0;
+static Accessibility_DeviceEvent pressed_event;
+static SpiDEController *saved_controller; 
+static void wait_for_release_event (XEvent *event, SpiDEController *controller);
+
 /* Our parent Gtk object type */
 #define PARENT_TYPE BONOBO_TYPE_OBJECT
 
@@ -59,11 +78,12 @@ static unsigned int mouse_mask_state = 0;
 static unsigned int mouse_button_mask =
   Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask;
 static unsigned int key_modifier_mask =
-  Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask | Mod5Mask | ShiftMask | LockMask | ControlMask;
+  Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask | Mod5Mask | ShiftMask | LockMask | ControlMask | SPI_KEYMASK_NUMLOCK;
+static unsigned int _numlock_physical_mask = Mod2Mask; /* a guess, will be reset */
 
 static GQuark spi_dec_private_quark = 0;
 
-int (*x_default_error_handler) (Display *display, XErrorEvent *error_event);
+static int (*x_default_error_handler) (Display *display, XErrorEvent *error_event);
 
 typedef enum {
   SPI_DEVICE_TYPE_KBD,
@@ -106,6 +126,9 @@ typedef struct {
   unsigned int xkb_latch_mask;
   unsigned int pending_xkb_mod_relatch_mask;
   XkbDescPtr xkb_desc;
+  KeyCode reserved_keycode;
+  KeySym reserved_keysym;
+  guint  reserved_reset_timeout;
 } DEControllerPrivateData;
 
 static void     spi_controller_register_with_devices          (SpiDEController           *controller);
@@ -114,7 +137,7 @@ static gboolean spi_controller_update_key_grabs               (SpiDEController
 static gboolean spi_controller_register_device_listener       (SpiDEController           *controller,
                                                               DEControllerListener      *l,
                                                               CORBA_Environment         *ev);
-static void     spi_device_event_controller_forward_key_event (SpiDEController           *controller,
+static gboolean spi_device_event_controller_forward_key_event (SpiDEController           *controller,
                                                               const XEvent              *event);
 static void     spi_deregister_controller_device_listener (SpiDEController            *controller,
                                                           DEControllerListener *listener,
@@ -137,10 +160,125 @@ static gboolean spi_dec_poll_mouse_idle (gpointer data);
 
 /* Private methods */
 
+static unsigned int
+keysym_mod_mask (KeySym keysym, KeyCode keycode)
+{
+       /* we really should use XKB and look directly at the keymap */
+       /* this is very inelegant */
+       Display *display = spi_get_display ();
+       unsigned int mods_rtn = 0;
+       unsigned int retval = 0;
+       KeySym sym_rtn;
+
+       if (XkbLookupKeySym (display, keycode, 0, &mods_rtn, &sym_rtn) &&
+           (sym_rtn == keysym)) {
+               retval = 0;
+       }
+       else if (XkbLookupKeySym (display, keycode, ShiftMask, &mods_rtn, &sym_rtn) &&
+                (sym_rtn == keysym)) {
+               retval = ShiftMask;
+       }
+       else if (XkbLookupKeySym (display, keycode, Mod2Mask, &mods_rtn, &sym_rtn) &&
+                (sym_rtn == keysym)) {
+               retval = Mod2Mask;
+       }
+       else if (XkbLookupKeySym (display, keycode, Mod3Mask, &mods_rtn, &sym_rtn) &&
+                (sym_rtn == keysym)) {
+               retval = Mod3Mask;
+       }
+       else if (XkbLookupKeySym (display, keycode, 
+                                 ShiftMask | Mod2Mask, &mods_rtn, &sym_rtn) &&
+                (sym_rtn == keysym)) {
+               retval = (Mod2Mask | ShiftMask);
+       }
+       else if (XkbLookupKeySym (display, keycode, 
+                                 ShiftMask | Mod3Mask, &mods_rtn, &sym_rtn) &&
+                (sym_rtn == keysym)) {
+               retval = (Mod3Mask | ShiftMask);
+       }
+       else if (XkbLookupKeySym (display, keycode, 
+                                 ShiftMask | Mod4Mask, &mods_rtn, &sym_rtn) &&
+                (sym_rtn == keysym)) {
+               retval = (Mod4Mask | ShiftMask);
+       }
+       else
+               retval = 0xFFFF;
+       return retval;
+}
+
+static gboolean
+spi_dec_replace_map_keysym (DEControllerPrivateData *priv, KeyCode keycode, KeySym keysym)
+{
+#ifdef HAVE_XKB
+  Display *dpy = spi_get_display ();
+  XkbDescPtr desc;
+  if (!(desc = XkbGetMap (dpy, XkbAllMapComponentsMask, XkbUseCoreKbd)))
+    {
+      fprintf (stderr, "ERROR getting map\n");
+    }
+  XFlush (dpy);
+  XSync (dpy, False);
+  if (desc && desc->map)
+    {
+      gint offset = desc->map->key_sym_map[keycode].offset;
+      desc->map->syms[offset] = keysym; 
+    }
+  else
+    {
+      fprintf (stderr, "Error changing key map: empty server structure\n");
+    }          
+  XkbSetMap (dpy, XkbAllMapComponentsMask, desc);
+  /**
+   *  FIXME: the use of XkbChangeMap, and the reuse of the priv->xkb_desc structure, 
+   * would be far preferable.
+   * HOWEVER it does not seem to work using XFree 4.3. 
+   **/
+  /*       XkbChangeMap (dpy, priv->xkb_desc, priv->changes); */
+  XFlush (dpy);
+  XSync (dpy, False);
+  XkbFreeKeyboard (desc, 0, TRUE);
+
+  return TRUE;
+#else
+  return FALSE;
+#endif
+}
+
+static gboolean
+spi_dec_reset_reserved (gpointer data)
+{
+  DEControllerPrivateData *priv = data;
+  spi_dec_replace_map_keysym (priv, priv->reserved_keycode, priv->reserved_keysym);
+  priv->reserved_reset_timeout = 0;
+  return FALSE;
+}
+
 static KeyCode
-keycode_for_keysym (long keysym)
+keycode_for_keysym (SpiDEController *controller, long keysym, unsigned int *modmask)
 {
-  return XKeysymToKeycode (spi_get_display (), (KeySym) keysym);
+       KeyCode keycode = 0;
+       keycode = XKeysymToKeycode (spi_get_display (), (KeySym) keysym);
+       if (!keycode) 
+       {
+               DEControllerPrivateData *priv = (DEControllerPrivateData *)
+                       g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
+               /* if there's no keycode available, fix it */
+               if (spi_dec_replace_map_keysym (priv, priv->reserved_keycode, keysym))
+               {
+                       keycode = priv->reserved_keycode;
+                       /* 
+                        * queue a timer to restore the old keycode.  Ugly, but required 
+                        * due to races / asynchronous X delivery.   
+                        * Long-term fix is to extend the X keymap here instead of replace entries.
+                        */
+                       priv->reserved_reset_timeout = g_timeout_add (500, spi_dec_reset_reserved, priv);
+               }               
+               *modmask = 0;
+               return keycode;
+       }
+       if (modmask) 
+               *modmask = keysym_mod_mask (keysym, keycode);
+       return keycode;
 }
 
 static DEControllerGrabMask *
@@ -185,13 +323,20 @@ spi_dec_set_unlatch_pending (SpiDEController *controller, unsigned mask)
   DEControllerPrivateData *priv = 
     g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
 #ifdef SPI_XKB_DEBUG
-  if (priv->xkb_latch_mask) fprintf (stderr, "unlatch pending! %x\n", mask);
+  if (priv->xkb_latch_mask) fprintf (stderr, "unlatch pending! %x\n", 
+                                    priv->xkb_latch_mask);
 #endif
   priv->pending_xkb_mod_relatch_mask |= priv->xkb_latch_mask; 
 }
  
-static gint poll_count = 0;
-
+static void
+spi_dec_clear_unlatch_pending (SpiDEController *controller)
+{
+  DEControllerPrivateData *priv = 
+    g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
+  priv->xkb_latch_mask = 0; 
+}
 static gboolean
 spi_dec_button_update_and_emit (SpiDEController *controller, 
                                guint mask_return)
@@ -280,7 +425,7 @@ spi_dec_button_update_and_emit (SpiDEController *controller,
 #endif
        snprintf (event_name, 22, "mouse:button:%d%c", button_number,
                  (is_down) ? 'p' : 'r');
-       /* TODO: distinguish between physical and 
+       /* TODO: FIXME distinguish between physical and 
         * logical buttons 
         */
        mouse_e.type      = (is_down) ? 
@@ -300,7 +445,10 @@ spi_dec_button_update_and_emit (SpiDEController *controller,
        e.source = BONOBO_OBJREF (controller->registry->desktop);
        e.detail1 = last_mouse_pos->x;
        e.detail2 = last_mouse_pos->y;
-       spi_init_any_nil (&e.any_data);
+       spi_init_any_nil (&e.any_data, 
+                   spi_accessible_new_return (atk_get_root (), FALSE, NULL),
+                   Accessibility_ROLE_UNKNOWN,
+                   "");
        CORBA_exception_init (&ev);
        if (!is_consumed)
          {
@@ -310,6 +458,8 @@ spi_dec_button_update_and_emit (SpiDEController *controller,
          }
        else
          spi_dec_set_unlatch_pending (controller, mask_return);
+
+        CORBA_free (e.any_data._value);
       }
       return TRUE;
     }
@@ -325,9 +475,9 @@ spi_dec_mouse_check (SpiDEController *controller,
                     int *x, int *y, gboolean *moved)
 {
   Accessibility_Event e;
+  Accessibility_EventDetails *details;
   CORBA_Environment ev;
   int win_x_return,win_y_return;
-  int poll_count_modulus = 10;
   unsigned int mask_return;
   Window root_return, child_return;
   Display *display = spi_get_display ();
@@ -349,31 +499,38 @@ spi_dec_mouse_check (SpiDEController *controller,
       while (spi_dec_button_update_and_emit (controller, mask_return));
     }
 
-  if (poll_count++ == poll_count_modulus) {
-    poll_count = 0;
-    e.type = "mouse:abs";  
-    e.source = BONOBO_OBJREF (controller->registry->desktop);
-    e.detail1 = *x;
-    e.detail2 = *y;
-    spi_init_any_nil (&e.any_data);
-    CORBA_exception_init (&ev);
-    Accessibility_Registry_notifyEvent (BONOBO_OBJREF (controller->registry),
-                                       &e,
-                                       &ev);
-  }
   if (*x != last_mouse_pos->x || *y != last_mouse_pos->y) 
     {
+      e.type = "mouse:abs";  
+      e.source = BONOBO_OBJREF (controller->registry->desktop);
+      e.detail1 = *x;
+      e.detail2 = *y;
+      spi_init_any_nil (&e.any_data,
+                   spi_accessible_new_return (atk_get_root (), FALSE, NULL),
+                   Accessibility_ROLE_UNKNOWN,
+                   "");
+      CORBA_exception_init (&ev);
+      Accessibility_Registry_notifyEvent (BONOBO_OBJREF (controller->registry),
+                                         &e,
+                                         &ev);
+      details = e.any_data._value;
+      CORBA_free (details);
       e.type = "mouse:rel";  
       e.source = BONOBO_OBJREF (controller->registry->desktop);
       e.detail1 = *x - last_mouse_pos->x;
       e.detail2 = *y - last_mouse_pos->y;
-      spi_init_any_nil (&e.any_data);
+      spi_init_any_nil (&e.any_data,
+                   spi_accessible_new_return (atk_get_root (), FALSE, NULL),
+                   Accessibility_ROLE_UNKNOWN,
+                   "");
       CORBA_exception_init (&ev);
       last_mouse_pos->x = *x;
       last_mouse_pos->y = *y;
       Accessibility_Registry_notifyEvent (BONOBO_OBJREF (controller->registry),
                                          &e,
                                          &ev);
+      details = e.any_data._value;
+      CORBA_free (details);
       *moved = True;
     }
   else
@@ -395,15 +552,26 @@ spi_dec_emit_modifier_event (SpiDEController *controller, guint prev_mask,
   fprintf (stderr, "MODIFIER CHANGE EVENT! %x to %x\n", 
           prev_mask, current_mask);
 #endif
+
+  /* set bits for the virtual modifiers like NUMLOCK */
+  if (prev_mask & _numlock_physical_mask) 
+    prev_mask |= SPI_KEYMASK_NUMLOCK;
+  if (current_mask & _numlock_physical_mask) 
+    current_mask |= SPI_KEYMASK_NUMLOCK;
+
   e.type = "keyboard:modifiers";  
   e.source = BONOBO_OBJREF (controller->registry->desktop);
   e.detail1 = prev_mask & key_modifier_mask;
   e.detail2 = current_mask & key_modifier_mask;
-  spi_init_any_nil (&e.any_data);
+  spi_init_any_nil (&e.any_data,
+                   spi_accessible_new_return (atk_get_root (), FALSE, NULL),
+                   Accessibility_ROLE_UNKNOWN,
+                   "");
   CORBA_exception_init (&ev);
   Accessibility_Registry_notifyEvent (BONOBO_OBJREF (controller->registry),
                                      &e,
                                      &ev);
+  CORBA_free (e.any_data._value);
 }
 
 static gboolean
@@ -451,6 +619,7 @@ spi_dec_poll_mouse_moving (gpointer data)
     }
 }
 
+#ifdef WE_NEED_UGRAB_MOUSE
 static int
 spi_dec_ungrab_mouse (gpointer data)
 {
@@ -462,24 +631,58 @@ spi_dec_ungrab_mouse (gpointer data)
          }
        return FALSE;
 }
+#endif
 
 static void
 spi_dec_init_mouse_listener (SpiRegistry *registry)
 {
+#ifdef GRAB_BUTTON
   Display *display = spi_get_display ();
+#endif
   g_timeout_add (100, spi_dec_poll_mouse_idle, registry);
 
+#ifdef GRAB_BUTTON
   if (display)
     {
-      XGrabButton (display, AnyButton, AnyModifier,
-                  gdk_x11_get_default_root_xwindow (),
-                  True, ButtonPressMask | ButtonReleaseMask,
-                  GrabModeSync, GrabModeAsync, None, None);
+      if (XGrabButton (display, AnyButton, AnyModifier,
+                      gdk_x11_get_default_root_xwindow (),
+                      True, ButtonPressMask | ButtonReleaseMask,
+                      GrabModeSync, GrabModeAsync, None, None) != Success) {
+#ifdef SPI_DEBUG
+       fprintf (stderr, "WARNING: could not grab mouse buttons!\n");
+#endif
+       ;
+      }
       XSync (display, False);
 #ifdef SPI_DEBUG
       fprintf (stderr, "mouse buttons grabbed\n");
 #endif
     }
+#endif
+}
+
+/**
+ * Eventually we can use this to make the marshalling of mask types
+ * more sane, but for now we just use this to detect 
+ * the use of 'virtual' masks such as numlock and convert them to
+ * system-specific mask values (i.e. ModMask).
+ * 
+ **/
+static Accessibility_ControllerEventMask
+spi_dec_translate_mask (Accessibility_ControllerEventMask mask)
+{
+  Accessibility_ControllerEventMask tmp_mask;
+  gboolean has_numlock;
+
+  has_numlock = (mask & SPI_KEYMASK_NUMLOCK);
+  tmp_mask = mask;
+  if (has_numlock)
+    {
+      tmp_mask = mask ^ SPI_KEYMASK_NUMLOCK;
+      tmp_mask |= _numlock_physical_mask;
+    }
+  return tmp_mask;
 }
 
 static DEControllerKeyListener *
@@ -494,7 +697,7 @@ spi_dec_key_listener_new (CORBA_Object                            l,
   key_listener->listener.object = bonobo_object_dup_ref (l, ev);
   key_listener->listener.type = SPI_DEVICE_TYPE_KBD;
   key_listener->keys = ORBit_copy_value (keys, TC_Accessibility_KeySet);
-  key_listener->mask = mask;
+  key_listener->mask = spi_dec_translate_mask (mask);
   key_listener->listener.typeseq = ORBit_copy_value (typeseq, TC_Accessibility_EventTypeSeq);
   if (mode)
     key_listener->mode = ORBit_copy_value (mode, TC_Accessibility_EventListenerMode);
@@ -684,7 +887,10 @@ spi_controller_register_global_keygrabs (SpiDEController         *controller,
                                         DEControllerKeyListener *key_listener)
 {
   handle_keygrab (controller, key_listener, _register_keygrab);
-  return spi_controller_update_key_grabs (controller, NULL);
+  if (controller->xevie_display == NULL)
+    return spi_controller_update_key_grabs (controller, NULL);
+  else
+    return TRUE;
 }
 
 static void
@@ -692,7 +898,8 @@ spi_controller_deregister_global_keygrabs (SpiDEController         *controller,
                                           DEControllerKeyListener *key_listener)
 {
   handle_keygrab (controller, key_listener, _deregister_keygrab);
-  spi_controller_update_key_grabs (controller, NULL);
+  if (controller->xevie_display == NULL)
+    spi_controller_update_key_grabs (controller, NULL);
 }
 
 static gboolean
@@ -734,7 +941,9 @@ spi_controller_notify_mouselisteners (SpiDEController                 *controlle
   GSList  *notify = NULL, *l2;
   GList  **listeners = &controller->mouse_listeners;
   gboolean is_consumed;
-
+#ifdef SPI_KEYEVENT_DEBUG
+  gboolean found = FALSE;
+#endif
   if (!listeners)
     {
       return FALSE;
@@ -753,12 +962,15 @@ spi_controller_notify_mouselisteners (SpiDEController                 *controlle
               /* we clone (don't dup) the listener, to avoid refcount inc. */
               notify = g_slist_prepend (notify,
                                         spi_listener_clone (listener, ev));
+#ifdef SPI_KEYEVENT_DEBUG
+               found = TRUE;
+#endif
             }
          }
     }
 
 #ifdef SPI_KEYEVENT_DEBUG
-  if (!notify)
+  if (!found)
     {
       g_print ("no match for event\n");
     }
@@ -814,7 +1026,7 @@ spi_device_event_controller_forward_mouse_event (SpiDEController *controller,
   int button = xbutton_event->button;
   
   unsigned int mouse_button_state = xbutton_event->state;
-  
+
   switch (button)
     {
     case 1:
@@ -846,7 +1058,7 @@ spi_device_event_controller_forward_mouse_event (SpiDEController *controller,
   snprintf (event_name, 22, "mouse:button:%d%c", button,
            (xevent->type == ButtonPress) ? 'p' : 'r');
 
-  /* TODO: distinguish between physical and logical buttons */
+  /* TODO: FIXME distinguish between physical and logical buttons */
   mouse_e.type      = (xevent->type == ButtonPress) ? 
                       Accessibility_BUTTON_PRESSED_EVENT :
                       Accessibility_BUTTON_RELEASED_EVENT;
@@ -870,12 +1082,16 @@ spi_device_event_controller_forward_mouse_event (SpiDEController *controller,
       e.source = BONOBO_OBJREF (controller->registry->desktop);
       e.detail1 = last_mouse_pos->x;
       e.detail2 = last_mouse_pos->y;
-      spi_init_any_nil (&e.any_data);
+      spi_init_any_nil (&e.any_data,
+                   spi_accessible_new_return (atk_get_root (), FALSE, NULL),
+                   Accessibility_ROLE_UNKNOWN,
+                   "");
       CORBA_exception_init (&ev);
       
       Accessibility_Registry_notifyEvent (BONOBO_OBJREF (controller->registry),
                                          &e,
                                          &ev);
+      CORBA_free (e.any_data._value);
     }
 
   xkb_mod_unlatch_occurred = (xevent->type == ButtonPress ||
@@ -884,7 +1100,7 @@ spi_device_event_controller_forward_mouse_event (SpiDEController *controller,
   /* if client wants to consume this event, and XKB latch state was
    *   unset by this button event, we reset it
    */
-  if (is_consumed && (xkb_mod_unlatch_occurred))
+  if (is_consumed && xkb_mod_unlatch_occurred)
     spi_dec_set_unlatch_pending (controller, mouse_mask_state);
   
   XAllowEvents (spi_get_display (),
@@ -905,7 +1121,43 @@ global_filter_fn (GdkXEvent *gdk_xevent, GdkEvent *event, gpointer data)
 
   if (xevent->type == KeyPress || xevent->type == KeyRelease)
     {
-      spi_device_event_controller_forward_key_event (controller, xevent);
+      if (controller->xevie_display == NULL)
+        {
+          gboolean is_consumed;
+
+          is_consumed =
+            spi_device_event_controller_forward_key_event (controller, xevent);
+
+          if (is_consumed)
+            {
+              int n_events;
+              int i;
+              XEvent next_event;
+              n_events = XPending (display);
+
+#ifdef SPI_KEYEVENT_DEBUG
+              g_print ("Number of events pending: %d\n", n_events);
+#endif
+              for (i = 0; i < n_events; i++)
+                {
+                  XNextEvent (display, &next_event);
+                 if (next_event.type != KeyPress &&
+                     next_event.type != KeyRelease)
+                       g_warning ("Unexpected event type %d in queue", next_event.type);
+                 }
+
+              XAllowEvents (display, AsyncKeyboard, CurrentTime);
+              if (n_events)
+                XUngrabKeyboard (display, CurrentTime);
+            }
+          else
+            {
+              if (xevent->type == KeyPress)
+                wait_for_release_event (xevent, controller);
+              XAllowEvents (display, ReplayKeyboard, CurrentTime);
+            }
+        }
+
       return GDK_FILTER_CONTINUE;
     }
   if (xevent->type == ButtonPress || xevent->type == ButtonRelease)
@@ -916,7 +1168,7 @@ global_filter_fn (GdkXEvent *gdk_xevent, GdkEvent *event, gpointer data)
     {
       XkbAnyEvent * xkb_ev = (XkbAnyEvent *) xevent;
       /* ugly but probably necessary...*/
-      XSynchronize (spi_get_display (), TRUE);
+      XSynchronize (display, TRUE);
 
       if (xkb_ev->xkb_type == XkbStateNotify)
         {
@@ -953,6 +1205,7 @@ global_filter_fn (GdkXEvent *gdk_xevent, GdkEvent *event, gpointer data)
                              &= ~(XkbAX_StickyKeysFBMask);
                XkbChangeControls (display, priv->xkb_desc, &changes);
              }
+             /* TODO: account for lock as well as latch */
              XkbLatchModifiers (display,
                                 XkbUseCoreKbd,
                                 priv->pending_xkb_mod_relatch_mask,
@@ -977,13 +1230,13 @@ global_filter_fn (GdkXEvent *gdk_xevent, GdkEvent *event, gpointer data)
        }
         else
               DBG (2, g_warning ("XKB event %d\n", xkb_ev->xkb_type));
-      XSynchronize (spi_get_display (), FALSE);
+      XSynchronize (display, FALSE);
     }
   
   return GDK_FILTER_CONTINUE;
 }
 
-int
+static int
 _spi_controller_device_error_handler (Display *display, XErrorEvent *error)
 {
   if (error->error_code == BadAccess) 
@@ -1005,7 +1258,6 @@ spi_controller_register_with_devices (SpiDEController *controller)
          g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);     
   /* FIXME: should check for extension first! */
   XTestGrabControl (spi_get_display (), True);
-  priv->xkb_desc = XkbGetMap (spi_get_display (), 0, XkbUseCoreKbd);
 
   /* calls to device-specific implementations and routines go here */
   /* register with: keyboard hardware code handler */
@@ -1017,10 +1269,58 @@ spi_controller_register_with_devices (SpiDEController *controller)
                                      &priv->xkb_base_error_code, NULL, NULL);
   if (priv->have_xkb)
     {
+      gint i;
+      guint64 reserved = 0;
+      priv->xkb_desc = XkbGetMap (spi_get_display (), XkbKeySymsMask, XkbUseCoreKbd);
       XkbSelectEvents (spi_get_display (),
                       XkbUseCoreKbd,
                       XkbStateNotifyMask, XkbStateNotifyMask);     
+      _numlock_physical_mask = XkbKeysymToModifiers (spi_get_display (), 
+                                                    XK_Num_Lock);
+      for (i = priv->xkb_desc->max_key_code; i >= priv->xkb_desc->min_key_code; --i)
+      {
+         if (priv->xkb_desc->map->key_sym_map[i].kt_index[0] == XkbOneLevelIndex)
+         { 
+             if (XKeycodeToKeysym (spi_get_display (), i, 0) != 0)
+             {
+                 /* don't use this one if there's a grab client! */
+                 gdk_error_trap_push ();
+                 XGrabKey (spi_get_display (), i, 0, 
+                           gdk_x11_get_default_root_xwindow (),
+                           TRUE,
+                           GrabModeSync, GrabModeSync);
+                 XSync (spi_get_display (), TRUE);
+                 XUngrabKey (spi_get_display (), i, 0, 
+                             gdk_x11_get_default_root_xwindow ());
+                 if (!gdk_error_trap_pop ())
+                 {
+                     reserved = i;
+                     break;
+                 }
+             }
+         }
+      }
+      if (reserved) 
+      {
+         priv->reserved_keycode = reserved;
+         priv->reserved_keysym = XKeycodeToKeysym (spi_get_display (), reserved, 0);
+      }
+      else
+      { 
+         priv->reserved_keycode = XKeysymToKeycode (spi_get_display (), XK_numbersign);
+         priv->reserved_keysym = XK_numbersign;
+      }
+#ifdef SPI_RESERVED_DEBUG
+      unsigned sym = 0;
+      sym = XKeycodeToKeysym (spi_get_display (), reserved, 0);
+      fprintf (stderr, "%x\n", sym);
+      fprintf (stderr, "setting the reserved keycode to %d (%s)\n", 
+              reserved, 
+              XKeysymToString (XKeycodeToKeysym (spi_get_display (),
+                                                            reserved, 0)));
+#endif
     }  
+
   gdk_window_add_filter (NULL, global_filter_fn, controller);
 
   gdk_window_set_events (gdk_get_default_root_window (),
@@ -1053,10 +1353,13 @@ spi_key_set_contains_key (Accessibility_KeySet            *key_set,
   for (i = 0; i < len; ++i)
     {
 #ifdef SPI_KEYEVENT_DEBUG          
-      g_print ("key_set[%d] = %d; key_event %d, code %d, string %s\n",
-               i, (int) key_set->_buffer[i].keycode,
-              (int) key_event->id, (int) key_event->hw_code,
-              key_event->event_string); 
+      g_print ("key_set[%d] event = %d, code = %d; key_event %d, code %d, string %s\n",
+                i,
+                (int)key_set->_buffer[i].keysym,
+                (int) key_set->_buffer[i].keycode,
+                (int) key_event->id,
+                (int) key_event->hw_code,
+                key_event->event_string); 
 #endif
       if (key_set->_buffer[i].keysym == (CORBA_long) key_event->id)
         {
@@ -1072,7 +1375,7 @@ spi_key_set_contains_key (Accessibility_KeySet            *key_set,
           return TRUE;
        }
     }
-  
+
   return FALSE;
 }
 
@@ -1117,7 +1420,7 @@ spi_key_event_matches_listener (const Accessibility_DeviceEvent *key_event,
                                DEControllerKeyListener         *listener,
                                CORBA_boolean                    is_system_global)
 {
-  if ((key_event->modifiers == (CORBA_unsigned_short) (listener->mask & 0xFFFF)) &&
+  if (((key_event->modifiers & 0xFF) == (CORBA_unsigned_short) (listener->mask & 0xFF)) &&
        spi_key_set_contains_key (listener->keys, key_event) &&
        spi_eventtype_seq_contains_event (listener->listener.typeseq, key_event) && 
       (is_system_global == listener->mode->global))
@@ -1132,7 +1435,7 @@ spi_key_event_matches_listener (const Accessibility_DeviceEvent *key_event,
 
 static gboolean
 spi_controller_notify_keylisteners (SpiDEController                 *controller,
-                                   const Accessibility_DeviceEvent *key_event,
+                                   Accessibility_DeviceEvent       *key_event,
                                    CORBA_boolean                    is_system_global,
                                    CORBA_Environment               *ev)
 {
@@ -1146,6 +1449,10 @@ spi_controller_notify_keylisteners (SpiDEController                 *controller,
       return FALSE;
     }
 
+  /* set the NUMLOCK event mask bit if appropriate: see bug #143702 */
+  if (key_event->modifiers & _numlock_physical_mask)
+      key_event->modifiers |= SPI_KEYMASK_NUMLOCK;
+
   for (l = *key_listeners; l; l = l->next)
     {
        DEControllerKeyListener *key_listener = l->data;
@@ -1176,7 +1483,8 @@ spi_controller_notify_keylisteners (SpiDEController                 *controller,
       DEControllerKeyListener *key_listener = l2->data;            
       Accessibility_DeviceEventListener ls = key_listener->listener.object;
 
-      is_consumed = Accessibility_DeviceEventListener_notifyEvent (ls, key_event, ev);
+      is_consumed = Accessibility_DeviceEventListener_notifyEvent (ls, key_event, ev) &&
+                   key_listener->mode->preemptive;
 
       if (BONOBO_EX (ev))
         {
@@ -1205,7 +1513,7 @@ spi_controller_notify_keylisteners (SpiDEController                 *controller,
 }
 
 static gboolean
-spi_clear_error_state ()
+spi_clear_error_state (void)
 {
        gboolean retval = spi_error_code != 0;
        spi_error_code = 0;
@@ -1218,18 +1526,19 @@ spi_keystroke_from_x_key_event (XKeyEvent *x_key_event)
   Accessibility_DeviceEvent key_event;
   KeySym keysym;
   const int cbuf_bytes = 20;
-  char cbuf [cbuf_bytes];
-  
-  keysym = XLookupKeysym (x_key_event, 0);
+  char cbuf [21];
+  int nbytes;
+
+  nbytes = XLookupString (x_key_event, cbuf, cbuf_bytes, &keysym, NULL);  
   key_event.id = (CORBA_long)(keysym);
   key_event.hw_code = (CORBA_short) x_key_event->keycode;
   if (((XEvent *) x_key_event)->type == KeyPress)
     {
-      key_event.type = Accessibility_KEY_PRESSED;
+      key_event.type = Accessibility_KEY_PRESSED_EVENT;
     }
   else
     {
-      key_event.type = Accessibility_KEY_RELEASED;
+      key_event.type = Accessibility_KEY_RELEASED_EVENT;
     } 
   key_event.modifiers = (CORBA_unsigned_short)(x_key_event->state);
   key_event.is_text = CORBA_FALSE;
@@ -1239,9 +1548,6 @@ spi_keystroke_from_x_key_event (XKeyEvent *x_key_event)
         key_event.event_string = CORBA_string_dup ("space");
         break;
       case XK_Tab:
-#ifdef SPI_KEYEVENT_DEBUG
-       fprintf(stderr, "Tab\n");
-#endif
         key_event.event_string = CORBA_string_dup ("Tab");
        break;
       case XK_BackSpace:
@@ -1314,12 +1620,16 @@ spi_keystroke_from_x_key_event (XKeyEvent *x_key_event)
         key_event.event_string = CORBA_string_dup ("Right");
        break;
       default:
-        if (XLookupString (x_key_event, cbuf, cbuf_bytes, &keysym, NULL) > 0)
+        if (nbytes > 0)
           {
+           gunichar c;
+           cbuf[nbytes] = '\0'; /* OK since length is cbuf_bytes+1 */
             key_event.event_string = CORBA_string_dup (cbuf);
-           if (isgraph (keysym))
+           c = keysym2ucs (keysym);
+           if (c > 0 && !g_unichar_iscntrl (c))
              {
-               key_event.is_text = CORBA_TRUE; /* FIXME: incorrect for some composed chars? */
+               key_event.is_text = CORBA_TRUE; 
+               /* incorrect for some composed chars? */
              }
           }
         else
@@ -1330,17 +1640,33 @@ spi_keystroke_from_x_key_event (XKeyEvent *x_key_event)
 
   key_event.timestamp = (CORBA_unsigned_long) x_key_event->time;
 #ifdef SPI_KEYEVENT_DEBUG
-  fprintf (stderr,
-     "Key %lu pressed (%c), modifiers %d\n",
-     (unsigned long) keysym,
-     keysym ? (int) keysym : '*',
-     (int) x_key_event->state);
+  {
+    char *pressed_str  = "pressed";
+    char *released_str = "released";
+    char *state_ptr;
+
+    if (key_event.type == Accessibility_KEY_PRESSED_EVENT)
+      state_ptr = pressed_str;
+    else
+      state_ptr = released_str;
+    fprintf (stderr,
+            "Key %lu %s (%c), modifiers %d; string=%s [%x] %s\n",
+            (unsigned long) keysym,
+            state_ptr,
+            keysym ? (int) keysym : '*',
+            (int) x_key_event->state,
+            key_event.event_string,
+            key_event.event_string[0],
+            (key_event.is_text == CORBA_TRUE) ? "(text)" : "(not text)");
+  }
 #endif
 #ifdef SPI_DEBUG
-  fprintf (stderr, "%s%c",
+  fprintf (stderr, "%s%c\n",
      (x_key_event->state & Mod1Mask)?"Alt-":"",
      ((x_key_event->state & ShiftMask)^(x_key_event->state & LockMask))?
      g_ascii_toupper (keysym) : g_ascii_tolower (keysym));
+  fprintf (stderr, "serial: %x Time: %x\n", x_key_event->serial, x_key_event->time);
 #endif /* SPI_DEBUG */
   return key_event;    
 }
@@ -1351,6 +1677,7 @@ spi_controller_update_key_grabs (SpiDEController           *controller,
 {
   GList *l, *next;
   gboolean   update_failed = FALSE;
+  KeyCode keycode = 0;
   
   g_return_val_if_fail (controller != NULL, FALSE);
 
@@ -1363,6 +1690,8 @@ spi_controller_update_key_grabs (SpiDEController           *controller,
    *
    * ControlMask grabs are broken, must be in use already
    */
+  if (recv)
+    keycode = keycode_for_keysym (controller, recv->id, NULL);
   for (l = controller->keygrabs_list; l; l = next)
     {
       gboolean do_remove;
@@ -1372,9 +1701,8 @@ spi_controller_update_key_grabs (SpiDEController           *controller,
       next = l->next;
 
       re_issue_grab = recv &&
-/*           (recv->type == Accessibility_KEY_RELEASED) && - (?) */
              (recv->modifiers & grab_mask->mod_mask) &&
-             (grab_mask->key_val == keycode_for_keysym (recv->id));
+             (grab_mask->key_val == keycode);
 
 #ifdef SPI_DEBUG
       fprintf (stderr, "mask=%lx %lx (%c%c) %s\n",
@@ -1458,6 +1786,16 @@ spi_device_event_controller_object_finalize (GObject *object)
   /* disconnect any special listeners, get rid of outstanding keygrabs */
   XUngrabKey (spi_get_display (), AnyKey, AnyModifier, DefaultRootWindow (spi_get_display ()));
 
+#ifdef HAVE_XEVIE
+  if (controller->xevie_display != NULL)
+    {
+      XevieEnd(controller->xevie_display);
+#ifdef SPI_KEYEVENT_DEBUG
+      printf("XevieEnd(dpy) finished \n");
+#endif
+    }
+#endif
+
   private = g_object_get_data (G_OBJECT (controller), "spi-dec-private");
   if (private->xkb_desc)
          XkbFreeKeyboard (private->xkb_desc, 0, True);
@@ -1734,6 +2072,7 @@ dec_synth_keycode_press (SpiDEController *controller,
        }
         XTestFakeKeyEvent (spi_get_display (), keycode, True, time);
        priv->last_press_keycode = keycode;
+       XFlush (spi_get_display ());
        XSync (spi_get_display (), False);
        gettimeofday (&priv->last_press_time, NULL);
        return TRUE;
@@ -1782,6 +2121,124 @@ dec_synth_keycode_release (SpiDEController *controller,
        return TRUE;
 }
 
+static unsigned
+dec_get_modifier_state (SpiDEController *controller)
+{
+       return mouse_mask_state;
+}
+
+static gboolean
+dec_lock_modifiers (SpiDEController *controller, unsigned modifiers)
+{
+       return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
+                         modifiers, modifiers);
+}
+
+static gboolean
+dec_unlock_modifiers (SpiDEController *controller, unsigned modifiers)
+{
+       return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
+                         modifiers, 0);
+}
+
+static KeySym
+dec_keysym_for_unichar (SpiDEController *controller, gunichar unichar)
+{
+       return ucs2keysym ((long) unichar);
+}
+
+static gboolean
+dec_synth_keysym (SpiDEController *controller, KeySym keysym)
+{
+       KeyCode key_synth_code;
+       unsigned int modifiers, synth_mods, lock_mods;
+
+       key_synth_code = keycode_for_keysym (controller, keysym, &synth_mods);
+
+       if ((key_synth_code == 0) || (synth_mods == 0xFF)) return FALSE;
+
+       /* TODO: set the modifiers accordingly! */
+       modifiers = dec_get_modifier_state (controller);
+       /* side-effect; we may unset mousebutton modifiers here! */
+
+       lock_mods = 0;
+       if (synth_mods != modifiers) {
+               lock_mods = synth_mods & ~modifiers;
+               dec_lock_modifiers (controller, lock_mods);
+       }
+       dec_synth_keycode_press (controller, key_synth_code);
+       dec_synth_keycode_release (controller, key_synth_code);
+
+       if (synth_mods != modifiers) 
+               dec_unlock_modifiers (controller, lock_mods);
+       return TRUE;
+}
+
+
+static gboolean
+dec_synth_keystring (SpiDEController *controller, const CORBA_char *keystring)
+{
+       /* probably we need to create and inject an XIM handler eventually. */
+       /* for now, try to match the string to existing 
+        * keycode+modifier states. 
+         */
+       KeySym *keysyms;
+       gint maxlen = 0;
+       gunichar unichar = 0;
+       gint i = 0;
+       gboolean retval = TRUE;
+       const gchar *c;
+
+       maxlen = strlen (keystring);
+       keysyms = g_new0 (KeySym, maxlen);
+       if (!(keystring && *keystring && g_utf8_validate (keystring, -1, &c))) { 
+               retval = FALSE;
+       } 
+       else {
+#ifdef SPI_DEBUG
+               fprintf (stderr, "[keystring synthesis attempted on %s]\n", keystring);
+#endif
+               while (keystring && (unichar = g_utf8_get_char (keystring))) {
+                       KeySym keysym;
+                       char bytes[6];
+                       gint mbytes;
+                       
+                       mbytes = g_unichar_to_utf8 (unichar, bytes);
+                       bytes[mbytes] = '\0';
+#ifdef SPI_DEBUG
+                       fprintf (stderr, "[unichar %s]", bytes);
+#endif
+                       keysym = dec_keysym_for_unichar (controller, unichar);
+                       if (keysym == NoSymbol) {
+#ifdef SPI_DEBUG
+                               fprintf (stderr, "no keysym for %s", bytes);
+#endif
+                               retval = FALSE;
+                               break;
+                       }
+                       keysyms[i++] = keysym;
+                       keystring = g_utf8_next_char (keystring); 
+               }
+               keysyms[i++] = 0;
+               XSynchronize (spi_get_display (), TRUE);
+               for (i = 0; keysyms[i]; ++i) {
+                       if (!dec_synth_keysym (controller, keysyms[i])) {
+#ifdef SPI_DEBUG
+                               fprintf (stderr, "could not synthesize %c\n",
+                                        (int) keysyms[i]);
+#endif
+                               retval = FALSE;
+                               break;
+                       }
+               }
+               XSynchronize (spi_get_display (), FALSE);
+       }
+       g_free (keysyms);
+
+       return retval;
+}
+
+
 /*
  * CORBA Accessibility::DEController::registerKeystrokeListener
  *     method implementation
@@ -1795,11 +2252,8 @@ impl_generate_keyboard_event (PortableServer_Servant           servant,
 {
   SpiDEController *controller =
        SPI_DEVICE_EVENT_CONTROLLER (bonobo_object (servant));
-  DEControllerPrivateData *priv;
-  long key_synth_code;
-  unsigned int slow_keys_delay;
-  unsigned int press_time;
-  unsigned int release_time;
+  gint err;
+  KeySym keysym;
 
 #ifdef SPI_DEBUG
        fprintf (stderr, "synthesizing keystroke %ld, type %d\n",
@@ -1812,9 +2266,7 @@ impl_generate_keyboard_event (PortableServer_Servant           servant,
    * and fall back to XSendEvent() if XTest is not available.
    */
   
-  /* TODO: implement keystring mode also */
   gdk_error_trap_push ();
-  key_synth_code = keycode;
 
   switch (synth_type)
     {
@@ -1830,17 +2282,32 @@ impl_generate_keyboard_event (PortableServer_Servant           servant,
 #ifdef SPI_XKB_DEBUG         
              fprintf (stderr, "KeySym synthesis\n");
 #endif
-             key_synth_code = keycode_for_keysym (keycode);
-             dec_synth_keycode_press (controller, key_synth_code);
-             dec_synth_keycode_release (controller, key_synth_code);
+             /* 
+              * note: we are using long for 'keycode'
+              * in our arg list; it can contain either
+              * a keycode or a keysym.
+              */
+             dec_synth_keysym (controller, (KeySym) keycode);
              break;
       case Accessibility_KEY_STRING:
-             fprintf (stderr, "Not yet implemented\n");
+             if (!dec_synth_keystring (controller, keystring))
+                     fprintf (stderr, "Keystring synthesis failure, string=%s\n",
+                              keystring);
              break;
     }
-  if (gdk_error_trap_pop ())
+  if ((err = gdk_error_trap_pop ()))
     {
-      DBG (-1, g_warning ("Error emitting keystroke"));
+      DBG (-1, g_warning ("Error [%d] emitting keystroke", err));
+    }
+  if (synth_type == Accessibility_KEY_SYM) {
+    keysym = keycode;
+  }
+  else {
+    keysym = XkbKeycodeToKeysym (spi_get_display (), keycode, 0, 0);
+  }
+  if (XkbKeysymToModifiers (spi_get_display (), keysym) == 0) 
+    {
+      spi_dec_clear_unlatch_pending (controller);
     }
 }
 
@@ -1852,7 +2319,7 @@ impl_generate_mouse_event (PortableServer_Servant servant,
                           const CORBA_char      *eventName,
                           CORBA_Environment     *ev)
 {
-  int button;
+  int button = 0;
   gboolean error = FALSE;
   Display *display = spi_get_display ();
 #ifdef SPI_DEBUG
@@ -1874,6 +2341,12 @@ impl_generate_mouse_event (PortableServer_Servant servant,
          case '3':
                  button = 3;
                  break;
+         case '4':
+                 button = 4;
+                 break;
+         case '5':
+                 button = 5;
+                 break;
          default:
                  error = TRUE;
          }
@@ -1917,7 +2390,9 @@ impl_notify_listeners_sync (PortableServer_Servant           servant,
   g_print ("notifylistening listeners synchronously: controller %p, event id %d\n",
           controller, (int) event->id);
 #endif
-  return spi_controller_notify_keylisteners (controller, event, CORBA_FALSE, ev) ?
+  return spi_controller_notify_keylisteners (controller,
+                                            (Accessibility_DeviceEvent *) 
+                                            event, CORBA_FALSE, ev) ?
          CORBA_TRUE : CORBA_FALSE; 
 }
 
@@ -1932,7 +2407,8 @@ impl_notify_listeners_async (PortableServer_Servant           servant,
 #ifdef SPI_DEBUG
   fprintf (stderr, "notifying listeners asynchronously\n");
 #endif
-  spi_controller_notify_keylisteners (controller, event, CORBA_FALSE, ev); 
+  spi_controller_notify_keylisteners (controller, (Accessibility_DeviceEvent *)
+                                     event, CORBA_FALSE, ev); 
 }
 
 static void
@@ -1958,21 +2434,72 @@ spi_device_event_controller_class_init (SpiDEControllerClass *klass)
          spi_dec_private_quark = g_quark_from_static_string ("spi-dec-private");
 }
 
+#ifdef HAVE_XEVIE
+static Bool isEvent(Display *dpy, XEvent *event, char *arg)
+{
+   return TRUE;
+}
+
+static gboolean
+handle_io (GIOChannel *source,
+           GIOCondition condition,
+           gpointer data) 
+{
+  SpiDEController *controller = (SpiDEController *) data;
+  gboolean is_consumed = FALSE;
+  XEvent ev;
+
+  while (XCheckIfEvent(controller->xevie_display, &ev, isEvent, NULL))
+    {
+      if (ev.type == KeyPress || ev.type == KeyRelease)
+        is_consumed = spi_device_event_controller_forward_key_event (controller, &ev);
+
+      if (! is_consumed)
+        XevieSendEvent(controller->xevie_display, &ev, XEVIE_UNMODIFIED);
+    }
+
+  return TRUE;
+}
+#endif /* HAVE_XEVIE */
+
 static void
 spi_device_event_controller_init (SpiDEController *device_event_controller)
 {
+#ifdef HAVE_XEVIE
+  GIOChannel *ioc;
+  int fd;
+#endif /* HAVE_XEVIE */
+
   DEControllerPrivateData *private;    
   device_event_controller->key_listeners   = NULL;
   device_event_controller->mouse_listeners = NULL;
   device_event_controller->keygrabs_list   = NULL;
+  device_event_controller->xevie_display   = NULL;
+
+#ifdef HAVE_XEVIE
+  device_event_controller->xevie_display = XOpenDisplay(NULL);
+
+  if (XevieStart(device_event_controller->xevie_display) == TRUE)
+    {
+#ifdef SPI_KEYEVENT_DEBUG
+      fprintf (stderr, "XevieStart() success \n");
+#endif
+      XevieSelectInput(device_event_controller->xevie_display, KeyPressMask | KeyReleaseMask);
+
+      fd = ConnectionNumber(device_event_controller->xevie_display);
+      ioc = g_io_channel_unix_new (fd);
+      g_io_add_watch (ioc, G_IO_IN | G_IO_HUP, handle_io, device_event_controller);
+      g_io_channel_unref (ioc);
+    }
+  else
+    {
+      device_event_controller->xevie_display = NULL;
+#ifdef SPI_KEYEVENT_DEBUG
+      fprintf (stderr, "XevieStart() failed, only one client is allowed to do event int exception\n");
+#endif
+    }
+#endif /* HAVE_XEVIE */
 
-  /*
-   * TODO: fixme, this module makes the foolish assumptions that
-   * registryd uses the same display as the apps, and that the
-   * DISPLAY environment variable is set.
-   */
-  gdk_init (NULL, NULL);
-  
   private = g_new0 (DEControllerPrivateData, 1);
   gettimeofday (&private->last_press_time, NULL);
   gettimeofday (&private->last_release_time, NULL);
@@ -1982,13 +2509,13 @@ spi_device_event_controller_init (SpiDEController *device_event_controller)
   spi_controller_register_with_devices (device_event_controller);
 }
 
-static void
+static gboolean
 spi_device_event_controller_forward_key_event (SpiDEController *controller,
                                               const XEvent    *event)
 {
-  gboolean is_consumed = FALSE;
   CORBA_Environment ev;
   Accessibility_DeviceEvent key_event;
+  gboolean ret;
 
   g_assert (event->type == KeyPress || event->type == KeyRelease);
 
@@ -1996,20 +2523,13 @@ spi_device_event_controller_forward_key_event (SpiDEController *controller,
 
   key_event = spi_keystroke_from_x_key_event ((XKeyEvent *) event);
 
-  spi_controller_update_key_grabs (controller, &key_event);
+  if (controller->xevie_display == NULL)
+    spi_controller_update_key_grabs (controller, &key_event);
 
   /* relay to listeners, and decide whether to consume it or not */
-  is_consumed = spi_controller_notify_keylisteners (
-         controller, &key_event, CORBA_TRUE, &ev);
-
-  if (is_consumed)
-    {
-      XAllowEvents (spi_get_display (), AsyncKeyboard, CurrentTime);
-    }
-  else
-    {
-      XAllowEvents (spi_get_display (), ReplayKeyboard, CurrentTime);
-    }
+  ret = spi_controller_notify_keylisteners (controller, &key_event, CORBA_TRUE, &ev);
+  CORBA_free(key_event.event_string);
+  return ret;
 }
 
 SpiDEController *
@@ -2017,7 +2537,6 @@ spi_device_event_controller_new (SpiRegistry *registry)
 {
   SpiDEController *retval = g_object_new (
     SPI_DEVICE_EVENT_CONTROLLER_TYPE, NULL);
-  DEControllerPrivateData *private;
   
   retval->registry = SPI_REGISTRY (bonobo_object_ref (
          BONOBO_OBJECT (registry)));
@@ -2027,7 +2546,46 @@ spi_device_event_controller_new (SpiRegistry *registry)
   return retval;
 }
 
+static gboolean
+is_key_released (KeyCode code)
+{
+  char keys[32];
+  int down;
+
+  XQueryKeymap (spi_get_display (), keys);
+  down = BIT (keys, code);
+  return (down == 0);
+}
+
+static gboolean
+check_release (gpointer data)
+{
+  gboolean released;
+  Accessibility_DeviceEvent *event = (Accessibility_DeviceEvent *)data;
+  KeyCode code = event->hw_code;
+  CORBA_Environment ev;
+
+  released = is_key_released (code);
+
+  if (released)
+    {
+      check_release_handler = 0;
+      event->type = Accessibility_KEY_RELEASED_EVENT;
+      ev._major = CORBA_NO_EXCEPTION;
+      spi_controller_notify_keylisteners (saved_controller, event, CORBA_TRUE, &ev);
+    }
+  return (released == 0);
+}
+
+static void wait_for_release_event (XEvent          *event,
+                                    SpiDEController *controller)
+{
+  pressed_event = spi_keystroke_from_x_key_event ((XKeyEvent *) event);
+  saved_controller = controller;
+  check_release_handler = g_timeout_add (CHECK_RELEASE_DELAY, check_release, &pressed_event);
+}
+
 BONOBO_TYPE_FUNC_FULL (SpiDEController,
                       Accessibility_DeviceEventController,
                       PARENT_TYPE,
-                      spi_device_event_controller);
+                      spi_device_event_controller)