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