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