misc: unref bus at the end of cleanup
[platform/upstream/at-spi2-core.git] / atspi / atspi-misc.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 Sun Microsystems Inc.,
6  * Copyright 2001, 2002 Ximian, Inc.
7  * Copyright 2010, 2011 Novell, Inc.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /*
26  *
27  * Basic SPI initialization and event loop function prototypes
28  *
29  */
30
31 #include "atspi-private.h"
32 #ifdef HAVE_X11
33 #include "X11/Xlib.h"
34 #endif
35 #include "atspi-gmain.h"
36 #include <stdio.h>
37 #include <string.h>
38
39 /* This value is not fixed, could be changed. */
40 #define HASH_TABLE_SIZE_MAX 1000
41
42 static void handle_get_items (DBusPendingCall *pending, void *user_data);
43
44 static DBusConnection *bus = NULL;
45 static GHashTable *live_refs = NULL;
46 static gint method_call_timeout = 800;
47 static gint app_startup_time = 15000;
48 static gboolean allow_sync = TRUE;
49
50 GMainLoop *atspi_main_loop;
51 GMainContext *atspi_main_context;
52 gboolean atspi_no_cache;
53
54 const char *atspi_path_dec = ATSPI_DBUS_PATH_DEC;
55 const char *atspi_path_registry = ATSPI_DBUS_PATH_REGISTRY;
56 const char *atspi_path_root = ATSPI_DBUS_PATH_ROOT;
57 const char *atspi_bus_registry = ATSPI_DBUS_NAME_REGISTRY;
58 const char *atspi_interface_accessible = ATSPI_DBUS_INTERFACE_ACCESSIBLE;
59 const char *atspi_interface_action = ATSPI_DBUS_INTERFACE_ACTION;
60 const char *atspi_interface_application = ATSPI_DBUS_INTERFACE_APPLICATION;
61 const char *atspi_interface_collection = ATSPI_DBUS_INTERFACE_COLLECTION;
62 const char *atspi_interface_component = ATSPI_DBUS_INTERFACE_COMPONENT;
63 const char *atspi_interface_dec = ATSPI_DBUS_INTERFACE_DEC;
64 const char *atspi_interface_device_event_listener = ATSPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER;
65 const char *atspi_interface_document = ATSPI_DBUS_INTERFACE_DOCUMENT;
66 const char *atspi_interface_editable_text = ATSPI_DBUS_INTERFACE_EDITABLE_TEXT;
67 const char *atspi_interface_event_object = ATSPI_DBUS_INTERFACE_EVENT_OBJECT;
68 const char *atspi_interface_hyperlink = ATSPI_DBUS_INTERFACE_HYPERLINK;
69 const char *atspi_interface_hypertext = ATSPI_DBUS_INTERFACE_HYPERTEXT;
70 const char *atspi_interface_image = ATSPI_DBUS_INTERFACE_IMAGE;
71 const char *atspi_interface_registry = ATSPI_DBUS_INTERFACE_REGISTRY;
72 const char *atspi_interface_selection = ATSPI_DBUS_INTERFACE_SELECTION;
73 const char *atspi_interface_table = ATSPI_DBUS_INTERFACE_TABLE;
74 const char *atspi_interface_table_cell = ATSPI_DBUS_INTERFACE_TABLE_CELL;
75 const char *atspi_interface_text = ATSPI_DBUS_INTERFACE_TEXT;
76 const char *atspi_interface_cache = ATSPI_DBUS_INTERFACE_CACHE;
77 const char *atspi_interface_value = ATSPI_DBUS_INTERFACE_VALUE;
78
79 static const char *interfaces[] =
80 {
81   ATSPI_DBUS_INTERFACE_ACCESSIBLE,
82   ATSPI_DBUS_INTERFACE_ACTION,
83   ATSPI_DBUS_INTERFACE_APPLICATION,
84   ATSPI_DBUS_INTERFACE_COLLECTION,
85   ATSPI_DBUS_INTERFACE_COMPONENT,
86   ATSPI_DBUS_INTERFACE_DOCUMENT,
87   ATSPI_DBUS_INTERFACE_EDITABLE_TEXT,
88   ATSPI_DBUS_INTERFACE_HYPERLINK,
89   ATSPI_DBUS_INTERFACE_HYPERTEXT,
90   ATSPI_DBUS_INTERFACE_IMAGE,
91   "org.a11y.atspi.LoginHelper",
92   ATSPI_DBUS_INTERFACE_SELECTION,
93   ATSPI_DBUS_INTERFACE_TABLE,
94   ATSPI_DBUS_INTERFACE_TABLE_CELL,
95   ATSPI_DBUS_INTERFACE_TEXT,
96   ATSPI_DBUS_INTERFACE_VALUE,
97   NULL
98 };
99
100 gint
101 _atspi_get_iface_num (const char *iface)
102 {
103   /* TODO: Use a binary search or hash to improve performance */
104   int i;
105
106   for (i = 0; interfaces[i]; i++)
107   {
108     if (!strcmp(iface, interfaces[i])) return i;
109   }
110   return -1;
111 }
112
113 GHashTable *
114 _atspi_get_live_refs (void)
115 {
116   if (!live_refs)
117     {
118       live_refs = g_hash_table_new (g_direct_hash, g_direct_equal);
119     }
120   return live_refs;
121 }
122
123 /* TODO: Add an application parameter */
124 DBusConnection *
125 _atspi_bus ()
126 {
127   if (!bus)
128     atspi_init ();
129   if (!bus)
130     g_error ("AT-SPI: Couldn't connect to accessibility bus. Is at-spi-bus-launcher running?");
131   return bus;
132 }
133
134 #define APP_IS_REGISTRY(app) (!strcmp (app->bus_name, atspi_bus_registry))
135
136 static AtspiAccessible *desktop;
137
138 static void cleanup_deferred_message (void);
139
140 static void
141 cleanup ()
142 {
143   GHashTable *refs;
144   gint i;
145
146   refs = live_refs;
147   live_refs = NULL;
148   if (refs)
149     {
150       g_hash_table_destroy (refs);
151     }
152
153   cleanup_deferred_message();
154
155   if (!desktop)
156     goto end;
157
158   /* TODO: Do we need this code, or should we just dispose the desktop? */
159   for (i = desktop->children->len - 1; i >= 0; i--)
160   {
161     AtspiAccessible *child = g_ptr_array_index (desktop->children, i);
162     if (child->parent.app)
163       g_object_run_dispose (G_OBJECT (child->parent.app));
164     g_object_run_dispose (G_OBJECT (child));
165   }
166
167   g_object_run_dispose (G_OBJECT (desktop->parent.app));
168   g_object_unref (desktop);
169   desktop = NULL;
170
171 end:
172   if (bus)
173     {
174       dbus_connection_close (bus);
175       dbus_connection_unref (bus);
176       bus = NULL;
177     }
178 }
179
180 static gboolean atspi_inited = FALSE;
181
182 static GHashTable *app_hash = NULL;
183
184 static void
185 handle_get_bus_address (DBusPendingCall *pending, void *user_data)
186 {
187   AtspiApplication *app = user_data;
188   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
189   DBusMessage *message;
190   const char *address;
191   DBusPendingCall *new_pending;
192   dbus_bool_t result;
193
194   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_METHOD_RETURN)
195   {
196     if (dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &address,
197                                DBUS_TYPE_INVALID) && address [0])
198     {
199       DBusError error;
200       DBusConnection *bus;
201
202       dbus_error_init (&error);
203       bus = dbus_connection_open_private (address, &error);
204       if (bus)
205       {
206         if (app->bus)
207           {
208             dbus_connection_unref (app->bus);
209           }
210         app->bus = bus;
211         atspi_dbus_connection_setup_with_g_main(bus, g_main_context_default());
212       }
213       else
214       {
215         if (!strcmp (error.name, DBUS_ERROR_FILE_NOT_FOUND))
216           g_warning ("AT-SPI: Unable to open bus connection: %s", error.message);
217         dbus_error_free (&error);
218       }
219     }
220   }
221   dbus_message_unref (reply);
222   dbus_pending_call_unref (pending);
223
224   if (!app->bus)
225     return; /* application has gone away / been disposed */
226
227   message = dbus_message_new_method_call (app->bus_name,
228                                           "/org/a11y/atspi/cache",
229                                           atspi_interface_cache, "GetItems");
230
231   result = dbus_connection_send_with_reply (app->bus, message, &new_pending, 2000);
232   dbus_message_unref (message);
233   if (!result || !new_pending)
234     return;
235   dbus_pending_call_set_notify (new_pending, handle_get_items, app, NULL);
236 }
237
238 static AtspiApplication *
239 get_application (const char *bus_name)
240 {
241   AtspiApplication *app = NULL;
242   char *bus_name_dup;
243   DBusMessage *message;
244   DBusPendingCall *pending = NULL;
245   dbus_bool_t result;
246
247   if (!app_hash)
248   {
249     app_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_object_unref);
250     if (!app_hash) return NULL;
251   }
252   app = g_hash_table_lookup (app_hash, bus_name);
253   if (app) return app;
254   bus_name_dup = g_strdup (bus_name);
255   if (!bus_name_dup) return NULL;
256   // TODO: change below to something that will send state-change:defunct notification if necessary */
257   app = _atspi_application_new (bus_name);
258   app->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
259   app->bus = dbus_connection_ref (_atspi_bus ());
260   gettimeofday (&app->time_added, NULL);
261   app->cache = ATSPI_CACHE_UNDEFINED;
262   g_hash_table_insert (app_hash, bus_name_dup, app);
263   message = dbus_message_new_method_call (bus_name, atspi_path_root,
264                                           atspi_interface_application, "GetApplicationBusAddress");
265
266   result = dbus_connection_send_with_reply (app->bus, message, &pending, 2000);
267   dbus_message_unref (message);
268   if (!result || !pending)
269   {
270     g_hash_table_remove (app_hash, bus_name_dup);
271     return NULL;
272   }
273   dbus_pending_call_set_notify (pending, handle_get_bus_address, app, NULL);
274   return app;
275 }
276
277 AtspiAccessible *
278 ref_accessible (const char *app_name, const char *path)
279 {
280   AtspiApplication *app;
281   AtspiAccessible *a;
282
283   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
284     return NULL;
285
286   app = get_application (app_name);
287
288   if (!strcmp (path, "/org/a11y/atspi/accessible/root"))
289   {
290     if (!app->root)
291     {
292       app->root = _atspi_accessible_new (app, atspi_path_root);
293       app->root->accessible_parent = atspi_get_desktop (0);
294       g_ptr_array_add (app->root->accessible_parent->children, g_object_ref (app->root));
295     }
296     return g_object_ref (app->root);
297   }
298
299   a = g_hash_table_lookup (app->hash, path);
300   if (a)
301   {
302     return g_object_ref (a);
303   }
304   a = _atspi_accessible_new (app, path);
305   if (!a)
306     return NULL;
307
308   if (g_hash_table_size (app->hash) > HASH_TABLE_SIZE_MAX)
309   {
310      g_warning ("Accessible hash table is bigger than MAX: %d\n", HASH_TABLE_SIZE_MAX);
311      g_hash_table_remove_all(app->hash);
312   }
313
314   g_hash_table_insert (app->hash, g_strdup (a->parent.path), g_object_ref (a));
315   return a;
316 }
317
318 static AtspiHyperlink *
319 ref_hyperlink (const char *app_name, const char *path)
320 {
321   AtspiApplication *app = get_application (app_name);
322   AtspiHyperlink *hyperlink;
323
324   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
325     return NULL;
326
327   hyperlink = g_hash_table_lookup (app->hash, path);
328   if (hyperlink)
329   {
330     return g_object_ref (hyperlink);
331   }
332   hyperlink = _atspi_hyperlink_new (app, path);
333   g_hash_table_insert (app->hash, g_strdup (hyperlink->parent.path), hyperlink);
334   /* TODO: This should be a weak ref */
335   g_object_ref (hyperlink);     /* for the hash */
336   return hyperlink;
337 }
338
339 typedef struct
340 {
341   char *path;
342   char *parent;
343   GArray *children;
344   GArray *interfaces;
345   char *name;
346   dbus_uint32_t role;
347   char *description;
348   GArray *state_bitflags;
349 } CACHE_ADDITION;
350
351 static DBusHandlerResult
352 handle_remove_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
353 {
354   const char *sender = dbus_message_get_sender (message);
355   AtspiApplication *app;
356   const char *path;
357   DBusMessageIter iter, iter_struct;
358   const char *signature = dbus_message_get_signature (message);
359   AtspiAccessible *a;
360
361   if (strcmp (signature, "(so)") != 0)
362   {
363     g_warning ("AT-SPI: Unknown signature %s for RemoveAccessible", signature);
364     return DBUS_HANDLER_RESULT_HANDLED;
365   }
366
367   dbus_message_iter_init (message, &iter);
368   dbus_message_iter_recurse (&iter, &iter_struct);
369   dbus_message_iter_get_basic (&iter_struct, &sender);
370   dbus_message_iter_next (&iter_struct);
371   dbus_message_iter_get_basic (&iter_struct, &path);
372   app = get_application (sender);
373   a = ref_accessible (sender, path);
374   if (!a)
375     return DBUS_HANDLER_RESULT_HANDLED;
376   g_object_run_dispose (G_OBJECT (a));
377   g_hash_table_remove (app->hash, a->parent.path);
378   g_object_unref (a);   /* unref our own ref */
379   return DBUS_HANDLER_RESULT_HANDLED;
380 }
381
382 void
383 remove_accessible_from_app_hash (const char *app_name, AtspiAccessible *a)
384 {
385   AtspiApplication *app;
386
387   if (!a) return;
388
389   app = get_application (app_name);
390   if (!app) return;
391
392   if (!g_hash_table_lookup (app->hash, a->parent.path)) return;
393
394   g_hash_table_remove (app->hash, a->parent.path);
395 }
396
397 static DBusHandlerResult
398 handle_name_owner_changed (DBusConnection *bus, DBusMessage *message, void *user_data)
399 {
400   const char *name, *new, *old;
401   static gboolean registry_lost = FALSE;
402
403   if (!dbus_message_get_args (message, NULL,
404                               DBUS_TYPE_STRING, &name,
405                               DBUS_TYPE_STRING, &old,
406                               DBUS_TYPE_STRING, &new,
407                               DBUS_TYPE_INVALID))
408   {
409     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
410   }
411
412   if (!strcmp (name, "org.a11y.atspi.Registry"))
413   {
414     if (registry_lost && !old[0])
415     {
416       _atspi_reregister_event_listeners ();
417       _atspi_reregister_device_listeners ();
418       registry_lost = FALSE;
419     }
420     else if (!new[0])
421       registry_lost = TRUE;
422   }
423   else if (app_hash)
424   {
425     AtspiApplication *app = g_hash_table_lookup (app_hash, old);
426     if (app && app->bus_name && !strcmp(app->bus_name, name))
427       g_object_run_dispose (G_OBJECT (app));
428   }
429   return DBUS_HANDLER_RESULT_HANDLED;
430 }
431
432 static gboolean
433 add_app_to_desktop (AtspiAccessible *a, const char *bus_name)
434 {
435   AtspiAccessible *obj = ref_accessible (bus_name, atspi_path_root);
436   /* The app will be added to the desktop as a side-effect of calling
437    * ref_accessible */
438   g_object_unref (obj);
439   return (obj != NULL);
440 }
441
442 void
443 get_reference_from_iter (DBusMessageIter *iter, const char **app_name, const char **path)
444 {
445   DBusMessageIter iter_struct;
446
447   dbus_message_iter_recurse (iter, &iter_struct);
448   dbus_message_iter_get_basic (&iter_struct, app_name);
449   dbus_message_iter_next (&iter_struct);
450   dbus_message_iter_get_basic (&iter_struct, path);
451   dbus_message_iter_next (iter);
452 }
453
454 static void
455 add_accessible_from_iter (DBusMessageIter *iter)
456 {
457   DBusMessageIter iter_struct, iter_array;
458   const char *app_name, *path;
459   AtspiAccessible *accessible;
460   const char *name, *description;
461   dbus_uint32_t role;
462   gboolean children_cached = FALSE;
463   dbus_int32_t count, index;
464
465   dbus_message_iter_recurse (iter, &iter_struct);
466
467   /* get accessible */
468   get_reference_from_iter (&iter_struct, &app_name, &path);
469   accessible = ref_accessible (app_name, path);
470   if (!accessible)
471     return;
472
473   /* Get application: TODO */
474   dbus_message_iter_next (&iter_struct);
475
476   /* get parent */
477   get_reference_from_iter (&iter_struct, &app_name, &path);
478   if (accessible->accessible_parent)
479     g_object_unref (accessible->accessible_parent);
480   accessible->accessible_parent = ref_accessible (app_name, path);
481
482   if (dbus_message_iter_get_arg_type (&iter_struct) == 'i')
483   {
484     /* Get index in parent */
485     dbus_message_iter_get_basic (&iter_struct, &index);
486     if (index >= 0 && accessible->accessible_parent)
487     {
488       if (index >= accessible->accessible_parent->children->len) {
489         /* There is no room for this object */
490         g_ptr_array_set_size (accessible->accessible_parent->children, index + 1);
491       } else {
492         /* This place is already taken - let's free this place with dignity */
493         g_object_unref (g_ptr_array_index (accessible->accessible_parent->children, index));
494       }
495       g_ptr_array_index (accessible->accessible_parent->children, index) = g_object_ref (accessible);
496     }
497
498     /* get child count */
499     dbus_message_iter_next (&iter_struct);
500     dbus_message_iter_get_basic (&iter_struct, &count);
501     if (count >= 0)
502     {
503       g_ptr_array_set_size (accessible->children, count);
504       children_cached = TRUE;
505     }
506   }
507   else if (dbus_message_iter_get_arg_type (&iter_struct) == 'a')
508   {
509     /* It's the old API with a list of children */
510     /* TODO: Perhaps remove this code eventually */
511     dbus_message_iter_recurse (&iter_struct, &iter_array);
512     while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
513     {
514       AtspiAccessible *child;
515       get_reference_from_iter (&iter_array, &app_name, &path);
516       child = ref_accessible (app_name, path);
517       g_ptr_array_remove (accessible->children, child);
518       g_ptr_array_add (accessible->children, child);
519     }
520     children_cached = TRUE;
521   }
522
523   /* interfaces */
524   dbus_message_iter_next (&iter_struct);
525   _atspi_dbus_set_interfaces (accessible, &iter_struct);
526   dbus_message_iter_next (&iter_struct);
527
528   /* name */
529   if (accessible->name)
530     g_free (accessible->name);
531   dbus_message_iter_get_basic (&iter_struct, &name);
532   accessible->name = g_strdup (name);
533   dbus_message_iter_next (&iter_struct);
534
535   /* role */
536   dbus_message_iter_get_basic (&iter_struct, &role);
537   accessible->role = role;
538   dbus_message_iter_next (&iter_struct);
539
540   /* description */
541   if (accessible->description)
542     g_free (accessible->description);
543   dbus_message_iter_get_basic (&iter_struct, &description);
544   accessible->description = g_strdup (description);
545   dbus_message_iter_next (&iter_struct);
546
547   _atspi_dbus_set_state (accessible, &iter_struct);
548   dbus_message_iter_next (&iter_struct);
549
550   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_NAME | ATSPI_CACHE_ROLE |
551                                ATSPI_CACHE_PARENT | ATSPI_CACHE_DESCRIPTION);
552   if (!atspi_state_set_contains (accessible->states,
553                                        ATSPI_STATE_MANAGES_DESCENDANTS) &&
554                                        children_cached)
555     _atspi_accessible_add_cache (accessible, ATSPI_CACHE_CHILDREN);
556
557   /* This is a bit of a hack since the cache holds a ref, so we don't need
558    * the one provided for us anymore */
559   g_object_unref (accessible);
560 }
561
562 static void
563 handle_get_items (DBusPendingCall *pending, void *user_data)
564 {
565   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
566   DBusMessageIter iter, iter_array;
567
568   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
569   {
570     const char *sender = dbus_message_get_sender (reply);
571     const char *error = NULL;
572     const char *error_name = dbus_message_get_error_name (reply);
573     if (!strcmp (error_name, DBUS_ERROR_SERVICE_UNKNOWN)
574      || !strcmp (error_name, DBUS_ERROR_NO_REPLY))
575     {
576     }
577     else
578     {
579       dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &error,
580                              DBUS_TYPE_INVALID);
581       g_warning ("AT-SPI: Error in GetItems, sender=%s, error=%s", sender, error);
582     }
583     dbus_message_unref (reply);
584     dbus_pending_call_unref (pending);
585     return;
586   }
587
588   dbus_message_iter_init (reply, &iter);
589   dbus_message_iter_recurse (&iter, &iter_array);
590   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
591   {
592     add_accessible_from_iter (&iter_array);
593     dbus_message_iter_next (&iter_array);
594   }
595   dbus_message_unref (reply);
596   dbus_pending_call_unref (pending);
597 }
598
599 /* TODO: Do we stil need this function? */
600 static AtspiAccessible *
601 ref_accessible_desktop (AtspiApplication *app)
602 {
603   GError *error;
604   DBusMessage *message, *reply;
605   DBusMessageIter iter, iter_array;
606   gchar *bus_name_dup;
607
608   if (desktop)
609   {
610     g_object_ref (desktop);
611     return desktop;
612   }
613   desktop = _atspi_accessible_new (app, atspi_path_root);
614   if (!desktop)
615   {
616     return NULL;
617   }
618   g_hash_table_insert (app->hash, g_strdup (desktop->parent.path),
619                        g_object_ref (desktop));
620   app->root = g_object_ref (desktop);
621   desktop->name = g_strdup ("main");
622   message = dbus_message_new_method_call (atspi_bus_registry,
623         atspi_path_root,
624         atspi_interface_accessible,
625         "GetChildren");
626   if (!message)
627     return NULL;
628   error = NULL;
629   reply = _atspi_dbus_send_with_reply_and_block (message, &error);
630   if (!reply || strcmp (dbus_message_get_signature (reply), "a(so)") != 0)
631   {
632     if (error != NULL)
633     {
634       g_warning ("Couldn't get application list: %s", error->message);
635       g_clear_error (&error);
636     }
637     if (reply)
638       dbus_message_unref (reply);
639     return NULL;
640   }
641   dbus_message_iter_init (reply, &iter);
642   dbus_message_iter_recurse (&iter, &iter_array);
643   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
644   {
645     const char *app_name, *path;
646     get_reference_from_iter (&iter_array, &app_name, &path);
647     add_app_to_desktop (desktop, app_name);
648   }
649
650   /* Record the alternate name as an alias for org.a11y.atspi.Registry */
651   bus_name_dup = g_strdup (dbus_message_get_sender (reply));
652   if (bus_name_dup)
653     g_hash_table_insert (app_hash, bus_name_dup, app);
654
655   dbus_message_unref (reply);
656
657   return g_object_ref (desktop);
658 }
659
660 AtspiAccessible *
661 _atspi_ref_accessible (const char *app, const char *path)
662 {
663   AtspiApplication *a = get_application (app);
664   if (!a)
665     return NULL;
666   if ( APP_IS_REGISTRY(a))
667   {
668     if (!a->root)
669       g_object_unref (ref_accessible_desktop (a));      /* sets a->root */
670     return g_object_ref (a->root);
671   }
672   return ref_accessible (app, path);
673 }
674
675 AtspiAccessible *
676 _atspi_dbus_return_accessible_from_message (DBusMessage *message)
677 {
678   DBusMessageIter iter;
679   AtspiAccessible *retval = NULL;
680   const char *signature;
681
682   if (!message)
683     return NULL;
684
685   signature = dbus_message_get_signature (message);
686   if (!strcmp (signature, "(so)"))
687   {
688     dbus_message_iter_init (message, &iter);
689     retval =  _atspi_dbus_return_accessible_from_iter (&iter);
690   }
691   else
692   {
693     g_warning ("AT-SPI: Called _atspi_dbus_return_accessible_from_message with strange signature %s", signature);
694   }
695   dbus_message_unref (message);
696   return retval;
697 }
698
699 AtspiAccessible *
700 _atspi_dbus_return_accessible_from_iter (DBusMessageIter *iter)
701 {
702   const char *app_name, *path;
703
704   get_reference_from_iter (iter, &app_name, &path);
705   return ref_accessible (app_name, path);
706 }
707
708 AtspiHyperlink *
709 _atspi_dbus_return_hyperlink_from_message (DBusMessage *message)
710 {
711   DBusMessageIter iter;
712   AtspiHyperlink *retval = NULL;
713   const char *signature;
714
715   if (!message)
716     return NULL;
717
718   signature = dbus_message_get_signature (message);
719   if (!strcmp (signature, "(so)"))
720   {
721     dbus_message_iter_init (message, &iter);
722     retval =  _atspi_dbus_return_hyperlink_from_iter (&iter);
723   }
724   else
725   {
726     g_warning ("AT-SPI: Called _atspi_dbus_return_hyperlink_from_message with strange signature %s", signature);
727   }
728   dbus_message_unref (message);
729   return retval;
730 }
731
732 AtspiHyperlink *
733 _atspi_dbus_return_hyperlink_from_iter (DBusMessageIter *iter)
734 {
735   const char *app_name, *path;
736
737   get_reference_from_iter (iter, &app_name, &path);
738   return ref_hyperlink (app_name, path);
739 }
740
741 const char *cache_signal_type = "((so)(so)(so)iiassusau)";
742 const char *old_cache_signal_type = "((so)(so)(so)a(so)assusau)";
743
744 static DBusHandlerResult
745 handle_add_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
746 {
747   DBusMessageIter iter;
748   const char *signature = dbus_message_get_signature (message);
749
750   if (strcmp (signature, cache_signal_type) != 0 &&
751       strcmp (signature, old_cache_signal_type) != 0)
752   {
753     g_warning ("AT-SPI: AddAccessible with unknown signature %s\n", signature);
754     return DBUS_HANDLER_RESULT_HANDLED;
755   }
756
757   dbus_message_iter_init (message, &iter);
758   add_accessible_from_iter (&iter);
759   return DBUS_HANDLER_RESULT_HANDLED;
760 }
761
762 typedef struct
763 {
764   DBusConnection *bus;
765   DBusMessage *message;
766   void *data;
767 } BusDataClosure;
768
769 static GSource *process_deferred_messages_source = NULL;
770
771 static void
772 process_deferred_message (BusDataClosure *closure)
773 {
774   int type = dbus_message_get_type (closure->message);
775   const char *interface = dbus_message_get_interface (closure->message);
776
777   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
778       !strncmp (interface, "org.a11y.atspi.Event.", 21))
779   {
780     _atspi_dbus_handle_event (closure->bus, closure->message, closure->data);
781   }
782   if (dbus_message_is_method_call (closure->message, atspi_interface_device_event_listener, "NotifyEvent"))
783   {
784     _atspi_dbus_handle_DeviceEvent (closure->bus,
785                                    closure->message, closure->data);
786   }
787   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "AddAccessible"))
788   {
789     handle_add_accessible (closure->bus, closure->message, closure->data);
790   }
791   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "RemoveAccessible"))
792   {
793     handle_remove_accessible (closure->bus, closure->message, closure->data);
794   }
795   if (dbus_message_is_signal (closure->message, "org.freedesktop.DBus", "NameOwnerChanged"))
796   {
797     handle_name_owner_changed (closure->bus, closure->message, closure->data);
798   }
799 }
800
801 static GQueue *deferred_messages = NULL;
802
803 static void
804 destroy_deferred_message_item(gpointer ptr)
805 {
806   /* TODO this is still memory leak on c->data */
807   BusDataClosure *c = ptr;
808   dbus_message_unref (c->message);
809   dbus_connection_unref (c->bus);
810   g_free(c);
811 }
812
813 static void
814 cleanup_deferred_message(void)
815 {
816   g_queue_free_full(deferred_messages, destroy_deferred_message_item);
817   deferred_messages = NULL;
818 }
819
820 static gboolean
821 process_deferred_messages (void)
822 {
823   static int in_process_deferred_messages = 0;
824   BusDataClosure *closure;
825
826   if (in_process_deferred_messages)
827     return TRUE;
828   in_process_deferred_messages = 1;
829   while ((closure = g_queue_pop_head (deferred_messages)))
830   {
831     process_deferred_message (closure);
832     dbus_message_unref (closure->message);
833     dbus_connection_unref (closure->bus);
834     g_free (closure);
835   }
836   in_process_deferred_messages = 0;
837   return FALSE;
838 }
839
840 static gboolean
841 process_deferred_messages_callback (gpointer data)
842 {
843   if (process_deferred_messages ())
844     return G_SOURCE_CONTINUE;
845
846   process_deferred_messages_source = NULL;
847   return G_SOURCE_REMOVE;
848 }
849
850 static DBusHandlerResult
851 defer_message (DBusConnection *connection, DBusMessage *message, void *user_data)
852 {
853   BusDataClosure *closure = g_new (BusDataClosure, 1);
854
855   closure->bus = dbus_connection_ref (bus);
856   closure->message = dbus_message_ref (message);
857   closure->data = user_data;
858
859   g_queue_push_tail (deferred_messages, closure);
860
861   if (process_deferred_messages_source == NULL)
862   {
863     process_deferred_messages_source = g_idle_source_new ();
864     g_source_set_callback (process_deferred_messages_source,
865                            process_deferred_messages_callback, NULL, NULL);
866     g_source_attach (process_deferred_messages_source, atspi_main_context);
867     g_source_unref (process_deferred_messages_source);
868   }
869
870   return DBUS_HANDLER_RESULT_HANDLED;
871 }
872
873 static DBusHandlerResult
874 atspi_dbus_filter (DBusConnection *bus, DBusMessage *message, void *data)
875 {
876   int type = dbus_message_get_type (message);
877   const char *interface = dbus_message_get_interface (message);
878
879   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
880       !strncmp (interface, "org.a11y.atspi.Event.", 21))
881   {
882     return defer_message (bus, message, data);
883   }
884   if (dbus_message_is_method_call (message, atspi_interface_device_event_listener, "NotifyEvent"))
885   {
886     return defer_message (bus, message, data);
887   }
888   if (dbus_message_is_signal (message, atspi_interface_cache, "AddAccessible"))
889   {
890     return defer_message (bus, message, data);
891   }
892   if (dbus_message_is_signal (message, atspi_interface_cache, "RemoveAccessible"))
893   {
894     return defer_message (bus, message, data);
895   }
896   if (dbus_message_is_signal (message, "org.freedesktop.DBus", "NameOwnerChanged"))
897   {
898     defer_message (bus, message, data);
899     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
900   }
901   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
902 }
903
904 /*
905  * Returns a 'canonicalized' value for DISPLAY,
906  * with the screen number stripped off if present.
907  *
908  * TODO: Avoid having duplicate functions for this here and in at-spi2-atk
909  */
910 static gchar *
911 spi_display_name (void)
912 {
913   char *canonical_display_name = NULL;
914   const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
915
916   if (!display_env)
917     {
918       display_env = g_getenv ("DISPLAY");
919       if (!display_env || !display_env[0])
920         return NULL;
921       else
922         {
923           gchar *display_p, *screen_p;
924           canonical_display_name = g_strdup (display_env);
925           display_p = g_utf8_strrchr (canonical_display_name, -1, ':');
926           screen_p = g_utf8_strrchr (canonical_display_name, -1, '.');
927           if (screen_p && display_p && (screen_p > display_p))
928             {
929               *screen_p = '\0';
930             }
931         }
932     }
933   else
934     {
935       canonical_display_name = g_strdup (display_env);
936     }
937
938   return canonical_display_name;
939 }
940
941 /**
942  * atspi_init:
943  *
944  * Connects to the accessibility registry and initializes the SPI.
945  *
946  * Returns: 0 on success, 1 if already initialized, or an integer error code.
947  **/
948 int
949 atspi_init (void)
950 {
951   char *match;
952   const gchar *no_cache;
953
954   if (atspi_inited)
955     {
956       return 1;
957     }
958
959   atspi_inited = TRUE;
960
961   _atspi_get_live_refs();
962
963   bus = atspi_get_a11y_bus ();
964   if (!bus)
965     return 2;
966   if (!dbus_bus_register (bus, NULL))
967     return 2;
968   atspi_dbus_connection_setup_with_g_main(bus, g_main_context_default());
969   dbus_connection_add_filter (bus, atspi_dbus_filter, NULL, NULL);
970   match = g_strdup_printf ("type='signal',interface='%s',member='AddAccessible'", atspi_interface_cache);
971   dbus_bus_add_match (bus, match, NULL);
972   g_free (match);
973   match = g_strdup_printf ("type='signal',interface='%s',member='RemoveAccessible'", atspi_interface_cache);
974   dbus_bus_add_match (bus, match, NULL);
975   g_free (match);
976   match = g_strdup_printf ("type='signal',interface='%s',member='ChildrenChanged'", atspi_interface_event_object);
977   dbus_bus_add_match (bus, match, NULL);
978   g_free (match);
979   match = g_strdup_printf ("type='signal',interface='%s',member='PropertyChange'", atspi_interface_event_object);
980   dbus_bus_add_match (bus, match, NULL);
981   g_free (match);
982   match = g_strdup_printf ("type='signal',interface='%s',member='StateChanged'", atspi_interface_event_object);
983   dbus_bus_add_match (bus, match, NULL);
984   g_free (match);
985
986   dbus_bus_add_match (bus,
987                       "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged'",
988                       NULL);
989
990   no_cache = g_getenv ("ATSPI_NO_CACHE");
991   if (no_cache && g_strcmp0 (no_cache, "0") != 0)
992     atspi_no_cache = TRUE;
993
994   deferred_messages = g_queue_new ();
995
996   return 0;
997 }
998
999 /**
1000  * atspi_is_initialized:
1001  *
1002  * Indicates whether AT-SPI has been initialized.
1003  *
1004  * Returns: %True if initialized; %False otherwise.
1005  */
1006 gboolean
1007 atspi_is_initialized ()
1008 {
1009   return atspi_inited;
1010 }
1011
1012 /**
1013  * atspi_event_main:
1014  *
1015  * Starts/enters the main event loop for the AT-SPI services.
1016  *
1017  * NOTE: This method does not return control; it is exited via a call to
1018  * #atspi_event_quit from within an event handler.
1019  *
1020  **/
1021 void
1022 atspi_event_main (void)
1023 {
1024   atspi_main_loop = g_main_loop_new (NULL, FALSE);
1025   g_main_loop_run (atspi_main_loop);
1026   g_main_loop_unref(atspi_main_loop);
1027   atspi_main_loop = NULL;
1028 }
1029
1030 /**
1031  * atspi_event_quit:
1032  *
1033  * Quits the last main event loop for the AT-SPI services,
1034  * See: #atspi_event_main
1035  **/
1036 void
1037 atspi_event_quit (void)
1038 {
1039   g_main_loop_quit (atspi_main_loop);
1040 }
1041
1042 /**
1043  * atspi_exit:
1044  *
1045  * Disconnects from #AtspiRegistry instances and releases
1046  * any floating resources. Call only once at exit.
1047  *
1048  * Returns: 0 if there were no leaks, otherwise other integer values.
1049  **/
1050 int
1051 atspi_exit (void)
1052 {
1053   int leaked;
1054
1055   if (!atspi_inited)
1056     {
1057       return 0;
1058     }
1059
1060   atspi_inited = FALSE;
1061
1062   if (live_refs)
1063     {
1064       leaked = g_hash_table_size (live_refs);
1065     }
1066   else
1067     {
1068       leaked = 0;
1069     }
1070
1071   cleanup ();
1072
1073   return leaked;
1074 }
1075
1076 static GSList *hung_processes;
1077
1078 static void
1079 remove_hung_process (DBusPendingCall *pending, void *data)
1080 {
1081   hung_processes = g_slist_remove (hung_processes, data);
1082   g_free (data);
1083   dbus_pending_call_unref (pending);
1084 }
1085
1086 static void
1087 check_for_hang (DBusMessage *message, DBusError *error, DBusConnection *bus, const char *bus_name)
1088 {
1089   if (!message && error->name &&
1090       !strcmp (error->name, "org.freedesktop.DBus.Error.NoReply"))
1091   {
1092     GSList *l;
1093     DBusMessage *message;
1094     gchar *bus_name_dup;
1095     DBusPendingCall *pending = NULL;
1096     dbus_bool_t result;
1097     for (l = hung_processes; l; l = l->next)
1098       if (!strcmp (l->data, bus_name))
1099         return;
1100     message = dbus_message_new_method_call (bus_name, "/",
1101                                             "org.freedesktop.DBus.Peer",
1102                                             "Ping");
1103     if (!message)
1104       return;
1105     result = dbus_connection_send_with_reply (bus, message, &pending, -1);
1106     dbus_message_unref (message);
1107     if (!result || !pending)
1108       return;
1109     bus_name_dup = g_strdup (bus_name);
1110     hung_processes = g_slist_append (hung_processes, bus_name_dup);
1111     dbus_pending_call_set_notify (pending, remove_hung_process, bus_name_dup, NULL);
1112   }
1113 }
1114
1115 static gboolean
1116 connection_is_hung (const char *bus_name)
1117 {
1118   GSList *l;
1119
1120   for (l = hung_processes; l; l = l->next)
1121     if (!strcmp (l->data, bus_name))
1122       return TRUE;
1123   return FALSE;
1124 }
1125
1126 static gboolean
1127 check_app (AtspiApplication *app, GError **error)
1128 {
1129   if (!app || !app->bus)
1130   {
1131     g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_APPLICATION_GONE,
1132                           _("The application no longer exists"));
1133     return FALSE;
1134   }
1135
1136   if (atspi_main_loop && connection_is_hung (app->bus_name))
1137   {
1138       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC,
1139                            "The process appears to be hung.");
1140     return FALSE;
1141   }
1142
1143   return TRUE;
1144 }
1145
1146 static void
1147 set_timeout (AtspiApplication *app)
1148 {
1149   struct timeval tv;
1150   int diff;
1151
1152   if (app && app_startup_time > 0)
1153   {
1154     gettimeofday (&tv, NULL);
1155     diff = (tv.tv_sec - app->time_added.tv_sec) * 1000 + (tv.tv_usec - app->time_added.tv_usec) / 1000;
1156     dbind_set_timeout (MAX(method_call_timeout, app_startup_time - diff));
1157   }
1158   else
1159     dbind_set_timeout (method_call_timeout);
1160 }
1161
1162 dbus_bool_t
1163 _atspi_dbus_call (gpointer obj, const char *interface, const char *method, GError **error, const char *type, ...)
1164 {
1165   va_list args;
1166   dbus_bool_t retval;
1167   DBusError err;
1168   AtspiObject *aobj = ATSPI_OBJECT (obj);
1169
1170   if (!check_app (aobj->app, error))
1171     return FALSE;
1172
1173   if (!allow_sync)
1174   {
1175     _atspi_set_error_no_sync (error);
1176     return FALSE;
1177   }
1178
1179   va_start (args, type);
1180   dbus_error_init (&err);
1181   set_timeout (aobj->app);
1182   retval = dbind_method_call_reentrant_va (aobj->app->bus, aobj->app->bus_name,
1183                                            aobj->path, interface, method, &err,
1184                                            type, args);
1185   va_end (args);
1186   check_for_hang (NULL, &err, aobj->app->bus, aobj->app->bus_name);
1187   process_deferred_messages ();
1188   if (dbus_error_is_set (&err))
1189   {
1190     g_set_error(error, ATSPI_ERROR, ATSPI_ERROR_IPC, "%s", err.message);
1191     dbus_error_free (&err);
1192   }
1193   return retval;
1194 }
1195
1196 DBusMessage *
1197 _atspi_dbus_call_partial (gpointer obj,
1198                           const char *interface,
1199                           const char *method,
1200                           GError **error,
1201                           const char *type, ...)
1202 {
1203   va_list args;
1204   DBusMessage * result;
1205   va_start (args, type);
1206   result =  _atspi_dbus_call_partial_va (obj, interface, method, error, type, args);
1207   va_end (args);
1208   return result;
1209 }
1210
1211
1212 DBusMessage *
1213 _atspi_dbus_call_partial_va (gpointer obj,
1214                           const char *interface,
1215                           const char *method,
1216                           GError **error,
1217                           const char *type,
1218                           va_list args)
1219 {
1220   AtspiObject *aobj = ATSPI_OBJECT (obj);
1221   DBusError err;
1222   DBusMessage *msg = NULL, *reply = NULL;
1223   DBusMessageIter iter;
1224   const char *p;
1225
1226   dbus_error_init (&err);
1227
1228   if (!check_app (aobj->app, error))
1229     goto out;
1230
1231   msg = dbus_message_new_method_call (aobj->app->bus_name, aobj->path, interface, method);
1232   if (!msg)
1233     goto out;
1234
1235   p = type;
1236   dbus_message_iter_init_append (msg, &iter);
1237   dbind_any_marshal_va (&iter, &p, args);
1238
1239   set_timeout (aobj->app);
1240   reply = dbind_send_and_allow_reentry (aobj->app->bus, msg, &err);
1241   check_for_hang (reply, &err, aobj->app->bus, aobj->app->bus_name);
1242 out:
1243   va_end (args);
1244   if (msg)
1245     dbus_message_unref (msg);
1246   process_deferred_messages ();
1247   if (dbus_error_is_set (&err))
1248   {
1249     g_set_error_literal(error, ATSPI_ERROR, ATSPI_ERROR_IPC, err.message);
1250     dbus_error_free (&err);
1251     if (reply)
1252       dbus_message_unref(reply);
1253     return NULL;
1254   }
1255   else if (reply && dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
1256   {
1257     const char *err_str = NULL;
1258     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &err_str, DBUS_TYPE_INVALID);
1259     if (err_str)
1260       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err_str);
1261     dbus_message_unref (reply);
1262     return NULL;
1263   }
1264   return reply;
1265 }
1266
1267 dbus_bool_t
1268 _atspi_dbus_get_property (gpointer obj, const char *interface, const char *name, GError **error, const char *type, void *data)
1269 {
1270   DBusMessage *message, *reply;
1271   DBusMessageIter iter, iter_variant;
1272   DBusError err;
1273   dbus_bool_t retval = FALSE;
1274   AtspiObject *aobj = ATSPI_OBJECT (obj);
1275   char expected_type = (type [0] == '(' ? 'r' : type [0]);
1276
1277   if (!aobj)
1278     return FALSE;
1279
1280   if (!check_app (aobj->app, error))
1281     return FALSE;
1282
1283   if (!allow_sync)
1284   {
1285     _atspi_set_error_no_sync (error);
1286     return FALSE;
1287   }
1288
1289   message = dbus_message_new_method_call (aobj->app->bus_name,
1290                                           aobj->path,
1291                                           "org.freedesktop.DBus.Properties",
1292                                           "Get");
1293   if (!message)
1294   {
1295     // TODO: throw exception
1296     return FALSE;
1297   }
1298   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1299   dbus_error_init (&err);
1300   set_timeout (aobj->app);
1301   reply = dbind_send_and_allow_reentry (aobj->app->bus, message, &err);
1302   check_for_hang (reply, &err, aobj->app->bus, aobj->app->bus_name);
1303   dbus_message_unref (message);
1304   process_deferred_messages ();
1305   if (!reply)
1306   {
1307     // TODO: throw exception
1308     goto done;
1309   }
1310
1311   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
1312   {
1313     const char *err_str = NULL;
1314     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &err_str, DBUS_TYPE_INVALID);
1315     if (err_str)
1316       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err_str);
1317     goto done;
1318   }
1319
1320   dbus_message_iter_init (reply, &iter);
1321   if (dbus_message_iter_get_arg_type (&iter) != 'v')
1322   {
1323     g_warning ("atspi_dbus_get_property: expected a variant when fetching %s from interface %s; got %s\n", name, interface, dbus_message_get_signature (reply));
1324     goto done;
1325   }
1326   dbus_message_iter_recurse (&iter, &iter_variant);
1327   if (dbus_message_iter_get_arg_type (&iter_variant) != expected_type)
1328   {
1329     g_warning ("atspi_dbus_get_property: Wrong type: expected %s, got %c\n", type, dbus_message_iter_get_arg_type (&iter_variant));
1330     goto done;
1331   }
1332   if (!strcmp (type, "(so)"))
1333   {
1334     g_object_unref(*(AtspiAccessible**)data);
1335     *((AtspiAccessible **)data) = _atspi_dbus_return_accessible_from_iter (&iter_variant);
1336   }
1337   else
1338   {
1339     if (type [0] == 's')
1340     {
1341       g_free(*(char**)data);
1342       *(char**) data = NULL;
1343     }
1344
1345     dbus_message_iter_get_basic (&iter_variant, data);
1346
1347     if (type [0] == 's')
1348       *(char **)data = g_strdup (*(char **)data);
1349   }
1350   retval = TRUE;
1351 done:
1352   dbus_error_free (&err);
1353   if (reply)
1354     dbus_message_unref (reply);
1355   return retval;
1356 }
1357
1358 DBusMessage *
1359 _atspi_dbus_send_with_reply_and_block (DBusMessage *message, GError **error)
1360 {
1361   DBusMessage *reply;
1362   DBusError err;
1363   AtspiApplication *app;
1364   DBusConnection *bus;
1365
1366   app = get_application (dbus_message_get_destination (message));
1367
1368   if (app && !app->bus)
1369     return NULL;        /* will fail anyway; app has been disposed */
1370
1371   bus = (app ? app->bus : _atspi_bus());
1372   dbus_error_init (&err);
1373   set_timeout (app);
1374   reply = dbind_send_and_allow_reentry (bus, message, &err);
1375   process_deferred_messages ();
1376   dbus_message_unref (message);
1377   if (dbus_error_is_set (&err))
1378   {
1379     if (error)
1380       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err.message);
1381     dbus_error_free (&err);
1382   }
1383   return reply;
1384 }
1385
1386 GHashTable *
1387 _atspi_dbus_return_hash_from_message (DBusMessage *message)
1388 {
1389   DBusMessageIter iter;
1390   GHashTable *ret;
1391
1392   if (!message)
1393     return NULL;
1394
1395   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1396
1397   dbus_message_iter_init (message, &iter);
1398   ret = _atspi_dbus_hash_from_iter (&iter);
1399   dbus_message_unref (message);
1400   return ret;
1401 }
1402
1403 GHashTable *
1404 _atspi_dbus_hash_from_iter (DBusMessageIter *iter)
1405 {
1406   GHashTable *hash = g_hash_table_new_full (g_str_hash, g_str_equal,
1407                                             (GDestroyNotify) g_free,
1408                                             (GDestroyNotify) g_free);
1409   DBusMessageIter iter_array, iter_dict;
1410
1411   dbus_message_iter_recurse (iter, &iter_array);
1412   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1413   {
1414     const char *name, *value;
1415     dbus_message_iter_recurse (&iter_array, &iter_dict);
1416     dbus_message_iter_get_basic (&iter_dict, &name);
1417     dbus_message_iter_next (&iter_dict);
1418     dbus_message_iter_get_basic (&iter_dict, &value);
1419     g_hash_table_insert (hash, g_strdup (name), g_strdup (value));
1420     dbus_message_iter_next (&iter_array);
1421   }
1422   return hash;
1423 }
1424
1425 GArray *
1426 _atspi_dbus_return_attribute_array_from_message (DBusMessage *message)
1427 {
1428   DBusMessageIter iter;
1429   GArray *ret;
1430
1431   if (!message)
1432     return NULL;
1433
1434   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1435
1436   dbus_message_iter_init (message, &iter);
1437
1438   ret = _atspi_dbus_attribute_array_from_iter (&iter);
1439   dbus_message_unref (message);
1440   return ret;
1441 }
1442
1443 GArray *
1444 _atspi_dbus_attribute_array_from_iter (DBusMessageIter *iter)
1445 {
1446   DBusMessageIter iter_array, iter_dict;
1447   GArray *array = g_array_new (TRUE, TRUE, sizeof (gchar *));
1448
1449   dbus_message_iter_recurse (iter, &iter_array);
1450   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1451   {
1452     const char *name, *value;
1453     gchar *str;
1454     dbus_message_iter_recurse (&iter_array, &iter_dict);
1455     dbus_message_iter_get_basic (&iter_dict, &name);
1456     dbus_message_iter_next (&iter_dict);
1457     dbus_message_iter_get_basic (&iter_dict, &value);
1458     str = g_strdup_printf ("%s:%s", name, value);
1459     array = g_array_append_val (array, str);
1460     dbus_message_iter_next (&iter_array);;
1461   }
1462   return array;
1463 }
1464
1465 void
1466 _atspi_dbus_set_interfaces (AtspiAccessible *accessible, DBusMessageIter *iter)
1467 {
1468   DBusMessageIter iter_array;
1469   char *iter_sig = dbus_message_iter_get_signature (iter);
1470
1471   accessible->interfaces = 0;
1472   if (strcmp (iter_sig, "as") != 0)
1473   {
1474     g_warning ("_atspi_dbus_set_interfaces: Passed iterator with invalid signature %s", iter_sig);
1475     dbus_free (iter_sig);
1476     return;
1477   }
1478   dbus_free (iter_sig);
1479   dbus_message_iter_recurse (iter, &iter_array);
1480   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1481   {
1482     const char *iface;
1483     gint n;
1484     dbus_message_iter_get_basic (&iter_array, &iface);
1485     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable")) continue;
1486     n = _atspi_get_iface_num (iface);
1487     if (n == -1)
1488     {
1489       g_warning ("AT-SPI: Unknown interface %s", iface);
1490     }
1491     else
1492       accessible->interfaces |= (1 << n);
1493     dbus_message_iter_next (&iter_array);
1494   }
1495   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_INTERFACES);
1496 }
1497
1498 void
1499 _atspi_dbus_set_state (AtspiAccessible *accessible, DBusMessageIter *iter)
1500 {
1501   DBusMessageIter iter_array;
1502   gint count;
1503   dbus_uint32_t *states;
1504
1505   dbus_message_iter_recurse (iter, &iter_array);
1506   dbus_message_iter_get_fixed_array (&iter_array, &states, &count);
1507   if (count != 2)
1508   {
1509     g_warning ("AT-SPI: expected 2 values in states array; got %d\n", count);
1510     if (!accessible->states)
1511       accessible->states = _atspi_state_set_new_internal (accessible, 0);
1512   }
1513   else
1514   {
1515     guint64 val = ((guint64)states [1]) << 32;
1516     val += states [0];
1517     if (!accessible->states)
1518       accessible->states = _atspi_state_set_new_internal (accessible, val);
1519     else
1520       accessible->states->states = val;
1521   }
1522   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_STATES);
1523 }
1524
1525 GQuark
1526 _atspi_error_quark (void)
1527 {
1528   return g_quark_from_static_string ("atspi_error");
1529 }
1530
1531 /*
1532  * Gets the IOR from the XDisplay.
1533  */
1534 #ifdef HAVE_X11
1535 static char *
1536 get_accessibility_bus_address_x11 (void)
1537 {
1538   Atom AT_SPI_BUS;
1539   Atom actual_type;
1540   Display *bridge_display = NULL;
1541   int actual_format;
1542   char *data;
1543   unsigned char *data_x11 = NULL;
1544   unsigned long nitems;
1545   unsigned long leftover;
1546   char *display_name;
1547
1548   display_name = spi_display_name ();
1549   if (!display_name)
1550     return NULL;
1551
1552   bridge_display = XOpenDisplay (display_name);
1553   g_free (display_name);
1554
1555   if (!bridge_display)
1556     {
1557       g_warning ("Could not open X display");
1558       return NULL;
1559     }
1560
1561   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
1562   XGetWindowProperty (bridge_display,
1563                       XDefaultRootWindow (bridge_display),
1564                       AT_SPI_BUS, 0L,
1565                       (long) BUFSIZ, False,
1566                       (Atom) 31, &actual_type, &actual_format,
1567                       &nitems, &leftover, &data_x11);
1568   XCloseDisplay (bridge_display);
1569
1570   data = g_strdup ((gchar *)data_x11);
1571   XFree (data_x11);
1572   return data;
1573 }
1574 #endif
1575
1576 static char *
1577 get_accessibility_bus_address_dbus (void)
1578 {
1579   DBusConnection *session_bus = NULL;
1580   DBusMessage *message;
1581   DBusMessage *reply;
1582   DBusError error;
1583   char *address = NULL;
1584
1585   session_bus = dbus_bus_get (DBUS_BUS_SESSION, NULL);
1586   if (!session_bus)
1587     return NULL;
1588
1589   message = dbus_message_new_method_call ("org.a11y.Bus",
1590                                           "/org/a11y/bus",
1591                                           "org.a11y.Bus",
1592                                           "GetAddress");
1593
1594   dbus_error_init (&error);
1595   reply = dbus_connection_send_with_reply_and_block (session_bus,
1596                                                      message,
1597                                                      -1,
1598                                                      &error);
1599   dbus_message_unref (message);
1600
1601   if (!reply)
1602   {
1603     g_warning ("AT-SPI: Error retrieving accessibility bus address: %s: %s",
1604                error.name, error.message);
1605     dbus_error_free (&error);
1606     goto out;
1607   }
1608
1609   {
1610     const char *tmp_address;
1611     if (!dbus_message_get_args (reply,
1612                                 NULL,
1613                                 DBUS_TYPE_STRING,
1614                                 &tmp_address,
1615                                 DBUS_TYPE_INVALID))
1616       {
1617         dbus_message_unref (reply);
1618         goto out;
1619       }
1620     address = g_strdup (tmp_address);
1621     dbus_message_unref (reply);
1622   }
1623
1624 out:
1625   dbus_connection_unref (session_bus);
1626   return address;
1627 }
1628
1629 static DBusConnection *a11y_bus;
1630 static dbus_int32_t a11y_dbus_slot = -1;
1631
1632 static void
1633 a11y_bus_free (void *data)
1634 {
1635   if (data == a11y_bus)
1636     {
1637       a11y_bus = NULL;
1638       dbus_connection_free_data_slot (&a11y_dbus_slot);
1639     }
1640 }
1641
1642 /**
1643  * atspi_get_a11y_bus: (skip)
1644  */
1645 DBusConnection *
1646 atspi_get_a11y_bus (void)
1647 {
1648   DBusError error;
1649   char *address = NULL;
1650   const char *address_env = NULL;
1651
1652   if (a11y_bus && dbus_connection_get_is_connected (a11y_bus))
1653     return a11y_bus;
1654
1655   if (a11y_dbus_slot == -1)
1656     if (!dbus_connection_allocate_data_slot (&a11y_dbus_slot))
1657       g_warning ("AT-SPI: Unable to allocate D-Bus slot");
1658
1659   address_env = g_getenv ("AT_SPI_BUS_ADDRESS");
1660   if (address_env != NULL && *address_env != 0)
1661     address = g_strdup (address_env);
1662 #ifdef HAVE_X11
1663   if (!address && g_getenv ("DISPLAY") != NULL &&
1664       g_getenv ("WAYLAND_DISPLAY") == NULL)
1665     address = get_accessibility_bus_address_x11 ();
1666 #endif
1667   if (!address)
1668     address = get_accessibility_bus_address_dbus ();
1669   if (!address)
1670     return NULL;
1671
1672   dbus_error_init (&error);
1673   a11y_bus = dbus_connection_open_private (address, &error);
1674   g_free (address);
1675
1676   if (!a11y_bus)
1677     {
1678       if (!g_getenv("SSH_CONNECTION"))
1679         g_warning ("Couldn't connect to accessibility bus: %s", error.message);
1680       dbus_error_free (&error);
1681       return NULL;
1682     }
1683   else
1684     {
1685       if (!dbus_bus_register (a11y_bus, &error))
1686         {
1687           g_warning ("Couldn't register with accessibility bus: %s", error.message);
1688           dbus_error_free (&error);
1689           dbus_connection_close (a11y_bus);
1690           dbus_connection_unref (a11y_bus);
1691           a11y_bus = NULL;
1692           return NULL;
1693         }
1694     }
1695
1696   /* Simulate a weak ref on the bus */
1697   dbus_connection_set_data (a11y_bus, a11y_dbus_slot, a11y_bus, a11y_bus_free);
1698
1699   return a11y_bus;
1700 }
1701
1702 /**
1703  * atspi_set_timeout:
1704  * @val: The timeout value, in milliseconds, or -1 to disable the timeout.
1705  * @startup_time: The amount of time, in milliseconds, to allow to pass
1706  * before enforcing timeouts on an application. Can be used to prevent
1707  * timeout exceptions if an application is likely to block for an extended
1708  * period of time on initialization. -1 can be passed to disable this
1709  * behavior.
1710  *
1711  * Set the timeout used for method calls. If this is not set explicitly,
1712  * a default of 0.8 ms is used.
1713  * Note that at-spi2-registryd currently uses a timeout of 3 seconds when
1714  * sending a keyboard event notification. This means that, if an AT makes
1715  * a call in response to the keyboard notification and the application
1716  * being called does not respond before the timeout is reached,
1717  * at-spi2-registryd will time out on the keyboard event notification and
1718  * pass the key onto the application (ie, reply to indicate that the key
1719  * was not consumed), so this may make it undesirable to set a timeout
1720  * larger than 3 seconds.
1721  *
1722  * By default, the normal timeout is set to 800 ms, and the application startup
1723  * timeout is set to 15 seconds.
1724  */
1725 void
1726 atspi_set_timeout (gint val, gint startup_time)
1727 {
1728   method_call_timeout = val;
1729   app_startup_time = startup_time;
1730 }
1731
1732 /**
1733  * atspi_set_main_context:
1734  * @cnx: The #GMainContext to use.
1735  *
1736  * Sets the main loop context that AT-SPI should assume is in use when
1737  * setting an idle callback.
1738  * This function should be called by application-side implementors (ie,
1739  * at-spi2-atk) when it is desirable to re-enter the main loop.
1740  */
1741 void
1742 atspi_set_main_context (GMainContext *cnx)
1743 {
1744   if (atspi_main_context == cnx)
1745     return;
1746   if (process_deferred_messages_source != NULL)
1747   {
1748     g_source_destroy (process_deferred_messages_source);
1749     process_deferred_messages_source = g_idle_source_new ();
1750     g_source_set_callback (process_deferred_messages_source,
1751                            process_deferred_messages_callback, NULL, NULL);
1752     g_source_attach (process_deferred_messages_source, cnx);
1753     g_source_unref (process_deferred_messages_source);
1754   }
1755   atspi_main_context = cnx;
1756   atspi_dbus_connection_setup_with_g_main (atspi_get_a11y_bus (), cnx);
1757
1758   if (desktop)
1759   {
1760     gint i;
1761     for (i = desktop->children->len - 1; i >= 0; i--)
1762     {
1763       AtspiAccessible *child = g_ptr_array_index (desktop->children, i);
1764       if (child->parent.app && child->parent.app->bus)
1765         atspi_dbus_connection_setup_with_g_main (child->parent.app->bus, cnx);
1766     }
1767   }
1768 }
1769
1770 #ifdef DEBUG_REF_COUNTS
1771 static void
1772 print_disposed (gpointer key, gpointer value, gpointer data)
1773 {
1774   AtspiAccessible *accessible = key;
1775   if (accessible->parent.app)
1776     return;
1777   g_print ("disposed: %s %d\n", accessible->name, accessible->role);
1778 }
1779
1780 void
1781 debug_disposed ()
1782 {
1783   g_hash_table_foreach (live_refs, print_disposed, NULL);
1784 }
1785 #endif
1786
1787 gchar *
1788 _atspi_name_compat (gchar *name)
1789 {
1790   gchar *p = name;
1791
1792   while (*p)
1793   {
1794     if (*p == '-')
1795       *p = ' ';
1796     p++;
1797   }
1798   return name;
1799 }
1800
1801 /**
1802  * atspi_role_get_name:
1803  * @role: an #AtspiRole object to query.
1804  *
1805  * Gets a localizable string that indicates the name of an #AtspiRole.
1806  * <em>DEPRECATED.</em>
1807  *
1808  * Returns: a localizable string name for an #AtspiRole enumerated type.
1809  **/
1810 gchar *
1811 atspi_role_get_name (AtspiRole role)
1812 {
1813   gchar *retval = NULL;
1814   GTypeClass *type_class;
1815   GEnumValue *value;
1816
1817   type_class = g_type_class_ref (ATSPI_TYPE_ROLE);
1818   g_return_val_if_fail (G_IS_ENUM_CLASS (type_class), NULL);
1819
1820   value = g_enum_get_value (G_ENUM_CLASS (type_class), role);
1821
1822   if (value)
1823     {
1824       retval = g_strdup (value->value_nick);
1825     }
1826
1827   g_type_class_unref (type_class);
1828
1829   if (retval)
1830     return _atspi_name_compat (retval);
1831
1832   return NULL;
1833 }
1834
1835 GHashTable *
1836 _atspi_dbus_update_cache_from_dict (AtspiAccessible *accessible, DBusMessageIter *iter)
1837 {
1838   GHashTable *cache = _atspi_accessible_ref_cache (accessible);
1839   DBusMessageIter iter_dict, iter_dict_entry, iter_struct, iter_variant;
1840
1841   dbus_message_iter_recurse (iter, &iter_dict);
1842   while (dbus_message_iter_get_arg_type (&iter_dict) != DBUS_TYPE_INVALID)
1843   {
1844     const char *key;
1845     GValue *val = NULL;
1846     dbus_message_iter_recurse (&iter_dict, &iter_dict_entry);
1847     dbus_message_iter_get_basic (&iter_dict_entry, &key);
1848     dbus_message_iter_next (&iter_dict_entry);
1849     dbus_message_iter_recurse (&iter_dict_entry, &iter_variant);
1850     if (!strcmp (key, "interfaces"))
1851     {
1852       _atspi_dbus_set_interfaces (accessible, &iter_variant);
1853     }
1854     else if (!strcmp (key, "Attributes"))
1855     {
1856       char *iter_sig = dbus_message_iter_get_signature (&iter_variant);
1857       val = g_new0 (GValue, 1);;
1858       g_value_init (val, G_TYPE_HASH_TABLE);
1859       if (strcmp (iter_sig, "a{ss}") != 0)
1860       {
1861         dbus_free (iter_sig);
1862         break;
1863       }
1864       dbus_free (iter_sig);
1865       g_value_take_boxed (val, _atspi_dbus_hash_from_iter (&iter_variant));
1866     }
1867     else if (!strcmp (key, "Component.ScreenExtents"))
1868     {
1869       dbus_int32_t d_int;
1870       AtspiRect extents;
1871       char *iter_sig = dbus_message_iter_get_signature (&iter_variant);
1872       val = g_new0 (GValue, 1);;
1873       g_value_init (val, ATSPI_TYPE_RECT);
1874       if (strcmp (iter_sig, "(iiii)") != 0)
1875       {
1876         dbus_free (iter_sig);
1877         break;
1878       }
1879       dbus_free (iter_sig);
1880       dbus_message_iter_recurse (&iter_variant, &iter_struct);
1881       dbus_message_iter_get_basic (&iter_struct, &d_int);
1882       extents.x = d_int;
1883       dbus_message_iter_next (&iter_struct);
1884       dbus_message_iter_get_basic (&iter_struct, &d_int);
1885       extents.y = d_int;
1886       dbus_message_iter_next (&iter_struct);
1887       dbus_message_iter_get_basic (&iter_struct, &d_int);
1888       extents.width = d_int;
1889       dbus_message_iter_next (&iter_struct);
1890       dbus_message_iter_get_basic (&iter_struct, &d_int);
1891       extents.height = d_int;
1892       g_value_set_boxed (val, &extents);
1893     }
1894     if (val)
1895       g_hash_table_insert (cache, g_strdup (key), val);
1896     dbus_message_iter_next (&iter_dict);
1897   }
1898
1899   return cache;
1900 }
1901
1902 gboolean
1903 _atspi_get_allow_sync ()
1904 {
1905   return allow_sync;
1906 }
1907
1908 gboolean
1909 _atspi_set_allow_sync (gboolean val)
1910 {
1911   gboolean ret = allow_sync;
1912
1913   allow_sync = val;
1914   return ret;
1915 }
1916
1917 void
1918 _atspi_set_error_no_sync (GError **error)
1919 {
1920   g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_SYNC_NOT_ALLOWED,
1921                         _("Attempted synchronous call where prohibited"));
1922 }
1923
1924 static const char *sr_introspection = "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
1925 "\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
1926 "<node name=\"/org/a11y/atspi/screenreader\">\n"
1927 "  <interface name=\"org.a11y.Atspi.ScreenReader\">\n"
1928 "    <signal name=\"ReadingPosition\">\n"
1929 "      <arg type=\"i\"/>\n"
1930 "      <arg type=\"i\"/>\n"
1931 "    </signal>\n"
1932 "  </interface>\n"
1933 "</node>";
1934
1935 static DBusHandlerResult
1936 screen_reader_filter (DBusConnection *bus, DBusMessage *message, void *user_data)
1937 {
1938   if (dbus_message_is_method_call (message, DBUS_INTERFACE_INTROSPECTABLE,
1939       "Introspect"))
1940   {
1941     DBusMessage *reply = dbus_message_new_method_return (message);
1942     dbus_message_append_args (reply, DBUS_TYPE_STRING, &sr_introspection,
1943                               DBUS_TYPE_INVALID);
1944     dbus_connection_send (bus, reply, NULL);
1945     dbus_message_unref (reply);
1946     return DBUS_HANDLER_RESULT_HANDLED;
1947   }
1948   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1949 }
1950
1951 gboolean
1952 _atspi_prepare_screen_reader_interface ()
1953 {
1954   static gint initialized = 0;
1955   DBusConnection *a11y_bus = _atspi_bus ();
1956
1957   if (initialized)
1958     return (initialized > 0);
1959
1960   if (dbus_bus_request_name (a11y_bus, "org.a11y.Atspi.ScreenReader", 0, NULL) < 0)
1961   {
1962     initialized = -1;
1963     return FALSE;
1964   }
1965
1966   initialized = 1;
1967   dbus_connection_add_filter (a11y_bus, screen_reader_filter, NULL, NULL);
1968   return TRUE;
1969 }