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