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