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