2008-08-27 Mark Doffman <mark.doffman@codethink.co.uk>
[platform/core/uifw/at-spi2-atk.git] / atk-adaptor / bridge.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2001, 2002, 2003 Sun Microsystems Inc.,
6  * Copyright 2001, 2002, 2003 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 #include "config.h"
25 #include "dbus/dbus-glib-lowlevel.h"
26
27 #include <X11/Xlib.h>
28 #include <X11/Xatom.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <unistd.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <atk/atk.h>
35 #include <atk/atkobject.h>
36 #include <atk/atknoopobject.h>
37 #include "accessible.h"
38
39 #undef SPI_BRIDGE_DEBUG
40
41 #define DBG(a,b) if(_dbg>=(a))b
42
43 #define bridge_threads_leave() \
44   if (!during_init_shutdown && !g_main_context_is_owner (NULL)) atk_misc_threads_leave(misc);
45 #define bridge_threads_enter() \
46   if (!during_init_shutdown && !g_main_context_is_owner (NULL)) atk_misc_threads_enter(misc);
47
48 typedef struct _SpiAppData SpiAppData;
49 struct _SpiAppData
50 {
51   AtkObject *root;
52   DRouteData droute;
53 };
54
55 int _dbg = 0;
56 static const char *registry = NULL;
57 static char *device_event_controller = NULL;
58 static SpiAppData *this_app = NULL;
59 static gboolean registry_died = FALSE;
60 static gboolean atk_listeners_registered = FALSE;
61 static gint toplevels = 0;
62 static gboolean exiting = FALSE;
63 static AtkMisc *misc = NULL;
64 static gboolean during_init_shutdown = TRUE;
65
66 static guint atk_signal_text_changed;
67 static guint atk_signal_children_changed;
68 static guint atk_signal_active_descendant_changed;
69 static guint atk_signal_text_selection_changed;
70
71 /* NOT YET USED
72    static guint atk_signal_row_reordered;
73    static guint atk_signal_row_inserted;
74    static guint atk_signal_row_deleted;
75    static guint atk_signal_column_reordered;
76    static guint atk_signal_column_inserted;
77    static guint atk_signal_column_deleted;
78 */
79
80 static guint atk_signal_link_selected;
81 static guint atk_signal_bounds_changed;
82
83 static const char *spi_atk_bridge_get_registry (void);
84 static gboolean spi_atk_bridge_do_registration         (void);
85 static void     spi_atk_bridge_toplevel_added          (AtkObject             *object,
86                                                         guint                 index,
87                                                         AtkObject             *child);
88 static void     spi_atk_bridge_toplevel_removed        (AtkObject             *object,
89                                                         guint                 index,
90                                                         AtkObject             *child);
91
92 static void     spi_atk_bridge_exit_func               (void);
93 static void     spi_atk_register_event_listeners       (void);
94 static void     spi_atk_bridge_focus_tracker           (AtkObject             *object);
95 static gchar   *spi_atk_bridge_get_registry_ior        (void);
96 static void     spi_atk_bridge_register_application    (const char *registry);
97 static gboolean spi_atk_bridge_property_event_listener (GSignalInvocationHint *signal_hint,
98                                                         guint                  n_param_values,
99                                                         const GValue          *param_values,
100                                                         gpointer               data);
101
102 static gboolean
103 spi_atk_bridge_window_event_listener (GSignalInvocationHint *signal_hint,
104                                 guint n_param_values,
105                                 const GValue *param_values,
106                                 gpointer data);
107 static gboolean
108 spi_atk_bridge_document_event_listener (GSignalInvocationHint *signal_hint,
109                                 guint n_param_values,
110                                 const GValue *param_values,
111                                 gpointer data);
112 static gboolean
113 spi_atk_bridge_state_event_listener (GSignalInvocationHint *signal_hint,
114                                      guint n_param_values,
115                                      const GValue *param_values,
116                                      gpointer data);
117 static gboolean spi_atk_bridge_signal_listener         (GSignalInvocationHint *signal_hint,
118                                                         guint                  n_param_values,
119                                                         const GValue          *param_values,
120                                                         gpointer               data);
121 static gint     spi_atk_bridge_key_listener            (AtkKeyEventStruct     *event,
122                                                         gpointer               data);
123 static void     spi_atk_tidy_windows                   (void);
124 static void     deregister_application                 (SpiAppData *app);
125 static void reinit_register_vars (void);
126
127 /* For automatic libgnome init */
128 extern void gnome_accessibility_module_init     (void);
129 extern void gnome_accessibility_module_shutdown (void);
130
131 static int     atk_bridge_initialized = FALSE;
132 static pid_t   atk_bridge_pid = 0;
133 static guint   atk_bridge_focus_tracker_id = 0;
134 static guint   atk_bridge_key_event_listener_id = 0;
135 static GArray *listener_ids = NULL;
136
137 /*
138  *   These exported symbols are hooked by gnome-program
139  * to provide automatic module initialization and shutdown.
140  */
141 extern void gnome_accessibility_module_init     (void);
142 extern void gnome_accessibility_module_shutdown (void);
143
144 static void
145 spi_atk_bridge_init_event_type_consts ()
146 {
147   static gboolean done = FALSE;
148
149   if (done)
150     return;
151
152   atk_signal_children_changed = g_signal_lookup ("children_changed", 
153                                               ATK_TYPE_OBJECT);
154   atk_signal_text_changed = g_signal_lookup ("text_changed", 
155                                              ATK_TYPE_TEXT);
156   atk_signal_bounds_changed = g_signal_lookup ("bounds_changed", 
157                                               ATK_TYPE_COMPONENT);
158   atk_signal_active_descendant_changed = 
159          g_signal_lookup ("active_descendant_changed", 
160                           ATK_TYPE_OBJECT); 
161   atk_signal_link_selected = g_signal_lookup ("link_selected", 
162                                               ATK_TYPE_HYPERTEXT);
163   atk_signal_text_selection_changed = g_signal_lookup ("text_selection_changed", 
164                                               ATK_TYPE_TEXT);
165   done = TRUE;
166 }
167
168 static gboolean
169 post_init (gpointer data)
170 {
171   during_init_shutdown = FALSE;
172   return FALSE;
173 }
174
175 static DBusObjectPathVTable droute_vtable =
176 {
177   NULL,
178   &droute_message,
179   NULL, NULL, NULL, NULL
180 };
181
182 static gchar* atspi_dbus_name;
183 static gboolean atspi_no_register; 
184
185 static GOptionEntry atspi_option_entries[] = 
186 {
187   {"atspi-dbus-name", 0, 0, G_OPTION_ARG_STRING, &atspi_dbus_name, "D-Bus bus name to register as", NULL},
188   {"atspi-no-register", 0, 0, G_OPTION_ARG_NONE, &atspi_no_register, "Do not register with Registry Daemon", NULL},
189   {NULL}
190 };
191
192 static SpiAppData *
193 spi_app_init (AtkObject *root, gint *argc, gchar **argv[])
194 {
195   GOptionContext *opt;
196   SpiAppData *ad = g_new0(SpiAppData, 1);
197   GError *err = NULL;
198   DBusError error;
199   int i;
200
201   opt = g_option_context_new(NULL);
202   g_option_context_add_main_entries(opt, atspi_option_entries, NULL);
203   g_option_context_set_ignore_unknown_options(opt, TRUE);
204   if (!g_option_context_parse(opt, argc, argv, &err))
205       g_warning("Option parsing failed: %s\n", err->message);
206
207   dbus_error_init(&error);
208   ad->root = root;
209   ad->droute.bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
210   g_print("D-Bus unique name is : %s\n", dbus_bus_get_unique_name(ad->droute.bus));
211
212   if (!ad->droute.bus)
213   {
214     g_warning("Couldn't connect to dbus: %s\n", error.message);
215     free(ad);
216     return NULL;
217   }
218   if (atspi_dbus_name != NULL && dbus_bus_request_name(ad->droute.bus, 
219                                                        atspi_dbus_name,
220                                                        0,
221                                                        &error))
222   {
223     g_print("\nRecieved D-Bus name - %s\n", atspi_dbus_name);
224   }
225   spi_register_tree_object(ad->droute.bus, &ad->droute, "/org/freedesktop/atspi/tree");
226   if (!dbus_connection_try_register_fallback (ad->droute.bus, 
227                                               "/org/freedesktop/atspi/accessible", 
228                                               &droute_vtable, 
229                                               &ad->droute, 
230                                               &error))
231   {
232     g_warning("Couldn't register droute.\n");
233     free(ad);
234     return NULL;
235   }
236
237   dbus_connection_setup_with_g_main(ad->droute.bus, g_main_context_default());
238
239   spi_dbus_initialize (&ad->droute);
240   return ad;
241 }
242
243 static int
244 atk_bridge_init (gint *argc, gchar **argv[])
245 {
246   const char *debug_env_string = g_getenv ("AT_SPI_DEBUG");
247   gchar *fname;
248   gboolean success = FALSE;
249
250   if (atk_bridge_initialized)
251     {
252       return 0;
253     }
254   atk_bridge_initialized = TRUE;
255   atk_bridge_pid = getpid ();
256
257   misc = atk_misc_get_instance();
258
259   if (g_getenv ("ATK_BRIDGE_REDIRECT_LOG"))
260     {
261       fname = g_strconcat ("/tmp/", g_get_prgname (), ".at-spi-log", NULL);
262       /* make sure we're not being redirected - security issue */
263       if (!g_file_test (fname, G_FILE_TEST_IS_SYMLINK))
264           freopen (fname, "w", stderr);
265       g_free (fname);
266     }
267
268   if (debug_env_string) 
269       _dbg = (int) g_ascii_strtod (debug_env_string, NULL);
270
271   /* Connect to dbus */
272   this_app = spi_app_init (atk_get_root (), argc, argv);
273
274   /*
275    * We only want to enable the bridge for top level
276    * applications, we detect bonobo components by seeing
277    * if they were activated with the intention of extracting
278    * an impl. by IID - very solid.
279    */
280 #ifdef WITH_BONOBO
281   // TODO: Figure out if this is still needed
282   if (bonobo_activation_iid_get ())
283 #else
284   if (0)
285 #endif
286     {
287       DBG (1, g_message ("Found Bonobo component\n"));
288       g_signal_connect (atk_get_root (), 
289                         "children-changed::add",
290                         (GCallback) spi_atk_bridge_toplevel_added, 
291                         NULL);
292       g_signal_connect (atk_get_root (), 
293                         "children-changed::remove",
294                         (GCallback) spi_atk_bridge_toplevel_removed, 
295                         NULL);
296       /* in this case we redefine 'success' to mean 'registry is present' */
297       success = (spi_atk_bridge_get_registry () != NULL);
298     }
299   else
300     {
301       success = spi_atk_bridge_do_registration ();
302     }
303   /*
304    * we must emit events even if we are not registered as a
305    * full-fledged app; See bugzilla #400709.
306    */
307   if (success) 
308     {
309       spi_atk_register_event_listeners ();
310       spi_atk_bridge_init_event_type_consts ();
311     }
312   else
313     {
314       atk_bridge_initialized = FALSE;
315     }
316   g_idle_add (post_init, NULL);
317
318   return 0;
319 }
320
321 static gboolean
322 spi_atk_bridge_do_registration (void)
323 {
324   if (spi_atk_bridge_get_registry () == NULL)
325     {
326       g_warning ("Could not locate registry");
327       return FALSE;
328     }
329
330   /* Create the accessible application server object */
331   if (this_app == NULL)
332     this_app = spi_app_init (atk_get_root (), 0, NULL);
333
334   DBG (1, g_message ("About to register application\n"));
335
336   spi_atk_bridge_register_application (spi_atk_bridge_get_registry ());
337   
338   g_atexit (spi_atk_bridge_exit_func);
339
340   DBG (1, g_message ("Application registered & listening\n"));
341   return TRUE;
342 }
343
344 static void
345 spi_atk_bridge_toplevel_added (AtkObject *object,
346                                guint     index,
347                                AtkObject *child)
348 {
349   if (toplevels == 0)
350     {
351       spi_atk_bridge_do_registration ();
352     }
353   toplevels++;
354 }
355
356 static void
357 spi_atk_bridge_toplevel_removed (AtkObject *object,
358                                  guint     index,
359                                  AtkObject *child)
360 {
361   toplevels--;
362   if (toplevels == 0)
363     {
364       deregister_application (this_app);
365       reinit_register_vars ();
366     }
367   if (toplevels < 0)
368     {
369       g_warning ("More toplevels removed than added\n");
370       toplevels = 0;
371     }
372 }
373
374 static void
375 spi_atk_bridge_register_application (const char *registry)
376 {
377   DBusMessage *message, *reply;
378   DBusError error;
379
380   bridge_threads_leave ();
381   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY, SPI_DBUS_PATH_REGISTRY, SPI_DBUS_INTERFACE_REGISTRY, "registerApplication");
382   dbus_error_init (&error);
383   reply = dbus_connection_send_with_reply_and_block(this_app->droute.bus, message, 1000, &error);
384   if (error.message) g_warning (error.message);
385   if (reply) dbus_message_unref (reply);
386   if (message) dbus_message_unref (message);
387   bridge_threads_enter ();
388 }
389
390 /* 
391  * Returns a 'canonicalized' value for DISPLAY,
392  * with the screen number stripped off if present.
393  */
394 static const gchar*
395 spi_display_name (void)
396 {
397     static const char *canonical_display_name = NULL;
398     if (!canonical_display_name)
399       {
400         const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
401         if (!display_env)
402           {
403             display_env = g_getenv ("DISPLAY");
404             if (!display_env || !display_env[0]) 
405                 canonical_display_name = ":0";
406             else
407               {
408                 gchar *display_p, *screen_p;
409                 canonical_display_name = g_strdup (display_env);
410                 display_p = strrchr (canonical_display_name, ':');
411                 screen_p = strrchr (canonical_display_name, '.');
412                 if (screen_p && display_p && (screen_p > display_p))
413                   {
414                     *screen_p = '\0';
415                   }
416               }
417           }
418         else
419           {
420             canonical_display_name = display_env;
421           }
422       }
423     return canonical_display_name;
424 }
425
426 static     Display *bridge_display = NULL;
427
428 static gchar *
429 spi_atk_bridge_get_registry_ior (void)
430 {
431      
432      Atom AT_SPI_IOR;
433      Atom actual_type;
434      int actual_format;
435      unsigned char *data = NULL;  
436      unsigned long nitems;
437      unsigned long leftover;
438      if (!bridge_display) 
439        bridge_display = XOpenDisplay (spi_display_name ());
440
441      AT_SPI_IOR = XInternAtom (bridge_display, "AT_SPI_IOR", False); 
442      XGetWindowProperty(bridge_display, 
443                         XDefaultRootWindow (bridge_display),
444                         AT_SPI_IOR, 0L, 
445                         (long)BUFSIZ, False, 
446                         (Atom) 31, &actual_type, &actual_format,
447                         &nitems, &leftover, &data);
448      if (data == NULL)
449           g_warning (_("AT_SPI_REGISTRY was not started at session startup."));
450      
451      return (gchar *) data;
452      
453 }
454
455
456 static const char *
457 spi_atk_bridge_get_registry (void)
458 {
459   // TODO: check for registry dying, as the old code attempted to do
460   return "org.freedesktop.atspi.registry";
461 }
462
463 static const char *
464 spi_atk_bridge_get_dec (void)
465 {
466   return "/dec";
467 }
468
469 int
470 gtk_module_init (gint *argc, gchar **argv[])
471 {
472         //printf("Pointer to argc %x %x\n", (short) ((argc && 0xffff0000) >> 16), (short) (argc && 0xffff));
473         return atk_bridge_init (argc, argv);
474 }
475
476 static void
477 add_signal_listener (const char *signal_name)
478 {
479   guint id;
480
481   id = atk_add_global_event_listener (
482     spi_atk_bridge_signal_listener, signal_name);
483
484   g_array_append_val (listener_ids, id);
485 }
486
487 static void
488 spi_atk_register_event_listeners (void)
489 {
490   /*
491    * kludge to make sure the Atk interface types are registered, otherwise
492    * the AtkText signal handlers below won't get registered
493    */
494   guint      id;
495   GObject   *ao = g_object_new (ATK_TYPE_OBJECT, NULL);
496   AtkObject *bo = atk_no_op_object_new (ao);
497
498
499   if (atk_listeners_registered) 
500     {
501       g_object_unref (G_OBJECT (bo));
502       g_object_unref (ao);
503       return;
504     }
505
506   atk_listeners_registered = TRUE;
507
508   /* Register for focus event notifications, and register app with central registry  */
509
510   listener_ids = g_array_sized_new (FALSE, TRUE, sizeof (guint), 16);
511
512   atk_bridge_focus_tracker_id = atk_add_focus_tracker (spi_atk_bridge_focus_tracker);
513
514   id = atk_add_global_event_listener (spi_atk_bridge_property_event_listener,
515                                       "Gtk:AtkObject:property-change");
516   g_array_append_val (listener_ids, id);
517   id = atk_add_global_event_listener (spi_atk_bridge_window_event_listener,
518                                       "window:create");
519   g_array_append_val (listener_ids, id);
520   id = atk_add_global_event_listener (spi_atk_bridge_window_event_listener,
521                                       "window:destroy");
522   g_array_append_val (listener_ids, id);
523   id = atk_add_global_event_listener (spi_atk_bridge_window_event_listener,
524                                       "window:minimize");
525   g_array_append_val (listener_ids, id);
526   id = atk_add_global_event_listener (spi_atk_bridge_window_event_listener,
527                                       "window:maximize");
528   g_array_append_val (listener_ids, id);
529   id = atk_add_global_event_listener (spi_atk_bridge_window_event_listener,
530                                       "window:restore");
531   g_array_append_val (listener_ids, id);
532   id = atk_add_global_event_listener (spi_atk_bridge_window_event_listener,
533                                       "window:activate");
534   g_array_append_val (listener_ids, id);
535   id = atk_add_global_event_listener (spi_atk_bridge_window_event_listener,
536                                       "window:deactivate");
537   g_array_append_val (listener_ids, id);
538   id = atk_add_global_event_listener (spi_atk_bridge_document_event_listener,
539                                       "Gtk:AtkDocument:load-complete");
540   g_array_append_val (listener_ids, id);
541   id = atk_add_global_event_listener (spi_atk_bridge_document_event_listener,
542                                       "Gtk:AtkDocument:reload");
543   g_array_append_val (listener_ids, id);
544   id = atk_add_global_event_listener (spi_atk_bridge_document_event_listener,
545                                       "Gtk:AtkDocument:load-stopped");
546   g_array_append_val (listener_ids, id);
547   id = atk_add_global_event_listener (spi_atk_bridge_state_event_listener,
548                                       "Gtk:AtkObject:state-change");
549   g_array_append_val (listener_ids, id);
550
551   add_signal_listener ("Gtk:AtkObject:children-changed");
552   add_signal_listener ("Gtk:AtkObject:visible-data-changed");
553   add_signal_listener ("Gtk:AtkObject:active-descendant-changed");
554   add_signal_listener ("Gtk:AtkComponent:bounds-changed");
555   add_signal_listener ("Gtk:AtkSelection:selection-changed");
556   add_signal_listener ("Gtk:AtkText:text-selection-changed");
557   add_signal_listener ("Gtk:AtkText:text-changed");
558   add_signal_listener ("Gtk:AtkText:text-caret-moved");
559   add_signal_listener ("Gtk:AtkTable:row-inserted");
560   add_signal_listener ("Gtk:AtkTable:row-reordered");
561   add_signal_listener ("Gtk:AtkTable:row-deleted");
562   add_signal_listener ("Gtk:AtkTable:column-inserted");
563   add_signal_listener ("Gtk:AtkTable:column-reordered");
564   add_signal_listener ("Gtk:AtkTable:column-deleted");
565   add_signal_listener ("Gtk:AtkTable:model-changed");
566   add_signal_listener ("Gtk:AtkHypertext:link-selected");
567 /*
568  * May add the following listeners to implement preemptive key listening for GTK+
569  *
570  * atk_add_global_event_listener (spi_atk_bridge_widgetkey_listener, "Gtk:GtkWidget:key-press-event");
571  * atk_add_global_event_listener (spi_atk_bridge_widgetkey_listener, "Gtk:GtkWidget:key-release-event");
572  */
573   atk_bridge_key_event_listener_id = atk_add_key_event_listener (
574     spi_atk_bridge_key_listener, NULL);
575   
576   g_object_unref (G_OBJECT (bo));
577   g_object_unref (ao);
578 }
579
580 static void
581 deregister_application (SpiAppData *app)
582 {
583   const char *registry = spi_atk_bridge_get_registry ();
584   bridge_threads_leave ();
585   // todo: deregister
586   bridge_threads_enter ();
587 }
588
589 static void
590 spi_atk_bridge_exit_func (void)
591 {
592   SpiAppData *app = (SpiAppData *) this_app;
593
594   DBG (1, g_message ("exiting bridge\n"));
595
596   if (!app)
597     {
598       return;
599     }
600   if (atk_bridge_pid != getpid ())
601     {
602       _exit (0);
603     }
604
605   during_init_shutdown = TRUE;
606   exiting = TRUE;
607   /*
608    * Check whether we still have windows which have not been deleted.
609    */
610   spi_atk_tidy_windows ();
611   /*
612    *  FIXME: this may be incorrect for apps that do their own bonobo
613    *  shutdown, until we can explicitly shutdown to get the ordering
614    *  right.
615    */
616   if (!registry_died)
617     deregister_application (this_app);
618   this_app = NULL;
619   DBG (1, g_message ("bridge exit func complete.\n"));
620
621   if (g_getenv ("AT_BRIDGE_SHUTDOWN"))
622     {
623     }
624   if (bridge_display)
625     XCloseDisplay (bridge_display);
626 }
627
628 void
629 gnome_accessibility_module_init (void)
630 {
631   atk_bridge_init (0, NULL);
632
633   if (g_getenv ("AT_BRIDGE_SHUTDOWN"))
634     {
635         g_print("Atk Accessibility bridge initialized\n");
636     }
637 }
638
639 void
640 gnome_accessibility_module_shutdown (void)
641 {
642   int     i;
643   GArray *ids = listener_ids;
644   
645   if (!atk_bridge_initialized)
646     {
647       return;
648     }
649   during_init_shutdown = TRUE;
650   atk_bridge_initialized = FALSE;
651
652   if (g_getenv ("AT_BRIDGE_SHUTDOWN"))
653     {
654         g_print("Atk Accessibility bridge shutdown\n");
655     }
656
657   listener_ids = NULL;
658   if (atk_bridge_focus_tracker_id)
659         atk_remove_focus_tracker (atk_bridge_focus_tracker_id);
660   
661   for (i = 0; ids && i < ids->len; i++)
662     {
663           atk_remove_global_event_listener (g_array_index (ids, guint, i));
664     }
665   
666   if (atk_bridge_key_event_listener_id)
667           atk_remove_key_event_listener (atk_bridge_key_event_listener_id);
668
669   deregister_application (this_app);
670   this_app = NULL;
671
672   misc = NULL;
673 }
674
675 static void emit(AtkObject *object,
676                  const char *name,
677                  const char *detail,
678                  dbus_int32_t detail1,
679                  dbus_int32_t detail2,
680                  int type,
681                  const void *val)
682 {
683   DBusMessage *sig;
684   char *path = spi_dbus_get_path(object);
685   DBusMessageIter iter, sub;
686   const char *type_as_string = NULL;
687   dbus_int32_t dummy = 0;
688
689   spi_dbus_update_cache(&this_app->droute);
690   if (type == DBUS_TYPE_OBJECT_PATH)
691   {
692     type_as_string = "o";
693     if (!val) val = "";
694   }
695   else if (type == DBUS_TYPE_STRING)
696   {
697     type_as_string = "s";
698     if (!val) val = "";
699   }
700   else if (type == DBUS_TYPE_INT32) type_as_string = "i";
701   else if (type == DBUS_TYPE_UINT32) type_as_string = "u";
702   else if (type == DBUS_TYPE_INVALID)
703   {
704     type = DBUS_TYPE_UINT32;
705     type_as_string = "u";
706     if (!val) val = &dummy;
707   }
708   else
709   {
710     g_warning("Unknown type %d in property change signal", type);
711   }
712   sig = dbus_message_new_signal(path, SPI_DBUS_INTERFACE_ACCESSIBLE, name);
713   dbus_message_iter_init_append(sig, &iter);
714   if (!detail) detail = "";
715   dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &detail);
716   dbus_message_iter_append_basic(&iter, DBUS_TYPE_INT32, &detail1);
717   dbus_message_iter_append_basic(&iter, DBUS_TYPE_INT32, &detail2);
718   dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, type_as_string, &sub);
719   dbus_message_iter_append_basic(&sub, type, &val);
720   dbus_message_iter_close_container(&iter, &sub);
721   dbus_connection_send(this_app->droute.bus, sig, NULL);
722   g_free(path);
723   dbus_message_unref(sig);
724 }
725
726 static void
727 spi_atk_bridge_focus_tracker (AtkObject *object)
728 {
729   emit(object, "focus", NULL, 0, 0, DBUS_TYPE_INVALID, NULL);
730 }
731
732 static void emit_rect(AtkObject *object, const char *name, const char *detail, AtkRectangle *rect)
733 {
734   DBusMessage *sig;
735   char *path = spi_dbus_get_path(object);
736   DBusMessageIter iter, iter_variant, sub;
737   dbus_uint32_t x, y, width, height;
738   dbus_int32_t dummy = 0;
739
740   spi_dbus_update_cache(&this_app->droute);
741   x = rect->x;
742   y = rect->y;
743   width = rect->width;
744   height = rect->height;
745   sig = dbus_message_new_signal(path, SPI_DBUS_INTERFACE_ACCESSIBLE, name);
746   if (!detail) detail = "";
747   if (sig)
748     {
749       dbus_message_iter_init_append (sig, &iter);
750       dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &detail);
751       dbus_message_iter_append_basic (&iter, DBUS_TYPE_INT32, &dummy);
752       dbus_message_iter_append_basic (&iter, DBUS_TYPE_INT32, &dummy);
753       if (!dbus_message_iter_open_container (&iter, DBUS_TYPE_VARIANT, "(iiii)", &iter_variant))
754         goto oom;
755       if (!dbus_message_iter_open_container (&iter_variant, DBUS_TYPE_STRUCT, NULL, &sub))
756         goto oom;
757       dbus_message_iter_append_basic (&sub, DBUS_TYPE_INT32, &x);
758       dbus_message_iter_append_basic (&sub, DBUS_TYPE_INT32, &y);
759       dbus_message_iter_append_basic (&sub, DBUS_TYPE_INT32, &width);
760       dbus_message_iter_append_basic (&sub, DBUS_TYPE_INT32, &height);
761       if (!dbus_message_iter_close_container (&iter_variant, &sub))
762         goto oom;
763       if (!dbus_message_iter_close_container (&iter, &iter_variant))
764         goto oom;
765     }
766   dbus_connection_send(this_app->droute.bus, sig, NULL);
767 oom:
768   g_free(path);
769   dbus_message_unref(sig);
770 }
771
772 static const char *PropertyChange = "object_property_change";
773
774 static gboolean
775 spi_atk_bridge_property_event_listener (GSignalInvocationHint *signal_hint,
776                                         guint n_param_values,
777                                         const GValue *param_values,
778                                         gpointer data)
779 {
780   AtkPropertyValues *values;
781   AtkObject *obj;
782   const gchar *prop_name;
783   const gchar *sp = NULL;
784   AtkObject *ao;
785   char *s_ao = NULL;
786   gint i;
787   const gchar *name = NULL;
788
789 #ifdef SPI_BRIDGE_DEBUG
790   GSignalQuery signal_query;
791   const gchar *signame;
792   const gchar *s, *s2;
793   
794   g_signal_query (signal_hint->signal_id, &signal_query);
795   signame = signal_query.signal_name;
796
797   s2 = g_type_name (G_OBJECT_TYPE (g_value_get_object (param_values + 0)));
798   s = atk_object_get_name (ATK_OBJECT (g_value_get_object (param_values + 0)));
799   values = (AtkPropertyValues*) g_value_get_pointer (param_values + 1);
800   DBG (2, g_message ("Received (property) signal %s:%s:%s from object %s (gail %s)\n",
801            g_type_name (signal_query.itype), signame, values->property_name, s, s2));
802   
803 #endif
804
805   obj = g_value_get_object (param_values + 0);
806   name = atk_object_get_name (obj);
807   values = (AtkPropertyValues*) g_value_get_pointer (param_values + 1);
808
809   prop_name = values->property_name;
810   if (strcmp (prop_name, "accessible-name") == 0)
811     {
812       spi_dbus_notify_change(obj, FALSE, &this_app->droute);
813     }
814   else if (strcmp (prop_name, "accessible-description") == 0)
815     {
816       spi_dbus_notify_change(obj, FALSE, &this_app->droute);
817     }
818   else if (strcmp (prop_name, "accessible-parent") == 0)
819     {
820       spi_dbus_notify_change(obj, FALSE, &this_app->droute);
821     }
822   else if (strcmp (prop_name, "accessible-table-summary") == 0)
823     {
824       ao = atk_table_get_summary (ATK_TABLE (obj));
825       s_ao = spi_dbus_get_path(ao);
826       emit(obj, PropertyChange, prop_name, 0, 0, DBUS_TYPE_OBJECT_PATH, s_ao);
827     }
828   else if (strcmp (prop_name, "accessible-table-column-header") == 0)
829     {
830       i = g_value_get_int (&(values->new_value));
831       ao = atk_table_get_column_header (ATK_TABLE (obj), i);
832       s_ao = spi_dbus_get_path(ao);
833       emit(obj, PropertyChange, prop_name, 0, 0, DBUS_TYPE_OBJECT_PATH, s_ao);
834     }
835   else if (strcmp (prop_name, "accessible-table-row-header") == 0)
836     {
837       i = g_value_get_int (&(values->new_value));
838       ao = atk_table_get_row_header (ATK_TABLE (obj), i);
839       s_ao = spi_dbus_get_path(ao);
840       emit(obj, PropertyChange, prop_name, 0, 0, DBUS_TYPE_OBJECT_PATH, s_ao);
841     }
842   else if (strcmp (prop_name, "accessible-table-row-description") == 0)
843     {
844       i = g_value_get_int (&(values->new_value));
845       sp = atk_table_get_row_description (ATK_TABLE (obj), i);
846       emit(obj, PropertyChange, prop_name, 0, 0, DBUS_TYPE_STRING, sp);
847     }
848   else if (strcmp (prop_name, "accessible-table-column-description") == 0)
849     {
850       i = g_value_get_int (&(values->new_value));
851       sp = atk_table_get_column_description (ATK_TABLE(obj), i);
852       emit(obj, PropertyChange, prop_name, 0, 0, DBUS_TYPE_STRING, sp);
853     }
854   else if (strcmp (prop_name, "accessible-table-caption-object") == 0)
855     {
856       ao = atk_table_get_caption (ATK_TABLE(obj));
857       sp = atk_object_get_name (ao);
858       emit(obj, PropertyChange, prop_name, 0, 0, DBUS_TYPE_STRING, sp);
859     }
860   else
861     {
862       emit(obj, PropertyChange, prop_name, 0, 0, DBUS_TYPE_INVALID, NULL);
863     }
864   if (s_ao) g_free(s_ao);
865   return TRUE;
866 }
867
868 static gboolean
869 spi_atk_bridge_state_event_listener (GSignalInvocationHint *signal_hint,
870                                      guint n_param_values,
871                                      const GValue *param_values,
872                                      gpointer data)
873 {
874   AtkObject *obj;
875   gchar *property_name;
876   unsigned long detail1;
877 #ifdef SPI_BRIDGE_DEBUG
878   GSignalQuery signal_query;
879   const gchar *name;
880   
881   g_signal_query (signal_hint->signal_id, &signal_query);
882   name = signal_query.signal_name;
883   fprintf (stderr, "Received (state) signal %s:%s\n",
884            g_type_name (signal_query.itype), name);
885 #endif
886
887   obj = ATK_OBJECT(g_value_get_object (param_values + 0));
888   property_name = g_strdup (g_value_get_string (param_values + 1));
889   /* Ignore defunct for now; we'll send a tree update to remove it when
890      the object goes away */
891   /* Also ignore state changes for objects not yet broadcast */
892   if ((property_name && !strcmp(property_name, "defunct")) ||
893       !spi_dbus_object_is_known(obj))
894   {
895     g_free(property_name);
896     return TRUE;
897   }
898   detail1 = (g_value_get_boolean (param_values + 2))
899     ? 1 : 0;
900   emit(obj, "object_state_changed", property_name, detail1, 0, DBUS_TYPE_INVALID, NULL);
901   g_free (property_name);
902   return TRUE;
903 }
904
905 static void
906 spi_init_keystroke_from_atk_key_event (Accessibility_DeviceEvent  *keystroke,
907                                        AtkKeyEventStruct          *event)
908 {
909 #ifdef SPI_DEBUG
910   if (event)
911     {
912       g_print ("event %c (%d)\n", (int) event->keyval, (int) event->keycode);
913     }
914   else
915 #endif
916   if (!event)
917     { /* this doesn't really need translating */
918       g_print (_("WARNING: NULL key event reported."));
919     }
920   
921   keystroke->id        = (dbus_int32_t) event->keyval;
922   keystroke->hw_code   = (dbus_int16_t) event->keycode;
923   keystroke->timestamp = (dbus_uint32_t) event->timestamp;
924   keystroke->modifiers = (dbus_uint16_t) (event->state & 0xFFFF);
925   if (event->string)
926     {
927       gunichar c;
928
929       keystroke->event_string = g_strdup (event->string);
930       c = g_utf8_get_char_validated (event->string, -1);
931       if (c > 0 && g_unichar_isprint (c))
932         keystroke->is_text = TRUE;
933       else
934         keystroke->is_text = FALSE;
935     }
936   else
937     {
938       keystroke->event_string = g_strdup ("");
939       keystroke->is_text = FALSE;
940     }
941   switch (event->type)
942     {
943     case (ATK_KEY_EVENT_PRESS):
944       keystroke->type = Accessibility_KEY_PRESSED_EVENT;
945       break;
946     case (ATK_KEY_EVENT_RELEASE):
947       keystroke->type = Accessibility_KEY_RELEASED_EVENT;
948       break;
949     default:
950       keystroke->type = 0;
951       break;
952     }
953 #if 0  
954   g_print ("key_event type %d; val=%d code=%d modifiers=%x name=%s is_text=%d, time=%lx\n",
955            (int) keystroke->type, (int) keystroke->id, (int) keystroke->hw_code,
956            (int) keystroke->modifiers,
957            keystroke->event_string, (int) keystroke->is_text, (unsigned long) keystroke->timestamp);
958 #endif
959 }
960
961 static gboolean Accessibility_DeviceEventController_notifyListenersSync(const Accessibility_DeviceEvent *key_event)
962 {
963   DBusMessage *message = dbus_message_new_method_call(SPI_DBUS_NAME_REGISTRY, SPI_DBUS_PATH_REGISTRY, SPI_DBUS_INTERFACE_DEC, "notifyListenersSync");
964   DBusError error;
965   dbus_bool_t consumed = FALSE;
966
967   dbus_error_init(&error);
968   if (spi_dbus_marshal_deviceEvent(message, key_event))
969   {
970     DBusMessage *reply = dbus_connection_send_with_reply_and_block(this_app->droute.bus, message, 1000, &error);
971     if (reply)
972     {
973       DBusError error;
974       dbus_error_init(&error);
975       dbus_message_get_args(reply, &error, DBUS_TYPE_BOOLEAN, &consumed, DBUS_TYPE_INVALID);
976       dbus_message_unref(reply);
977     }
978   }
979   dbus_message_unref(message);
980   return consumed;
981 }
982
983 static gint
984 spi_atk_bridge_key_listener (AtkKeyEventStruct *event, gpointer data)
985 {
986   gboolean             result;
987   Accessibility_DeviceEvent key_event;
988
989   spi_init_keystroke_from_atk_key_event (&key_event, event);
990
991   bridge_threads_leave ();
992   result = Accessibility_DeviceEventController_notifyListenersSync (&key_event);
993   bridge_threads_enter ();
994
995   if (key_event.event_string) g_free (key_event.event_string);
996
997   return result;
998 }
999
1000 static gboolean
1001 spi_atk_bridge_signal_listener (GSignalInvocationHint *signal_hint,
1002                                 guint n_param_values,
1003                                 const GValue *param_values,
1004                                 gpointer data)
1005 {
1006   AtkObject *obj;
1007   GSignalQuery signal_query;
1008   const gchar *name;
1009   const gchar *detail = NULL;
1010   char *sp = NULL;
1011   AtkObject *ao;
1012   gint detail1 = 0, detail2 = 0;
1013   char *s_ao = NULL;
1014   gchar *sig_name;
1015   char *p;
1016 #ifdef SPI_BRIDGE_DEBUG
1017   const gchar *s, *s2;
1018 #endif 
1019   
1020   g_signal_query (signal_hint->signal_id, &signal_query);
1021
1022   name = signal_query.signal_name;
1023   if (signal_hint->detail)
1024   {
1025     detail = g_quark_to_string (signal_hint->detail);
1026   }
1027   sig_name = g_strdup_printf("object_%s", name);
1028   while ((p = strchr(sig_name, '-')) != NULL) *p = '_';
1029
1030 #ifdef SPI_BRIDGE_DEBUG
1031   s2 = g_type_name (G_OBJECT_TYPE (g_value_get_object (param_values + 0)));
1032   s = atk_object_get_name (ATK_OBJECT (g_value_get_object (param_values + 0)));
1033   fprintf (stderr, "Received signal %s:%s detail: %s from object %s (gail %s)\n",
1034            g_type_name (signal_query.itype), name, 
1035            detail ? detail : "<NULL>", s ? s : "<NULL>" , s2);
1036 #endif
1037   
1038   obj = ATK_OBJECT(g_value_get_object (param_values + 0));
1039
1040   if (signal_query.signal_id == atk_signal_active_descendant_changed)
1041     {
1042       gpointer child = g_value_get_pointer (param_values + 1);
1043
1044       g_return_val_if_fail (ATK_IS_OBJECT (child), TRUE);
1045
1046       ao = ATK_OBJECT (child);
1047
1048       detail1 = atk_object_get_index_in_parent (ao);
1049       s_ao = spi_dbus_get_path(child);
1050       emit(obj, sig_name, detail, detail1, 0, DBUS_TYPE_OBJECT_PATH, s_ao);
1051       g_free(s_ao);
1052     }
1053   else if (signal_query.signal_id == atk_signal_link_selected)
1054     {
1055       if (G_VALUE_TYPE (param_values + 1) == G_TYPE_INT)
1056         detail1 = g_value_get_int (param_values + 1);
1057       emit(obj, sig_name, detail, detail1, 0, DBUS_TYPE_INVALID, NULL);
1058     }
1059   else if (signal_query.signal_id == atk_signal_bounds_changed)
1060     {
1061       AtkRectangle *atk_rect = NULL;
1062
1063       if (G_VALUE_HOLDS_BOXED (param_values + 1))
1064           atk_rect = g_value_get_boxed (param_values + 1);
1065       emit_rect(obj, sig_name, detail, atk_rect);
1066     }
1067   else if ((signal_query.signal_id == atk_signal_children_changed) && obj)
1068     {
1069       spi_dbus_notify_change(obj, FALSE, &this_app->droute);
1070     }
1071   else
1072     {
1073       if (n_param_values >= 2)
1074         {
1075           if (G_VALUE_TYPE (param_values + 1) == G_TYPE_INT)
1076             detail1 = g_value_get_int (param_values + 1);
1077           if (n_param_values >= 3)
1078             {
1079               if (G_VALUE_TYPE (param_values + 2) == G_TYPE_INT)
1080                 detail2 = g_value_get_int (param_values + 2);
1081             }
1082         }
1083
1084       if (signal_query.signal_id == atk_signal_text_changed)
1085         {
1086           sp = atk_text_get_text (ATK_TEXT (obj),
1087                                   detail1,
1088                                   detail1+detail2);
1089           emit(obj, sig_name, detail, detail1, detail2, DBUS_TYPE_STRING, sp);
1090         }
1091       else if (signal_query.signal_id == atk_signal_text_selection_changed)
1092         {
1093           /* Return NULL as the selected string */
1094           emit(obj, sig_name, detail, detail1, detail2, DBUS_TYPE_STRING, "");
1095         }
1096       else
1097         {
1098           emit(obj, sig_name, detail, 0, 0, DBUS_TYPE_INVALID, NULL);
1099         }
1100     }
1101
1102   if (sp) 
1103     g_free (sp);
1104
1105   if (s_ao)
1106      g_free (s_ao);
1107   g_free(sig_name);
1108
1109   return TRUE;
1110 }
1111
1112 static gboolean
1113 spi_atk_bridge_window_event_listener (GSignalInvocationHint *signal_hint,
1114                                       guint n_param_values,
1115                                       const GValue *param_values,
1116                                       gpointer data)
1117 {
1118   AtkObject *obj;
1119   GSignalQuery signal_query;
1120   const gchar *name, *s;
1121 #ifdef SPI_BRIDGE_DEBUG
1122   const gchar *s2;
1123 #endif
1124   
1125   g_signal_query (signal_hint->signal_id, &signal_query);
1126
1127   name = signal_query.signal_name;
1128   gchar *sig_name;
1129
1130 #ifdef SPI_BRIDGE_DEBUG
1131   s2 = g_type_name (G_OBJECT_TYPE (g_value_get_object (param_values + 0)));
1132   s = atk_object_get_name (ATK_OBJECT (g_value_get_object (param_values + 0)));
1133   fprintf (stderr, "Received signal %s:%s from object %s (gail %s)\n",
1134            g_type_name (signal_query.itype), name, s ? s : "<NULL>" , s2);
1135 #endif
1136   
1137   obj = ATK_OBJECT(g_value_get_object (param_values + 0));
1138
1139   s = atk_object_get_name (obj);
1140   sig_name = g_strdup_printf("window_%s", name);
1141   emit(obj, sig_name, NULL, 0, 0, DBUS_TYPE_STRING, s);
1142   g_free(sig_name);
1143
1144   return TRUE;
1145 }
1146
1147 static gboolean
1148 spi_atk_bridge_document_event_listener (GSignalInvocationHint *signal_hint,
1149                                       guint n_param_values,
1150                                       const GValue *param_values,
1151                                       gpointer data)
1152 {
1153   AtkObject *obj;
1154   GSignalQuery signal_query;
1155   const gchar *name, *s;
1156   gchar *sig_name;
1157 #ifdef SPI_BRIDGE_DEBUG
1158   const gchar *s2;
1159 #endif
1160
1161   g_signal_query (signal_hint->signal_id, &signal_query);
1162
1163   name = signal_query.signal_name;
1164
1165 #ifdef SPI_BRIDGE_DEBUG
1166   s2 = g_type_name (G_OBJECT_TYPE (g_value_get_object (param_values + 0)));
1167   s = atk_object_get_name (ATK_OBJECT (g_value_get_object (param_values + 0)));
1168   fprintf (stderr, "Received signal %s:%s from object %s (gail %s)\n",
1169            g_type_name (signal_query.itype), name, s ? s : "<NULL>" , s2);
1170 #endif
1171
1172   obj = ATK_OBJECT(g_value_get_object (param_values + 0));
1173
1174   s = atk_object_get_name (obj);
1175   sig_name = g_strdup_printf("document_%s", name);
1176   emit(obj, sig_name, NULL, 0, 0, DBUS_TYPE_STRING, s);
1177   g_free(sig_name);
1178   return TRUE;
1179 }
1180
1181 static void
1182 spi_atk_tidy_windows (void)
1183 {
1184   AtkObject *root;
1185   gint n_children;
1186   gint i;
1187
1188   root = atk_get_root ();
1189   n_children = atk_object_get_n_accessible_children (root);
1190   for (i = 0; i < n_children; i++)
1191     {
1192       AtkObject *child;
1193       AtkStateSet *stateset;
1194       const gchar *name;
1195      
1196       child = atk_object_ref_accessible_child (root, i);
1197       stateset = atk_object_ref_state_set (child);
1198       
1199       name = atk_object_get_name (child);
1200       if (atk_state_set_contains_state (stateset, ATK_STATE_ACTIVE))
1201         {
1202           emit(child, "window_deactivate", NULL, 0, 0, DBUS_TYPE_STRING, name);
1203         }
1204       g_object_unref (stateset);
1205
1206       emit(child, "window_destroy", NULL, 0, 0, DBUS_TYPE_STRING, name);
1207       g_object_unref (child);
1208     }
1209 }
1210
1211 static void
1212 reinit_register_vars (void)
1213 {
1214   registry = NULL;
1215   device_event_controller = NULL;
1216   this_app = NULL;
1217 }