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