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