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