Add registryd
[platform/core/uifw/at-spi2-atk.git] / registryd / deviceeventcontroller.c
index 41e616a..ee43061 100644 (file)
@@ -39,6 +39,7 @@
 #include <X11/extensions/XTest.h>
 #include <X11/XKBlib.h>
 #define XK_MISCELLANY
+#define XK_LATIN1
 #include <X11/keysymdef.h>
 
 #ifdef HAVE_XEVIE
@@ -56,6 +57,7 @@
 #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)))
@@ -80,8 +82,9 @@ static unsigned int key_modifier_mask =
 static unsigned int _numlock_physical_mask = Mod2Mask; /* a guess, will be reset */
 
 static GQuark spi_dec_private_quark = 0;
+static XModifierKeymap* xmkeymap = NULL;
 
-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,
@@ -124,6 +127,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);
@@ -201,11 +207,76 @@ keysym_mod_mask (KeySym keysym, KeyCode keycode)
        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, unsigned int *modmask)
+keycode_for_keysym (SpiDEController *controller, long keysym, unsigned int *modmask)
 {
        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;
@@ -375,7 +446,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)
          {
@@ -385,6 +459,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;
     }
@@ -400,6 +476,7 @@ 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;
   unsigned int mask_return;
@@ -429,22 +506,32 @@ spi_dec_mouse_check (SpiDEController *controller,
       e.source = BONOBO_OBJREF (controller->registry->desktop);
       e.detail1 = *x;
       e.detail2 = *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);
+      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
@@ -477,11 +564,15 @@ spi_dec_emit_modifier_event (SpiDEController *controller, guint prev_mask,
   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
@@ -546,9 +637,12 @@ spi_dec_ungrab_mouse (gpointer data)
 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)
     {
       if (XGrabButton (display, AnyButton, AnyModifier,
@@ -565,22 +659,31 @@ spi_dec_init_mouse_listener (SpiRegistry *registry)
       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 Mumlock and convert them to
+ * 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)
 {
-  if (mask == SPI_KEYMASK_NUMLOCK) {
-    mask = _numlock_physical_mask;
-  }
-  return 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 *
@@ -839,8 +942,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;
@@ -859,7 +963,9 @@ 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
             }
          }
     }
@@ -977,12 +1083,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 ||
@@ -1010,19 +1120,45 @@ global_filter_fn (GdkXEvent *gdk_xevent, GdkEvent *event, gpointer data)
   priv = (DEControllerPrivateData *)
          g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);  
 
+  if (xevent->type == MappingNotify)
+    xmkeymap = NULL;
+
   if (xevent->type == KeyPress || xevent->type == KeyRelease)
     {
       if (controller->xevie_display == NULL)
         {
-          gboolean is_consumed =
+          gboolean is_consumed;
+
+          is_consumed =
             spi_device_event_controller_forward_key_event (controller, xevent);
 
           if (is_consumed)
-            XAllowEvents (spi_get_display (), AsyncKeyboard, CurrentTime);
+            {
+              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
             {
-              wait_for_release_event (xevent, controller);
-              XAllowEvents (spi_get_display (), ReplayKeyboard, CurrentTime);
+              if (xevent->type == KeyPress)
+                wait_for_release_event (xevent, controller);
+              XAllowEvents (display, ReplayKeyboard, CurrentTime);
             }
         }
 
@@ -1036,7 +1172,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)
         {
@@ -1098,13 +1234,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) 
@@ -1137,12 +1273,56 @@ spi_controller_register_with_devices (SpiDEController *controller)
                                      &priv->xkb_base_error_code, NULL, NULL);
   if (priv->have_xkb)
     {
-      priv->xkb_desc = XkbGetMap (spi_get_display (), 0, XkbUseCoreKbd);
+      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);
@@ -1244,7 +1424,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 & 0xFF)) &&
+  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))
@@ -1259,7 +1439,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)
 {
@@ -1273,6 +1453,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;
@@ -1303,7 +1487,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))
         {
@@ -1332,7 +1517,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;
@@ -1345,7 +1530,7 @@ 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+1];
+  char cbuf [21];
   int nbytes;
 
   nbytes = XLookupString (x_key_event, cbuf, cbuf_bytes, &keysym, NULL);  
@@ -1444,8 +1629,8 @@ spi_keystroke_from_x_key_event (XKeyEvent *x_key_event)
            gunichar c;
            cbuf[nbytes] = '\0'; /* OK since length is cbuf_bytes+1 */
             key_event.event_string = CORBA_string_dup (cbuf);
-           c = g_utf8_get_char_validated (cbuf, nbytes);
-           if ((c > 0) && g_unichar_isprint (c))
+           c = keysym2ucs (keysym);
+           if (c > 0 && !g_unichar_iscntrl (c))
              {
                key_event.is_text = CORBA_TRUE; 
                /* incorrect for some composed chars? */
@@ -1485,6 +1670,7 @@ spi_keystroke_from_x_key_event (XKeyEvent *x_key_event)
      (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;    
 }
@@ -1495,6 +1681,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);
 
