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