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