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