ref_accessible_desktop: don't unref reply until we're finished with it
[platform/upstream/at-spi2-core.git] / atspi / atspi-misc.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2001, 2002 Sun Microsystems Inc.,
6  * Copyright 2001, 2002 Ximian, Inc.
7  * Copyright 2010, 2011 Novell, Inc.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 /*
26  *
27  * Basic SPI initialization and event loop function prototypes
28  *
29  */
30
31 #include "atspi-private.h"
32 #ifdef HAVE_X11
33 #include "X11/Xlib.h"
34 #endif
35 #include "atspi-gmain.h"
36 #include <stdio.h>
37 #include <string.h>
38
39 static void handle_get_items (DBusPendingCall *pending, void *user_data);
40
41 static DBusConnection *bus = NULL;
42 static GHashTable *live_refs = NULL;
43 static gint method_call_timeout = 800;
44 static gint app_startup_time = 15000;
45 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       }
202       else
203       {
204         if (!strcmp (error.name, DBUS_ERROR_FILE_NOT_FOUND))
205           g_warning ("Unable to open bus connection: %s", error.message);
206         dbus_error_free (&error);
207       }
208     }
209   }
210   dbus_message_unref (reply);
211   dbus_pending_call_unref (pending);
212
213   if (!app->bus)
214     return; /* application has gone away / been disposed */
215
216   message = dbus_message_new_method_call (app->bus_name,
217                                           "/org/a11y/atspi/cache",
218                                           atspi_interface_cache, "GetItems");
219
220   dbus_connection_send_with_reply (app->bus, message, &new_pending, 2000);
221   dbus_message_unref (message);
222   if (!new_pending)
223     return;
224   dbus_pending_call_set_notify (new_pending, handle_get_items, app, NULL);
225 }
226
227 static AtspiApplication *
228 get_application (const char *bus_name)
229 {
230   AtspiApplication *app = NULL;
231   char *bus_name_dup;
232   DBusMessage *message;
233   DBusPendingCall *pending = NULL;
234
235   if (!app_hash)
236   {
237     app_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_object_unref);
238     if (!app_hash) return NULL;
239   }
240   app = g_hash_table_lookup (app_hash, bus_name);
241   if (app) return app;
242   bus_name_dup = g_strdup (bus_name);
243   if (!bus_name_dup) return NULL;
244   // TODO: change below to something that will send state-change:defunct notification if necessary */
245   app = _atspi_application_new (bus_name);
246   app->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
247   app->bus = dbus_connection_ref (_atspi_bus ());
248   gettimeofday (&app->time_added, NULL);
249   app->cache = ATSPI_CACHE_UNDEFINED;
250   g_hash_table_insert (app_hash, bus_name_dup, app);
251   message = dbus_message_new_method_call (bus_name, atspi_path_root,
252                                           atspi_interface_application, "GetApplicationBusAddress");
253
254   dbus_connection_send_with_reply (app->bus, message, &pending, 2000);
255   dbus_message_unref (message);
256   if (!pending)
257   {
258     g_hash_table_remove (app_hash, bus_name_dup);
259     return NULL;
260   }
261   dbus_pending_call_set_notify (pending, handle_get_bus_address, app, NULL);
262   return app;
263 }
264
265 static AtspiAccessible *
266 ref_accessible (const char *app_name, const char *path)
267 {
268   AtspiApplication *app;
269   AtspiAccessible *a;
270
271   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
272     return NULL;
273
274   app = get_application (app_name);
275
276   if (!strcmp (path, "/org/a11y/atspi/accessible/root"))
277   {
278     if (!app->root)
279     {
280       app->root = _atspi_accessible_new (app, atspi_path_root);
281       app->root->accessible_parent = atspi_get_desktop (0);
282       g_ptr_array_add (app->root->accessible_parent->children, g_object_ref (app->root));
283     }
284     return g_object_ref (app->root);
285   }
286
287   a = g_hash_table_lookup (app->hash, path);
288   if (a)
289   {
290     return g_object_ref (a);
291   }
292   a = _atspi_accessible_new (app, path);
293   if (!a)
294     return NULL;
295   g_hash_table_insert (app->hash, g_strdup (a->parent.path), g_object_ref (a));
296   return a;
297 }
298
299 static AtspiHyperlink *
300 ref_hyperlink (const char *app_name, const char *path)
301 {
302   AtspiApplication *app = get_application (app_name);
303   AtspiHyperlink *hyperlink;
304
305   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
306     return NULL;
307
308   hyperlink = g_hash_table_lookup (app->hash, path);
309   if (hyperlink)
310   {
311     return g_object_ref (hyperlink);
312   }
313   hyperlink = _atspi_hyperlink_new (app, path);
314   g_hash_table_insert (app->hash, g_strdup (hyperlink->parent.path), hyperlink);
315   /* TODO: This should be a weak ref */
316   g_object_ref (hyperlink);     /* for the hash */
317   return hyperlink;
318 }
319
320 typedef struct
321 {
322   char *path;
323   char *parent;
324   GArray *children;
325   GArray *interfaces;
326   char *name;
327   dbus_uint32_t role;
328   char *description;
329   GArray *state_bitflags;
330 } CACHE_ADDITION;
331
332 static DBusHandlerResult
333 handle_remove_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
334 {
335   const char *sender = dbus_message_get_sender (message);
336   AtspiApplication *app;
337   const char *path;
338   DBusMessageIter iter, iter_struct;
339   const char *signature = dbus_message_get_signature (message);
340   AtspiAccessible *a;
341
342   if (strcmp (signature, "(so)") != 0)
343   {
344     g_warning ("AT-SPI: Unknown signature %s for RemoveAccessible", signature);
345     return DBUS_HANDLER_RESULT_HANDLED;
346   }
347
348   dbus_message_iter_init (message, &iter);
349   dbus_message_iter_recurse (&iter, &iter_struct);
350   dbus_message_iter_get_basic (&iter_struct, &sender);
351   dbus_message_iter_next (&iter_struct);
352   dbus_message_iter_get_basic (&iter_struct, &path);
353   app = get_application (sender);
354   a = ref_accessible (sender, path);
355   if (!a)
356     return DBUS_HANDLER_RESULT_HANDLED;
357   g_object_run_dispose (G_OBJECT (a));
358   g_hash_table_remove (app->hash, a->parent.path);
359   g_object_unref (a);   /* unref our own ref */
360   return DBUS_HANDLER_RESULT_HANDLED;
361 }
362
363 static DBusHandlerResult
364 handle_name_owner_changed (DBusConnection *bus, DBusMessage *message, void *user_data)
365 {
366   const char *name, *new, *old;
367   static gboolean registry_lost = FALSE;
368
369   if (!dbus_message_get_args (message, NULL,
370                               DBUS_TYPE_STRING, &name,
371                               DBUS_TYPE_STRING, &old,
372                               DBUS_TYPE_STRING, &new,
373                               DBUS_TYPE_INVALID))
374   {
375     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
376   }
377
378   if (!strcmp (name, "org.a11y.atspi.Registry"))
379   {
380     if (registry_lost && !old[0])
381     {
382       _atspi_reregister_event_listeners ();
383       _atspi_reregister_device_listeners ();
384       registry_lost = FALSE;
385     }
386     else if (!new[0])
387       registry_lost = TRUE;
388   }
389   else if (app_hash)
390   {
391     AtspiApplication *app = g_hash_table_lookup (app_hash, old);
392     if (app)
393       g_object_run_dispose (G_OBJECT (app));
394   }
395   return DBUS_HANDLER_RESULT_HANDLED;
396 }
397
398 static gboolean
399 add_app_to_desktop (AtspiAccessible *a, const char *bus_name)
400 {
401   AtspiAccessible *obj = ref_accessible (bus_name, atspi_path_root);
402   /* The app will be added to the desktop as a side-effect of calling
403    * ref_accessible */
404   g_object_unref (obj);
405   return (obj != NULL);
406 }
407
408 void
409 get_reference_from_iter (DBusMessageIter *iter, const char **app_name, const char **path)
410 {
411   DBusMessageIter iter_struct;
412
413   dbus_message_iter_recurse (iter, &iter_struct);
414   dbus_message_iter_get_basic (&iter_struct, app_name);
415   dbus_message_iter_next (&iter_struct);
416   dbus_message_iter_get_basic (&iter_struct, path);
417   dbus_message_iter_next (iter);
418 }
419
420 static void
421 add_accessible_from_iter (DBusMessageIter *iter)
422 {
423   DBusMessageIter iter_struct, iter_array;
424   const char *app_name, *path;
425   AtspiAccessible *accessible;
426   const char *name, *description;
427   dbus_uint32_t role;
428   gboolean children_cached = FALSE;
429   dbus_int32_t count, index;
430
431   dbus_message_iter_recurse (iter, &iter_struct);
432
433   /* get accessible */
434   get_reference_from_iter (&iter_struct, &app_name, &path);
435   accessible = ref_accessible (app_name, path);
436   if (!accessible)
437     return;
438
439   /* Get application: TODO */
440   dbus_message_iter_next (&iter_struct);
441
442   /* get parent */
443   get_reference_from_iter (&iter_struct, &app_name, &path);
444   if (accessible->accessible_parent)
445     g_object_unref (accessible->accessible_parent);
446   accessible->accessible_parent = ref_accessible (app_name, path);
447
448   if (dbus_message_iter_get_arg_type (&iter_struct) == 'i')
449   {
450     /* Get index in parent */
451     dbus_message_iter_get_basic (&iter_struct, &index);
452     if (index >= 0 && accessible->accessible_parent)
453     {
454       if (index >= accessible->accessible_parent->children->len)
455         g_ptr_array_set_size (accessible->accessible_parent->children, index + 1);
456       g_ptr_array_index (accessible->accessible_parent->children, index) = g_object_ref (accessible);
457     }
458
459     /* get child count */
460     dbus_message_iter_next (&iter_struct);
461     dbus_message_iter_get_basic (&iter_struct, &count);
462     if (count >= 0)
463     {
464       g_ptr_array_set_size (accessible->children, count);
465       children_cached = TRUE;
466     }
467   }
468   else if (dbus_message_iter_get_arg_type (&iter_struct) == 'a')
469   {
470     /* It's the old API with a list of children */
471     /* TODO: Perhaps remove this code eventually */
472     dbus_message_iter_recurse (&iter_struct, &iter_array);
473     while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
474     {
475       AtspiAccessible *child;
476       get_reference_from_iter (&iter_array, &app_name, &path);
477       child = ref_accessible (app_name, path);
478       g_ptr_array_remove (accessible->children, child);
479       g_ptr_array_add (accessible->children, child);
480     }
481     children_cached = TRUE;
482   }
483
484   /* interfaces */
485   dbus_message_iter_next (&iter_struct);
486   _atspi_dbus_set_interfaces (accessible, &iter_struct);
487   dbus_message_iter_next (&iter_struct);
488
489   /* name */
490   if (accessible->name)
491     g_free (accessible->name);
492   dbus_message_iter_get_basic (&iter_struct, &name);
493   accessible->name = g_strdup (name);
494   dbus_message_iter_next (&iter_struct);
495
496   /* role */
497   dbus_message_iter_get_basic (&iter_struct, &role);
498   accessible->role = role;
499   dbus_message_iter_next (&iter_struct);
500
501   /* description */
502   if (accessible->description)
503     g_free (accessible->description);
504   dbus_message_iter_get_basic (&iter_struct, &description);
505   accessible->description = g_strdup (description);
506   dbus_message_iter_next (&iter_struct);
507
508   _atspi_dbus_set_state (accessible, &iter_struct);
509   dbus_message_iter_next (&iter_struct);
510
511   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_NAME | ATSPI_CACHE_ROLE |
512                                ATSPI_CACHE_PARENT | ATSPI_CACHE_DESCRIPTION);
513   if (!atspi_state_set_contains (accessible->states,
514                                        ATSPI_STATE_MANAGES_DESCENDANTS) &&
515                                        children_cached)
516     _atspi_accessible_add_cache (accessible, ATSPI_CACHE_CHILDREN);
517
518   /* This is a bit of a hack since the cache holds a ref, so we don't need
519    * the one provided for us anymore */
520   g_object_unref (accessible);
521 }
522
523 static void
524 handle_get_items (DBusPendingCall *pending, void *user_data)
525 {
526   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
527   DBusMessageIter iter, iter_array;
528
529   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
530   {
531     const char *sender = dbus_message_get_sender (reply);
532     const char *error = NULL;
533     if (!strcmp (dbus_message_get_error_name (reply),
534                  DBUS_ERROR_SERVICE_UNKNOWN))
535     {
536     }
537     else
538     {
539       dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &error,
540                              DBUS_TYPE_INVALID);
541       g_warning ("AT-SPI: Error in GetItems, sender=%s, error=%s", sender, error);
542     }
543     dbus_message_unref (reply);
544     dbus_pending_call_unref (pending);
545     return;
546   }
547
548   dbus_message_iter_init (reply, &iter);
549   dbus_message_iter_recurse (&iter, &iter_array);
550   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
551   {
552     add_accessible_from_iter (&iter_array);
553     dbus_message_iter_next (&iter_array);
554   }
555   dbus_message_unref (reply);
556   dbus_pending_call_unref (pending);
557 }
558
559 /* TODO: Do we stil need this function? */
560 static AtspiAccessible *
561 ref_accessible_desktop (AtspiApplication *app)
562 {
563   GError *error;
564   DBusMessage *message, *reply;
565   DBusMessageIter iter, iter_array;
566   gchar *bus_name_dup;
567
568   if (desktop)
569   {
570     g_object_ref (desktop);
571     return desktop;
572   }
573   desktop = _atspi_accessible_new (app, atspi_path_root);
574   if (!desktop)
575   {
576     return NULL;
577   }
578   g_hash_table_insert (app->hash, g_strdup (desktop->parent.path),
579                        g_object_ref (desktop));
580   app->root = g_object_ref (desktop);
581   desktop->name = g_strdup ("main");
582   message = dbus_message_new_method_call (atspi_bus_registry,
583         atspi_path_root,
584         atspi_interface_accessible,
585         "GetChildren");
586   if (!message)
587     return NULL;
588   error = NULL;
589   reply = _atspi_dbus_send_with_reply_and_block (message, &error);
590   if (!reply || strcmp (dbus_message_get_signature (reply), "a(so)") != 0)
591   {
592     if (error != NULL)
593     {
594       g_warning ("Couldn't get application list: %s", error->message);
595       g_clear_error (&error);
596     }
597     if (reply)
598       dbus_message_unref (reply);
599     return NULL;
600   }
601   dbus_message_iter_init (reply, &iter);
602   dbus_message_iter_recurse (&iter, &iter_array);
603   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
604   {
605     const char *app_name, *path;
606     get_reference_from_iter (&iter_array, &app_name, &path);
607     add_app_to_desktop (desktop, app_name);
608   }
609
610   /* Record the alternate name as an alias for org.a11y.atspi.Registry */
611   bus_name_dup = g_strdup (dbus_message_get_sender (reply));
612   if (bus_name_dup)
613     g_hash_table_insert (app_hash, bus_name_dup, app);
614
615   dbus_message_unref (reply);
616
617   return g_object_ref (desktop);
618 }
619
620 AtspiAccessible *
621 _atspi_ref_accessible (const char *app, const char *path)
622 {
623   AtspiApplication *a = get_application (app);
624   if (!a)
625     return NULL;
626   if ( APP_IS_REGISTRY(a))
627   {
628     if (!a->root)
629       g_object_unref (ref_accessible_desktop (a));      /* sets a->root */
630     return g_object_ref (a->root);
631   }
632   return ref_accessible (app, path);
633 }
634
635 AtspiAccessible *
636 _atspi_dbus_return_accessible_from_message (DBusMessage *message)
637 {
638   DBusMessageIter iter;
639   AtspiAccessible *retval = NULL;
640   const char *signature;
641
642   if (!message)
643     return NULL;
644
645   signature = dbus_message_get_signature (message);
646   if (!strcmp (signature, "(so)"))
647   {
648     dbus_message_iter_init (message, &iter);
649     retval =  _atspi_dbus_return_accessible_from_iter (&iter);
650   }
651   else
652   {
653     g_warning ("AT-SPI: Called _atspi_dbus_return_accessible_from_message with strange signature %s", signature);
654   }
655   dbus_message_unref (message);
656   return retval;
657 }
658
659 AtspiAccessible *
660 _atspi_dbus_return_accessible_from_iter (DBusMessageIter *iter)
661 {
662   const char *app_name, *path;
663
664   get_reference_from_iter (iter, &app_name, &path);
665   return ref_accessible (app_name, path);
666 }
667
668 AtspiHyperlink *
669 _atspi_dbus_return_hyperlink_from_message (DBusMessage *message)
670 {
671   DBusMessageIter iter;
672   AtspiHyperlink *retval = NULL;
673   const char *signature;
674    
675   if (!message)
676     return NULL;
677
678   signature = dbus_message_get_signature (message);
679   if (!strcmp (signature, "(so)"))
680   {
681     dbus_message_iter_init (message, &iter);
682     retval =  _atspi_dbus_return_hyperlink_from_iter (&iter);
683   }
684   else
685   {
686     g_warning ("AT-SPI: Called _atspi_dbus_return_hyperlink_from_message with strange signature %s", signature);
687   }
688   dbus_message_unref (message);
689   return retval;
690 }
691
692 AtspiHyperlink *
693 _atspi_dbus_return_hyperlink_from_iter (DBusMessageIter *iter)
694 {
695   const char *app_name, *path;
696
697   get_reference_from_iter (iter, &app_name, &path);
698   return ref_hyperlink (app_name, path);
699 }
700
701 const char *cache_signal_type = "((so)(so)(so)iiassusau)";
702 const char *old_cache_signal_type = "((so)(so)(so)a(so)assusau)";
703
704 static DBusHandlerResult
705 handle_add_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
706 {
707   DBusMessageIter iter;
708   const char *signature = dbus_message_get_signature (message);
709
710   if (strcmp (signature, cache_signal_type) != 0 &&
711       strcmp (signature, old_cache_signal_type) != 0)
712   {
713     g_warning ("AT-SPI: AddAccessible with unknown signature %s\n", signature);
714     return DBUS_HANDLER_RESULT_HANDLED;
715   }
716
717   dbus_message_iter_init (message, &iter);
718   add_accessible_from_iter (&iter);
719   return DBUS_HANDLER_RESULT_HANDLED;
720 }
721
722 typedef struct
723 {
724   DBusConnection *bus;
725   DBusMessage *message;
726   void *data;
727 } BusDataClosure;
728
729 static GSource *process_deferred_messages_source = NULL;
730
731 static void
732 process_deferred_message (BusDataClosure *closure)
733 {
734   int type = dbus_message_get_type (closure->message);
735   const char *interface = dbus_message_get_interface (closure->message);
736
737   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
738       !strncmp (interface, "org.a11y.atspi.Event.", 21))
739   {
740     _atspi_dbus_handle_event (closure->bus, closure->message, closure->data);
741   }
742   if (dbus_message_is_method_call (closure->message, atspi_interface_device_event_listener, "NotifyEvent"))
743   {
744     _atspi_dbus_handle_DeviceEvent (closure->bus,
745                                    closure->message, closure->data);
746   }
747   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "AddAccessible"))
748   {
749     handle_add_accessible (closure->bus, closure->message, closure->data);
750   }
751   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "RemoveAccessible"))
752   {
753     handle_remove_accessible (closure->bus, closure->message, closure->data);
754   }
755   if (dbus_message_is_signal (closure->message, "org.freedesktop.DBus", "NameOwnerChanged"))
756   {
757     handle_name_owner_changed (closure->bus, closure->message, closure->data);
758   }
759 }
760
761 static GQueue *deferred_messages = NULL;
762
763 static gboolean
764 process_deferred_messages (void)
765 {
766   static int in_process_deferred_messages = 0;
767   BusDataClosure *closure;
768
769   if (in_process_deferred_messages)
770     return TRUE;
771   in_process_deferred_messages = 1;
772   while ((closure = g_queue_pop_head (deferred_messages)))
773   {
774     process_deferred_message (closure);
775     dbus_message_unref (closure->message);
776     dbus_connection_unref (closure->bus);
777     g_free (closure);
778   }
779   in_process_deferred_messages = 0;
780   return FALSE;
781 }
782
783 static gboolean
784 process_deferred_messages_callback (gpointer data)
785 {
786   if (process_deferred_messages ())
787     return G_SOURCE_CONTINUE;
788
789   process_deferred_messages_source = NULL;
790   return G_SOURCE_REMOVE;
791 }
792
793 static DBusHandlerResult
794 defer_message (DBusConnection *connection, DBusMessage *message, void *user_data)
795 {
796   BusDataClosure *closure = g_new (BusDataClosure, 1);
797
798   closure->bus = dbus_connection_ref (bus);
799   closure->message = dbus_message_ref (message);
800   closure->data = user_data;
801
802   g_queue_push_tail (deferred_messages, closure);
803
804   if (process_deferred_messages_source == NULL)
805   {
806     process_deferred_messages_source = g_idle_source_new ();
807     g_source_set_callback (process_deferred_messages_source,
808                            process_deferred_messages_callback, NULL, NULL);
809     g_source_attach (process_deferred_messages_source, atspi_main_context);
810     g_source_unref (process_deferred_messages_source);
811   }
812
813   return DBUS_HANDLER_RESULT_HANDLED;
814 }
815
816 static DBusHandlerResult
817 atspi_dbus_filter (DBusConnection *bus, DBusMessage *message, void *data)
818 {
819   int type = dbus_message_get_type (message);
820   const char *interface = dbus_message_get_interface (message);
821
822   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
823       !strncmp (interface, "org.a11y.atspi.Event.", 21))
824   {
825     return defer_message (bus, message, data);
826   }
827   if (dbus_message_is_method_call (message, atspi_interface_device_event_listener, "NotifyEvent"))
828   {
829     return defer_message (bus, message, data);
830   }
831   if (dbus_message_is_signal (message, atspi_interface_cache, "AddAccessible"))
832   {
833     return defer_message (bus, message, data);
834   }
835   if (dbus_message_is_signal (message, atspi_interface_cache, "RemoveAccessible"))
836   {
837     return defer_message (bus, message, data);
838   }
839   if (dbus_message_is_signal (message, "org.freedesktop.DBus", "NameOwnerChanged"))
840   {
841     defer_message (bus, message, data);
842     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
843   }
844   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
845 }
846
847 /*
848  * Returns a 'canonicalized' value for DISPLAY,
849  * with the screen number stripped off if present.
850  *
851  * TODO: Avoid having duplicate functions for this here and in at-spi2-atk
852  */
853 static gchar *
854 spi_display_name (void)
855 {
856   char *canonical_display_name = NULL;
857   const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
858
859   if (!display_env)
860     {
861       display_env = g_getenv ("DISPLAY");
862       if (!display_env || !display_env[0])
863         return NULL;
864       else
865         {
866           gchar *display_p, *screen_p;
867           canonical_display_name = g_strdup (display_env);
868           display_p = g_utf8_strrchr (canonical_display_name, -1, ':');
869           screen_p = g_utf8_strrchr (canonical_display_name, -1, '.');
870           if (screen_p && display_p && (screen_p > display_p))
871             {
872               *screen_p = '\0';
873             }
874         }
875     }
876   else
877     {
878       canonical_display_name = g_strdup (display_env);
879     }
880
881   return canonical_display_name;
882 }
883
884 /**
885  * atspi_init:
886  *
887  * Connects to the accessibility registry and initializes the SPI.
888  *
889  * Returns: 0 on success, 1 if already initialized, or an integer error code.  
890  **/
891 int
892 atspi_init (void)
893 {
894   char *match;
895   const gchar *no_cache;
896
897   if (atspi_inited)
898     {
899       return 1;
900     }
901
902   atspi_inited = TRUE;
903
904   _atspi_get_live_refs();
905
906   bus = atspi_get_a11y_bus ();
907   if (!bus)
908     return 2;
909   dbus_bus_register (bus, NULL);
910   atspi_dbus_connection_setup_with_g_main(bus, g_main_context_default());
911   dbus_connection_add_filter (bus, atspi_dbus_filter, NULL, NULL);
912   match = g_strdup_printf ("type='signal',interface='%s',member='AddAccessible'", atspi_interface_cache);
913   dbus_bus_add_match (bus, match, NULL);
914   g_free (match);
915   match = g_strdup_printf ("type='signal',interface='%s',member='RemoveAccessible'", atspi_interface_cache);
916   dbus_bus_add_match (bus, match, NULL);
917   g_free (match);
918   match = g_strdup_printf ("type='signal',interface='%s',member='ChildrenChanged'", atspi_interface_event_object);
919   dbus_bus_add_match (bus, match, NULL);
920   g_free (match);
921   match = g_strdup_printf ("type='signal',interface='%s',member='PropertyChange'", atspi_interface_event_object);
922   dbus_bus_add_match (bus, match, NULL);
923   g_free (match);
924   match = g_strdup_printf ("type='signal',interface='%s',member='StateChanged'", atspi_interface_event_object);
925   dbus_bus_add_match (bus, match, NULL);
926   g_free (match);
927
928   dbus_bus_add_match (bus,
929                       "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged'",
930                       NULL);
931
932   no_cache = g_getenv ("ATSPI_NO_CACHE");
933   if (no_cache && g_strcmp0 (no_cache, "0") != 0)
934     atspi_no_cache = TRUE;
935
936   deferred_messages = g_queue_new ();
937
938   return 0;
939 }
940
941 /**
942  * atspi_is_initialized:
943  *
944  * Indicates whether AT-SPI has been initialized.
945  *
946  * Returns: %True if initialized; %False otherwise.
947  */
948 gboolean
949 atspi_is_initialized ()
950 {
951   return atspi_inited;
952 }
953
954 /**
955  * atspi_event_main:
956  *
957  * Starts/enters the main event loop for the AT-SPI services.
958  *
959  * NOTE: This method does not return control; it is exited via a call to
960  * #atspi_event_quit from within an event handler.
961  *
962  **/
963 void
964 atspi_event_main (void)
965 {
966   atspi_main_loop = g_main_loop_new (NULL, FALSE);
967   g_main_loop_run (atspi_main_loop);
968   atspi_main_loop = NULL;
969 }
970
971 /**
972  * atspi_event_quit:
973  *
974  * Quits the last main event loop for the AT-SPI services,
975  * See: #atspi_event_main
976  **/
977 void
978 atspi_event_quit (void)
979 {
980   g_main_loop_quit (atspi_main_loop);
981 }
982
983 /**
984  * atspi_exit:
985  *
986  * Disconnects from #AtspiRegistry instances and releases 
987  * any floating resources. Call only once at exit.
988  *
989  * Returns: 0 if there were no leaks, otherwise other integer values.
990  **/
991 int
992 atspi_exit (void)
993 {
994   int leaked;
995
996   if (!atspi_inited)
997     {
998       return 0;
999     }
1000
1001   atspi_inited = FALSE;
1002
1003   if (live_refs)
1004     {
1005       leaked = g_hash_table_size (live_refs);
1006     }
1007   else
1008     {
1009       leaked = 0;
1010     }
1011
1012   cleanup ();
1013
1014   return leaked;
1015 }
1016
1017 static GSList *hung_processes;
1018
1019 static void
1020 remove_hung_process (DBusPendingCall *pending, void *data)
1021 {
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 ("AT-SPI: 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 ("Error retrieving accessibility bus address: %s: %s",
1534                error.name, error.message);
1535     dbus_error_free (&error);
1536     return NULL;
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         return NULL;
1549       }
1550     address = g_strdup (tmp_address);
1551     dbus_message_unref (reply);
1552   }
1553   
1554   return address;
1555 }
1556
1557 static DBusConnection *a11y_bus;
1558 static dbus_int32_t a11y_dbus_slot = -1;
1559
1560 static void
1561 a11y_bus_free (void *data)
1562 {
1563   if (data == a11y_bus)
1564     {
1565       a11y_bus = NULL;
1566       dbus_connection_free_data_slot (&a11y_dbus_slot);
1567     }
1568 }
1569
1570 /**
1571  * atspi_get_a11y_bus: (skip)
1572  */
1573 DBusConnection *
1574 atspi_get_a11y_bus (void)
1575 {
1576   DBusError error;
1577   char *address = NULL;
1578
1579   if (a11y_bus && dbus_connection_get_is_connected (a11y_bus))
1580     return a11y_bus;
1581
1582   if (a11y_dbus_slot == -1)
1583     if (!dbus_connection_allocate_data_slot (&a11y_dbus_slot))
1584       g_warning ("at-spi: Unable to allocate D-Bus slot");
1585
1586 #ifdef HAVE_X11
1587   address = get_accessibility_bus_address_x11 ();
1588 #endif
1589   if (!address)
1590     address = get_accessibility_bus_address_dbus ();
1591   if (!address)
1592     return NULL;
1593
1594   dbus_error_init (&error);
1595   a11y_bus = dbus_connection_open_private (address, &error);
1596   g_free (address);
1597
1598   if (!a11y_bus)
1599     {
1600       if (!g_getenv("SSH_CONNECTION"))
1601         g_warning ("Couldn't connect to accessibility bus: %s", error.message);
1602       dbus_error_free (&error);
1603       return NULL;
1604     }
1605   else
1606     {
1607       if (!dbus_bus_register (a11y_bus, &error))
1608         {
1609           g_warning ("Couldn't register with accessibility bus: %s", error.message);
1610           dbus_error_free (&error);
1611           dbus_connection_close (a11y_bus);
1612           dbus_connection_unref (a11y_bus);
1613           a11y_bus = NULL;
1614           return NULL;
1615         }
1616     }
1617   
1618   /* Simulate a weak ref on the bus */
1619   dbus_connection_set_data (a11y_bus, a11y_dbus_slot, a11y_bus, a11y_bus_free);
1620
1621   return a11y_bus;
1622 }
1623
1624 /**
1625  * atspi_set_timeout:
1626  * @val: The timeout value, in milliseconds, or -1 to disable the timeout.
1627  * @startup_time: The amount of time, in milliseconds, to allow to pass
1628  * before enforcing timeouts on an application. Can be used to prevent
1629  * timeout exceptions if an application is likely to block for an extended
1630  * period of time on initialization. -1 can be passed to disable this
1631  * behavior.
1632  *
1633  * Set the timeout used for method calls. If this is not set explicitly,
1634  * a default of 0.8 ms is used.
1635  * Note that at-spi2-registryd currently uses a timeout of 3 seconds when
1636  * sending a keyboard event notification. This means that, if an AT makes
1637  * a call in response to the keyboard notification and the application
1638  * being called does not respond before the timeout is reached,
1639  * at-spi2-registryd will time out on the keyboard event notification and
1640  * pass the key onto the application (ie, reply to indicate that the key
1641  * was not consumed), so this may make it undesirable to set a timeout
1642  * larger than 3 seconds.
1643  *
1644  * By default, the normal timeout is set to 800 ms, and the application startup
1645  * timeout is set to 15 seconds.
1646  */
1647 void
1648 atspi_set_timeout (gint val, gint startup_time)
1649 {
1650   method_call_timeout = val;
1651   app_startup_time = startup_time;
1652 }
1653
1654 /**
1655  * atspi_set_main_context:
1656  * @cnx: The #GMainContext to use.
1657  *
1658  * Sets the main loop context that AT-SPI should assume is in use when
1659  * setting an idle callback.
1660  * This function should be called by application-side implementors (ie,
1661  * at-spi2-atk) when it is desirable to re-enter the main loop.
1662  */
1663 void
1664 atspi_set_main_context (GMainContext *cnx)
1665 {
1666   if (atspi_main_context == cnx)
1667     return;
1668   if (process_deferred_messages_source != NULL)
1669   {
1670     g_source_destroy (process_deferred_messages_source);
1671     process_deferred_messages_source = g_idle_source_new ();
1672     g_source_set_callback (process_deferred_messages_source,
1673                            process_deferred_messages_callback, NULL, NULL);
1674     g_source_attach (process_deferred_messages_source, cnx);
1675     g_source_unref (process_deferred_messages_source);
1676   }
1677   atspi_main_context = cnx;
1678   atspi_dbus_connection_setup_with_g_main (atspi_get_a11y_bus (), cnx);
1679 }
1680
1681 #ifdef DEBUG_REF_COUNTS
1682 static void
1683 print_disposed (gpointer key, gpointer value, gpointer data)
1684 {
1685   AtspiAccessible *accessible = key;
1686   if (accessible->parent.app)
1687     return;
1688   g_print ("disposed: %s %d\n", accessible->name, accessible->role);
1689 }
1690
1691 void
1692 debug_disposed ()
1693 {
1694   g_hash_table_foreach (live_refs, print_disposed, NULL);
1695 }
1696 #endif
1697
1698 gchar *
1699 _atspi_name_compat (gchar *name)
1700 {
1701   gchar *p = name;
1702
1703   while (*p)
1704   {
1705     if (*p == '-')
1706       *p = ' ';
1707     p++;
1708   }
1709   return name;
1710 }
1711
1712 /**
1713  * atspi_role_get_name:
1714  * @role: an #AtspiRole object to query.
1715  *
1716  * Gets a localizable string that indicates the name of an #AtspiRole.
1717  * <em>DEPRECATED.</em>
1718  *
1719  * Returns: a localizable string name for an #AtspiRole enumerated type.
1720  **/
1721 gchar *
1722 atspi_role_get_name (AtspiRole role)
1723 {
1724   gchar *retval = NULL;
1725   GTypeClass *type_class;
1726   GEnumValue *value;
1727
1728   type_class = g_type_class_ref (ATSPI_TYPE_ROLE);
1729   g_return_val_if_fail (G_IS_ENUM_CLASS (type_class), NULL);
1730
1731   value = g_enum_get_value (G_ENUM_CLASS (type_class), role);
1732
1733   if (value)
1734     {
1735       retval = g_strdup (value->value_nick);
1736     }
1737
1738   g_type_class_unref (type_class);
1739
1740   if (retval)
1741     return _atspi_name_compat (retval);
1742
1743   return NULL;
1744 }
1745
1746 GHashTable *
1747 _atspi_dbus_update_cache_from_dict (AtspiAccessible *accessible, DBusMessageIter *iter)
1748 {
1749   GHashTable *cache = _atspi_accessible_ref_cache (accessible);
1750   DBusMessageIter iter_dict, iter_dict_entry, iter_struct, iter_variant;
1751
1752   dbus_message_iter_recurse (iter, &iter_dict);
1753   while (dbus_message_iter_get_arg_type (&iter_dict) != DBUS_TYPE_INVALID)
1754   {
1755     const char *key;
1756     GValue *val = NULL;
1757     dbus_message_iter_recurse (&iter_dict, &iter_dict_entry);
1758     dbus_message_iter_get_basic (&iter_dict_entry, &key);
1759     dbus_message_iter_next (&iter_dict_entry);
1760     dbus_message_iter_recurse (&iter_dict_entry, &iter_variant);
1761     if (!strcmp (key, "interfaces"))
1762     {
1763       _atspi_dbus_set_interfaces (accessible, &iter_variant);
1764     }
1765     else if (!strcmp (key, "Attributes"))
1766     {
1767       char *iter_sig = dbus_message_iter_get_signature (&iter_variant);
1768       val = g_new0 (GValue, 1);;
1769       g_value_init (val, G_TYPE_HASH_TABLE);
1770       if (strcmp (iter_sig, "a{ss}") != 0)
1771       {
1772         dbus_free (iter_sig);
1773         break;
1774       }
1775       dbus_free (iter_sig);
1776       g_value_take_boxed (val, _atspi_dbus_hash_from_iter (&iter_variant));
1777     }
1778     else if (!strcmp (key, "Component.ScreenExtents"))
1779     {
1780       dbus_int32_t d_int;
1781       AtspiRect extents;
1782       char *iter_sig = dbus_message_iter_get_signature (&iter_variant);
1783       val = g_new0 (GValue, 1);;
1784       g_value_init (val, ATSPI_TYPE_RECT);
1785       if (strcmp (iter_sig, "(iiii)") != 0)
1786       {
1787         dbus_free (iter_sig);
1788         break;
1789       }
1790       dbus_free (iter_sig);
1791       dbus_message_iter_recurse (&iter_variant, &iter_struct);
1792       dbus_message_iter_get_basic (&iter_struct, &d_int);
1793       extents.x = d_int;
1794       dbus_message_iter_next (&iter_struct);
1795       dbus_message_iter_get_basic (&iter_struct, &d_int);
1796       extents.y = d_int;
1797       dbus_message_iter_next (&iter_struct);
1798       dbus_message_iter_get_basic (&iter_struct, &d_int);
1799       extents.width = d_int;
1800       dbus_message_iter_next (&iter_struct);
1801       dbus_message_iter_get_basic (&iter_struct, &d_int);
1802       extents.height = d_int;
1803       g_value_set_boxed (val, &extents);
1804     }
1805     if (val)
1806       g_hash_table_insert (cache, g_strdup (key), val); 
1807     dbus_message_iter_next (&iter_dict);
1808   }
1809
1810   return cache;
1811 }
1812
1813 gboolean
1814 _atspi_get_allow_sync ()
1815 {
1816   return allow_sync;
1817 }
1818
1819 gboolean
1820 _atspi_set_allow_sync (gboolean val)
1821 {
1822   gboolean ret = allow_sync;
1823
1824   allow_sync = val;
1825   return ret;
1826 }
1827
1828 void
1829 _atspi_set_error_no_sync (GError **error)
1830 {
1831   g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_SYNC_NOT_ALLOWED,
1832                         _("Attempted synchronous call where prohibited"));
1833 }