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