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