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