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