0cbb6bda2c8749d2828532c4ddc7357d39361eb2
[platform/core/uifw/at-spi2-atk.git] / cspi / spi-main.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 <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <cspi/spi-private.h>
34 #include "spi.h"
35
36 #undef DEBUG_OBJECTS
37
38 static DBusConnection *bus = NULL;
39 static GHashTable *apps = NULL;
40 static GHashTable *live_refs = NULL;
41 static GQueue *exception_handlers = NULL;
42 static DBusError exception;
43
44 static void
45 cspi_object_release (gpointer value)
46 {
47 }
48
49 gboolean
50 cspi_exception_throw (DBusError *error, const char *desc_prefix)
51 {
52   SPIExceptionHandler *handler = NULL;
53   SPIException ex;
54   if (exception_handlers) handler = g_queue_peek_head (exception_handlers);
55
56   ex.type = SPI_EXCEPTION_SOURCE_UNSPECIFIED;
57   ex.source = NULL;
58   ex.code = SPI_EXCEPTION_UNSPECIFIED;
59   ex.error = error;
60   // TODO: Fill in description
61   
62   if (handler)
63     return (*handler) (&ex, FALSE);
64   else
65     return FALSE; /* means exception was not handled */
66 }
67
68 const char *spi_path_dec = SPI_DBUS_PATH_DEC;
69 const char *spi_path_registry = SPI_DBUS_PATH_REGISTRY;
70 const char *spi_bus_registry = SPI_DBUS_NAME_REGISTRY;
71 const char *spi_path_desktop = SPI_DBUS_PATH_DESKTOP;
72 const char *spi_interface_accessible = SPI_DBUS_INTERFACE_ACCESSIBLE;
73 const char *spi_interface_action = SPI_DBUS_INTERFACE_ACTION;
74 const char *spi_interface_application = SPI_DBUS_INTERFACE_APPLICATION;
75 const char *spi_interface_component = SPI_DBUS_INTERFACE_COMPONENT;
76 const char *spi_interface_dec = SPI_DBUS_INTERFACE_DEC;
77 const char *spi_interface_desktop = SPI_DBUS_INTERFACE_DESKTOP;
78 const char *spi_interface_device_event_listener = SPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER;
79 const char *spi_interface_document = SPI_DBUS_INTERFACE_DOCUMENT;
80 const char *spi_interface_editable_text = SPI_DBUS_INTERFACE_EDITABLE_TEXT;
81 const char *spi_interface_hyperlink = SPI_DBUS_INTERFACE_HYPERLINK;
82 const char *spi_interface_hypertext = SPI_DBUS_INTERFACE_HYPERTEXT;
83 const char *spi_interface_image = SPI_DBUS_INTERFACE_IMAGE;
84 const char *spi_interface_registry = SPI_DBUS_INTERFACE_REGISTRY;
85 const char *spi_interface_selection = SPI_DBUS_INTERFACE_SELECTION;
86 const char *spi_interface_table = SPI_DBUS_INTERFACE_TABLE;
87 const char *spi_interface_text = SPI_DBUS_INTERFACE_TEXT;
88 const char *spi_interface_tree = SPI_DBUS_INTERFACE_TREE;
89 const char *spi_interface_value = SPI_DBUS_INTERFACE_VALUE;
90
91 static const char *interfaces[] =
92 {
93   SPI_DBUS_INTERFACE_ACCESSIBLE,
94   SPI_DBUS_INTERFACE_ACTION,
95   SPI_DBUS_INTERFACE_APPLICATION,
96   SPI_DBUS_INTERFACE_COLLECTION,
97   SPI_DBUS_INTERFACE_COMPONENT,
98   SPI_DBUS_INTERFACE_DOCUMENT,
99   SPI_DBUS_INTERFACE_EDITABLE_TEXT,
100   SPI_DBUS_INTERFACE_HYPERLINK,
101   SPI_DBUS_INTERFACE_HYPERTEXT,
102   SPI_DBUS_INTERFACE_IMAGE,
103   "org.a11y.atspi.LoginHelper",
104   SPI_DBUS_INTERFACE_SELECTION,
105   "org.a11y.atspi.Selector",
106   SPI_DBUS_INTERFACE_TABLE,
107   SPI_DBUS_INTERFACE_TEXT,
108   SPI_DBUS_INTERFACE_VALUE,
109   NULL
110 };
111
112 static gint get_iface_num (const char *iface)
113 {
114   // TODO: Use a binary search or hash to improve performance
115   int i;
116
117   for (i = 0; interfaces[i]; i++)
118   {
119     if (!strcmp(iface, interfaces[i])) return i;
120   }
121   return -1;
122 }
123
124 SPIBoolean
125 cspi_accessible_is_a (Accessible *accessible,
126                       const char *interface_name)
127 {
128   int n;
129
130   if (accessible == NULL)
131     {
132       return FALSE;
133     }
134
135   n = get_iface_num (interface_name);
136   if (n == -1) return FALSE;
137   return (SPIBoolean)((accessible->interfaces & (1 << n))? TRUE: FALSE);
138 }
139
140 static GHashTable *
141 cspi_get_live_refs (void)
142 {
143   if (!live_refs) 
144     {
145       live_refs = g_hash_table_new (g_direct_hash, g_direct_equal);
146     }
147   return live_refs;
148 }
149
150 DBusConnection *
151 SPI_bus (void)
152 {
153   return bus;
154 }
155
156 SPIBoolean
157 cspi_exception (void)
158 {
159   if (dbus_error_is_set (&exception))
160   {
161     dbus_error_free (&exception);
162     return TRUE;
163   }
164   return FALSE;
165 }
166
167 SPIBoolean
168 cspi_check_ev (const char *error_string)
169 {
170   if (dbus_error_is_set (&exception))
171   {
172     cspi_exception_throw (&exception, error_string);
173     return FALSE;
174   }
175   return TRUE;
176 }
177
178 Accessible *
179 cspi_object_add (Accessible *accessible)
180 {
181   if (accessible) cspi_object_ref (accessible);
182   return accessible;
183 }
184
185 void
186 cspi_object_ref (Accessible *accessible)
187 {
188   g_return_if_fail (accessible != NULL);
189
190   accessible->ref_count++;
191   g_hash_table_insert (live_refs, accessible, accessible);
192 }
193
194 #define APP_IS_REGISTRY(app) (!strcmp (app->bus_name, spi_bus_registry))
195
196 static void
197 cspi_object_unref_internal (Accessible *accessible, gboolean defunct)
198 {
199   gboolean cached;
200
201   if (accessible == NULL)
202     {
203       return;
204     }
205
206   if (--accessible->ref_count == 0 || (accessible->ref_count == 1 && !defunct) && g_hash_table_lookup (live_refs, accessible))
207   {
208     AccessibleEvent e;
209     memset (&e, 0, sizeof(e));
210     e.type = "object:state-change:defunct";
211     e.source = accessible;
212     e.detail1 = 1;
213     cspi_dispatch_event (&e);
214     g_hash_table_remove (live_refs, accessible);
215   }
216   if (accessible->ref_count == 0)
217   {
218     if (APP_IS_REGISTRY (accessible->app))
219     {
220       g_free (accessible->v.path);
221     }
222     if (accessible->states)
223       spi_state_set_cache_unref (accessible->states);
224     g_free (accessible->description);
225     g_free (accessible->name);
226     g_free(accessible);
227   }
228 }
229
230 void
231 cspi_object_unref (Accessible *accessible)
232 {
233   cspi_object_unref_internal (accessible, FALSE);
234 }
235
236 static void
237 cspi_cleanup (void)
238 {
239   GHashTable *refs;
240
241   cspi_streams_close_all ();
242
243   refs = live_refs;
244   live_refs = NULL;
245   if (refs)
246     {
247       g_hash_table_destroy (refs);
248     }
249 }
250
251 static gboolean SPI_inited = FALSE;
252
253 static GHashTable *app_hash = NULL;
254
255 static Accessible *
256 ref_accessible (CSpiApplication *app, const char *path)
257 {
258   int id;
259   guint *id_val;
260
261   if (sscanf (path, "/org/a11y/atspi/accessible/%d", &id) != 1)
262   {
263     return NULL;
264   }
265   Accessible *a = g_hash_table_lookup (app->hash, &id);
266   if (a)
267   {
268     cspi_object_ref (a);
269     return a;
270   }
271   id_val = g_new (guint, 1);
272   if (!id_val) return NULL;
273   *id_val = id;
274   a = g_new0 (Accessible, 1);
275   if (!a)
276   {
277     g_free (id_val);
278     return NULL;
279   }
280   g_hash_table_insert (app->hash, id_val, a);
281   a->app = app;
282   a->v.id = id;
283   a->ref_count = 2;     /* one for the caller, one for the hash */
284   return a;
285 }
286
287 static CSpiApplication *
288 cspi_get_application (const char *bus_name)
289 {
290   CSpiApplication *app = NULL;
291   char *bus_name_dup;
292
293   if (!app_hash)
294   {
295     app_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_hash_table_unref);
296     if (!app_hash) return NULL;
297   }
298   app = g_hash_table_lookup (app_hash, bus_name);
299   if (app) return app;
300   bus_name_dup = g_strdup (bus_name);
301   if (!bus_name_dup) return NULL;
302   // TODO: change below to something that will send state-change:defunct notification if necessary */
303   app = g_new (CSpiApplication, 1);
304   if (!app)
305   {
306     g_free (bus_name_dup);
307     return NULL;
308   }
309   app->bus_name = bus_name_dup;
310   if (APP_IS_REGISTRY (app))
311   {
312     app->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, cspi_object_unref);
313   }
314   else
315   {
316     app->hash = g_hash_table_new_full (g_int_hash, g_int_equal, g_free, cspi_object_unref);
317   }
318   g_hash_table_insert (app_hash, bus_name_dup, app);
319   return app;
320 }
321
322 typedef struct
323 {
324   char *path;
325   char *parent;
326   GArray *children;
327   GArray *interfaces;
328   char *name;
329   dbus_uint32_t role;
330   char *description;
331   GArray *state_bitflags;
332 } CACHE_ADDITION;
333
334 static void
335 handle_addition (CSpiApplication*app, CACHE_ADDITION *ca)
336 {
337   gint i;
338   GList *new_list;
339
340   Accessible *a = ref_accessible (app, ca->path);
341   /* Note: children don't hold refs for their parents or vice versa */
342   a->parent = ref_accessible (app, ca->parent);
343   if (a->parent) cspi_object_unref (a->parent);
344   if (a->children)
345   {
346     g_list_free (a->children);
347     a->children = NULL;
348   }
349   for (i = 0; i < ca->children->len; i++)
350   {
351     const char *child_path = g_array_index (ca->children, const char *, i);
352     Accessible *child = ref_accessible (app, child_path);
353     new_list = g_list_append (a->children, child);
354     if (new_list) a->children = new_list;
355     cspi_object_unref (child);
356   }
357   a->interfaces = 0;
358   for (i = 0; i < ca->interfaces->len; i++)
359   {
360     const char *iface = g_array_index (ca->interfaces, const char *, i);
361     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable")) continue;
362     gint n = get_iface_num (iface);
363     if (n == -1)
364     {
365       g_warning ("Unknown interface %s", iface);
366     }
367     else a->interfaces |= (1 << n);
368     g_free (iface);
369   }
370   if (a->name) g_free (a->name);
371   a->name = ca->name;
372   a->role = ca->role;
373   if (a->description) g_free (a->description);
374   a->description = ca->description;
375   a->states = spi_state_set_cache_new (ca->state_bitflags);
376   g_array_free (ca->interfaces, TRUE);
377   g_array_free (ca->children, TRUE);
378   /* spi_state_set_cache_new frees state_bitflags */
379   /* This is a bit of a hack since ref_accessible sets ref_count to 2
380    * for a new object, one of the refs being for the cache */
381   cspi_object_unref (a);
382 }
383
384 /* Update the cache with added/modified objects and free the array */
385 static void
386 handle_additions (CSpiApplication*app, GArray *additions)
387 {
388   gint i;
389
390   if (!additions)
391   {
392     return;
393   }
394   for (i = 0; i < additions->len; i++)
395   {
396     CACHE_ADDITION *ca = &g_array_index (additions, CACHE_ADDITION, i);
397     handle_addition (app, ca);
398   }
399 }
400
401 static DBusHandlerResult
402 cspi_dbus_handle_remove_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
403 {
404   const char *sender = dbus_message_get_sender (message);
405   CSpiApplication *app = cspi_get_application (sender);
406   const char *path;
407   Accessible *a;
408
409   if (!dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &path, DBUS_TYPE_INVALID))
410   {
411     g_warning ("Received RemoveAccessible with invalid arguments");
412     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
413   }
414   a = ref_accessible (app, path);
415   if (a->parent && g_list_find (a->parent->children, a))
416   {
417     a->parent->children = g_list_remove (a->parent->children, a);
418     // TODO: Send children-changed:remove event
419     /* Note: children don't hold refs for their parents or vice versa */
420   }
421   g_hash_table_remove (app->hash, &a->v.id);
422   cspi_object_unref_internal (a, TRUE); /* unref our own ref */
423   return DBUS_HANDLER_RESULT_HANDLED;
424 }
425
426 static gboolean
427 add_app_to_desktop (Accessible *a, const char *bus_name)
428 {
429   DBusError error;
430   char *root_path;
431
432   dbus_error_init (&error);
433   if (dbind_method_call_reentrant (bus, bus_name, "/org/a11y/atspi/tree", spi_interface_tree, "getRoot", &error, "=>o", &root_path))
434   {
435     Accessible *obj = cspi_ref_accessible (bus_name, root_path);
436     if (obj)
437     {
438       GList *new_list = g_list_append (a->children, obj);
439       if (new_list)
440       {
441         a->children = new_list;
442         return TRUE;
443       }
444     }
445     g_free (root_path);
446   }
447   else
448   {
449     g_warning ("Error calling getRoot for %s: %s", bus_name, error.message);
450   }
451   return FALSE;
452 }
453
454 static void
455 send_children_changed (Accessible *parent, Accessible *child, gboolean add)
456 {
457   AccessibleEvent e;
458
459   memset (&e, 0, sizeof(e));
460   e.type = (add? "object:children-changed:add": "object:children-changed:remove");
461   e.source = parent;
462   e.detail1 = g_list_index (parent->children, child);
463   cspi_dispatch_event (&e);
464 }
465
466 static void
467 unref_object_and_children (Accessible *obj)
468 {
469   GList *l;
470
471   for (l = obj->children; l; l = l->next)
472   {
473     unref_object_and_children (l->data);
474   }
475   cspi_object_unref_internal (obj, TRUE);
476 }
477
478 static gboolean
479 remove_app_from_desktop (Accessible *a, const char *bus_name)
480 {
481   GList *l;
482   Accessible *child;
483
484   for (l = a->children; l; l = l->next)
485   {
486     child = l->data;
487     if (!strcmp (bus_name, child->app->bus_name)) break;
488   }
489   if (!l)
490   {
491     g_warning ("Removing unregistered app %s; doing nothing\n", bus_name);
492     return FALSE;
493   }
494   send_children_changed (a, child, FALSE);
495   a->children = g_list_remove (a->children, child);
496   unref_object_and_children (child);
497   return TRUE;
498 }
499
500 static Accessible *desktop;
501
502 static Accessible *
503 ref_accessible_desktop (CSpiApplication *app)
504 {
505   DBusError error;
506   GArray *apps = NULL;
507   GArray *additions;
508   gint i;
509
510   if (desktop)
511   {
512     cspi_object_ref (desktop);
513     return desktop;
514   }
515   desktop = g_new0 (Accessible, 1);
516   if (!desktop)
517   {
518     return NULL;
519   }
520   g_hash_table_insert (app->hash, "", desktop);
521   desktop->app = app;
522   desktop->ref_count = 2;       /* one for the caller, one for the hash */
523   desktop->name = g_strdup ("");
524   dbus_error_init (&error);
525   if (!dbind_method_call_reentrant (bus, spi_bus_registry, spi_path_registry, spi_interface_registry, "getApplications", &error, "=>as", &apps))
526   {
527     g_error ("Couldn't get application list: %s", error.message);
528   }
529   for (i = 0; i < apps->len; i++)
530   {
531     const char *app_name = g_array_index (apps, char *, i);
532     if (app_name[0] == '\0')
533     {
534       g_warning ("Got empty app name");
535       continue;
536     }
537     CSpiApplication *app = cspi_get_application (app_name);
538     additions = NULL;
539     dbus_error_init (&error);
540     dbind_method_call_reentrant (bus, app_name, "/org/a11y/atspi/tree", spi_interface_tree, "getTree", &error, "=>a(ooaoassusau)", &additions);
541     if (error.message)
542     {
543       g_warning ("getTree (%s): %s", app_name, error.message);
544     }
545     handle_additions (app, additions);
546     add_app_to_desktop (desktop, app_name);
547   }
548   g_array_free (apps, TRUE);
549   return desktop;
550 }
551
552 Accessible *
553 cspi_ref_accessible (const char *app, const char *path)
554 {
555   CSpiApplication *a = cspi_get_application (app);
556   if (!a) return NULL;
557   if ( APP_IS_REGISTRY(a))
558   {
559     return ref_accessible_desktop (a);
560   }
561   return ref_accessible (a, path);
562 }
563
564 Accessible *
565 cspi_ref_related_accessible (Accessible *obj, const char *path)
566 {
567   return ref_accessible (obj->app, path);
568 }
569
570 static const char *cacheSignalType = "(ooaoassusau)";
571
572 static DBusHandlerResult
573 cspi_dbus_handle_update_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
574 {
575   DBusMessageIter iter;
576   CACHE_ADDITION ca;
577   void *p = &ca;
578   const char *sender = dbus_message_get_sender (message);
579   CSpiApplication *app = cspi_get_application (sender);
580   const char *type = cacheSignalType;
581
582   if (!app)
583   {
584     g_warning ("UpdateAccessible from unknown app.  Should we add it?", sender);
585     return DBUS_HANDLER_RESULT_HANDLED;
586   }
587   dbus_message_iter_init (message, &iter);
588   // TODO: Check signature
589   dbind_any_demarshal (&iter, &type, &p);       /* additions */
590   handle_addition (app, &ca);
591   return DBUS_HANDLER_RESULT_HANDLED;
592 }
593
594 static DBusHandlerResult
595 cspi_dbus_handle_register_application (DBusConnection *bus, DBusMessage *message, void *user_data)
596 {
597   DBusError error;
598   dbus_uint32_t v;
599   Accessible *a;
600   char *bus_name;
601
602   dbus_error_init (&error);
603   a = cspi_ref_accessible (spi_bus_registry, spi_path_registry);
604   if (add_app_to_desktop (a, dbus_message_get_sender (message)))
605   {
606     send_children_changed (a, g_list_last (a->children)->data, TRUE);
607   }
608   cspi_object_unref (a);
609   return DBUS_HANDLER_RESULT_HANDLED;
610 }
611
612 static DBusHandlerResult
613 cspi_dbus_handle_deregister_application (DBusConnection *bus, DBusMessage *message, void *user_data)
614 {
615   Accessible *a;
616   DBusError error;
617   char *bus_name;
618  
619   dbus_error_init (&error);
620   if (!dbus_message_get_args (message, &error, DBUS_TYPE_STRING, &bus_name, DBUS_TYPE_INVALID))
621   {
622     g_warning ("Error processing %s: %s\n", dbus_message_get_member(message), error.message);
623     dbus_error_free (&error);
624     return DBUS_HANDLER_RESULT_HANDLED;
625   }
626
627   a = cspi_ref_accessible (spi_bus_registry, spi_path_registry);
628   remove_app_from_desktop (a, bus_name);
629   cspi_object_unref (a);
630   return DBUS_HANDLER_RESULT_HANDLED;
631 }
632
633
634 static DBusHandlerResult
635 cspi_dbus_filter (DBusConnection *bus, DBusMessage *message, void *data)
636 {
637   int type = dbus_message_get_type (message);
638   const char *interface = dbus_message_get_interface (message);
639   const char *member = dbus_message_get_member (message); 
640   dbus_uint32_t v;
641   char *bus_name;
642
643   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
644       !strncmp (interface, "org.a11y.atspi.Event.", 28))
645   {
646     return cspi_dbus_handle_event (bus, message, data);
647   }
648   if (dbus_message_is_method_call (message, spi_interface_device_event_listener, "notifyEvent"))
649   {
650     return cspi_dbus_handle_deviceEvent (bus, message, data);
651   }
652   if (dbus_message_is_signal (message, spi_interface_tree, "updateAccessible"))
653   {
654     return cspi_dbus_handle_update_accessible (bus, message, data);
655   }
656   if (dbus_message_is_signal (message, spi_interface_tree, "removeAccessible"))
657   {
658     return cspi_dbus_handle_remove_accessible (bus, message, data);
659   }
660   if (dbus_message_is_method_call (message, spi_interface_registry, "registerApplication"))
661   {
662     return cspi_dbus_handle_register_application (bus, message, data);
663   }
664   if (dbus_message_is_method_call (message, spi_interface_registry, "deregisterApplication"))
665   {
666     return cspi_dbus_handle_deregister_application (bus, message, data);
667   }
668   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
669 }
670
671 static const char *signal_interfaces[] =
672 {
673   "org.a11y.atspi.Event.Object",
674   "org.a11y.atspi.Event.Window",
675   "org.a11y.atspi.Event.Mouse",
676   "org.a11y.atspi.Event.Terminal",
677   "org.a11y.atspi.Event.Document",
678   "org.a11y.atspi.Event.Focus",
679   NULL
680 };
681
682 /**
683  * SPI_init:
684  *
685  * Connects to the accessibility registry and initializes the SPI.
686  *
687  * Returns: 0 on success, otherwise an integer error code.  
688  **/
689 int
690 SPI_init (void)
691 {
692   DBusError error;
693   char *match;
694   int i;
695
696   if (SPI_inited)
697     {
698       return 1;
699     }
700
701   SPI_inited = TRUE;
702
703   g_type_init ();
704
705   cspi_get_live_refs();
706   g_atexit (cspi_cleanup);
707
708   dbus_error_init (&error);
709   bus = dbus_bus_get (DBUS_BUS_SESSION, &error);
710   if (!bus)
711   {
712     g_error ("Couldn't get session bus");
713     return 2;
714   }
715   dbus_bus_register (bus, &error);
716   dbus_connection_setup_with_g_main(bus, g_main_context_default());
717   dbus_connection_add_filter (bus, cspi_dbus_filter, NULL, NULL);
718   match = g_strdup_printf ("type='signal',interface='%s',member='updateAccessible'", spi_interface_tree);
719   dbus_error_init (&error);
720   dbus_bus_add_match (bus, match, &error);
721   g_free (match);
722   match = g_strdup_printf ("type='signal',interface='%s',member='removeAccessible'", spi_interface_tree);
723   dbus_error_init (&error);
724   dbus_bus_add_match (bus, match, &error);
725   g_free (match);
726   match = g_strdup_printf ("type='method_call',interface='%s'", spi_interface_registry);
727   dbus_bus_add_match (bus, match, &error);
728   g_free (match);
729   for (i = 0; signal_interfaces[i]; i++)
730   {
731     match = g_strdup_printf ("type='signal',interface='%s'", signal_interfaces[i]);
732     dbus_bus_add_match (bus, match, &error);
733     g_free (match);
734   }
735   return 0;
736 }
737
738   static GMainLoop *mainloop;
739
740 /**
741  * SPI_event_main:
742  *
743  * Starts/enters the main event loop for the SPI services.
744  *
745  * (NOTE: This method does not return control, it is exited via a call to
746  *  SPI_event_quit () from within an event handler).
747  *
748  **/
749 void
750 SPI_event_main (void)
751 {
752
753   mainloop = g_main_loop_new (NULL, FALSE);
754   g_main_loop_run (mainloop);
755 }
756
757 /**
758  * SPI_event_quit:
759  *
760  * Quits the last main event loop for the SPI services,
761  * see SPI_event_main
762  **/
763 void
764 SPI_event_quit (void)
765 {
766   g_main_loop_quit (mainloop);
767 }
768
769 /**
770  * SPI_eventIsReady:
771  *
772  * Checks to see if an SPI event is waiting in the event queue.
773  * Used by clients that don't wish to use SPI_event_main().
774  *
775  * Not Yet Implemented.
776  *
777  * Returns: #TRUE if an event is waiting, otherwise #FALSE.
778  *
779  **/
780 SPIBoolean
781 SPI_eventIsReady (void)
782 {
783   return FALSE;
784 }
785
786 /**
787  * SPI_nextEvent:
788  * @waitForEvent: a #SPIBoolean indicating whether to block or not.
789  *
790  * Gets the next event in the SPI event queue; blocks if no event
791  * is pending and @waitForEvent is #TRUE.
792  * Used by clients that don't wish to use SPI_event_main().
793  *
794  * Not Yet Implemented.
795  *
796  * Returns: the next #AccessibleEvent in the SPI event queue.
797  **/
798 AccessibleEvent *
799 SPI_nextEvent (SPIBoolean waitForEvent)
800 {
801   return NULL;
802 }
803
804 #ifdef PRINT_LEAKS
805 static void
806 report_leaked_ref (gpointer key, gpointer val, gpointer user_data)
807 {
808   char *name, *role;
809   Accessible *a = (Accessible *) val;
810   
811   name = Accessible_getName (a);
812   if (cspi_exception ())
813     {
814       name = NULL;
815     }
816
817   role = Accessible_getRoleName (a);
818   if (cspi_exception ())
819     {
820       role = NULL;
821     }
822
823   fprintf (stderr, "leaked %d references to object %s, role %s %p\n",
824            a->ref_count, name ? name : "<?>", role ? role : "<?>", a);
825
826   SPI_freeString (name);
827 }
828 #endif
829
830 /**
831  * SPI_exit:
832  *
833  * Disconnects from the Accessibility Registry and releases 
834  * any floating resources. Call only once at exit.
835  *
836  * Returns: 0 if there were no leaks, otherwise non zero.
837  **/
838 int
839 SPI_exit (void)
840 {
841   int leaked;
842
843   if (!SPI_inited)
844     {
845       return 0;
846     }
847
848   SPI_inited = FALSE;
849
850   if (live_refs)
851     {
852       leaked = g_hash_table_size (live_refs);
853 #ifdef DEBUG_OBJECTS
854       fprintf (stderr, "Leaked %d SPI handles\n", leaked);
855
856 #define PRINT_LEAKS
857 #ifdef PRINT_LEAKS
858       g_hash_table_foreach (live_refs, report_leaked_ref, NULL);
859 #endif
860
861 #endif
862     }
863   else
864     {
865       leaked = 0;
866     }
867
868   cspi_cleanup ();
869
870   return leaked;
871 }
872
873 /**
874  * SPI_freeString:
875  * @s: a character string returned from another at-spi call.
876  *
877  * Free a character string returned from an at-spi call.  Clients of
878  * at-spi should use this function instead of free () or g_free().
879  * A NULL string @s will be silently ignored.
880  * This API should not be used to free strings
881  * from other libraries or allocated by the client.
882  **/
883 void
884 SPI_freeString (char *s)
885 {
886   if (s)
887     {
888       g_free (s);
889     }
890 }
891
892 /**
893  * SPI_freeRect:
894  * @r: a pointer to an SPIRect returned from another at-spi call.
895  *
896  * Free a SPIRect structure returned from an at-spi call.  Clients of
897  * at-spi should use this function instead of free () or g_free().
898  * A NULL rect @r will be silently ignored.
899  * This API should not be used to free data
900  * from other libraries or allocated by the client.
901  *
902  * @Since: AT-SPI 1.6
903  **/
904 void
905 SPI_freeRect (SPIRect *r)
906 {
907   if (r)
908     {
909       /* err, okay, in this case the client _could_ 
910          have called g_free, but we don't want to guarantee it */
911       g_free (r);
912     }
913 }
914
915 /**
916  * SPI_dupString:
917  * @s: a UTF-8 string to be duplicated
918  * 
919  * @Since: AT-SPI 1.4
920  *
921  * Returns: a duplicate of the string passed as a parameter, which should
922  * be freed via SPI_freeString after use.
923  **/
924 char *
925 SPI_dupString (char *s)
926 {
927   if (s)
928     {
929       return g_strdup (s);
930     }
931   else 
932     return NULL;
933 }
934
935 /**
936  * SPI_exceptionHandlerPush:
937  * @handler: an #SPIExceptionHandler to install as the first code to deal with exceptions.
938  *
939  * Install a client-side handler for #SPIException instances, which can see and handle any
940  * exceptions before chaining them to the next exception handler in the stack.
941  *
942  * @Since: AT-SPI 1.4
943  *
944  * Returns %TRUE if the result succeeded, %FALSE if @hander could not be registered.
945  **/
946 SPIBoolean SPI_exceptionHandlerPush (SPIExceptionHandler *handler)
947 {
948   if (!exception_handlers)
949     exception_handlers = g_queue_new ();
950   g_queue_push_head (exception_handlers, handler);
951   return TRUE;
952 }
953
954 /**
955  * SPI_exceptionHandlerPop:
956  * 
957  * Remove/pop an #SPIExceptionHandler off the error handler stack and return the new handler.
958  *
959  * @Since: AT-SPI 1.4
960  *
961  * Returns the #SPIExceptionHandler which is now at the top of the error handler stack after the call.
962  **/
963 SPIExceptionHandler* SPI_exceptionHandlerPop (void)
964 {
965   return (SPIExceptionHandler *) g_queue_pop_head (exception_handlers);
966 }
967
968 /**
969  * SPIException_getSourceType:
970  * @err: the exception being queried
971  *
972  * Get the #SPIExceptionType of an exception which has been thrown.
973  *
974  * @Since: AT-SPI 1.4
975  *
976  * Returns: the #SPIExceptionType corresponding to exception @err.
977  **/
978 SPIExceptionType SPIException_getSourceType (SPIException *err)
979 {
980   if (err)
981     return err->type;
982   else
983     return SPI_EXCEPTION_SOURCE_UNSPECIFIED;
984 }
985
986 /**
987  * SPIException_getExceptionCode:
988  * @err: the #SPIException being queried.
989  *
990  * Get the #SPIExceptionCode telling what type of exception condition has occurred.
991  *
992  * @Since: AT-SPI 1.4
993  *
994  * Returns: the #SPIExceptionCode corresponding to exception @err.
995  **/
996 SPIExceptionCode SPIException_getExceptionCode (SPIException *err)
997 {  
998   return err->code;
999 }
1000
1001 /**
1002  * SPIAccessibleException_getSource:
1003  * @err: the #SPIException being queried.
1004  *
1005  * Get the identity of the object which threw an exception.
1006  *
1007  * @Since: AT-SPI 1.4
1008  *
1009  * Returns: a pointer to the #Accessible object which threw the exception.
1010  **/
1011 Accessible* SPIAccessibleException_getSource (SPIException *err)
1012 {
1013   if (err->type == SPI_EXCEPTION_SOURCE_ACCESSIBLE)
1014     cspi_object_ref (err->source);
1015     return err->source;
1016   return NULL;
1017 }
1018
1019 /**
1020  * SPIException_getDescription:
1021  * @err: the #SPIException being queried.
1022  *
1023  * Get a text description of the exception that has been thrown.
1024  * Unfortunately these descriptions tend to be terse and limited in
1025  * the detail which they can provide.
1026  *
1027  * Returns: a brief character string describing the exception.
1028  **/
1029 char* SPIException_getDescription (SPIException *err)
1030 {
1031   /* TODO: friendlier error messages? */
1032   if (err->error)
1033     return err->error->message;
1034   return NULL;
1035 }
1036
1037 static char *
1038 get_path (Accessible *obj)
1039 {
1040   if (APP_IS_REGISTRY (obj->app))
1041   {
1042     return g_strdup_printf (SPI_DBUS_PATH_REGISTRY);
1043   }
1044   return g_strdup_printf ("/org/a11y/atspi/accessible/%d", obj->v.id);
1045 }
1046
1047 dbus_bool_t
1048 cspi_dbus_call (Accessible *obj, const char *interface, const char *method, DBusError *error, const char *type, ...)
1049 {
1050   va_list args;
1051   char *path = get_path (obj);
1052   dbus_bool_t retval;
1053   DBusError err;
1054
1055   if (!error) error = &err;
1056   dbus_error_init (error);
1057   va_start (args, type);
1058   retval = dbind_method_call_reentrant_va (SPI_bus(), obj->app->bus_name, path, interface, method, error, type, args);
1059   va_end (args);
1060   g_free (path);
1061   if (dbus_error_is_set (error))
1062   {
1063     if (!dbus_error_is_set (&exception))
1064     {
1065       // TODO: Should we call cspi_exception_throw?
1066       dbus_move_error (error, &exception);
1067     }
1068     else if (error == &err) dbus_error_free (error);
1069   }
1070   return retval;
1071 }
1072
1073 dbus_bool_t
1074 cspi_dbus_get_property (Accessible *obj, const char *interface, const char *name, DBusError *error, const char *type, void *data)
1075 {
1076   DBusMessage *message, *reply;
1077   char *path = get_path (obj);
1078   DBusMessageIter iter, iter_variant;
1079   DBusError err;
1080   dbus_bool_t retval = FALSE;
1081
1082   message = dbus_message_new_method_call (obj->app->bus_name, path, "org.freedesktop.DBus.Properties", "Get");
1083   if (!message)
1084   {
1085     // TODO: throw exception
1086     goto done;
1087   }
1088   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1089   if (!error) error = &err;
1090   dbus_error_init (error);
1091   reply = dbus_connection_send_with_reply_and_block (SPI_bus(), message, 1000, error);
1092   dbus_message_unref (message);
1093   if (!reply)
1094   {
1095     // TODO: throw exception
1096     goto done;
1097   }
1098   dbus_message_iter_init (reply, &iter);
1099   dbus_message_iter_recurse (&iter, &iter_variant);
1100   if (dbus_message_iter_get_arg_type (&iter_variant) != type[0])
1101   {
1102     g_warning ("cspi_dbus_get_property: Wrong type: expected %s, got %c\n", type, dbus_message_iter_get_arg_type (&iter_variant));
1103     goto done;
1104   }
1105   dbus_message_iter_get_basic (&iter_variant, data);
1106   dbus_message_unref (reply);
1107   if (type[0] == 's') *(char **)data = g_strdup (*(char **)data);
1108   retval = TRUE;
1109 done:
1110   g_free (path);
1111   return retval;
1112 }