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