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