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