Fix a possible crash when an application is short-lived
[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   return bus;
116 }
117
118 #define APP_IS_REGISTRY(app) (!strcmp (app->bus_name, atspi_bus_registry))
119
120 static void
121 cleanup ()
122 {
123   GHashTable *refs;
124
125   refs = live_refs;
126   live_refs = NULL;
127   if (refs)
128     {
129       g_hash_table_destroy (refs);
130     }
131 }
132
133 static gboolean atspi_inited = FALSE;
134
135 static GHashTable *app_hash = NULL;
136
137 static void
138 handle_get_bus_address (DBusPendingCall *pending, void *user_data)
139 {
140   AtspiApplication *app = user_data;
141   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
142   DBusMessage *message;
143   const char *address;
144   DBusPendingCall *new_pending;
145
146   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_METHOD_RETURN)
147   {
148     if (dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &address,
149                                DBUS_TYPE_INVALID))
150     {
151       DBusError error;
152       dbus_error_init (&error);
153       DBusConnection *bus = dbus_connection_open (address, &error);
154       if (bus)
155       {
156         if (app->bus)
157           dbus_connection_unref (app->bus);
158         app->bus = bus;
159       }
160     }
161   }
162   dbus_message_unref (reply);
163   dbus_pending_call_unref (pending);
164
165   if (!app->bus)
166     return; /* application has gone away / been disposed */
167
168   message = dbus_message_new_method_call (app->bus_name,
169                                           "/org/a11y/atspi/cache",
170                                           atspi_interface_cache, "GetItems");
171
172    dbus_connection_send_with_reply (app->bus, message, &new_pending, 2000);
173   dbus_pending_call_set_notify (new_pending, handle_get_items, app, NULL);
174   dbus_message_unref (message);
175 }
176
177 static AtspiApplication *
178 get_application (const char *bus_name)
179 {
180   AtspiApplication *app = NULL;
181   char *bus_name_dup;
182   DBusMessage *message;
183   DBusError error;
184   DBusPendingCall *pending = NULL;
185
186   if (!app_hash)
187   {
188     app_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_object_unref);
189     if (!app_hash) return NULL;
190   }
191   app = g_hash_table_lookup (app_hash, bus_name);
192   if (app) return app;
193   bus_name_dup = g_strdup (bus_name);
194   if (!bus_name_dup) return NULL;
195   // TODO: change below to something that will send state-change:defunct notification if necessary */
196   app = _atspi_application_new (bus_name);
197   if (!app) return NULL;
198   app->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
199   app->bus = dbus_connection_ref (_atspi_bus ());
200   app->cache = ATSPI_CACHE_UNDEFINED;
201   g_hash_table_insert (app_hash, bus_name_dup, app);
202   dbus_error_init (&error);
203   message = dbus_message_new_method_call (bus_name, atspi_path_root,
204                                           atspi_interface_application, "GetApplicationBusAddress");
205
206    dbus_connection_send_with_reply (app->bus, message, &pending, 2000);
207   dbus_pending_call_set_notify (pending, handle_get_bus_address, app, NULL);
208   dbus_message_unref (message);
209   return app;
210 }
211
212 static AtspiAccessible *
213 ref_accessible (const char *app_name, const char *path)
214 {
215   AtspiApplication *app;
216   AtspiAccessible *a;
217
218   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
219     return NULL;
220
221   app = get_application (app_name);
222
223   if (!strcmp (path, "/org/a11y/atspi/accessible/root"))
224   {
225     if (!app->root)
226     {
227       app->root = atspi_accessible_new (app, atspi_path_root);
228       app->root->accessible_parent = atspi_get_desktop (0);
229     }
230     return g_object_ref (app->root);
231   }
232
233   a = g_hash_table_lookup (app->hash, path);
234   if (a)
235   {
236     return g_object_ref (a);
237   }
238   a = atspi_accessible_new (app, path);
239   if (!a)
240     return NULL;
241   g_hash_table_insert (app->hash, g_strdup (a->parent.path), a);
242   g_object_ref (a);     /* for the hash */
243   return a;
244 }
245
246 static AtspiHyperlink *
247 ref_hyperlink (const char *app_name, const char *path)
248 {
249   AtspiApplication *app = get_application (app_name);
250   AtspiHyperlink *hyperlink;
251
252   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
253     return NULL;
254
255   hyperlink = g_hash_table_lookup (app->hash, path);
256   if (hyperlink)
257   {
258     return g_object_ref (hyperlink);
259   }
260   hyperlink = atspi_hyperlink_new (app, path);
261   if (!hyperlink)
262     return NULL;
263   g_hash_table_insert (app->hash, g_strdup (hyperlink->parent.path), hyperlink);
264   /* TODO: This should be a weak ref */
265   g_object_ref (hyperlink);     /* for the hash */
266   return hyperlink;
267 }
268
269 typedef struct
270 {
271   char *path;
272   char *parent;
273   GArray *children;
274   GArray *interfaces;
275   char *name;
276   dbus_uint32_t role;
277   char *description;
278   GArray *state_bitflags;
279 } CACHE_ADDITION;
280
281 static DBusHandlerResult
282 handle_remove_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
283 {
284   const char *sender = dbus_message_get_sender (message);
285   AtspiApplication *app;
286   const char *path;
287   DBusMessageIter iter, iter_struct;
288   const char *signature = dbus_message_get_signature (message);
289   AtspiAccessible *a;
290
291   if (strcmp (signature, "(so)") != 0)
292   {
293     g_warning (_("AT-SPI: Unknown signature %s for RemoveAccessible"), signature);
294     return DBUS_HANDLER_RESULT_HANDLED;
295   }
296
297   dbus_message_iter_init (message, &iter);
298   dbus_message_iter_recurse (&iter, &iter_struct);
299   dbus_message_iter_get_basic (&iter_struct, &sender);
300   dbus_message_iter_next (&iter_struct);
301   dbus_message_iter_get_basic (&iter_struct, &path);
302   app = get_application (sender);
303   a = ref_accessible (sender, path);
304   if (!a)
305     return DBUS_HANDLER_RESULT_HANDLED;
306   g_object_run_dispose (G_OBJECT (a));
307   g_hash_table_remove (app->hash, a->parent.path);
308   g_object_unref (a);   /* unref our own ref */
309   return DBUS_HANDLER_RESULT_HANDLED;
310 }
311
312 static gboolean
313 add_app_to_desktop (AtspiAccessible *a, const char *bus_name)
314 {
315   DBusError error;
316
317   dbus_error_init (&error);
318   AtspiAccessible *obj = ref_accessible (bus_name, atspi_path_root);
319   if (obj)
320   {
321     GList *new_list = g_list_append (a->children, obj);
322     if (new_list)
323     {
324       a->children = new_list;
325       return TRUE;
326     }
327   }
328   else
329   {
330     g_warning (_("AT-SPI: Error calling getRoot for %s: %s"), bus_name, error.message);
331   }
332   return FALSE;
333 }
334
335 static void
336 send_children_changed (AtspiAccessible *parent, AtspiAccessible *child, gboolean add)
337 {
338   AtspiEvent e;
339
340   memset (&e, 0, sizeof (e));
341   e.type = (add? "object:children-changed:add": "object:children-changed:remove");
342   e.source = parent;
343   e.detail1 = g_list_index (parent->children, child);
344   e.detail2 = 0;
345   _atspi_send_event (&e);
346 }
347
348 static void
349 unref_object_and_descendants (AtspiAccessible *obj)
350 {
351   GList *l;
352
353   for (l = obj->children; l; l = l->next)
354   {
355     unref_object_and_descendants (l->data);
356   }
357   g_object_unref (obj);
358 }
359
360 static gboolean
361 remove_app_from_desktop (AtspiAccessible *a, const char *bus_name)
362 {
363   GList *l;
364   AtspiAccessible *child;
365
366   for (l = a->children; l; l = l->next)
367   {
368     child = l->data;
369     if (!strcmp (bus_name, child->parent.app->bus_name)) break;
370   }
371   if (!l)
372   {
373     return FALSE;
374   }
375   send_children_changed (a, child, FALSE);
376   a->children = g_list_remove (a->children, child);
377   unref_object_and_descendants (child);
378   return TRUE;
379 }
380
381 static AtspiAccessible *desktop;
382
383 void
384 get_reference_from_iter (DBusMessageIter *iter, const char **app_name, const char **path)
385 {
386   DBusMessageIter iter_struct;
387
388   dbus_message_iter_recurse (iter, &iter_struct);
389   dbus_message_iter_get_basic (&iter_struct, app_name);
390   dbus_message_iter_next (&iter_struct);
391   dbus_message_iter_get_basic (&iter_struct, path);
392   dbus_message_iter_next (iter);
393 }
394
395 static void
396 add_accessible_from_iter (DBusMessageIter *iter)
397 {
398   GList *new_list;
399   DBusMessageIter iter_struct, iter_array;
400   const char *app_name, *path;
401   AtspiAccessible *accessible;
402   const char *name, *description;
403   dbus_uint32_t role;
404
405   dbus_message_iter_recurse (iter, &iter_struct);
406
407   /* get accessible */
408   get_reference_from_iter (&iter_struct, &app_name, &path);
409   accessible = ref_accessible (app_name, path);
410   if (!accessible)
411     return;
412
413   /* Get application: TODO */
414   dbus_message_iter_next (&iter_struct);
415
416   /* get parent */
417   get_reference_from_iter (&iter_struct, &app_name, &path);
418   if (accessible->accessible_parent)
419     g_object_unref (accessible->accessible_parent);
420   accessible->accessible_parent = ref_accessible (app_name, path);
421
422   /* Get children */
423   while (accessible->children)
424   {
425     g_object_unref (accessible->children->data);
426     accessible->children = g_list_remove (accessible->children, accessible->children->data);
427   }
428   dbus_message_iter_recurse (&iter_struct, &iter_array);
429   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
430   {
431     AtspiAccessible *child;
432     get_reference_from_iter (&iter_array, &app_name, &path);
433     child = ref_accessible (app_name, path);
434     new_list = g_list_append (accessible->children, child);
435     if (new_list) accessible->children = new_list;
436   }
437
438   /* interfaces */
439   dbus_message_iter_next (&iter_struct);
440   _atspi_dbus_set_interfaces (accessible, &iter_struct);
441   dbus_message_iter_next (&iter_struct);
442
443   /* name */
444   if (accessible->name)
445     g_free (accessible->name);
446   dbus_message_iter_get_basic (&iter_struct, &name);
447   accessible->name = g_strdup (name);
448   dbus_message_iter_next (&iter_struct);
449
450   /* role */
451   dbus_message_iter_get_basic (&iter_struct, &role);
452   accessible->role = role;
453   dbus_message_iter_next (&iter_struct);
454
455   /* description */
456   if (accessible->description)
457     g_free (accessible->description);
458   dbus_message_iter_get_basic (&iter_struct, &description);
459   accessible->description = g_strdup (description);
460   dbus_message_iter_next (&iter_struct);
461
462   _atspi_dbus_set_state (accessible, &iter_struct);
463   dbus_message_iter_next (&iter_struct);
464
465   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_NAME | ATSPI_CACHE_ROLE |
466                                ATSPI_CACHE_PARENT | ATSPI_CACHE_DESCRIPTION);
467   if (!atspi_state_set_contains (accessible->states,
468                                        ATSPI_STATE_MANAGES_DESCENDANTS))
469     _atspi_accessible_add_cache (accessible, ATSPI_CACHE_CHILDREN);
470
471   /* This is a bit of a hack since the cache holds a ref, so we don't need
472    * the one provided for us anymore */
473   g_object_unref (accessible);
474 }
475
476 static void
477 handle_get_items (DBusPendingCall *pending, void *user_data)
478 {
479   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
480   DBusMessageIter iter, iter_array;
481
482   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
483   {
484     const char *sender = dbus_message_get_sender (reply);
485     const char *error = NULL;
486     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &error,
487                            DBUS_TYPE_INVALID);
488     g_warning (_("AT-SPI: Error in GetItems, sender=%s, error=%s"), sender, error);
489     dbus_message_unref (reply);
490     dbus_pending_call_unref (pending);
491     return;
492   }
493
494   dbus_message_iter_init (reply, &iter);
495   dbus_message_iter_recurse (&iter, &iter_array);
496   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
497   {
498     add_accessible_from_iter (&iter_array);
499     dbus_message_iter_next (&iter_array);
500   }
501   dbus_message_unref (reply);
502   dbus_pending_call_unref (pending);
503 }
504
505 /* TODO: Do we stil need this function? */
506 static AtspiAccessible *
507 ref_accessible_desktop (AtspiApplication *app)
508 {
509   DBusError error;
510   DBusMessage *message, *reply;
511   DBusMessageIter iter, iter_array;
512   gchar *bus_name_dup;
513
514   if (desktop)
515   {
516     g_object_ref (desktop);
517     return desktop;
518   }
519   desktop = atspi_accessible_new (app, atspi_path_root);
520   if (!desktop)
521   {
522     return NULL;
523   }
524   g_hash_table_insert (app->hash, desktop->parent.path, desktop);
525   g_object_ref (desktop);       /* for the hash */
526   desktop->name = g_strdup ("main");
527   dbus_error_init (&error);
528   message = dbus_message_new_method_call (atspi_bus_registry,
529         atspi_path_root,
530         atspi_interface_accessible,
531         "GetChildren");
532   if (!message)
533     return NULL;
534   reply = _atspi_dbus_send_with_reply_and_block (message, NULL);
535   if (!reply || strcmp (dbus_message_get_signature (reply), "a(so)") != 0)
536   {
537     g_warning ("Couldn't get application list: %s", error.message);
538     if (reply)
539       dbus_message_unref (reply);
540     return NULL;
541   }
542   dbus_message_iter_init (reply, &iter);
543   dbus_message_iter_recurse (&iter, &iter_array);
544   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
545   {
546     const char *app_name, *path;
547     get_reference_from_iter (&iter_array, &app_name, &path);
548     add_app_to_desktop (desktop, app_name);
549   }
550   dbus_message_unref (reply);
551
552   /* Record the alternate name as an alias for org.a11y.atspi.Registry */
553   bus_name_dup = g_strdup (dbus_message_get_sender (reply));
554   if (bus_name_dup)
555     g_hash_table_insert (app_hash, bus_name_dup, app);
556
557   return desktop;
558 }
559
560 AtspiAccessible *
561 _atspi_ref_accessible (const char *app, const char *path)
562 {
563   AtspiApplication *a = get_application (app);
564   if (!a) return NULL;
565   if ( APP_IS_REGISTRY(a))
566   {
567     return a->root = ref_accessible_desktop (a);
568   }
569   return ref_accessible (app, path);
570 }
571
572 AtspiAccessible *
573 _atspi_dbus_return_accessible_from_message (DBusMessage *message)
574 {
575   DBusMessageIter iter;
576   AtspiAccessible *retval = NULL;
577   const char *signature;
578
579   if (!message)
580     return NULL;
581
582   signature = dbus_message_get_signature (message);
583   if (!strcmp (signature, "(so)"))
584   {
585     dbus_message_iter_init (message, &iter);
586     retval =  _atspi_dbus_return_accessible_from_iter (&iter);
587   }
588   else
589   {
590     g_warning (_("AT-SPI: Called _atspi_dbus_return_accessible_from_message with strange signature %s"), signature);
591   }
592   dbus_message_unref (message);
593   return retval;
594 }
595
596 AtspiAccessible *
597 _atspi_dbus_return_accessible_from_iter (DBusMessageIter *iter)
598 {
599   const char *app_name, *path;
600
601   get_reference_from_iter (iter, &app_name, &path);
602   return ref_accessible (app_name, path);
603 }
604
605 AtspiHyperlink *
606 _atspi_dbus_return_hyperlink_from_message (DBusMessage *message)
607 {
608   DBusMessageIter iter;
609   AtspiHyperlink *retval = NULL;
610   const char *signature = dbus_message_get_signature (message);
611    
612   if (!strcmp (signature, "(so)"))
613   {
614     dbus_message_iter_init (message, &iter);
615     retval =  _atspi_dbus_return_hyperlink_from_iter (&iter);
616   }
617   else
618   {
619     g_warning (_("AT-SPI: Called _atspi_dbus_return_hyperlink_from_message with strange signature %s"), signature);
620   }
621   dbus_message_unref (message);
622   return retval;
623 }
624
625 AtspiHyperlink *
626 _atspi_dbus_return_hyperlink_from_iter (DBusMessageIter *iter)
627 {
628   const char *app_name, *path;
629
630   get_reference_from_iter (iter, &app_name, &path);
631   return ref_hyperlink (app_name, path);
632 }
633
634 const char *cache_signal_type = "((so)(so)(so)a(so)assusau)";
635
636 static DBusHandlerResult
637 handle_add_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
638 {
639   DBusMessageIter iter;
640   const char *sender = dbus_message_get_sender (message);
641
642   if (strcmp (dbus_message_get_signature (message), cache_signal_type) != 0)
643   {
644     g_warning (_("AT-SPI: AddAccessible with unknown signature %s\n"),
645                dbus_message_get_signature (message));
646     return DBUS_HANDLER_RESULT_HANDLED;
647   }
648
649   dbus_message_iter_init (message, &iter);
650   add_accessible_from_iter (&iter);
651   return DBUS_HANDLER_RESULT_HANDLED;
652 }
653
654 typedef struct
655 {
656   DBusConnection *bus;
657   DBusMessage *message;
658   void *data;
659 } BusDataClosure;
660
661 static guint process_deferred_messages_id = -1;
662
663 static void
664 process_deferred_message (BusDataClosure *closure)
665 {
666   int type = dbus_message_get_type (closure->message);
667   const char *interface = dbus_message_get_interface (closure->message);
668
669   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
670       !strncmp (interface, "org.a11y.atspi.Event.", 21))
671   {
672     atspi_dbus_handle_event (closure->bus, closure->message, closure->data);
673   }
674   if (dbus_message_is_method_call (closure->message, atspi_interface_device_event_listener, "NotifyEvent"))
675   {
676     atspi_dbus_handle_DeviceEvent (closure->bus,
677                                    closure->message, closure->data);
678   }
679   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "AddAccessible"))
680   {
681     handle_add_accessible (closure->bus, closure->message, closure->data);
682   }
683   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "RemoveAccessible"))
684   {
685     handle_remove_accessible (closure->bus, closure->message, closure->data);
686   }
687 }
688
689 static GList *deferred_messages = NULL;
690
691 gboolean
692 _atspi_process_deferred_messages (gpointer data)
693 {
694   static int in_process_deferred_messages = 0;
695
696   if (in_process_deferred_messages)
697     return TRUE;
698   in_process_deferred_messages = 1;
699   while (deferred_messages != NULL)
700   {
701     BusDataClosure *closure = deferred_messages->data;
702     process_deferred_message (closure);
703     deferred_messages = g_list_remove (deferred_messages, closure);
704     dbus_message_unref (closure->message);
705     dbus_connection_unref (closure->bus);
706     g_free (closure);
707   }
708   /* If data is NULL, assume that we were called from GLib */
709   if (!data)
710     process_deferred_messages_id = -1;
711   in_process_deferred_messages = 0;
712   return FALSE;
713 }
714
715 static DBusHandlerResult
716 defer_message (DBusConnection *connection, DBusMessage *message, void *user_data)
717 {
718   BusDataClosure *closure = g_new (BusDataClosure, 1);
719   GList *new_list;
720
721   if (!closure)
722     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
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
1023   if (!aobj)
1024     return FALSE;
1025
1026   if (!aobj->app || !aobj->app->bus)
1027   {
1028     g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_APPLICATION_GONE,
1029                           _("The application no longer exists"));
1030     return FALSE;
1031   }
1032
1033   message = dbus_message_new_method_call (aobj->app->bus_name,
1034                                           aobj->path,
1035                                           "org.freedesktop.DBus.Properties",
1036                                           "Get");
1037   if (!message)
1038   {
1039     // TODO: throw exception
1040     return FALSE;
1041   }
1042   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1043   dbus_error_init (&err);
1044   reply = dbind_send_and_allow_reentry (aobj->app->bus, message, &err);
1045   dbus_message_unref (message);
1046   _atspi_process_deferred_messages ((gpointer)TRUE);
1047   if (!reply)
1048   {
1049     // TODO: throw exception
1050     goto done;
1051   }
1052
1053   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
1054   {
1055     const char *err;
1056     dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &err, DBUS_TYPE_INVALID);
1057     if (err)
1058       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err);
1059     goto done;
1060   }
1061
1062   dbus_message_iter_init (reply, &iter);
1063   if (dbus_message_iter_get_arg_type (&iter) != 'v')
1064   {
1065     g_warning (_("AT-SPI: expected a variant when fetching %s from interface %s; got %s\n"), name, interface, dbus_message_get_signature (reply));
1066     goto done;
1067   }
1068   dbus_message_iter_recurse (&iter, &iter_variant);
1069   if (dbus_message_iter_get_arg_type (&iter_variant) != type[0])
1070   {
1071     g_warning (_("atspi_dbus_get_property: Wrong type: expected %s, got %c\n"), type, dbus_message_iter_get_arg_type (&iter_variant));
1072     goto done;
1073   }
1074   if (!strcmp (type, "(so)"))
1075   {
1076     *((AtspiAccessible **)data) = _atspi_dbus_return_accessible_from_iter (&iter_variant);
1077   }
1078   else
1079   {
1080     dbus_message_iter_get_basic (&iter_variant, data);
1081     if (type [0] == 's')
1082       *(char **)data = g_strdup (*(char **)data);
1083   }
1084   retval = TRUE;
1085 done:
1086   if (reply)
1087     dbus_message_unref (reply);
1088   return retval;
1089 }
1090
1091 DBusMessage *
1092 _atspi_dbus_send_with_reply_and_block (DBusMessage *message, GError **error)
1093 {
1094   DBusMessage *reply;
1095   DBusError err;
1096   AtspiApplication *app;
1097   DBusConnection *bus;
1098
1099   app = get_application (dbus_message_get_destination (message));
1100
1101   if (app && !app->bus)
1102     return NULL;        /* will fail anyway; app has been disposed */
1103
1104   bus = (app ? app->bus : _atspi_bus());
1105   dbus_error_init (&err);
1106   reply = dbind_send_and_allow_reentry (bus, message, &err);
1107   _atspi_process_deferred_messages ((gpointer)TRUE);
1108   dbus_message_unref (message);
1109   if (err.message)
1110   {
1111     if (error)
1112       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err.message);
1113     dbus_error_free (&err);
1114   }
1115   return reply;
1116 }
1117
1118 GHashTable *
1119 _atspi_dbus_return_hash_from_message (DBusMessage *message)
1120 {
1121   DBusMessageIter iter;
1122   GHashTable *ret;
1123
1124   if (!message)
1125     return NULL;
1126
1127   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1128
1129   dbus_message_iter_init (message, &iter);
1130   ret = _atspi_dbus_hash_from_iter (&iter);
1131   dbus_message_unref (message);
1132   return ret;
1133 }
1134
1135 GHashTable *
1136 _atspi_dbus_hash_from_iter (DBusMessageIter *iter)
1137 {
1138   GHashTable *hash = g_hash_table_new (g_str_hash, g_str_equal);
1139   DBusMessageIter iter_array, iter_dict;
1140
1141   dbus_message_iter_recurse (iter, &iter_array);
1142   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1143   {
1144     const char *name, *value;
1145     dbus_message_iter_recurse (&iter_array, &iter_dict);
1146     dbus_message_iter_get_basic (&iter_dict, &name);
1147     dbus_message_iter_next (&iter_dict);
1148     dbus_message_iter_get_basic (&iter_dict, &value);
1149     g_hash_table_insert (hash, g_strdup (name), g_strdup (value));
1150     dbus_message_iter_next (&iter_array);
1151   }
1152   return hash;
1153 }
1154
1155 GArray *
1156 _atspi_dbus_return_attribute_array_from_message (DBusMessage *message)
1157 {
1158   DBusMessageIter iter;
1159   GArray *ret;
1160
1161   if (!message)
1162     return NULL;
1163
1164   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1165
1166   dbus_message_iter_init (message, &iter);
1167
1168   ret = _atspi_dbus_attribute_array_from_iter (&iter);
1169   dbus_message_unref (message);
1170   return ret;
1171 }
1172
1173 GArray *
1174 _atspi_dbus_attribute_array_from_iter (DBusMessageIter *iter)
1175 {
1176   DBusMessageIter iter_array, iter_dict;
1177   GArray *array = g_array_new (TRUE, TRUE, sizeof (gchar *));
1178
1179   dbus_message_iter_recurse (iter, &iter_array);
1180   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1181   {
1182     const char *name, *value;
1183     gchar *str;
1184     GArray *new_array;
1185     dbus_message_iter_recurse (&iter_array, &iter_dict);
1186     dbus_message_iter_get_basic (&iter_dict, &name);
1187     dbus_message_iter_next (&iter_dict);
1188     dbus_message_iter_get_basic (&iter_dict, &value);
1189     str = g_strdup_printf ("%s:%s", name, value);
1190     new_array = g_array_append_val (array, str);
1191     if (new_array)
1192       array = new_array;
1193     dbus_message_iter_next (&iter_array);;
1194   }
1195   return array;
1196 }
1197
1198 void
1199 _atspi_dbus_set_interfaces (AtspiAccessible *accessible, DBusMessageIter *iter)
1200 {
1201   DBusMessageIter iter_array;
1202
1203   accessible->interfaces = 0;
1204   dbus_message_iter_recurse (iter, &iter_array);
1205   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1206   {
1207     const char *iface;
1208     gint n;
1209     dbus_message_iter_get_basic (&iter_array, &iface);
1210     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable")) continue;
1211     n = _atspi_get_iface_num (iface);
1212     if (n == -1)
1213     {
1214       g_warning (_("AT-SPI: Unknown interface %s"), iface);
1215     }
1216     else
1217       accessible->interfaces |= (1 << n);
1218     dbus_message_iter_next (&iter_array);
1219   }
1220   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_INTERFACES);
1221 }
1222
1223 void
1224 _atspi_dbus_set_state (AtspiAccessible *accessible, DBusMessageIter *iter)
1225 {
1226   DBusMessageIter iter_array;
1227   gint count;
1228   dbus_uint32_t *states;
1229
1230   dbus_message_iter_recurse (iter, &iter_array);
1231   dbus_message_iter_get_fixed_array (&iter_array, &states, &count);
1232   if (count != 2)
1233   {
1234     g_warning (_("AT-SPI: expected 2 values in states array; got %d\n"), count);
1235     if (!accessible->states)
1236       accessible->states = _atspi_state_set_new_internal (accessible, 0);
1237   }
1238   else
1239   {
1240     guint64 val = ((guint64)states [1]) << 32;
1241     val += states [0];
1242     if (!accessible->states)
1243       accessible->states = _atspi_state_set_new_internal (accessible, val);
1244     else
1245       accessible->states->states = val;
1246   }
1247   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_STATES);
1248 }
1249
1250 GQuark
1251 atspi_error_quark (void)
1252 {
1253   return g_quark_from_static_string ("atspi_error");
1254 }
1255
1256 /*
1257  * Gets the IOR from the XDisplay.
1258  */
1259 static char *
1260 get_accessibility_bus_address_x11 (void)
1261 {
1262   Atom AT_SPI_BUS;
1263   Atom actual_type;
1264   Display *bridge_display;
1265   int actual_format;
1266   unsigned char *data = NULL;
1267   unsigned long nitems;
1268   unsigned long leftover;
1269
1270   bridge_display = XOpenDisplay (spi_display_name ());
1271   if (!bridge_display)
1272     {
1273       g_warning ("Could not open X display");
1274       return NULL;
1275     }
1276       
1277   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
1278   XGetWindowProperty (bridge_display,
1279                       XDefaultRootWindow (bridge_display),
1280                       AT_SPI_BUS, 0L,
1281                       (long) BUFSIZ, False,
1282                       (Atom) 31, &actual_type, &actual_format,
1283                       &nitems, &leftover, &data);
1284   XCloseDisplay (bridge_display);
1285
1286   return g_strdup (data);
1287 }
1288
1289 static char *
1290 get_accessibility_bus_address_dbus (void)
1291 {
1292   DBusConnection *session_bus = NULL;
1293   DBusMessage *message;
1294   DBusMessage *reply;
1295   char *address = NULL;
1296
1297   session_bus = dbus_bus_get (DBUS_BUS_SESSION, NULL);
1298   if (!session_bus)
1299     return NULL;
1300
1301   message = dbus_message_new_method_call ("org.a11y.Bus",
1302                                           "/org/a11y/bus",
1303                                           "org.a11y.Bus",
1304                                           "GetAddress");
1305
1306   reply = dbus_connection_send_with_reply_and_block (session_bus,
1307                                                      message,
1308                                                      -1,
1309                                                      NULL);
1310   dbus_message_unref (message);
1311
1312   if (!reply)
1313     return NULL;
1314   
1315   {
1316     const char *tmp_address;
1317     if (!dbus_message_get_args (reply,
1318                                 NULL,
1319                                 DBUS_TYPE_STRING,
1320                                 &tmp_address,
1321                                 DBUS_TYPE_INVALID))
1322       {
1323         dbus_message_unref (reply);
1324         return NULL;
1325       }
1326     address = g_strdup (tmp_address);
1327     dbus_message_unref (reply);
1328   }
1329   
1330   return address;
1331 }
1332
1333 DBusConnection *
1334 atspi_get_a11y_bus (void)
1335 {
1336   DBusConnection *bus = NULL;
1337   DBusError error;
1338   char *address;
1339
1340   address = get_accessibility_bus_address_x11 ();
1341   if (!address)
1342     address = get_accessibility_bus_address_dbus ();
1343   if (!address)
1344     return NULL;
1345
1346   dbus_error_init (&error);
1347   bus = dbus_connection_open (address, &error);
1348   g_free (address);
1349
1350   if (!bus)
1351     {
1352       g_warning ("Couldn't connect to accessibility bus: %s", error.message);
1353       return NULL;
1354     }
1355   else
1356     {
1357       if (!dbus_bus_register (bus, &error))
1358         {
1359           g_warning ("Couldn't register with accessibility bus: %s", error.message);
1360           return NULL;
1361         }
1362     }
1363   
1364   return bus;
1365 }