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