atspi-misc: Prevent memory leak of main_loop pointer
[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 Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 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  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /*
26  *
27  * Basic SPI initialization and event loop function prototypes
28  *
29  */
30
31 #include "atspi-private.h"
32 #ifdef HAVE_X11
33 #include "X11/Xlib.h"
34 #endif
35 #include "atspi-gmain.h"
36 #include <stdio.h>
37 #include <string.h>
38
39 static void handle_get_items (DBusPendingCall *pending, void *user_data);
40
41 static DBusConnection *bus = NULL;
42 static GHashTable *live_refs = NULL;
43 static gint method_call_timeout = 800;
44 static gint app_startup_time = 15000;
45 static gboolean allow_sync = TRUE;
46
47 GMainLoop *atspi_main_loop;
48 GMainContext *atspi_main_context;
49 gboolean atspi_no_cache;
50
51 const char *atspi_path_dec = ATSPI_DBUS_PATH_DEC;
52 const char *atspi_path_registry = ATSPI_DBUS_PATH_REGISTRY;
53 const char *atspi_path_root = ATSPI_DBUS_PATH_ROOT;
54 const char *atspi_bus_registry = ATSPI_DBUS_NAME_REGISTRY;
55 const char *atspi_interface_accessible = ATSPI_DBUS_INTERFACE_ACCESSIBLE;
56 const char *atspi_interface_action = ATSPI_DBUS_INTERFACE_ACTION;
57 const char *atspi_interface_application = ATSPI_DBUS_INTERFACE_APPLICATION;
58 const char *atspi_interface_collection = ATSPI_DBUS_INTERFACE_COLLECTION;
59 const char *atspi_interface_component = ATSPI_DBUS_INTERFACE_COMPONENT;
60 const char *atspi_interface_dec = ATSPI_DBUS_INTERFACE_DEC;
61 const char *atspi_interface_device_event_listener = ATSPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER;
62 const char *atspi_interface_document = ATSPI_DBUS_INTERFACE_DOCUMENT;
63 const char *atspi_interface_editable_text = ATSPI_DBUS_INTERFACE_EDITABLE_TEXT;
64 const char *atspi_interface_event_object = ATSPI_DBUS_INTERFACE_EVENT_OBJECT;
65 const char *atspi_interface_hyperlink = ATSPI_DBUS_INTERFACE_HYPERLINK;
66 const char *atspi_interface_hypertext = ATSPI_DBUS_INTERFACE_HYPERTEXT;
67 const char *atspi_interface_image = ATSPI_DBUS_INTERFACE_IMAGE;
68 const char *atspi_interface_registry = ATSPI_DBUS_INTERFACE_REGISTRY;
69 const char *atspi_interface_selection = ATSPI_DBUS_INTERFACE_SELECTION;
70 const char *atspi_interface_table = ATSPI_DBUS_INTERFACE_TABLE;
71 const char *atspi_interface_table_cell = ATSPI_DBUS_INTERFACE_TABLE_CELL;
72 const char *atspi_interface_text = ATSPI_DBUS_INTERFACE_TEXT;
73 const char *atspi_interface_cache = ATSPI_DBUS_INTERFACE_CACHE;
74 const char *atspi_interface_value = ATSPI_DBUS_INTERFACE_VALUE;
75
76 static const char *interfaces[] =
77 {
78   ATSPI_DBUS_INTERFACE_ACCESSIBLE,
79   ATSPI_DBUS_INTERFACE_ACTION,
80   ATSPI_DBUS_INTERFACE_APPLICATION,
81   ATSPI_DBUS_INTERFACE_COLLECTION,
82   ATSPI_DBUS_INTERFACE_COMPONENT,
83   ATSPI_DBUS_INTERFACE_DOCUMENT,
84   ATSPI_DBUS_INTERFACE_EDITABLE_TEXT,
85   ATSPI_DBUS_INTERFACE_HYPERLINK,
86   ATSPI_DBUS_INTERFACE_HYPERTEXT,
87   ATSPI_DBUS_INTERFACE_IMAGE,
88   "org.a11y.atspi.LoginHelper",
89   ATSPI_DBUS_INTERFACE_SELECTION,
90   ATSPI_DBUS_INTERFACE_TABLE,
91   ATSPI_DBUS_INTERFACE_TABLE_CELL,
92   ATSPI_DBUS_INTERFACE_TEXT,
93   ATSPI_DBUS_INTERFACE_VALUE,
94   NULL
95 };
96
97 gint
98 _atspi_get_iface_num (const char *iface)
99 {
100   /* TODO: Use a binary search or hash to improve performance */
101   int i;
102
103   for (i = 0; interfaces[i]; i++)
104   {
105     if (!strcmp(iface, interfaces[i])) return i;
106   }
107   return -1;
108 }
109
110 GHashTable *
111 _atspi_get_live_refs (void)
112 {
113   if (!live_refs)
114     {
115       live_refs = g_hash_table_new (g_direct_hash, g_direct_equal);
116     }
117   return live_refs;
118 }
119
120 /* TODO: Add an application parameter */
121 DBusConnection *
122 _atspi_bus ()
123 {
124   if (!bus)
125     atspi_init ();
126   if (!bus)
127     g_error ("AT-SPI: Couldn't connect to accessibility bus. Is at-spi-bus-launcher running?");
128   return bus;
129 }
130
131 #define APP_IS_REGISTRY(app) (!strcmp (app->bus_name, atspi_bus_registry))
132
133 static AtspiAccessible *desktop;
134
135 static void
136 cleanup ()
137 {
138   GHashTable *refs;
139   gint i;
140
141   refs = live_refs;
142   live_refs = NULL;
143   if (refs)
144     {
145       g_hash_table_destroy (refs);
146     }
147
148   if (bus)
149     {
150       dbus_connection_close (bus);
151       dbus_connection_unref (bus);
152       bus = NULL;
153     }
154
155   if (!desktop)
156     return;
157
158   /* TODO: Do we need this code, or should we just dispose the desktop? */
159   for (i = desktop->children->len - 1; i >= 0; i--)
160   {
161     AtspiAccessible *child = g_ptr_array_index (desktop->children, i);
162     if (child->parent.app)
163       g_object_run_dispose (G_OBJECT (child->parent.app));
164     g_object_run_dispose (G_OBJECT (child));
165   }
166
167   g_object_run_dispose (G_OBJECT (desktop->parent.app));
168   g_object_unref (desktop);
169   desktop = NULL;
170 }
171
172 static gboolean atspi_inited = FALSE;
173
174 static GHashTable *app_hash = NULL;
175
176 static void
177 handle_get_bus_address (DBusPendingCall *pending, void *user_data)
178 {
179   AtspiApplication *app = user_data;
180   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
181   DBusMessage *message;
182   const char *address;
183   DBusPendingCall *new_pending;
184   dbus_bool_t result;
185
186   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_METHOD_RETURN)
187   {
188     if (dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &address,
189                                DBUS_TYPE_INVALID) && address [0])
190     {
191       DBusError error;
192       DBusConnection *bus;
193
194       dbus_error_init (&error);
195       bus = dbus_connection_open_private (address, &error);
196       if (bus)
197       {
198         if (app->bus)
199           {
200             dbus_connection_unref (app->bus);
201           }
202         app->bus = bus;
203         atspi_dbus_connection_setup_with_g_main(bus, g_main_context_default());
204       }
205       else
206       {
207         if (!strcmp (error.name, DBUS_ERROR_FILE_NOT_FOUND))
208           g_warning ("AT-SPI: Unable to open bus connection: %s", error.message);
209         dbus_error_free (&error);
210       }
211     }
212   }
213   dbus_message_unref (reply);
214   dbus_pending_call_unref (pending);
215
216   if (!app->bus)
217     return; /* application has gone away / been disposed */
218
219   message = dbus_message_new_method_call (app->bus_name,
220                                           "/org/a11y/atspi/cache",
221                                           atspi_interface_cache, "GetItems");
222
223   result = dbus_connection_send_with_reply (app->bus, message, &new_pending, 2000);
224   dbus_message_unref (message);
225   if (!result || !new_pending)
226     return;
227   dbus_pending_call_set_notify (new_pending, handle_get_items, app, NULL);
228 }
229
230 static AtspiApplication *
231 get_application (const char *bus_name)
232 {
233   AtspiApplication *app = NULL;
234   char *bus_name_dup;
235   DBusMessage *message;
236   DBusPendingCall *pending = NULL;
237   dbus_bool_t result;
238
239   if (!app_hash)
240   {
241     app_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_object_unref);
242     if (!app_hash) return NULL;
243   }
244   app = g_hash_table_lookup (app_hash, bus_name);
245   if (app) return app;
246   bus_name_dup = g_strdup (bus_name);
247   if (!bus_name_dup) return NULL;
248   // TODO: change below to something that will send state-change:defunct notification if necessary */
249   app = _atspi_application_new (bus_name);
250   app->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
251   app->bus = dbus_connection_ref (_atspi_bus ());
252   gettimeofday (&app->time_added, NULL);
253   app->cache = ATSPI_CACHE_UNDEFINED;
254   g_hash_table_insert (app_hash, bus_name_dup, app);
255   message = dbus_message_new_method_call (bus_name, atspi_path_root,
256                                           atspi_interface_application, "GetApplicationBusAddress");
257
258   result = dbus_connection_send_with_reply (app->bus, message, &pending, 2000);
259   dbus_message_unref (message);
260   if (!result || !pending)
261   {
262     g_hash_table_remove (app_hash, bus_name_dup);
263     return NULL;
264   }
265   dbus_pending_call_set_notify (pending, handle_get_bus_address, app, NULL);
266   return app;
267 }
268
269 AtspiAccessible *
270 ref_accessible (const char *app_name, const char *path)
271 {
272   AtspiApplication *app;
273   AtspiAccessible *a;
274
275   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
276     return NULL;
277
278   app = get_application (app_name);
279
280   if (!strcmp (path, "/org/a11y/atspi/accessible/root"))
281   {
282     if (!app->root)
283     {
284       app->root = _atspi_accessible_new (app, atspi_path_root);
285       app->root->accessible_parent = atspi_get_desktop (0);
286       g_ptr_array_add (app->root->accessible_parent->children, g_object_ref (app->root));
287     }
288     return g_object_ref (app->root);
289   }
290
291   a = g_hash_table_lookup (app->hash, path);
292   if (a)
293   {
294     return g_object_ref (a);
295   }
296   a = _atspi_accessible_new (app, path);
297   if (!a)
298     return NULL;
299   g_hash_table_insert (app->hash, g_strdup (a->parent.path), g_object_ref (a));
300   return a;
301 }
302
303 static AtspiHyperlink *
304 ref_hyperlink (const char *app_name, const char *path)
305 {
306   AtspiApplication *app = get_application (app_name);
307   AtspiHyperlink *hyperlink;
308
309   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
310     return NULL;
311
312   hyperlink = g_hash_table_lookup (app->hash, path);
313   if (hyperlink)
314   {
315     return g_object_ref (hyperlink);
316   }
317   hyperlink = _atspi_hyperlink_new (app, path);
318   g_hash_table_insert (app->hash, g_strdup (hyperlink->parent.path), hyperlink);
319   /* TODO: This should be a weak ref */
320   g_object_ref (hyperlink);     /* for the hash */
321   return hyperlink;
322 }
323
324 typedef struct
325 {
326   char *path;
327   char *parent;
328   GArray *children;
329   GArray *interfaces;
330   char *name;
331   dbus_uint32_t role;
332   char *description;
333   GArray *state_bitflags;
334 } CACHE_ADDITION;
335
336 static DBusHandlerResult
337 handle_remove_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
338 {
339   const char *sender = dbus_message_get_sender (message);
340   AtspiApplication *app;
341   const char *path;
342   DBusMessageIter iter, iter_struct;
343   const char *signature = dbus_message_get_signature (message);
344   AtspiAccessible *a;
345
346   if (strcmp (signature, "(so)") != 0)
347   {
348     g_warning ("AT-SPI: Unknown signature %s for RemoveAccessible", signature);
349     return DBUS_HANDLER_RESULT_HANDLED;
350   }
351
352   dbus_message_iter_init (message, &iter);
353   dbus_message_iter_recurse (&iter, &iter_struct);
354   dbus_message_iter_get_basic (&iter_struct, &sender);
355   dbus_message_iter_next (&iter_struct);
356   dbus_message_iter_get_basic (&iter_struct, &path);
357   app = get_application (sender);
358   a = ref_accessible (sender, path);
359   if (!a)
360     return DBUS_HANDLER_RESULT_HANDLED;
361   g_object_run_dispose (G_OBJECT (a));
362   g_hash_table_remove (app->hash, a->parent.path);
363   g_object_unref (a);   /* unref our own ref */
364   return DBUS_HANDLER_RESULT_HANDLED;
365 }
366
367 static DBusHandlerResult
368 handle_name_owner_changed (DBusConnection *bus, DBusMessage *message, void *user_data)
369 {
370   const char *name, *new, *old;
371   static gboolean registry_lost = FALSE;
372
373   if (!dbus_message_get_args (message, NULL,
374                               DBUS_TYPE_STRING, &name,
375                               DBUS_TYPE_STRING, &old,
376                               DBUS_TYPE_STRING, &new,
377                               DBUS_TYPE_INVALID))
378   {
379     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
380   }
381
382   if (!strcmp (name, "org.a11y.atspi.Registry"))
383   {
384     if (registry_lost && !old[0])
385     {
386       _atspi_reregister_event_listeners ();
387       _atspi_reregister_device_listeners ();
388       registry_lost = FALSE;
389     }
390     else if (!new[0])
391       registry_lost = TRUE;
392   }
393   else if (app_hash)
394   {
395     AtspiApplication *app = g_hash_table_lookup (app_hash, old);
396     if (app && app->bus_name && !strcmp(app->bus_name, name))
397       g_object_run_dispose (G_OBJECT (app));
398   }
399   return DBUS_HANDLER_RESULT_HANDLED;
400 }
401
402 static gboolean
403 add_app_to_desktop (AtspiAccessible *a, const char *bus_name)
404 {
405   AtspiAccessible *obj = ref_accessible (bus_name, atspi_path_root);
406   /* The app will be added to the desktop as a side-effect of calling
407    * ref_accessible */
408   g_object_unref (obj);
409   return (obj != NULL);
410 }
411
412 void
413 get_reference_from_iter (DBusMessageIter *iter, const char **app_name, const char **path)
414 {
415   DBusMessageIter iter_struct;
416
417   dbus_message_iter_recurse (iter, &iter_struct);
418   dbus_message_iter_get_basic (&iter_struct, app_name);
419   dbus_message_iter_next (&iter_struct);
420   dbus_message_iter_get_basic (&iter_struct, path);
421   dbus_message_iter_next (iter);
422 }
423
424 static void
425 add_accessible_from_iter (DBusMessageIter *iter)
426 {
427   DBusMessageIter iter_struct, iter_array;
428   const char *app_name, *path;
429   AtspiAccessible *accessible;
430   const char *name, *description;
431   dbus_uint32_t role;
432   gboolean children_cached = FALSE;
433   dbus_int32_t count, index;
434
435   dbus_message_iter_recurse (iter, &iter_struct);
436
437   /* get accessible */
438   get_reference_from_iter (&iter_struct, &app_name, &path);
439   accessible = ref_accessible (app_name, path);
440   if (!accessible)
441     return;
442
443   /* Get application: TODO */
444   dbus_message_iter_next (&iter_struct);
445
446   /* get parent */
447   get_reference_from_iter (&iter_struct, &app_name, &path);
448   if (accessible->accessible_parent)
449     g_object_unref (accessible->accessible_parent);
450   accessible->accessible_parent = ref_accessible (app_name, path);
451
452   if (dbus_message_iter_get_arg_type (&iter_struct) == 'i')
453   {
454     /* Get index in parent */
455     dbus_message_iter_get_basic (&iter_struct, &index);
456     if (index >= 0 && accessible->accessible_parent)
457     {
458       if (index >= accessible->accessible_parent->children->len)
459         g_ptr_array_set_size (accessible->accessible_parent->children, index + 1);
460       g_ptr_array_index (accessible->accessible_parent->children, index) = g_object_ref (accessible);
461     }
462
463     /* get child count */
464     dbus_message_iter_next (&iter_struct);
465     dbus_message_iter_get_basic (&iter_struct, &count);
466     if (count >= 0)
467     {
468       g_ptr_array_set_size (accessible->children, count);
469       children_cached = TRUE;
470     }
471   }
472   else if (dbus_message_iter_get_arg_type (&iter_struct) == 'a')
473   {
474     /* It's the old API with a list of children */
475     /* TODO: Perhaps remove this code eventually */
476     dbus_message_iter_recurse (&iter_struct, &iter_array);
477     while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
478     {
479       AtspiAccessible *child;
480       get_reference_from_iter (&iter_array, &app_name, &path);
481       child = ref_accessible (app_name, path);
482       g_ptr_array_remove (accessible->children, child);
483       g_ptr_array_add (accessible->children, child);
484     }
485     children_cached = TRUE;
486   }
487
488   /* interfaces */
489   dbus_message_iter_next (&iter_struct);
490   _atspi_dbus_set_interfaces (accessible, &iter_struct);
491   dbus_message_iter_next (&iter_struct);
492
493   /* name */
494   if (accessible->name)
495     g_free (accessible->name);
496   dbus_message_iter_get_basic (&iter_struct, &name);
497   accessible->name = g_strdup (name);
498   dbus_message_iter_next (&iter_struct);
499
500   /* role */
501   dbus_message_iter_get_basic (&iter_struct, &role);
502   accessible->role = role;
503   dbus_message_iter_next (&iter_struct);
504
505   /* description */
506   if (accessible->description)
507     g_free (accessible->description);
508   dbus_message_iter_get_basic (&iter_struct, &description);
509   accessible->description = g_strdup (description);
510   dbus_message_iter_next (&iter_struct);
511
512   _atspi_dbus_set_state (accessible, &iter_struct);
513   dbus_message_iter_next (&iter_struct);
514
515   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_NAME | ATSPI_CACHE_ROLE |
516                                ATSPI_CACHE_PARENT | ATSPI_CACHE_DESCRIPTION);
517   if (!atspi_state_set_contains (accessible->states,
518                                        ATSPI_STATE_MANAGES_DESCENDANTS) &&
519                                        children_cached)
520     _atspi_accessible_add_cache (accessible, ATSPI_CACHE_CHILDREN);
521
522   /* This is a bit of a hack since the cache holds a ref, so we don't need
523    * the one provided for us anymore */
524   g_object_unref (accessible);
525 }
526
527 static void
528 handle_get_items (DBusPendingCall *pending, void *user_data)
529 {
530   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
531   DBusMessageIter iter, iter_array;
532
533   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
534   {
535     const char *sender = dbus_message_get_sender (reply);
536     const char *error = NULL;
537     const char *error_name = dbus_message_get_error_name (reply);
538     if (!strcmp (error_name, DBUS_ERROR_SERVICE_UNKNOWN)
539      || !strcmp (error_name, DBUS_ERROR_NO_REPLY))
540     {
541     }
542     else
543     {
544       dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &error,
545                              DBUS_TYPE_INVALID);
546       g_warning ("AT-SPI: Error in GetItems, sender=%s, error=%s", sender, error);
547     }
548     dbus_message_unref (reply);
549     dbus_pending_call_unref (pending);
550     return;
551   }
552
553   dbus_message_iter_init (reply, &iter);
554   dbus_message_iter_recurse (&iter, &iter_array);
555   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
556   {
557     add_accessible_from_iter (&iter_array);
558     dbus_message_iter_next (&iter_array);
559   }
560   dbus_message_unref (reply);
561   dbus_pending_call_unref (pending);
562 }
563
564 /* TODO: Do we stil need this function? */
565 static AtspiAccessible *
566 ref_accessible_desktop (AtspiApplication *app)
567 {
568   GError *error;
569   DBusMessage *message, *reply;
570   DBusMessageIter iter, iter_array;
571   gchar *bus_name_dup;
572
573   if (desktop)
574   {
575     g_object_ref (desktop);
576     return desktop;
577   }
578   desktop = _atspi_accessible_new (app, atspi_path_root);
579   if (!desktop)
580   {
581     return NULL;
582   }
583   g_hash_table_insert (app->hash, g_strdup (desktop->parent.path),
584                        g_object_ref (desktop));
585   app->root = g_object_ref (desktop);
586   desktop->name = g_strdup ("main");
587   message = dbus_message_new_method_call (atspi_bus_registry,
588         atspi_path_root,
589         atspi_interface_accessible,
590         "GetChildren");
591   if (!message)
592     return NULL;
593   error = NULL;
594   reply = _atspi_dbus_send_with_reply_and_block (message, &error);
595   if (!reply || strcmp (dbus_message_get_signature (reply), "a(so)") != 0)
596   {
597     if (error != NULL)
598     {
599       g_warning ("Couldn't get application list: %s", error->message);
600       g_clear_error (&error);
601     }
602     if (reply)
603       dbus_message_unref (reply);
604     return NULL;
605   }
606   dbus_message_iter_init (reply, &iter);
607   dbus_message_iter_recurse (&iter, &iter_array);
608   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
609   {
610     const char *app_name, *path;
611     get_reference_from_iter (&iter_array, &app_name, &path);
612     add_app_to_desktop (desktop, app_name);
613   }
614
615   /* Record the alternate name as an alias for org.a11y.atspi.Registry */
616   bus_name_dup = g_strdup (dbus_message_get_sender (reply));
617   if (bus_name_dup)
618     g_hash_table_insert (app_hash, bus_name_dup, app);
619
620   dbus_message_unref (reply);
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)iiassusau)";
707 const char *old_cache_signal_type = "((so)(so)(so)a(so)assusau)";
708
709 static DBusHandlerResult
710 handle_add_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
711 {
712   DBusMessageIter iter;
713   const char *signature = dbus_message_get_signature (message);
714
715   if (strcmp (signature, cache_signal_type) != 0 &&
716       strcmp (signature, old_cache_signal_type) != 0)
717   {
718     g_warning ("AT-SPI: AddAccessible with unknown signature %s\n", signature);
719     return DBUS_HANDLER_RESULT_HANDLED;
720   }
721
722   dbus_message_iter_init (message, &iter);
723   add_accessible_from_iter (&iter);
724   return DBUS_HANDLER_RESULT_HANDLED;
725 }
726
727 typedef struct
728 {
729   DBusConnection *bus;
730   DBusMessage *message;
731   void *data;
732 } BusDataClosure;
733
734 static GSource *process_deferred_messages_source = NULL;
735
736 static void
737 process_deferred_message (BusDataClosure *closure)
738 {
739   int type = dbus_message_get_type (closure->message);
740   const char *interface = dbus_message_get_interface (closure->message);
741
742   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
743       !strncmp (interface, "org.a11y.atspi.Event.", 21))
744   {
745     _atspi_dbus_handle_event (closure->bus, closure->message, closure->data);
746   }
747   if (dbus_message_is_method_call (closure->message, atspi_interface_device_event_listener, "NotifyEvent"))
748   {
749     _atspi_dbus_handle_DeviceEvent (closure->bus,
750                                    closure->message, closure->data);
751   }
752   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "AddAccessible"))
753   {
754     handle_add_accessible (closure->bus, closure->message, closure->data);
755   }
756   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "RemoveAccessible"))
757   {
758     handle_remove_accessible (closure->bus, closure->message, closure->data);
759   }
760   if (dbus_message_is_signal (closure->message, "org.freedesktop.DBus", "NameOwnerChanged"))
761   {
762     handle_name_owner_changed (closure->bus, closure->message, closure->data);
763   }
764 }
765
766 static GQueue *deferred_messages = NULL;
767
768 static gboolean
769 process_deferred_messages (void)
770 {
771   static int in_process_deferred_messages = 0;
772   BusDataClosure *closure;
773
774   if (in_process_deferred_messages)
775     return TRUE;
776   in_process_deferred_messages = 1;
777   while ((closure = g_queue_pop_head (deferred_messages)))
778   {
779     process_deferred_message (closure);
780     dbus_message_unref (closure->message);
781     dbus_connection_unref (closure->bus);
782     g_free (closure);
783   }
784   in_process_deferred_messages = 0;
785   return FALSE;
786 }
787
788 static gboolean
789 process_deferred_messages_callback (gpointer data)
790 {
791   if (process_deferred_messages ())
792     return G_SOURCE_CONTINUE;
793
794   process_deferred_messages_source = NULL;
795   return G_SOURCE_REMOVE;
796 }
797
798 static DBusHandlerResult
799 defer_message (DBusConnection *connection, DBusMessage *message, void *user_data)
800 {
801   BusDataClosure *closure = g_new (BusDataClosure, 1);
802
803   closure->bus = dbus_connection_ref (bus);
804   closure->message = dbus_message_ref (message);
805   closure->data = user_data;
806
807   g_queue_push_tail (deferred_messages, closure);
808
809   if (process_deferred_messages_source == NULL)
810   {
811     process_deferred_messages_source = g_idle_source_new ();
812     g_source_set_callback (process_deferred_messages_source,
813                            process_deferred_messages_callback, NULL, NULL);
814     g_source_attach (process_deferred_messages_source, atspi_main_context);
815     g_source_unref (process_deferred_messages_source);
816   }
817
818   return DBUS_HANDLER_RESULT_HANDLED;
819 }
820
821 static DBusHandlerResult
822 atspi_dbus_filter (DBusConnection *bus, DBusMessage *message, void *data)
823 {
824   int type = dbus_message_get_type (message);
825   const char *interface = dbus_message_get_interface (message);
826
827   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
828       !strncmp (interface, "org.a11y.atspi.Event.", 21))
829   {
830     return defer_message (bus, message, data);
831   }
832   if (dbus_message_is_method_call (message, atspi_interface_device_event_listener, "NotifyEvent"))
833   {
834     return defer_message (bus, message, data);
835   }
836   if (dbus_message_is_signal (message, atspi_interface_cache, "AddAccessible"))
837   {
838     return defer_message (bus, message, data);
839   }
840   if (dbus_message_is_signal (message, atspi_interface_cache, "RemoveAccessible"))
841   {
842     return defer_message (bus, message, data);
843   }
844   if (dbus_message_is_signal (message, "org.freedesktop.DBus", "NameOwnerChanged"))
845   {
846     defer_message (bus, message, data);
847     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
848   }
849   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
850 }
851
852 /*
853  * Returns a 'canonicalized' value for DISPLAY,
854  * with the screen number stripped off if present.
855  *
856  * TODO: Avoid having duplicate functions for this here and in at-spi2-atk
857  */
858 static gchar *
859 spi_display_name (void)
860 {
861   char *canonical_display_name = NULL;
862   const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
863
864   if (!display_env)
865     {
866       display_env = g_getenv ("DISPLAY");
867       if (!display_env || !display_env[0])
868         return NULL;
869       else
870         {
871           gchar *display_p, *screen_p;
872           canonical_display_name = g_strdup (display_env);
873           display_p = g_utf8_strrchr (canonical_display_name, -1, ':');
874           screen_p = g_utf8_strrchr (canonical_display_name, -1, '.');
875           if (screen_p && display_p && (screen_p > display_p))
876             {
877               *screen_p = '\0';
878             }
879         }
880     }
881   else
882     {
883       canonical_display_name = g_strdup (display_env);
884     }
885
886   return canonical_display_name;
887 }
888
889 /**
890  * atspi_init:
891  *
892  * Connects to the accessibility registry and initializes the SPI.
893  *
894  * Returns: 0 on success, 1 if already initialized, or an integer error code.
895  **/
896 int
897 atspi_init (void)
898 {
899   char *match;
900   const gchar *no_cache;
901
902   if (atspi_inited)
903     {
904       return 1;
905     }
906
907   atspi_inited = TRUE;
908
909   _atspi_get_live_refs();
910
911   bus = atspi_get_a11y_bus ();
912   if (!bus)
913     return 2;
914   if (!dbus_bus_register (bus, NULL))
915     return 2;
916   atspi_dbus_connection_setup_with_g_main(bus, g_main_context_default());
917   dbus_connection_add_filter (bus, atspi_dbus_filter, NULL, NULL);
918   match = g_strdup_printf ("type='signal',interface='%s',member='AddAccessible'", atspi_interface_cache);
919   dbus_bus_add_match (bus, match, NULL);
920   g_free (match);
921   match = g_strdup_printf ("type='signal',interface='%s',member='RemoveAccessible'", atspi_interface_cache);
922   dbus_bus_add_match (bus, match, NULL);
923   g_free (match);
924   match = g_strdup_printf ("type='signal',interface='%s',member='ChildrenChanged'", atspi_interface_event_object);
925   dbus_bus_add_match (bus, match, NULL);
926   g_free (match);
927   match = g_strdup_printf ("type='signal',interface='%s',member='PropertyChange'", atspi_interface_event_object);
928   dbus_bus_add_match (bus, match, NULL);
929   g_free (match);
930   match = g_strdup_printf ("type='signal',interface='%s',member='StateChanged'", atspi_interface_event_object);
931   dbus_bus_add_match (bus, match, NULL);
932   g_free (match);
933
934   dbus_bus_add_match (bus,
935                       "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged'",
936                       NULL);
937
938   no_cache = g_getenv ("ATSPI_NO_CACHE");
939   if (no_cache && g_strcmp0 (no_cache, "0") != 0)
940     atspi_no_cache = TRUE;
941
942   deferred_messages = g_queue_new ();
943
944   return 0;
945 }
946
947 /**
948  * atspi_is_initialized:
949  *
950  * Indicates whether AT-SPI has been initialized.
951  *
952  * Returns: %True if initialized; %False otherwise.
953  */
954 gboolean
955 atspi_is_initialized ()
956 {
957   return atspi_inited;
958 }
959
960 /**
961  * atspi_event_main:
962  *
963  * Starts/enters the main event loop for the AT-SPI services.
964  *
965  * NOTE: This method does not return control; it is exited via a call to
966  * #atspi_event_quit from within an event handler.
967  *
968  **/
969 void
970 atspi_event_main (void)
971 {
972   atspi_main_loop = g_main_loop_new (NULL, FALSE);
973   g_main_loop_run (atspi_main_loop);
974   g_main_loop_unref(atspi_main_loop);
975   atspi_main_loop = NULL;
976 }
977
978 /**
979  * atspi_event_quit:
980  *
981  * Quits the last main event loop for the AT-SPI services,
982  * See: #atspi_event_main
983  **/
984 void
985 atspi_event_quit (void)
986 {
987   g_main_loop_quit (atspi_main_loop);
988 }
989
990 /**
991  * atspi_exit:
992  *
993  * Disconnects from #AtspiRegistry instances and releases
994  * any floating resources. Call only once at exit.
995  *
996  * Returns: 0 if there were no leaks, otherwise other integer values.
997  **/
998 int
999 atspi_exit (void)
1000 {
1001   int leaked;
1002
1003   if (!atspi_inited)
1004     {
1005       return 0;
1006     }
1007
1008   atspi_inited = FALSE;
1009
1010   if (live_refs)
1011     {
1012       leaked = g_hash_table_size (live_refs);
1013     }
1014   else
1015     {
1016       leaked = 0;
1017     }
1018
1019   cleanup ();
1020
1021   return leaked;
1022 }
1023
1024 static GSList *hung_processes;
1025
1026 static void
1027 remove_hung_process (DBusPendingCall *pending, void *data)
1028 {
1029   hung_processes = g_slist_remove (hung_processes, data);
1030   g_free (data);
1031   dbus_pending_call_unref (pending);
1032 }
1033
1034 static void
1035 check_for_hang (DBusMessage *message, DBusError *error, DBusConnection *bus, const char *bus_name)
1036 {
1037   if (!message && error->name &&
1038       !strcmp (error->name, "org.freedesktop.DBus.Error.NoReply"))
1039   {
1040     GSList *l;
1041     DBusMessage *message;
1042     gchar *bus_name_dup;
1043     DBusPendingCall *pending = NULL;
1044     dbus_bool_t result;
1045     for (l = hung_processes; l; l = l->next)
1046       if (!strcmp (l->data, bus_name))
1047         return;
1048     message = dbus_message_new_method_call (bus_name, "/",
1049                                             "org.freedesktop.DBus.Peer",
1050                                             "Ping");
1051     if (!message)
1052       return;
1053     result = dbus_connection_send_with_reply (bus, message, &pending, -1);
1054     dbus_message_unref (message);
1055     if (!result || !pending)
1056       return;
1057     bus_name_dup = g_strdup (bus_name);
1058     hung_processes = g_slist_append (hung_processes, bus_name_dup);
1059     dbus_pending_call_set_notify (pending, remove_hung_process, bus_name_dup, NULL);
1060   }
1061 }
1062
1063 static gboolean
1064 connection_is_hung (const char *bus_name)
1065 {
1066   GSList *l;
1067
1068   for (l = hung_processes; l; l = l->next)
1069     if (!strcmp (l->data, bus_name))
1070       return TRUE;
1071   return FALSE;
1072 }
1073
1074 static gboolean
1075 check_app (AtspiApplication *app, GError **error)
1076 {
1077   if (!app || !app->bus)
1078   {
1079     g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_APPLICATION_GONE,
1080                           _("The application no longer exists"));
1081     return FALSE;
1082   }
1083
1084   if (atspi_main_loop && connection_is_hung (app->bus_name))
1085   {
1086       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC,
1087                            "The process appears to be hung.");
1088     return FALSE;
1089   }
1090
1091   return TRUE;
1092 }
1093
1094 static void
1095 set_timeout (AtspiApplication *app)
1096 {
1097   struct timeval tv;
1098   int diff;
1099
1100   if (app && app_startup_time > 0)
1101   {
1102     gettimeofday (&tv, NULL);
1103     diff = (tv.tv_sec - app->time_added.tv_sec) * 1000 + (tv.tv_usec - app->time_added.tv_usec) / 1000;
1104     dbind_set_timeout (MAX(method_call_timeout, app_startup_time - diff));
1105   }
1106   else
1107     dbind_set_timeout (method_call_timeout);
1108 }
1109
1110 dbus_bool_t
1111 _atspi_dbus_call (gpointer obj, const char *interface, const char *method, GError **error, const char *type, ...)
1112 {
1113   va_list args;
1114   dbus_bool_t retval;
1115   DBusError err;
1116   AtspiObject *aobj = ATSPI_OBJECT (obj);
1117
1118   if (!check_app (aobj->app, error))
1119     return FALSE;
1120
1121   if (!allow_sync)
1122   {
1123     _atspi_set_error_no_sync (error);
1124     return FALSE;
1125   }
1126
1127   va_start (args, type);
1128   dbus_error_init (&err);
1129   set_timeout (aobj->app);
1130   retval = dbind_method_call_reentrant_va (aobj->app->bus, aobj->app->bus_name,
1131                                            aobj->path, interface, method, &err,
1132                                            type, args);
1133   va_end (args);
1134   check_for_hang (NULL, &err, aobj->app->bus, aobj->app->bus_name);
1135   process_deferred_messages ();
1136   if (dbus_error_is_set (&err))
1137   {
1138     g_set_error(error, ATSPI_ERROR, ATSPI_ERROR_IPC, "%s", err.message);
1139     dbus_error_free (&err);
1140   }
1141   return retval;
1142 }
1143
1144 DBusMessage *
1145 _atspi_dbus_call_partial (gpointer obj,
1146                           const char *interface,
1147                           const char *method,
1148                           GError **error,
1149                           const char *type, ...)
1150 {
1151   va_list args;
1152   DBusMessage * result;
1153   va_start (args, type);
1154   result =  _atspi_dbus_call_partial_va (obj, interface, method, error, type, args);
1155   va_end (args);
1156   return result;
1157 }
1158
1159
1160 DBusMessage *
1161 _atspi_dbus_call_partial_va (gpointer obj,
1162                           const char *interface,
1163                           const char *method,
1164                           GError **error,
1165                           const char *type,
1166                           va_list args)
1167 {
1168   AtspiObject *aobj = ATSPI_OBJECT (obj);
1169   DBusError err;
1170   DBusMessage *msg = NULL, *reply = NULL;
1171   DBusMessageIter iter;
1172   const char *p;
1173
1174   dbus_error_init (&err);
1175
1176   if (!check_app (aobj->app, error))
1177     goto out;
1178
1179   msg = dbus_message_new_method_call (aobj->app->bus_name, aobj->path, interface, method);
1180   if (!msg)
1181     goto out;
1182
1183   p = type;
1184   dbus_message_iter_init_append (msg, &iter);
1185   dbind_any_marshal_va (&iter, &p, args);
1186
1187   set_timeout (aobj->app);
1188   reply = dbind_send_and_allow_reentry (aobj->app->bus, msg, &err);
1189   check_for_hang (reply, &err, aobj->app->bus, aobj->app->bus_name);
1190 out:
1191   va_end (args);
1192   if (msg)
1193     dbus_message_unref (msg);
1194   process_deferred_messages ();
1195   if (dbus_error_is_set (&err))
1196   {
1197     g_set_error_literal(error, ATSPI_ERROR, ATSPI_ERROR_IPC, err.message);
1198     dbus_error_free (&err);
1199     if (reply)
1200       dbus_message_unref(reply);
1201     return NULL;
1202   }
1203   else if (reply && dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
1204   {
1205     const char *err_str = NULL;
1206     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &err_str, DBUS_TYPE_INVALID);
1207     if (err_str)
1208       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err_str);
1209     dbus_message_unref (reply);
1210     return NULL;
1211   }
1212   return reply;
1213 }
1214
1215 dbus_bool_t
1216 _atspi_dbus_get_property (gpointer obj, const char *interface, const char *name, GError **error, const char *type, void *data)
1217 {
1218   DBusMessage *message, *reply;
1219   DBusMessageIter iter, iter_variant;
1220   DBusError err;
1221   dbus_bool_t retval = FALSE;
1222   AtspiObject *aobj = ATSPI_OBJECT (obj);
1223   char expected_type = (type [0] == '(' ? 'r' : type [0]);
1224
1225   if (!aobj)
1226     return FALSE;
1227
1228   if (!check_app (aobj->app, error))
1229     return FALSE;
1230
1231   if (!allow_sync)
1232   {
1233     _atspi_set_error_no_sync (error);
1234     return FALSE;
1235   }
1236
1237   message = dbus_message_new_method_call (aobj->app->bus_name,
1238                                           aobj->path,
1239                                           "org.freedesktop.DBus.Properties",
1240                                           "Get");
1241   if (!message)
1242   {
1243     // TODO: throw exception
1244     return FALSE;
1245   }
1246   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1247   dbus_error_init (&err);
1248   set_timeout (aobj->app);
1249   reply = dbind_send_and_allow_reentry (aobj->app->bus, message, &err);
1250   check_for_hang (reply, &err, aobj->app->bus, aobj->app->bus_name);
1251   dbus_message_unref (message);
1252   process_deferred_messages ();
1253   if (!reply)
1254   {
1255     // TODO: throw exception
1256     goto done;
1257   }
1258
1259   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
1260   {
1261     const char *err_str = NULL;
1262     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &err_str, DBUS_TYPE_INVALID);
1263     if (err_str)
1264       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err_str);
1265     goto done;
1266   }
1267
1268   dbus_message_iter_init (reply, &iter);
1269   if (dbus_message_iter_get_arg_type (&iter) != 'v')
1270   {
1271     g_warning ("atspi_dbus_get_property: expected a variant when fetching %s from interface %s; got %s\n", name, interface, dbus_message_get_signature (reply));
1272     goto done;
1273   }
1274   dbus_message_iter_recurse (&iter, &iter_variant);
1275   if (dbus_message_iter_get_arg_type (&iter_variant) != expected_type)
1276   {
1277     g_warning ("atspi_dbus_get_property: Wrong type: expected %s, got %c\n", type, dbus_message_iter_get_arg_type (&iter_variant));
1278     goto done;
1279   }
1280   if (!strcmp (type, "(so)"))
1281   {
1282     *((AtspiAccessible **)data) = _atspi_dbus_return_accessible_from_iter (&iter_variant);
1283   }
1284   else
1285   {
1286     dbus_message_iter_get_basic (&iter_variant, data);
1287     if (type [0] == 's')
1288       *(char **)data = g_strdup (*(char **)data);
1289   }
1290   retval = TRUE;
1291 done:
1292   dbus_error_free (&err);
1293   if (reply)
1294     dbus_message_unref (reply);
1295   return retval;
1296 }
1297
1298 DBusMessage *
1299 _atspi_dbus_send_with_reply_and_block (DBusMessage *message, GError **error)
1300 {
1301   DBusMessage *reply;
1302   DBusError err;
1303   AtspiApplication *app;
1304   DBusConnection *bus;
1305
1306   app = get_application (dbus_message_get_destination (message));
1307
1308   if (app && !app->bus)
1309     return NULL;        /* will fail anyway; app has been disposed */
1310
1311   bus = (app ? app->bus : _atspi_bus());
1312   dbus_error_init (&err);
1313   set_timeout (app);
1314   reply = dbind_send_and_allow_reentry (bus, message, &err);
1315   process_deferred_messages ();
1316   dbus_message_unref (message);
1317   if (dbus_error_is_set (&err))
1318   {
1319     if (error)
1320       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err.message);
1321     dbus_error_free (&err);
1322   }
1323   return reply;
1324 }
1325
1326 GHashTable *
1327 _atspi_dbus_return_hash_from_message (DBusMessage *message)
1328 {
1329   DBusMessageIter iter;
1330   GHashTable *ret;
1331
1332   if (!message)
1333     return NULL;
1334
1335   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1336
1337   dbus_message_iter_init (message, &iter);
1338   ret = _atspi_dbus_hash_from_iter (&iter);
1339   dbus_message_unref (message);
1340   return ret;
1341 }
1342
1343 GHashTable *
1344 _atspi_dbus_hash_from_iter (DBusMessageIter *iter)
1345 {
1346   GHashTable *hash = g_hash_table_new_full (g_str_hash, g_str_equal,
1347                                             (GDestroyNotify) g_free,
1348                                             (GDestroyNotify) g_free);
1349   DBusMessageIter iter_array, iter_dict;
1350
1351   dbus_message_iter_recurse (iter, &iter_array);
1352   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1353   {
1354     const char *name, *value;
1355     dbus_message_iter_recurse (&iter_array, &iter_dict);
1356     dbus_message_iter_get_basic (&iter_dict, &name);
1357     dbus_message_iter_next (&iter_dict);
1358     dbus_message_iter_get_basic (&iter_dict, &value);
1359     g_hash_table_insert (hash, g_strdup (name), g_strdup (value));
1360     dbus_message_iter_next (&iter_array);
1361   }
1362   return hash;
1363 }
1364
1365 GArray *
1366 _atspi_dbus_return_attribute_array_from_message (DBusMessage *message)
1367 {
1368   DBusMessageIter iter;
1369   GArray *ret;
1370
1371   if (!message)
1372     return NULL;
1373
1374   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1375
1376   dbus_message_iter_init (message, &iter);
1377
1378   ret = _atspi_dbus_attribute_array_from_iter (&iter);
1379   dbus_message_unref (message);
1380   return ret;
1381 }
1382
1383 GArray *
1384 _atspi_dbus_attribute_array_from_iter (DBusMessageIter *iter)
1385 {
1386   DBusMessageIter iter_array, iter_dict;
1387   GArray *array = g_array_new (TRUE, TRUE, sizeof (gchar *));
1388
1389   dbus_message_iter_recurse (iter, &iter_array);
1390   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1391   {
1392     const char *name, *value;
1393     gchar *str;
1394     dbus_message_iter_recurse (&iter_array, &iter_dict);
1395     dbus_message_iter_get_basic (&iter_dict, &name);
1396     dbus_message_iter_next (&iter_dict);
1397     dbus_message_iter_get_basic (&iter_dict, &value);
1398     str = g_strdup_printf ("%s:%s", name, value);
1399     array = g_array_append_val (array, str);
1400     dbus_message_iter_next (&iter_array);;
1401   }
1402   return array;
1403 }
1404
1405 void
1406 _atspi_dbus_set_interfaces (AtspiAccessible *accessible, DBusMessageIter *iter)
1407 {
1408   DBusMessageIter iter_array;
1409   char *iter_sig = dbus_message_iter_get_signature (iter);
1410
1411   accessible->interfaces = 0;
1412   if (strcmp (iter_sig, "as") != 0)
1413   {
1414     g_warning ("_atspi_dbus_set_interfaces: Passed iterator with invalid signature %s", dbus_message_iter_get_signature (iter));
1415     dbus_free (iter_sig);
1416     return;
1417   }
1418   dbus_free (iter_sig);
1419   dbus_message_iter_recurse (iter, &iter_array);
1420   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1421   {
1422     const char *iface;
1423     gint n;
1424     dbus_message_iter_get_basic (&iter_array, &iface);
1425     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable")) continue;
1426     n = _atspi_get_iface_num (iface);
1427     if (n == -1)
1428     {
1429       g_warning ("AT-SPI: Unknown interface %s", iface);
1430     }
1431     else
1432       accessible->interfaces |= (1 << n);
1433     dbus_message_iter_next (&iter_array);
1434   }
1435   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_INTERFACES);
1436 }
1437
1438 void
1439 _atspi_dbus_set_state (AtspiAccessible *accessible, DBusMessageIter *iter)
1440 {
1441   DBusMessageIter iter_array;
1442   gint count;
1443   dbus_uint32_t *states;
1444
1445   dbus_message_iter_recurse (iter, &iter_array);
1446   dbus_message_iter_get_fixed_array (&iter_array, &states, &count);
1447   if (count != 2)
1448   {
1449     g_warning ("AT-SPI: expected 2 values in states array; got %d\n", count);
1450     if (!accessible->states)
1451       accessible->states = _atspi_state_set_new_internal (accessible, 0);
1452   }
1453   else
1454   {
1455     guint64 val = ((guint64)states [1]) << 32;
1456     val += states [0];
1457     if (!accessible->states)
1458       accessible->states = _atspi_state_set_new_internal (accessible, val);
1459     else
1460       accessible->states->states = val;
1461   }
1462   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_STATES);
1463 }
1464
1465 GQuark
1466 _atspi_error_quark (void)
1467 {
1468   return g_quark_from_static_string ("atspi_error");
1469 }
1470
1471 /*
1472  * Gets the IOR from the XDisplay.
1473  */
1474 #ifdef HAVE_X11
1475 static char *
1476 get_accessibility_bus_address_x11 (void)
1477 {
1478   Atom AT_SPI_BUS;
1479   Atom actual_type;
1480   Display *bridge_display = NULL;
1481   int actual_format;
1482   char *data;
1483   unsigned char *data_x11 = NULL;
1484   unsigned long nitems;
1485   unsigned long leftover;
1486   char *display_name;
1487
1488   display_name = spi_display_name ();
1489   if (!display_name)
1490     return NULL;
1491
1492   bridge_display = XOpenDisplay (display_name);
1493   g_free (display_name);
1494
1495   if (!bridge_display)
1496     {
1497       g_warning ("Could not open X display");
1498       return NULL;
1499     }
1500
1501   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
1502   XGetWindowProperty (bridge_display,
1503                       XDefaultRootWindow (bridge_display),
1504                       AT_SPI_BUS, 0L,
1505                       (long) BUFSIZ, False,
1506                       (Atom) 31, &actual_type, &actual_format,
1507                       &nitems, &leftover, &data_x11);
1508   XCloseDisplay (bridge_display);
1509
1510   data = g_strdup ((gchar *)data_x11);
1511   XFree (data_x11);
1512   return data;
1513 }
1514 #endif
1515
1516 static char *
1517 get_accessibility_bus_address_dbus (void)
1518 {
1519   DBusConnection *session_bus = NULL;
1520   DBusMessage *message;
1521   DBusMessage *reply;
1522   DBusError error;
1523   char *address = NULL;
1524
1525   session_bus = dbus_bus_get (DBUS_BUS_SESSION, NULL);
1526   if (!session_bus)
1527     return NULL;
1528
1529   message = dbus_message_new_method_call ("org.a11y.Bus",
1530                                           "/org/a11y/bus",
1531                                           "org.a11y.Bus",
1532                                           "GetAddress");
1533
1534   dbus_error_init (&error);
1535   reply = dbus_connection_send_with_reply_and_block (session_bus,
1536                                                      message,
1537                                                      -1,
1538                                                      &error);
1539   dbus_message_unref (message);
1540
1541   if (!reply)
1542   {
1543     g_warning ("AT-SPI: Error retrieving accessibility bus address: %s: %s",
1544                error.name, error.message);
1545     dbus_error_free (&error);
1546     goto out;
1547   }
1548
1549   {
1550     const char *tmp_address;
1551     if (!dbus_message_get_args (reply,
1552                                 NULL,
1553                                 DBUS_TYPE_STRING,
1554                                 &tmp_address,
1555                                 DBUS_TYPE_INVALID))
1556       {
1557         dbus_message_unref (reply);
1558         goto out;
1559       }
1560     address = g_strdup (tmp_address);
1561     dbus_message_unref (reply);
1562   }
1563   
1564 out:
1565   dbus_connection_unref (session_bus);
1566   return address;
1567 }
1568
1569 static DBusConnection *a11y_bus;
1570 static dbus_int32_t a11y_dbus_slot = -1;
1571
1572 static void
1573 a11y_bus_free (void *data)
1574 {
1575   if (data == a11y_bus)
1576     {
1577       a11y_bus = NULL;
1578       dbus_connection_free_data_slot (&a11y_dbus_slot);
1579     }
1580 }
1581
1582 /**
1583  * atspi_get_a11y_bus: (skip)
1584  */
1585 DBusConnection *
1586 atspi_get_a11y_bus (void)
1587 {
1588   DBusError error;
1589   char *address = NULL;
1590   const char *address_env = NULL;
1591
1592   if (a11y_bus && dbus_connection_get_is_connected (a11y_bus))
1593     return a11y_bus;
1594
1595   if (a11y_dbus_slot == -1)
1596     if (!dbus_connection_allocate_data_slot (&a11y_dbus_slot))
1597       g_warning ("AT-SPI: Unable to allocate D-Bus slot");
1598
1599   address_env = g_getenv ("AT_SPI_BUS_ADDRESS");
1600   if (address_env != NULL && *address_env != 0)
1601     address = g_strdup (address_env);
1602 #ifdef HAVE_X11
1603   if (!address && g_getenv ("DISPLAY") != NULL &&
1604       g_getenv ("WAYLAND_DISPLAY") == NULL)
1605     address = get_accessibility_bus_address_x11 ();
1606 #endif
1607   if (!address)
1608     address = get_accessibility_bus_address_dbus ();
1609   if (!address)
1610     return NULL;
1611
1612   dbus_error_init (&error);
1613   a11y_bus = dbus_connection_open_private (address, &error);
1614   g_free (address);
1615
1616   if (!a11y_bus)
1617     {
1618       if (!g_getenv("SSH_CONNECTION"))
1619         g_warning ("Couldn't connect to accessibility bus: %s", error.message);
1620       dbus_error_free (&error);
1621       return NULL;
1622     }
1623   else
1624     {
1625       if (!dbus_bus_register (a11y_bus, &error))
1626         {
1627           g_warning ("Couldn't register with accessibility bus: %s", error.message);
1628           dbus_error_free (&error);
1629           dbus_connection_close (a11y_bus);
1630           dbus_connection_unref (a11y_bus);
1631           a11y_bus = NULL;
1632           return NULL;
1633         }
1634     }
1635
1636   /* Simulate a weak ref on the bus */
1637   dbus_connection_set_data (a11y_bus, a11y_dbus_slot, a11y_bus, a11y_bus_free);
1638
1639   return a11y_bus;
1640 }
1641
1642 /**
1643  * atspi_set_timeout:
1644  * @val: The timeout value, in milliseconds, or -1 to disable the timeout.
1645  * @startup_time: The amount of time, in milliseconds, to allow to pass
1646  * before enforcing timeouts on an application. Can be used to prevent
1647  * timeout exceptions if an application is likely to block for an extended
1648  * period of time on initialization. -1 can be passed to disable this
1649  * behavior.
1650  *
1651  * Set the timeout used for method calls. If this is not set explicitly,
1652  * a default of 0.8 ms is used.
1653  * Note that at-spi2-registryd currently uses a timeout of 3 seconds when
1654  * sending a keyboard event notification. This means that, if an AT makes
1655  * a call in response to the keyboard notification and the application
1656  * being called does not respond before the timeout is reached,
1657  * at-spi2-registryd will time out on the keyboard event notification and
1658  * pass the key onto the application (ie, reply to indicate that the key
1659  * was not consumed), so this may make it undesirable to set a timeout
1660  * larger than 3 seconds.
1661  *
1662  * By default, the normal timeout is set to 800 ms, and the application startup
1663  * timeout is set to 15 seconds.
1664  */
1665 void
1666 atspi_set_timeout (gint val, gint startup_time)
1667 {
1668   method_call_timeout = val;
1669   app_startup_time = startup_time;
1670 }
1671
1672 /**
1673  * atspi_set_main_context:
1674  * @cnx: The #GMainContext to use.
1675  *
1676  * Sets the main loop context that AT-SPI should assume is in use when
1677  * setting an idle callback.
1678  * This function should be called by application-side implementors (ie,
1679  * at-spi2-atk) when it is desirable to re-enter the main loop.
1680  */
1681 void
1682 atspi_set_main_context (GMainContext *cnx)
1683 {
1684   if (atspi_main_context == cnx)
1685     return;
1686   if (process_deferred_messages_source != NULL)
1687   {
1688     g_source_destroy (process_deferred_messages_source);
1689     process_deferred_messages_source = g_idle_source_new ();
1690     g_source_set_callback (process_deferred_messages_source,
1691                            process_deferred_messages_callback, NULL, NULL);
1692     g_source_attach (process_deferred_messages_source, cnx);
1693     g_source_unref (process_deferred_messages_source);
1694   }
1695   atspi_main_context = cnx;
1696   atspi_dbus_connection_setup_with_g_main (atspi_get_a11y_bus (), cnx);
1697
1698   if (desktop)
1699   {
1700     gint i;
1701     for (i = desktop->children->len - 1; i >= 0; i--)
1702     {
1703       AtspiAccessible *child = g_ptr_array_index (desktop->children, i);
1704       if (child->parent.app && child->parent.app->bus)
1705         atspi_dbus_connection_setup_with_g_main (child->parent.app->bus, cnx);
1706     }
1707   }
1708 }
1709
1710 #ifdef DEBUG_REF_COUNTS
1711 static void
1712 print_disposed (gpointer key, gpointer value, gpointer data)
1713 {
1714   AtspiAccessible *accessible = key;
1715   if (accessible->parent.app)
1716     return;
1717   g_print ("disposed: %s %d\n", accessible->name, accessible->role);
1718 }
1719
1720 void
1721 debug_disposed ()
1722 {
1723   g_hash_table_foreach (live_refs, print_disposed, NULL);
1724 }
1725 #endif
1726
1727 gchar *
1728 _atspi_name_compat (gchar *name)
1729 {
1730   gchar *p = name;
1731
1732   while (*p)
1733   {
1734     if (*p == '-')
1735       *p = ' ';
1736     p++;
1737   }
1738   return name;
1739 }
1740
1741 /**
1742  * atspi_role_get_name:
1743  * @role: an #AtspiRole object to query.
1744  *
1745  * Gets a localizable string that indicates the name of an #AtspiRole.
1746  * <em>DEPRECATED.</em>
1747  *
1748  * Returns: a localizable string name for an #AtspiRole enumerated type.
1749  **/
1750 gchar *
1751 atspi_role_get_name (AtspiRole role)
1752 {
1753   gchar *retval = NULL;
1754   GTypeClass *type_class;
1755   GEnumValue *value;
1756
1757   type_class = g_type_class_ref (ATSPI_TYPE_ROLE);
1758   g_return_val_if_fail (G_IS_ENUM_CLASS (type_class), NULL);
1759
1760   value = g_enum_get_value (G_ENUM_CLASS (type_class), role);
1761
1762   if (value)
1763     {
1764       retval = g_strdup (value->value_nick);
1765     }
1766
1767   g_type_class_unref (type_class);
1768
1769   if (retval)
1770     return _atspi_name_compat (retval);
1771
1772   return NULL;
1773 }
1774
1775 GHashTable *
1776 _atspi_dbus_update_cache_from_dict (AtspiAccessible *accessible, DBusMessageIter *iter)
1777 {
1778   GHashTable *cache = _atspi_accessible_ref_cache (accessible);
1779   DBusMessageIter iter_dict, iter_dict_entry, iter_struct, iter_variant;
1780
1781   dbus_message_iter_recurse (iter, &iter_dict);
1782   while (dbus_message_iter_get_arg_type (&iter_dict) != DBUS_TYPE_INVALID)
1783   {
1784     const char *key;
1785     GValue *val = NULL;
1786     dbus_message_iter_recurse (&iter_dict, &iter_dict_entry);
1787     dbus_message_iter_get_basic (&iter_dict_entry, &key);
1788     dbus_message_iter_next (&iter_dict_entry);
1789     dbus_message_iter_recurse (&iter_dict_entry, &iter_variant);
1790     if (!strcmp (key, "interfaces"))
1791     {
1792       _atspi_dbus_set_interfaces (accessible, &iter_variant);
1793     }
1794     else if (!strcmp (key, "Attributes"))
1795     {
1796       char *iter_sig = dbus_message_iter_get_signature (&iter_variant);
1797       val = g_new0 (GValue, 1);;
1798       g_value_init (val, G_TYPE_HASH_TABLE);
1799       if (strcmp (iter_sig, "a{ss}") != 0)
1800       {
1801         dbus_free (iter_sig);
1802         break;
1803       }
1804       dbus_free (iter_sig);
1805       g_value_take_boxed (val, _atspi_dbus_hash_from_iter (&iter_variant));
1806     }
1807     else if (!strcmp (key, "Component.ScreenExtents"))
1808     {
1809       dbus_int32_t d_int;
1810       AtspiRect extents;
1811       char *iter_sig = dbus_message_iter_get_signature (&iter_variant);
1812       val = g_new0 (GValue, 1);;
1813       g_value_init (val, ATSPI_TYPE_RECT);
1814       if (strcmp (iter_sig, "(iiii)") != 0)
1815       {
1816         dbus_free (iter_sig);
1817         break;
1818       }
1819       dbus_free (iter_sig);
1820       dbus_message_iter_recurse (&iter_variant, &iter_struct);
1821       dbus_message_iter_get_basic (&iter_struct, &d_int);
1822       extents.x = d_int;
1823       dbus_message_iter_next (&iter_struct);
1824       dbus_message_iter_get_basic (&iter_struct, &d_int);
1825       extents.y = d_int;
1826       dbus_message_iter_next (&iter_struct);
1827       dbus_message_iter_get_basic (&iter_struct, &d_int);
1828       extents.width = d_int;
1829       dbus_message_iter_next (&iter_struct);
1830       dbus_message_iter_get_basic (&iter_struct, &d_int);
1831       extents.height = d_int;
1832       g_value_set_boxed (val, &extents);
1833     }
1834     if (val)
1835       g_hash_table_insert (cache, g_strdup (key), val);
1836     dbus_message_iter_next (&iter_dict);
1837   }
1838
1839   return cache;
1840 }
1841
1842 gboolean
1843 _atspi_get_allow_sync ()
1844 {
1845   return allow_sync;
1846 }
1847
1848 gboolean
1849 _atspi_set_allow_sync (gboolean val)
1850 {
1851   gboolean ret = allow_sync;
1852
1853   allow_sync = val;
1854   return ret;
1855 }
1856
1857 void
1858 _atspi_set_error_no_sync (GError **error)
1859 {
1860   g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_SYNC_NOT_ALLOWED,
1861                         _("Attempted synchronous call where prohibited"));
1862 }
1863
1864 static const char *sr_introspection = "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
1865 "\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
1866 "<node name=\"/org/a11y/atspi/screenreader\">\n"
1867 "  <interface name=\"org.a11y.Atspi.ScreenReader\">\n"
1868 "    <signal name=\"ReadingPosition\">\n"
1869 "      <arg type=\"i\"/>\n"
1870 "      <arg type=\"i\"/>\n"
1871 "    </signal>\n"
1872 "  </interface>\n"
1873 "</node>";
1874
1875 static DBusHandlerResult
1876 screen_reader_filter (DBusConnection *bus, DBusMessage *message, void *user_data)
1877 {
1878   if (dbus_message_is_method_call (message, DBUS_INTERFACE_INTROSPECTABLE,
1879       "Introspect"))
1880   {
1881     DBusMessage *reply = dbus_message_new_method_return (message);
1882     dbus_message_append_args (reply, DBUS_TYPE_STRING, &sr_introspection,
1883                               DBUS_TYPE_INVALID);
1884     dbus_connection_send (bus, reply, NULL);
1885     dbus_message_unref (reply);
1886     return DBUS_HANDLER_RESULT_HANDLED;
1887   }
1888   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1889 }
1890
1891 gboolean
1892 _atspi_prepare_screen_reader_interface ()
1893 {
1894   static gint initialized = 0;
1895   DBusConnection *a11y_bus = _atspi_bus ();
1896
1897   if (initialized)
1898     return (initialized > 0);
1899
1900   if (dbus_bus_request_name (a11y_bus, "org.a11y.Atspi.ScreenReader", 0, NULL) < 0)
1901   {
1902     initialized = -1;
1903     return FALSE;
1904   }
1905
1906   initialized = 1;
1907   dbus_connection_add_filter (a11y_bus, screen_reader_filter, NULL, NULL);
1908   return TRUE;
1909 }