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.klass = "object";
341   e.type.major = "chidren-changed";
342   e.type.minor = (add? "add": "remove");
343   e.source = parent;
344   e.detail1 = g_list_index (parent->children, child);
345   e.detail2 = 0;
346   _atspi_send_event (&e);
347 }
348
349 static void
350 unref_object_and_descendants (AtspiAccessible *obj)
351 {
352   GList *l;
353
354   for (l = obj->children; l; l = l->next)
355   {
356     unref_object_and_descendants (l->data);
357   }
358   g_object_unref (obj);
359 }
360
361 static gboolean
362 remove_app_from_desktop (AtspiAccessible *a, const char *bus_name)
363 {
364   GList *l;
365   AtspiAccessible *child;
366
367   for (l = a->children; l; l = l->next)
368   {
369     child = l->data;
370     if (!strcmp (bus_name, child->parent.app->bus_name)) break;
371   }
372   if (!l)
373   {
374     g_warning ("Removing unregistered app %s; doing nothing\n", bus_name);
375     return FALSE;
376   }
377   send_children_changed (a, child, FALSE);
378   a->children = g_list_remove (a->children, child);
379   unref_object_and_descendants (child);
380   return TRUE;
381 }
382
383 static AtspiAccessible *desktop;
384
385 void
386 get_reference_from_iter (DBusMessageIter *iter, const char **app_name, const char **path)
387 {
388   DBusMessageIter iter_struct;
389
390   dbus_message_iter_recurse (iter, &iter_struct);
391   dbus_message_iter_get_basic (&iter_struct, app_name);
392   dbus_message_iter_next (&iter_struct);
393   dbus_message_iter_get_basic (&iter_struct, path);
394   dbus_message_iter_next (iter);
395 }
396
397 static void
398 add_accessible_from_iter (DBusMessageIter *iter)
399 {
400   gint i;
401   GList *new_list;
402   DBusMessageIter iter_struct, iter_array;
403   const char *app_name, *path;
404   AtspiApplication *app;
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   accessible->cached_properties |= ATSPI_CACHE_NAME | ATSPI_CACHE_ROLE | ATSPI_CACHE_PARENT;
470   if (!atspi_state_set_contains (accessible->states,
471                                        ATSPI_STATE_MANAGES_DESCENDANTS))
472     accessible->cached_properties |= ATSPI_CACHE_CHILDREN;
473
474   /* This is a bit of a hack since the cache holds a ref, so we don't need
475    * the one provided for us anymore */
476   g_object_unref (accessible);
477 }
478
479 static void
480 handle_get_items (DBusPendingCall *pending, void *user_data)
481 {
482   AtspiApplication *app = user_data;
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 ("Atspi: Error in GetItems, sender=%s, error=%s", sender, error);
493     dbus_message_unref (reply);
494     return;
495   }
496
497   dbus_message_iter_init (reply, &iter);
498   dbus_message_iter_recurse (&iter, &iter_array);
499   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
500   {
501     add_accessible_from_iter (&iter_array);
502     dbus_message_iter_next (&iter_array);
503   }
504   dbus_message_unref (reply);
505 }
506
507 /* TODO: Do we stil need this function? */
508 static AtspiAccessible *
509 ref_accessible_desktop (AtspiApplication *app)
510 {
511   DBusError error;
512   GArray *apps = NULL;
513   GArray *additions;
514   gint i;
515   DBusMessage *message, *reply;
516   DBusMessageIter iter, iter_array;
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;
538   reply = _atspi_dbus_send_with_reply_and_block (message);
539   if (!reply || strcmp (dbus_message_get_signature (reply), "a(so)") != 0)
540   {
541     g_error ("Couldn't get application list: %s", error.message);
542     if (reply)
543       dbus_message_unref (reply);
544     return;
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   return desktop;
556 }
557
558 AtspiAccessible *
559 _atspi_ref_accessible (const char *app, const char *path)
560 {
561   AtspiApplication *a = get_application (app);
562   if (!a) return NULL;
563   if ( APP_IS_REGISTRY(a))
564   {
565     return ref_accessible_desktop (a);
566   }
567   return ref_accessible (app, path);
568 }
569
570 AtspiAccessible *
571 _atspi_dbus_return_accessible_from_message (DBusMessage *message)
572 {
573   DBusMessageIter iter;
574   AtspiAccessible *retval = NULL;
575   const char *signature;
576
577   if (!message)
578     return NULL;
579
580   signature = dbus_message_get_signature (message);
581   if (!strcmp (signature, "(so)"))
582   {
583     dbus_message_iter_init (message, &iter);
584     retval =  _atspi_dbus_return_accessible_from_iter (&iter);
585   }
586   else
587   {
588     g_warning ("Atspi: Called _atspi_dbus_return_accessible_from_message with strange signature %s", signature);
589   }
590   dbus_message_unref (message);
591   return retval;
592 }
593
594 AtspiAccessible *
595 _atspi_dbus_return_accessible_from_iter (DBusMessageIter *iter)
596 {
597   const char *app_name, *path;
598
599   get_reference_from_iter (iter, &app_name, &path);
600   return ref_accessible (app_name, path);
601 }
602
603 AtspiHyperlink *
604 _atspi_dbus_return_hyperlink_from_message (DBusMessage *message)
605 {
606   DBusMessageIter iter;
607   AtspiHyperlink *retval = NULL;
608   const char *signature = dbus_message_get_signature (message);
609    
610   if (!strcmp (signature, "(so)"))
611   {
612     dbus_message_iter_init (message, &iter);
613     retval =  _atspi_dbus_return_hyperlink_from_iter (&iter);
614   }
615   else
616   {
617     g_warning ("Atspi: Called _atspi_dbus_return_hyperlink_from_message with strange signature %s", signature);
618   }
619   dbus_message_unref (message);
620   return retval;
621 }
622
623 AtspiHyperlink *
624 _atspi_dbus_return_hyperlink_from_iter (DBusMessageIter *iter)
625 {
626   const char *app_name, *path;
627
628   get_reference_from_iter (iter, &app_name, &path);
629   return ref_hyperlink (app_name, path);
630 }
631
632 const char *cache_signal_type = "((so)(so)(so)a(so)assusau)";
633
634 static DBusHandlerResult
635 handle_add_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
636 {
637   DBusMessageIter iter;
638   const char *sender = dbus_message_get_sender (message);
639   AtspiApplication *app = get_application (sender);
640   const char *type = cache_signal_type;
641
642   if (strcmp (dbus_message_get_signature (message), cache_signal_type) != 0)
643   {
644     g_warning ("atspi: AddAccessible with unknown signature %s\n", dbus_message_get_signature (message));
645     return;
646   }
647
648   dbus_message_iter_init (message, &iter);
649   add_accessible_from_iter (&iter);
650 }
651
652 typedef struct
653 {
654   DBusConnection *bus;
655   DBusMessage *message;
656   void *data;
657 } BusDataClosure;
658
659 static guint process_deferred_messages_id = -1;
660
661 static void
662 process_deferred_message (BusDataClosure *closure)
663 {
664   int type = dbus_message_get_type (closure->message);
665   const char *interface = dbus_message_get_interface (closure->message);
666   const char *member = dbus_message_get_member (closure->message); 
667   dbus_uint32_t v;
668   char *bus_name;
669
670   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
671       !strncmp (interface, "org.a11y.atspi.Event.", 21))
672   {
673     atspi_dbus_handle_event (closure->bus, closure->message, closure->data);
674   }
675   if (dbus_message_is_method_call (closure->message, atspi_interface_device_event_listener, "NotifyEvent"))
676   {
677     atspi_dbus_handle_DeviceEvent (closure->bus,
678                                    closure->message, closure->data);
679   }
680   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "AddAccessible"))
681   {
682     handle_add_accessible (closure->bus, closure->message, closure->data);
683   }
684   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "RemoveAccessible"))
685   {
686     handle_remove_accessible (closure->bus, closure->message, closure->data);
687   }
688 }
689
690 static GList *deferred_messages = NULL;
691
692 gboolean
693 _atspi_process_deferred_messages (gpointer data)
694 {
695   static int in_process_deferred_messages = 0;
696
697   if (in_process_deferred_messages)
698     return;
699   in_process_deferred_messages = 1;
700   while (deferred_messages != NULL)
701   {
702     BusDataClosure *closure = deferred_messages->data;
703     process_deferred_message (closure);
704     deferred_messages = g_list_remove (deferred_messages, closure);
705     dbus_message_unref (closure->message);
706     dbus_connection_unref (closure->bus);
707     g_free (closure);
708   }
709   /* If data is NULL, assume that we were called from GLib */
710   if (!data)
711     process_deferred_messages_id = -1;
712   in_process_deferred_messages = 0;
713   return FALSE;
714 }
715
716 static DBusHandlerResult
717 defer_message (DBusConnection *connection, DBusMessage *message, void *user_data)
718 {
719   BusDataClosure *closure = g_new (BusDataClosure, 1);
720   GList *new_list;
721
722   if (!closure)
723     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
724   closure->bus = dbus_connection_ref (bus);
725   closure->message = dbus_message_ref (message);
726   closure->data = user_data;
727
728   new_list = g_list_append (deferred_messages, closure);
729   if (new_list)
730     deferred_messages = new_list;
731
732   if (process_deferred_messages_id == -1)
733     process_deferred_messages_id = g_idle_add (_atspi_process_deferred_messages, NULL);
734   return DBUS_HANDLER_RESULT_HANDLED;
735 }
736
737 static DBusHandlerResult
738 atspi_dbus_filter (DBusConnection *bus, DBusMessage *message, void *data)
739 {
740   int type = dbus_message_get_type (message);
741   const char *interface = dbus_message_get_interface (message);
742   const char *member = dbus_message_get_member (message); 
743   dbus_uint32_t v;
744   char *bus_name;
745
746   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
747       !strncmp (interface, "org.a11y.atspi.Event.", 21))
748   {
749     return defer_message (bus, message, data);
750   }
751   if (dbus_message_is_method_call (message, atspi_interface_device_event_listener, "NotifyEvent"))
752   {
753     return defer_message (bus, message, data);
754   }
755   if (dbus_message_is_signal (message, atspi_interface_cache, "AddAccessible"))
756   {
757     return defer_message (bus, message, data);
758   }
759   if (dbus_message_is_signal (message, atspi_interface_cache, "RemoveAccessible"))
760   {
761     return defer_message (bus, message, data);
762   }
763   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
764 }
765
766 static const char *signal_interfaces[] =
767 {
768   "org.a11y.atspi.Event.Object",
769   "org.a11y.atspi.Event.Window",
770   "org.a11y.atspi.Event.Mouse",
771   "org.a11y.atspi.Event.Terminal",
772   "org.a11y.atspi.Event.Document",
773   "org.a11y.atspi.Event.Focus",
774   NULL
775 };
776
777 /*
778  * Returns a 'canonicalized' value for DISPLAY,
779  * with the screen number stripped off if present.
780  *
781  * TODO: Avoid having duplicate functions for this here and in at-spi2-atk
782  */
783 static const gchar *
784 spi_display_name (void)
785 {
786   static const char *canonical_display_name = NULL;
787   if (!canonical_display_name)
788     {
789       const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
790       if (!display_env)
791         {
792           display_env = g_getenv ("DISPLAY");
793           if (!display_env || !display_env[0])
794             canonical_display_name = ":0";
795           else
796             {
797               gchar *display_p, *screen_p;
798               canonical_display_name = g_strdup (display_env);
799               display_p = g_utf8_strrchr (canonical_display_name, -1, ':');
800               screen_p = g_utf8_strrchr (canonical_display_name, -1, '.');
801               if (screen_p && display_p && (screen_p > display_p))
802                 {
803                   *screen_p = '\0';
804                 }
805             }
806         }
807       else
808         {
809           canonical_display_name = display_env;
810         }
811     }
812   return canonical_display_name;
813 }
814
815 /* TODO: Avoid having duplicate functions for this here and in at-spi2-atk */
816 static DBusConnection *
817 get_accessibility_bus ()
818 {
819   Atom AT_SPI_BUS;
820   Atom actual_type;
821   Display *bridge_display;
822   int actual_format;
823   unsigned char *data = NULL;
824   unsigned long nitems;
825   unsigned long leftover;
826
827   DBusConnection *bus = NULL;
828   DBusError error;
829
830   bridge_display = XOpenDisplay (spi_display_name ());
831   if (!bridge_display)
832     {
833       g_warning ("AT_SPI: Could not get the display\n");
834       return NULL;
835     }
836
837   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
838   XGetWindowProperty (bridge_display,
839                       XDefaultRootWindow (bridge_display),
840                       AT_SPI_BUS, 0L,
841                       (long) BUFSIZ, False,
842                       (Atom) 31, &actual_type, &actual_format,
843                       &nitems, &leftover, &data);
844
845   dbus_error_init (&error);
846
847   if (data == NULL)
848     {
849       g_warning
850         ("AT-SPI: Accessibility bus not found - Using session bus.\n");
851       bus = dbus_bus_get (DBUS_BUS_SESSION, &error);
852       if (!bus)
853         {
854           g_warning ("AT-SPI: Couldn't connect to bus: %s\n", error.message);
855           return NULL;
856         }
857     }
858   else
859     {
860       bus = dbus_connection_open (data, &error);
861       if (!bus)
862         {
863           g_warning ("AT-SPI: Couldn't connect to bus: %s\n", error.message);
864           return NULL;
865         }
866       else
867         {
868           if (!dbus_bus_register (bus, &error))
869             {
870               g_warning ("AT-SPI: Couldn't register with bus: %s\n", error.message);
871               return NULL;
872             }
873         }
874     }
875
876   return bus;
877 }
878
879 /**
880  * atspi_init:
881  *
882  * Connects to the accessibility registry and initializes the SPI.
883  *
884  * Returns: 0 on success, otherwise an integer error code.  
885  **/
886 int
887 atspi_init (void)
888 {
889   DBusError error;
890   char *match;
891   int i;
892
893   if (atspi_inited)
894     {
895       return 1;
896     }
897
898   atspi_inited = TRUE;
899
900   g_type_init ();
901
902   get_live_refs();
903
904   dbus_error_init (&error);
905   bus = get_accessibility_bus ();
906   if (!bus)
907   {
908     g_error ("Couldn't get session bus");
909     return 2;
910   }
911   dbus_bus_register (bus, &error);
912   dbus_connection_setup_with_g_main(bus, g_main_context_default());
913   dbus_connection_add_filter (bus, atspi_dbus_filter, NULL, NULL);
914   dbind_set_timeout (1000);
915   match = g_strdup_printf ("type='signal',interface='%s',member='AddAccessible'", atspi_interface_cache);
916   dbus_error_init (&error);
917   dbus_bus_add_match (bus, match, &error);
918   g_free (match);
919   match = g_strdup_printf ("type='signal',interface='%s',member='RemoveAccessible'", atspi_interface_cache);
920   dbus_bus_add_match (bus, match, &error);
921   g_free (match);
922   match = g_strdup_printf ("type='signal',interface='%s',member='ChildrenChanged'", atspi_interface_event_object);
923   dbus_bus_add_match (bus, match, &error);
924   g_free (match);
925   match = g_strdup_printf ("type='signal',interface='%s',member='PropertyChange'", atspi_interface_event_object);
926   dbus_bus_add_match (bus, match, &error);
927   g_free (match);
928   match = g_strdup_printf ("type='signal',interface='%s',member='StateChanged'", atspi_interface_event_object);
929   dbus_bus_add_match (bus, match, &error);
930   g_free (match);
931   return 0;
932 }
933
934   static GMainLoop *mainloop;
935
936 /**
937  * atspi_event_main:
938  *
939  * Starts/enters the main event loop for the AT-SPI services.
940  *
941  * (NOTE: This method does not return control, it is exited via a call to
942  *  atspi_event_quit () from within an event handler).
943  *
944  **/
945 void
946 atspi_event_main (void)
947 {
948   mainloop = g_main_loop_new (NULL, FALSE);
949   g_main_loop_run (mainloop);
950 }
951
952 /**
953  * atspi_event_quit:
954  *
955  * Quits the last main event loop for the SPI services,
956  * see atspi_event_main
957  **/
958 void
959 atspi_event_quit (void)
960 {
961   g_main_loop_quit (mainloop);
962 }
963
964 /**
965  * atspi_exit:
966  *
967  * Disconnects from the Accessibility Registry and releases 
968  * any floating resources. Call only once at exit.
969  *
970  * Returns: 0 if there were no leaks, otherwise non zero.
971  **/
972 int
973 atspi_exit (void)
974 {
975   int leaked;
976
977   if (!atspi_inited)
978     {
979       return 0;
980     }
981
982   atspi_inited = FALSE;
983
984   if (live_refs)
985     {
986       leaked = g_hash_table_size (live_refs);
987     }
988   else
989     {
990       leaked = 0;
991     }
992
993   cleanup ();
994
995   return leaked;
996 }
997
998 dbus_bool_t
999 _atspi_dbus_call (gpointer obj, const char *interface, const char *method, GError **error, const char *type, ...)
1000 {
1001   va_list args;
1002   dbus_bool_t retval;
1003   DBusError err;
1004   AtspiObject *aobj = ATSPI_OBJECT (obj);
1005
1006   va_start (args, type);
1007   dbus_error_init (&err);
1008   retval = dbind_method_call_reentrant_va (aobj->app->bus, aobj->app->bus_name,
1009                                            aobj->path, interface, method, &err,
1010                                            type, args);
1011   va_end (args);
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 retval;
1019 }
1020
1021 DBusMessage *
1022 _atspi_dbus_call_partial (gpointer obj,
1023                           const char *interface,
1024                           const char *method,
1025                           GError **error,
1026                           const char *type, ...)
1027 {
1028   va_list args;
1029
1030   va_start (args, type);
1031   return _atspi_dbus_call_partial_va (obj, interface, method, error, type, args);
1032 }
1033
1034 DBusMessage *
1035 _atspi_dbus_call_partial_va (gpointer obj,
1036                           const char *interface,
1037                           const char *method,
1038                           GError **error,
1039                           const char *type,
1040                           va_list args)
1041 {
1042   AtspiObject *aobj = ATSPI_OBJECT (obj);
1043   dbus_bool_t retval;
1044   DBusError err;
1045     DBusMessage *msg = NULL, *reply = NULL;
1046     DBusMessageIter iter;
1047     const char *p;
1048
1049   dbus_error_init (&err);
1050
1051     msg = dbus_message_new_method_call (aobj->app->bus_name, aobj->path, interface, method);
1052     if (!msg)
1053         goto out;
1054
1055     p = type;
1056     dbus_message_iter_init_append (msg, &iter);
1057     dbind_any_marshal_va (&iter, &p, args);
1058
1059     reply = dbind_send_and_allow_reentry (aobj->app->bus, msg, &err);
1060 out:
1061   va_end (args);
1062   _atspi_process_deferred_messages ((gpointer)TRUE);
1063   if (dbus_error_is_set (&err))
1064   {
1065     /* TODO: Set gerror */
1066     dbus_error_free (&err);
1067   }
1068   return reply;
1069 }
1070
1071 dbus_bool_t
1072 _atspi_dbus_get_property (gpointer obj, const char *interface, const char *name, GError **error, const char *type, void *data)
1073 {
1074   DBusMessage *message, *reply;
1075   DBusMessageIter iter, iter_variant;
1076   DBusError err;
1077   dbus_bool_t retval = FALSE;
1078   AtspiObject *aobj = ATSPI_OBJECT (obj);
1079
1080   if (!aobj)
1081     return FALSE;
1082
1083   message = dbus_message_new_method_call (aobj->app->bus_name,
1084                                           aobj->path,
1085                                           "org.freedesktop.DBus.Properties",
1086                                           "Get");
1087   if (!message)
1088   {
1089     // TODO: throw exception
1090     goto done;
1091   }
1092   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1093   dbus_error_init (&err);
1094   reply = dbind_send_and_allow_reentry (aobj->app->bus, message, &err);
1095   dbus_message_unref (message);
1096   _atspi_process_deferred_messages ((gpointer)TRUE);
1097   if (!reply)
1098   {
1099     // TODO: throw exception
1100     goto done;
1101   }
1102   dbus_message_iter_init (reply, &iter);
1103   if (dbus_message_iter_get_arg_type (&iter) != 'v')
1104   {
1105     g_warning ("at-spi: expected a variant when fetching %s from interface %s; got %s\n", name, interface, dbus_message_get_signature (reply));
1106     goto done;
1107   }
1108   dbus_message_iter_recurse (&iter, &iter_variant);
1109   if (dbus_message_iter_get_arg_type (&iter_variant) != type[0])
1110   {
1111     g_warning ("atspi_dbus_get_property: Wrong type: expected %s, got %c\n", type, dbus_message_iter_get_arg_type (&iter_variant));
1112     goto done;
1113   }
1114   if (!strcmp (type, "(so)"))
1115   {
1116     *((AtspiAccessible **)data) = _atspi_dbus_return_accessible_from_iter (&iter_variant);
1117   }
1118   else
1119   {
1120     dbus_message_iter_get_basic (&iter_variant, data);
1121     dbus_message_unref (reply);
1122     if (type [0] == 's')
1123       *(char **)data = g_strdup (*(char **)data);
1124   }
1125   retval = TRUE;
1126 done:
1127   return retval;
1128 }
1129
1130 DBusMessage *
1131 _atspi_dbus_send_with_reply_and_block (DBusMessage *message)
1132 {
1133   DBusMessage *reply;
1134   DBusError err;
1135   AtspiApplication *app;
1136   DBusConnection *bus;
1137
1138   app = get_application (dbus_message_get_destination (message));
1139   bus = (app ? app->bus : _atspi_bus());
1140   dbus_error_init (&err);
1141   reply = dbind_send_and_allow_reentry (bus, message, &err);
1142   _atspi_process_deferred_messages ((gpointer)TRUE);
1143   dbus_message_unref (message);
1144   if (err.message)
1145     g_warning ("Atspi: Got error: %s\n", err.message);
1146   return reply;
1147 }
1148
1149 GHashTable *
1150 _atspi_dbus_return_hash_from_message (DBusMessage *message)
1151 {
1152   DBusMessageIter iter;
1153   GHashTable *ret;
1154
1155   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL);
1156
1157   dbus_message_iter_init (message, &iter);
1158   ret = _atspi_dbus_hash_from_iter (&iter);
1159   dbus_message_unref (message);
1160   return ret;
1161 }
1162
1163 GHashTable *
1164 _atspi_dbus_hash_from_iter (DBusMessageIter *iter)
1165 {
1166   GHashTable *hash = g_hash_table_new (g_str_hash, g_str_equal);
1167   DBusMessageIter iter_array, iter_dict;
1168
1169   dbus_message_iter_recurse (iter, &iter_array);
1170   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1171   {
1172     const char *name, *value;
1173     dbus_message_iter_recurse (&iter_array, &iter_dict);
1174     dbus_message_iter_get_basic (&iter_dict, &name);
1175     dbus_message_iter_next (&iter_dict);
1176     dbus_message_iter_get_basic (&iter_dict, &value);
1177     g_hash_table_insert (hash, g_strdup (name), g_strdup (value));
1178     dbus_message_iter_next (&iter_array);
1179   }
1180   return hash;
1181 }
1182
1183 GArray *
1184 _atspi_dbus_return_attribute_array_from_message (DBusMessage *message)
1185 {
1186   DBusMessageIter iter;
1187   GArray *ret;
1188
1189   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL);
1190
1191   dbus_message_iter_init (message, &iter);
1192
1193   ret = _atspi_dbus_attribute_array_from_iter (&iter);
1194   dbus_message_unref (message);
1195   return ret;
1196 }
1197
1198 GArray *
1199 _atspi_dbus_attribute_array_from_iter (DBusMessageIter *iter)
1200 {
1201   DBusMessageIter iter_array, iter_dict;
1202   GArray *array = g_array_new (TRUE, TRUE, sizeof (gchar *));
1203   gint count = 0;
1204
1205   dbus_message_iter_recurse (iter, &iter_array);
1206   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1207   {
1208     const char *name, *value;
1209     gchar *str;
1210     GArray *new_array;
1211     dbus_message_iter_recurse (&iter_array, &iter_dict);
1212     dbus_message_iter_get_basic (&iter_dict, &name);
1213     dbus_message_iter_next (&iter_dict);
1214     dbus_message_iter_get_basic (&iter_dict, &value);
1215     str = g_strdup_printf ("%s:%s", name, value);
1216     new_array = g_array_append_val (array, str);
1217     if (new_array)
1218       array = new_array;
1219     dbus_message_iter_next (&iter_array);;
1220   }
1221   return array;
1222 }
1223
1224 void
1225 _atspi_dbus_set_interfaces (AtspiAccessible *accessible, DBusMessageIter *iter)
1226 {
1227   DBusMessageIter iter_array;
1228
1229   accessible->interfaces = 0;
1230   dbus_message_iter_recurse (iter, &iter_array);
1231   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1232   {
1233     const char *iface;
1234     gint n;
1235     dbus_message_iter_get_basic (&iter_array, &iface);
1236     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable")) continue;
1237     n = _atspi_get_iface_num (iface);
1238     if (n == -1)
1239     {
1240       g_warning ("at-spi: Unknown interface %s", iface);
1241     }
1242     else
1243       accessible->interfaces |= (1 << n);
1244     dbus_message_iter_next (&iter_array);
1245   }
1246   accessible->cached_properties |= ATSPI_CACHE_INTERFACES;
1247 }
1248
1249 void
1250 _atspi_dbus_set_state (AtspiAccessible *accessible, DBusMessageIter *iter)
1251 {
1252   DBusMessageIter iter_array;
1253   gint count;
1254   dbus_uint32_t *states;
1255
1256   dbus_message_iter_recurse (iter, &iter_array);
1257   dbus_message_iter_get_fixed_array (&iter_array, &states, &count);
1258   if (count != 2)
1259   {
1260     g_warning ("at-spi: expected 2 values in states array; got %d\n", count);
1261     if (!accessible->states)
1262       accessible->states = _atspi_state_set_new_internal (accessible, 0);
1263   }
1264   else
1265   {
1266     guint64 val = ((guint64)states [1]) << 32;
1267     val += states [0];
1268     if (!accessible->states)
1269       accessible->states = _atspi_state_set_new_internal (accessible, val);
1270     else
1271       accessible->states->states = val;
1272   }
1273   accessible->cached_properties |= ATSPI_CACHE_STATES;
1274 }