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