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