@@ -1507,6 +1694,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;
@@ -1517,7 +1706,7 @@ spi_controller_update_key_grabs (SpiDEController           *controller,
 
       re_issue_grab = recv &&
              (recv->modifiers & grab_mask->mod_mask) &&
-             (grab_mask->key_val == keycode_for_keysym (recv->id, NULL));
+             (grab_mask->key_val == keycode);
 
 #ifdef SPI_DEBUG
       fprintf (stderr, "mask=%lx %lx (%c%c) %s\n",
@@ -1887,6 +2076,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;
@@ -1944,15 +2134,37 @@ dec_get_modifier_state (SpiDEController *controller)
 static gboolean
 dec_lock_modifiers (SpiDEController *controller, unsigned modifiers)
 {
-       return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
-                         modifiers, modifiers);
+    DEControllerPrivateData *priv = (DEControllerPrivateData *) 
+    g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);  
+    
+    if (priv->have_xkb) {
+        return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
+                                  modifiers, modifiers);
+    } else {
+       int mod_index;
+       for (mod_index=0;mod_index<8;mod_index++)
+           if (modifiers & (1<<mod_index))
+               dec_synth_keycode_press(controller, xmkeymap->modifiermap[mod_index]);
+       return TRUE;
+    }
 }
 
 static gboolean
 dec_unlock_modifiers (SpiDEController *controller, unsigned modifiers)
 {
-       return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
-                         modifiers, 0);
+    DEControllerPrivateData *priv = (DEControllerPrivateData *) 
+    g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);  
+    
+    if (priv->have_xkb) {
+        return XkbLockModifiers (spi_get_display (), XkbUseCoreKbd, 
+                                  modifiers, 0);
+    } else {
+       int mod_index;
+       for (mod_index=0;mod_index<8;mod_index++)
+           if (modifiers & (1<<mod_index))
+               dec_synth_keycode_release(controller, xmkeymap->modifiermap[mod_index]);
+       return TRUE;
+    }
 }
 
 static KeySym
@@ -1967,7 +2179,7 @@ dec_synth_keysym (SpiDEController *controller, KeySym keysym)
        KeyCode key_synth_code;
        unsigned int modifiers, synth_mods, lock_mods;
 
-       key_synth_code = keycode_for_keysym (keysym, &synth_mods);
+       key_synth_code = keycode_for_keysym (controller, keysym, &synth_mods);
 
        if ((key_synth_code == 0) || (synth_mods == 0xFF)) return FALSE;
 
@@ -1982,6 +2194,7 @@ dec_synth_keysym (SpiDEController *controller, KeySym keysym)
        }
        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;
@@ -2033,6 +2246,7 @@ dec_synth_keystring (SpiDEController *controller, const CORBA_char *keystring)
                        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
@@ -2043,6 +2257,7 @@ dec_synth_keystring (SpiDEController *controller, const CORBA_char *keystring)
                                break;
                        }
                }
+               XSynchronize (spi_get_display (), FALSE);
        }
        g_free (keysyms);
 
@@ -2063,8 +2278,9 @@ impl_generate_keyboard_event (PortableServer_Servant           servant,
 {
   SpiDEController *controller =
        SPI_DEVICE_EVENT_CONTROLLER (bonobo_object (servant));
-  long key_synth_code;
+  gint err;
   KeySym keysym;
+  DEControllerPrivateData *priv;
 
 #ifdef SPI_DEBUG
        fprintf (stderr, "synthesizing keystroke %ld, type %d\n",
@@ -2078,7 +2294,13 @@ impl_generate_keyboard_event (PortableServer_Servant           servant,
    */
   
   gdk_error_trap_push ();
-  key_synth_code = keycode;
+
+  priv = (DEControllerPrivateData *) 
+      g_object_get_qdata (G_OBJECT (controller), spi_dec_private_quark);
+
+  if (!priv->have_xkb && xmkeymap==NULL) {
+    xmkeymap = XGetModifierMapping(spi_get_display ());
+  }
 
   switch (synth_type)
     {
@@ -2107,9 +2329,9 @@ impl_generate_keyboard_event (PortableServer_Servant           servant,
                               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;
@@ -2202,7 +2424,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; 
 }
 
@@ -2217,7 +2441,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
@@ -2244,15 +2469,12 @@ spi_device_event_controller_class_init (SpiDEControllerClass *klass)
 }
 
 #ifdef HAVE_XEVIE
-Bool isEvent(dpy,event,arg)
-     Display *dpy;
-     XEvent *event;
-     char *arg;
+static Bool isEvent(Display *dpy, XEvent *event, char *arg)
 {
    return TRUE;
 }
 
-gboolean
+static gboolean
 handle_io (GIOChannel *source,
            GIOCondition condition,
            gpointer data) 
@@ -2327,6 +2549,7 @@ spi_device_event_controller_forward_key_event (SpiDEController *controller,
 {
   CORBA_Environment ev;
   Accessibility_DeviceEvent key_event;
+  gboolean ret;
 
   g_assert (event->type == KeyPress || event->type == KeyRelease);
 
@@ -2338,7 +2561,9 @@ spi_device_event_controller_forward_key_event (SpiDEController *controller,
     spi_controller_update_key_grabs (controller, &key_event);
 
   /* relay to listeners, and decide whether to consume it or not */
-  return spi_controller_notify_keylisteners (controller, &key_event, CORBA_TRUE, &ev);
+  ret = spi_controller_notify_keylisteners (controller, &key_event, CORBA_TRUE, &ev);
+  CORBA_free(key_event.event_string);
+  return ret;
 }
 
 SpiDEController *
@@ -2360,7 +2585,6 @@ is_key_released (KeyCode code)
 {
   char keys[32];
   int down;
-  int i;
 
   XQueryKeymap (spi_get_display (), keys);
   down = BIT (keys, code);