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