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