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