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