Fix some warnings and documentation issues
[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   process_deferred_messages_source = NULL;
750   return G_SOURCE_REMOVE;
751 }
752
753 static DBusHandlerResult
754 defer_message (DBusConnection *connection, DBusMessage *message, void *user_data)
755 {
756   BusDataClosure *closure = g_new (BusDataClosure, 1);
757
758   closure->bus = dbus_connection_ref (bus);
759   closure->message = dbus_message_ref (message);
760   closure->data = user_data;
761
762   g_queue_push_tail (deferred_messages, closure);
763
764   if (process_deferred_messages_source == NULL)
765   {
766     process_deferred_messages_source = g_idle_source_new ();
767     g_source_set_callback (process_deferred_messages_source,
768                            process_deferred_messages_callback, NULL, NULL);
769     g_source_attach (process_deferred_messages_source, atspi_main_context);
770   }
771
772   return DBUS_HANDLER_RESULT_HANDLED;
773 }
774
775 static DBusHandlerResult
776 atspi_dbus_filter (DBusConnection *bus, DBusMessage *message, void *data)
777 {
778   int type = dbus_message_get_type (message);
779   const char *interface = dbus_message_get_interface (message);
780
781   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
782       !strncmp (interface, "org.a11y.atspi.Event.", 21))
783   {
784     return defer_message (bus, message, data);
785   }
786   if (dbus_message_is_method_call (message, atspi_interface_device_event_listener, "NotifyEvent"))
787   {
788     return defer_message (bus, message, data);
789   }
790   if (dbus_message_is_signal (message, atspi_interface_cache, "AddAccessible"))
791   {
792     return defer_message (bus, message, data);
793   }
794   if (dbus_message_is_signal (message, atspi_interface_cache, "RemoveAccessible"))
795   {
796     return defer_message (bus, message, data);
797   }
798   if (dbus_message_is_signal (message, "org.freedesktop.DBus", "NameOwnerChanged"))
799   {
800     defer_message (bus, message, data);
801     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
802   }
803   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
804 }
805
806 /*
807  * Returns a 'canonicalized' value for DISPLAY,
808  * with the screen number stripped off if present.
809  *
810  * TODO: Avoid having duplicate functions for this here and in at-spi2-atk
811  */
812 static gchar *
813 spi_display_name (void)
814 {
815   char *canonical_display_name = NULL;
816   const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
817
818   if (!display_env)
819     {
820       display_env = g_getenv ("DISPLAY");
821       if (!display_env || !display_env[0])
822         return NULL;
823       else
824         {
825           gchar *display_p, *screen_p;
826           canonical_display_name = g_strdup (display_env);
827           display_p = g_utf8_strrchr (canonical_display_name, -1, ':');
828           screen_p = g_utf8_strrchr (canonical_display_name, -1, '.');
829           if (screen_p && display_p && (screen_p > display_p))
830             {
831               *screen_p = '\0';
832             }
833         }
834     }
835   else
836     {
837       canonical_display_name = g_strdup (display_env);
838     }
839
840   return canonical_display_name;
841 }
842
843 /**
844  * atspi_init:
845  *
846  * Connects to the accessibility registry and initializes the SPI.
847  *
848  * Returns: 0 on success, 1 if already initialized, or an integer error code.  
849  **/
850 int
851 atspi_init (void)
852 {
853   char *match;
854   const gchar *no_cache;
855
856   if (atspi_inited)
857     {
858       return 1;
859     }
860
861   atspi_inited = TRUE;
862
863   g_type_init ();
864
865   _atspi_get_live_refs();
866
867   bus = atspi_get_a11y_bus ();
868   if (!bus)
869     return 2;
870   dbus_bus_register (bus, NULL);
871   atspi_dbus_connection_setup_with_g_main(bus, g_main_context_default());
872   dbus_connection_add_filter (bus, atspi_dbus_filter, NULL, NULL);
873   match = g_strdup_printf ("type='signal',interface='%s',member='AddAccessible'", atspi_interface_cache);
874   dbus_bus_add_match (bus, match, NULL);
875   g_free (match);
876   match = g_strdup_printf ("type='signal',interface='%s',member='RemoveAccessible'", atspi_interface_cache);
877   dbus_bus_add_match (bus, match, NULL);
878   g_free (match);
879   match = g_strdup_printf ("type='signal',interface='%s',member='ChildrenChanged'", atspi_interface_event_object);
880   dbus_bus_add_match (bus, match, NULL);
881   g_free (match);
882   match = g_strdup_printf ("type='signal',interface='%s',member='PropertyChange'", atspi_interface_event_object);
883   dbus_bus_add_match (bus, match, NULL);
884   g_free (match);
885   match = g_strdup_printf ("type='signal',interface='%s',member='StateChanged'", atspi_interface_event_object);
886   dbus_bus_add_match (bus, match, NULL);
887   g_free (match);
888
889   dbus_bus_add_match (bus,
890                       "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged'",
891                       NULL);
892
893   no_cache = g_getenv ("ATSPI_NO_CACHE");
894   if (no_cache && g_strcmp0 (no_cache, "0") != 0)
895     atspi_no_cache = TRUE;
896
897   deferred_messages = g_queue_new ();
898
899   return 0;
900 }
901
902 /**
903  * atspi_is_initialized:
904  *
905  * Indicates whether AT-SPI has been initialized.
906  *
907  * Returns: %True if initialized; %False otherwise.
908  */
909 gboolean
910 atspi_is_initialized ()
911 {
912   return atspi_inited;
913 }
914
915 /**
916  * atspi_event_main:
917  *
918  * Starts/enters the main event loop for the AT-SPI services.
919  *
920  * NOTE: This method does not return control; it is exited via a call to
921  * #atspi_event_quit from within an event handler.
922  *
923  **/
924 void
925 atspi_event_main (void)
926 {
927   atspi_main_loop = g_main_loop_new (NULL, FALSE);
928   g_main_loop_run (atspi_main_loop);
929   atspi_main_loop = NULL;
930 }
931
932 /**
933  * atspi_event_quit:
934  *
935  * Quits the last main event loop for the AT-SPI services,
936  * See: #atspi_event_main
937  **/
938 void
939 atspi_event_quit (void)
940 {
941   g_main_loop_quit (atspi_main_loop);
942 }
943
944 /**
945  * atspi_exit:
946  *
947  * Disconnects from #AtspiRegistry instances and releases 
948  * any floating resources. Call only once at exit.
949  *
950  * Returns: 0 if there were no leaks, otherwise other integer values.
951  **/
952 int
953 atspi_exit (void)
954 {
955   int leaked;
956
957   if (!atspi_inited)
958     {
959       return 0;
960     }
961
962   atspi_inited = FALSE;
963
964   if (live_refs)
965     {
966       leaked = g_hash_table_size (live_refs);
967     }
968   else
969     {
970       leaked = 0;
971     }
972
973   cleanup ();
974
975   return leaked;
976 }
977
978 static GSList *hung_processes;
979
980 static void
981 remove_hung_process (DBusPendingCall *pending, void *data)
982 {
983
984   hung_processes = g_slist_remove (hung_processes, data);
985   g_free (data);
986   dbus_pending_call_unref (pending);
987 }
988
989 static void
990 check_for_hang (DBusMessage *message, DBusError *error, DBusConnection *bus, const char *bus_name)
991 {
992   if (!message && error->name &&
993       !strcmp (error->name, "org.freedesktop.DBus.Error.NoReply"))
994   {
995     GSList *l;
996     DBusMessage *message;
997     gchar *bus_name_dup;
998     DBusPendingCall *pending = NULL;
999     for (l = hung_processes; l; l = l->next)
1000       if (!strcmp (l->data, bus_name))
1001         return;
1002     message = dbus_message_new_method_call (bus_name, "/",
1003                                             "org.freedesktop.DBus.Peer",
1004                                             "Ping");
1005     if (!message)
1006       return;
1007     dbus_connection_send_with_reply (bus, message, &pending, -1);
1008     dbus_message_unref (message);
1009     if (!pending)
1010       return;
1011     bus_name_dup = g_strdup (bus_name);
1012     hung_processes = g_slist_append (hung_processes, bus_name_dup);
1013     dbus_pending_call_set_notify (pending, remove_hung_process, bus_name_dup, NULL);
1014   }
1015 }
1016
1017 static gboolean
1018 connection_is_hung (const char *bus_name)
1019 {
1020   GSList *l;
1021
1022   for (l = hung_processes; l; l = l->next)
1023     if (!strcmp (l->data, bus_name))
1024       return TRUE;
1025   return FALSE;
1026 }
1027
1028 static gboolean
1029 check_app (AtspiApplication *app, GError **error)
1030 {
1031   if (!app || !app->bus)
1032   {
1033     g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_APPLICATION_GONE,
1034                           _("The application no longer exists"));
1035     return FALSE;
1036   }
1037
1038   if (atspi_main_loop && connection_is_hung (app->bus_name))
1039   {
1040       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC,
1041                            "The process appears to be hung.");
1042     return FALSE;
1043   }
1044
1045   return TRUE;
1046 }
1047
1048 static void
1049 set_timeout (AtspiApplication *app)
1050 {
1051   struct timeval tv;
1052   int diff;
1053
1054   if (app && app_startup_time > 0)
1055   {
1056     gettimeofday (&tv, NULL);
1057     diff = (tv.tv_sec - app->time_added.tv_sec) * 1000 + (tv.tv_usec - app->time_added.tv_usec) / 1000;
1058     dbind_set_timeout (MAX(method_call_timeout, app_startup_time - diff));
1059   }
1060   else
1061     dbind_set_timeout (method_call_timeout);
1062 }
1063
1064 dbus_bool_t
1065 _atspi_dbus_call (gpointer obj, const char *interface, const char *method, GError **error, const char *type, ...)
1066 {
1067   va_list args;
1068   dbus_bool_t retval;
1069   DBusError err;
1070   AtspiObject *aobj = ATSPI_OBJECT (obj);
1071
1072   if (!check_app (aobj->app, error))
1073     return FALSE;
1074
1075   va_start (args, type);
1076   dbus_error_init (&err);
1077   set_timeout (aobj->app);
1078   retval = dbind_method_call_reentrant_va (aobj->app->bus, aobj->app->bus_name,
1079                                            aobj->path, interface, method, &err,
1080                                            type, args);
1081   va_end (args);
1082   check_for_hang (NULL, &err, aobj->app->bus, aobj->app->bus_name);
1083   process_deferred_messages ();
1084   if (dbus_error_is_set (&err))
1085   {
1086     g_set_error(error, ATSPI_ERROR, ATSPI_ERROR_IPC, "%s", err.message);
1087     dbus_error_free (&err);
1088   }
1089   return retval;
1090 }
1091
1092 DBusMessage *
1093 _atspi_dbus_call_partial (gpointer obj,
1094                           const char *interface,
1095                           const char *method,
1096                           GError **error,
1097                           const char *type, ...)
1098 {
1099   va_list args;
1100
1101   va_start (args, type);
1102   return _atspi_dbus_call_partial_va (obj, interface, method, error, type, args);
1103 }
1104
1105
1106 DBusMessage *
1107 _atspi_dbus_call_partial_va (gpointer obj,
1108                           const char *interface,
1109                           const char *method,
1110                           GError **error,
1111                           const char *type,
1112                           va_list args)
1113 {
1114   AtspiObject *aobj = ATSPI_OBJECT (obj);
1115   DBusError err;
1116     DBusMessage *msg = NULL, *reply = NULL;
1117     DBusMessageIter iter;
1118     const char *p;
1119
1120   dbus_error_init (&err);
1121
1122   if (!check_app (aobj->app, error))
1123     goto out;
1124
1125   msg = dbus_message_new_method_call (aobj->app->bus_name, aobj->path, interface, method);
1126   if (!msg)
1127     goto out;
1128
1129   p = type;
1130   dbus_message_iter_init_append (msg, &iter);
1131   dbind_any_marshal_va (&iter, &p, args);
1132
1133   set_timeout (aobj->app);
1134   reply = dbind_send_and_allow_reentry (aobj->app->bus, msg, &err);
1135   check_for_hang (reply, &err, aobj->app->bus, aobj->app->bus_name);
1136 out:
1137   va_end (args);
1138   if (msg)
1139     dbus_message_unref (msg);
1140   process_deferred_messages ();
1141   if (dbus_error_is_set (&err))
1142   {
1143     /* TODO: Set gerror */
1144     dbus_error_free (&err);
1145   }
1146
1147   if (reply && dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
1148   {
1149     const char *err_str = NULL;
1150     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &err_str, DBUS_TYPE_INVALID);
1151     if (err_str)
1152       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err_str);
1153     dbus_message_unref (reply);
1154     return NULL;
1155   }
1156
1157   return reply;
1158 }
1159
1160 dbus_bool_t
1161 _atspi_dbus_get_property (gpointer obj, const char *interface, const char *name, GError **error, const char *type, void *data)
1162 {
1163   DBusMessage *message, *reply;
1164   DBusMessageIter iter, iter_variant;
1165   DBusError err;
1166   dbus_bool_t retval = FALSE;
1167   AtspiObject *aobj = ATSPI_OBJECT (obj);
1168   char expected_type = (type [0] == '(' ? 'r' : type [0]);
1169
1170   if (!aobj)
1171     return FALSE;
1172
1173   if (!check_app (aobj->app, error))
1174     return FALSE;
1175
1176   message = dbus_message_new_method_call (aobj->app->bus_name,
1177                                           aobj->path,
1178                                           "org.freedesktop.DBus.Properties",
1179                                           "Get");
1180   if (!message)
1181   {
1182     // TODO: throw exception
1183     return FALSE;
1184   }
1185   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1186   dbus_error_init (&err);
1187   set_timeout (aobj->app);
1188   reply = dbind_send_and_allow_reentry (aobj->app->bus, message, &err);
1189   check_for_hang (reply, &err, aobj->app->bus, aobj->app->bus_name);
1190   dbus_message_unref (message);
1191   process_deferred_messages ();
1192   if (!reply)
1193   {
1194     // TODO: throw exception
1195     goto done;
1196   }
1197
1198   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
1199   {
1200     const char *err_str = NULL;
1201     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &err_str, DBUS_TYPE_INVALID);
1202     if (err_str)
1203       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err_str);
1204     goto done;
1205   }
1206
1207   dbus_message_iter_init (reply, &iter);
1208   if (dbus_message_iter_get_arg_type (&iter) != 'v')
1209   {
1210     g_warning ("AT-SPI: expected a variant when fetching %s from interface %s; got %s\n", name, interface, dbus_message_get_signature (reply));
1211     goto done;
1212   }
1213   dbus_message_iter_recurse (&iter, &iter_variant);
1214   if (dbus_message_iter_get_arg_type (&iter_variant) != expected_type)
1215   {
1216     g_warning ("atspi_dbus_get_property: Wrong type: expected %s, got %c\n", type, dbus_message_iter_get_arg_type (&iter_variant));
1217     goto done;
1218   }
1219   if (!strcmp (type, "(so)"))
1220   {
1221     *((AtspiAccessible **)data) = _atspi_dbus_return_accessible_from_iter (&iter_variant);
1222   }
1223   else
1224   {
1225     dbus_message_iter_get_basic (&iter_variant, data);
1226     if (type [0] == 's')
1227       *(char **)data = g_strdup (*(char **)data);
1228   }
1229   retval = TRUE;
1230 done:
1231   dbus_error_free (&err);
1232   if (reply)
1233     dbus_message_unref (reply);
1234   return retval;
1235 }
1236
1237 DBusMessage *
1238 _atspi_dbus_send_with_reply_and_block (DBusMessage *message, GError **error)
1239 {
1240   DBusMessage *reply;
1241   DBusError err;
1242   AtspiApplication *app;
1243   DBusConnection *bus;
1244
1245   app = get_application (dbus_message_get_destination (message));
1246
1247   if (app && !app->bus)
1248     return NULL;        /* will fail anyway; app has been disposed */
1249
1250   bus = (app ? app->bus : _atspi_bus());
1251   dbus_error_init (&err);
1252   set_timeout (app);
1253   reply = dbind_send_and_allow_reentry (bus, message, &err);
1254   process_deferred_messages ();
1255   dbus_message_unref (message);
1256   if (dbus_error_is_set (&err))
1257   {
1258     if (error)
1259       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err.message);
1260     dbus_error_free (&err);
1261   }
1262   return reply;
1263 }
1264
1265 GHashTable *
1266 _atspi_dbus_return_hash_from_message (DBusMessage *message)
1267 {
1268   DBusMessageIter iter;
1269   GHashTable *ret;
1270
1271   if (!message)
1272     return NULL;
1273
1274   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1275
1276   dbus_message_iter_init (message, &iter);
1277   ret = _atspi_dbus_hash_from_iter (&iter);
1278   dbus_message_unref (message);
1279   return ret;
1280 }
1281
1282 GHashTable *
1283 _atspi_dbus_hash_from_iter (DBusMessageIter *iter)
1284 {
1285   GHashTable *hash = g_hash_table_new_full (g_str_hash, g_str_equal,
1286                                             (GDestroyNotify) g_free,
1287                                             (GDestroyNotify) g_free);
1288   DBusMessageIter iter_array, iter_dict;
1289
1290   dbus_message_iter_recurse (iter, &iter_array);
1291   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1292   {
1293     const char *name, *value;
1294     dbus_message_iter_recurse (&iter_array, &iter_dict);
1295     dbus_message_iter_get_basic (&iter_dict, &name);
1296     dbus_message_iter_next (&iter_dict);
1297     dbus_message_iter_get_basic (&iter_dict, &value);
1298     g_hash_table_insert (hash, g_strdup (name), g_strdup (value));
1299     dbus_message_iter_next (&iter_array);
1300   }
1301   return hash;
1302 }
1303
1304 GArray *
1305 _atspi_dbus_return_attribute_array_from_message (DBusMessage *message)
1306 {
1307   DBusMessageIter iter;
1308   GArray *ret;
1309
1310   if (!message)
1311     return NULL;
1312
1313   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1314
1315   dbus_message_iter_init (message, &iter);
1316
1317   ret = _atspi_dbus_attribute_array_from_iter (&iter);
1318   dbus_message_unref (message);
1319   return ret;
1320 }
1321
1322 GArray *
1323 _atspi_dbus_attribute_array_from_iter (DBusMessageIter *iter)
1324 {
1325   DBusMessageIter iter_array, iter_dict;
1326   GArray *array = g_array_new (TRUE, TRUE, sizeof (gchar *));
1327
1328   dbus_message_iter_recurse (iter, &iter_array);
1329   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1330   {
1331     const char *name, *value;
1332     gchar *str;
1333     dbus_message_iter_recurse (&iter_array, &iter_dict);
1334     dbus_message_iter_get_basic (&iter_dict, &name);
1335     dbus_message_iter_next (&iter_dict);
1336     dbus_message_iter_get_basic (&iter_dict, &value);
1337     str = g_strdup_printf ("%s:%s", name, value);
1338     array = g_array_append_val (array, str);
1339     dbus_message_iter_next (&iter_array);;
1340   }
1341   return array;
1342 }
1343
1344 void
1345 _atspi_dbus_set_interfaces (AtspiAccessible *accessible, DBusMessageIter *iter)
1346 {
1347   DBusMessageIter iter_array;
1348
1349   accessible->interfaces = 0;
1350   dbus_message_iter_recurse (iter, &iter_array);
1351   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1352   {
1353     const char *iface;
1354     gint n;
1355     dbus_message_iter_get_basic (&iter_array, &iface);
1356     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable")) continue;
1357     n = _atspi_get_iface_num (iface);
1358     if (n == -1)
1359     {
1360       g_warning ("AT-SPI: Unknown interface %s", iface);
1361     }
1362     else
1363       accessible->interfaces |= (1 << n);
1364     dbus_message_iter_next (&iter_array);
1365   }
1366   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_INTERFACES);
1367 }
1368
1369 void
1370 _atspi_dbus_set_state (AtspiAccessible *accessible, DBusMessageIter *iter)
1371 {
1372   DBusMessageIter iter_array;
1373   gint count;
1374   dbus_uint32_t *states;
1375
1376   dbus_message_iter_recurse (iter, &iter_array);
1377   dbus_message_iter_get_fixed_array (&iter_array, &states, &count);
1378   if (count != 2)
1379   {
1380     g_warning ("AT-SPI: expected 2 values in states array; got %d\n", count);
1381     if (!accessible->states)
1382       accessible->states = _atspi_state_set_new_internal (accessible, 0);
1383   }
1384   else
1385   {
1386     guint64 val = ((guint64)states [1]) << 32;
1387     val += states [0];
1388     if (!accessible->states)
1389       accessible->states = _atspi_state_set_new_internal (accessible, val);
1390     else
1391       accessible->states->states = val;
1392   }
1393   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_STATES);
1394 }
1395
1396 GQuark
1397 _atspi_error_quark (void)
1398 {
1399   return g_quark_from_static_string ("atspi_error");
1400 }
1401
1402 /*
1403  * Gets the IOR from the XDisplay.
1404  */
1405 #ifdef HAVE_X11
1406 static char *
1407 get_accessibility_bus_address_x11 (void)
1408 {
1409   Atom AT_SPI_BUS;
1410   Atom actual_type;
1411   Display *bridge_display = NULL;
1412   int actual_format;
1413   char *data;
1414   unsigned char *data_x11 = NULL;
1415   unsigned long nitems;
1416   unsigned long leftover;
1417   char *display_name;
1418
1419   display_name = spi_display_name ();
1420   if (!display_name)
1421     return NULL;
1422
1423   bridge_display = XOpenDisplay (display_name);
1424   g_free (display_name);
1425
1426   if (!bridge_display)
1427     {
1428       g_warning ("Could not open X display");
1429       return NULL;
1430     }
1431       
1432   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
1433   XGetWindowProperty (bridge_display,
1434                       XDefaultRootWindow (bridge_display),
1435                       AT_SPI_BUS, 0L,
1436                       (long) BUFSIZ, False,
1437                       (Atom) 31, &actual_type, &actual_format,
1438                       &nitems, &leftover, &data_x11);
1439   XCloseDisplay (bridge_display);
1440
1441   data = g_strdup ((gchar *)data_x11);
1442   XFree (data_x11);
1443   return data;
1444 }
1445 #endif
1446
1447 static char *
1448 get_accessibility_bus_address_dbus (void)
1449 {
1450   DBusConnection *session_bus = NULL;
1451   DBusMessage *message;
1452   DBusMessage *reply;
1453   DBusError error;
1454   char *address = NULL;
1455
1456   session_bus = dbus_bus_get (DBUS_BUS_SESSION, NULL);
1457   if (!session_bus)
1458     return NULL;
1459
1460   message = dbus_message_new_method_call ("org.a11y.Bus",
1461                                           "/org/a11y/bus",
1462                                           "org.a11y.Bus",
1463                                           "GetAddress");
1464
1465   dbus_error_init (&error);
1466   reply = dbus_connection_send_with_reply_and_block (session_bus,
1467                                                      message,
1468                                                      -1,
1469                                                      &error);
1470   dbus_message_unref (message);
1471
1472   if (!reply)
1473   {
1474     g_warning ("Error retrieving accessibility bus address: %s: %s",
1475                error.name, error.message);
1476     dbus_error_free (&error);
1477     return NULL;
1478   }
1479   
1480   {
1481     const char *tmp_address;
1482     if (!dbus_message_get_args (reply,
1483                                 NULL,
1484                                 DBUS_TYPE_STRING,
1485                                 &tmp_address,
1486                                 DBUS_TYPE_INVALID))
1487       {
1488         dbus_message_unref (reply);
1489         return NULL;
1490       }
1491     address = g_strdup (tmp_address);
1492     dbus_message_unref (reply);
1493   }
1494   
1495   return address;
1496 }
1497
1498 static DBusConnection *a11y_bus;
1499 static dbus_int32_t a11y_dbus_slot = -1;
1500
1501 static void
1502 a11y_bus_free (void *data)
1503 {
1504   if (data == a11y_bus)
1505     {
1506       a11y_bus = NULL;
1507       dbus_connection_free_data_slot (&a11y_dbus_slot);
1508     }
1509 }
1510
1511 DBusConnection *
1512 atspi_get_a11y_bus (void)
1513 {
1514   DBusError error;
1515   char *address = NULL;
1516
1517   if (a11y_bus && dbus_connection_get_is_connected (a11y_bus))
1518     return a11y_bus;
1519
1520   if (a11y_dbus_slot == -1)
1521     if (!dbus_connection_allocate_data_slot (&a11y_dbus_slot))
1522       g_warning ("at-spi: Unable to allocate D-Bus slot");
1523
1524 #ifdef HAVE_X11
1525   address = get_accessibility_bus_address_x11 ();
1526 #endif
1527   if (!address)
1528     address = get_accessibility_bus_address_dbus ();
1529   if (!address)
1530     return NULL;
1531
1532   dbus_error_init (&error);
1533   a11y_bus = dbus_connection_open_private (address, &error);
1534   g_free (address);
1535
1536   if (!a11y_bus)
1537     {
1538       g_warning ("Couldn't connect to accessibility bus: %s", error.message);
1539       dbus_error_free (&error);
1540       return NULL;
1541     }
1542   else
1543     {
1544       if (!dbus_bus_register (a11y_bus, &error))
1545         {
1546           g_warning ("Couldn't register with accessibility bus: %s", error.message);
1547           dbus_error_free (&error);
1548           dbus_connection_close (a11y_bus);
1549           dbus_connection_unref (a11y_bus);
1550           a11y_bus = NULL;
1551           return NULL;
1552         }
1553     }
1554   
1555   /* Simulate a weak ref on the bus */
1556   dbus_connection_set_data (a11y_bus, a11y_dbus_slot, a11y_bus, a11y_bus_free);
1557
1558   return a11y_bus;
1559 }
1560
1561 /**
1562  * atspi_set_timeout:
1563  *  @val: The timeout value, in milliseconds, or -1 to disable the timeout.
1564  *  @startup_time: The amount of time, in milliseconds, to allow to pass
1565  *  before enforcing timeouts on an application. Can be used to prevent
1566  *  timeout exceptions if an application is likely to block for an extended
1567  *  period of time on initialization. -1 can be passed to disable this
1568  *  behavior.
1569  *
1570  *  Set the timeout used for method calls. If this is not set explicitly,
1571  *  a default of 0.8 ms is used.
1572  *  Note that at-spi2-registryd currently uses a timeout of 3 seconds when
1573  *  sending a keyboard event notification. This means that, if an AT makes
1574  *  a call in response to the keyboard notification and the application
1575  *  being called does not respond before the timeout is reached,
1576  *  at-spi2-registryd will time out on the keyboard event notification and
1577  *  pass the key onto the application (ie, reply to indicate that the key
1578  *  was not consumed), so this may make it undesirable to set a timeout
1579  *  larger than 3 seconds.
1580  *
1581  * By default, the normal timeout is set to 800 ms, and the application startup
1582  * timeout is set to 15 seconds.
1583  */
1584 void
1585 atspi_set_timeout (gint val, gint startup_time)
1586 {
1587   method_call_timeout = val;
1588   app_startup_time = startup_time;
1589 }
1590
1591 /*
1592  * atspi_set_main_context:
1593  * @cnx: The #GmainContext to use.
1594  *
1595  * Sets the main loop context that AT-SPI should assume is in use when
1596  * setting an idle callback.
1597  * This function should be called by application-side implementors (ie,
1598  * at-spi2-atk) when it is desirable to re-enter the main loop.
1599  */
1600 void
1601 atspi_set_main_context (GMainContext *cnx)
1602 {
1603   if (atspi_main_context == cnx)
1604     return;
1605   if (process_deferred_messages_source != NULL)
1606   {
1607     g_source_destroy (process_deferred_messages_source);
1608     process_deferred_messages_source = g_idle_source_new ();
1609     g_source_set_callback (process_deferred_messages_source,
1610                            process_deferred_messages_callback, NULL, NULL);
1611     g_source_attach (process_deferred_messages_source, cnx);
1612   }
1613   atspi_main_context = cnx;
1614   atspi_dbus_connection_setup_with_g_main (atspi_get_a11y_bus (), cnx);
1615 }
1616
1617 #ifdef DEBUG_REF_COUNTS
1618 static void
1619 print_disposed (gpointer key, gpointer value, gpointer data)
1620 {
1621   AtspiAccessible *accessible = key;
1622   if (accessible->parent.app)
1623     return;
1624   g_print ("disposed: %s %d\n", accessible->name, accessible->role);
1625 }
1626
1627 void
1628 debug_disposed ()
1629 {
1630   g_hash_table_foreach (live_refs, print_disposed, NULL);
1631 }
1632 #endif
1633
1634 gchar *
1635 _atspi_name_compat (gchar *name)
1636 {
1637   gchar *p = name;
1638
1639   while (*p)
1640   {
1641     if (*p == '-')
1642       *p = ' ';
1643     p++;
1644   }
1645   return name;
1646 }
1647
1648 /**
1649  * atspi_role_get_name:
1650  * @role: an #AtspiRole object to query.
1651  *
1652  * Gets a localizable string that indicates the name of an #AtspiRole.
1653  * <em>DEPRECATED.</em>
1654  *
1655  * Returns: a localizable string name for an #AtspiRole enumerated type.
1656  **/
1657 gchar *
1658 atspi_role_get_name (AtspiRole role)
1659 {
1660   gchar *retval = NULL;
1661   GTypeClass *type_class;
1662   GEnumValue *value;
1663
1664   type_class = g_type_class_ref (ATSPI_TYPE_ROLE);
1665   g_return_val_if_fail (G_IS_ENUM_CLASS (type_class), NULL);
1666
1667   value = g_enum_get_value (G_ENUM_CLASS (type_class), role);
1668
1669   if (value)
1670     {
1671       retval = g_strdup (value->value_nick);
1672     }
1673
1674   if (retval)
1675     return _atspi_name_compat (retval);
1676
1677   return NULL;
1678 }