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