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