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