2009-05-14 Mike Gorse <mgorse@novell.com>
[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.freedesktop.atspi.LoginHelper",
104   SPI_DBUS_INTERFACE_SELECTION,
105   "org.freedesktop.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/freedesktop/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) return NULL;
305   app->bus_name = bus_name_dup;
306   if (APP_IS_REGISTRY (app))
307   {
308     app->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, cspi_object_unref);
309   }
310   else
311   {
312     app->hash = g_hash_table_new_full (g_int_hash, g_int_equal, g_free, cspi_object_unref);
313   }
314   g_hash_table_insert (app_hash, bus_name_dup, app);
315   return app;
316 }
317
318 typedef struct
319 {
320   char *path;
321   char *parent;
322   GArray *children;
323   GArray *interfaces;
324   char *name;
325   dbus_uint32_t role;
326   char *description;
327   GArray *state_bitflags;
328 } CACHE_ADDITION;
329
330 static void
331 handle_addition (CSpiApplication*app, CACHE_ADDITION *ca)
332 {
333   gint i;
334   GList *new_list;
335
336   Accessible *a = ref_accessible (app, ca->path);
337   /* Note: children don't hold refs for their parents or vice versa */
338   a->parent = ref_accessible (app, ca->parent);
339   if (a->parent) cspi_object_unref (a->parent);
340   if (a->children)
341   {
342     g_list_free (a->children);
343     a->children = NULL;
344   }
345   for (i = 0; i < ca->children->len; i++)
346   {
347     const char *child_path = g_array_index (ca->children, const char *, i);
348     Accessible *child = ref_accessible (app, child_path);
349     new_list = g_list_append (a->children, child);
350     if (new_list) a->children = new_list;
351     cspi_object_unref (child);
352   }
353   a->interfaces = 0;
354   for (i = 0; i < ca->interfaces->len; i++)
355   {
356     const char *iface = g_array_index (ca->interfaces, const char *, i);
357     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable")) continue;
358     gint n = get_iface_num (iface);
359     if (n == -1)
360     {
361       g_warning ("Unknown interface %s", iface);
362     }
363     else a->interfaces |= (1 << n);
364     g_free (iface);
365   }
366   if (a->name) g_free (a->name);
367   a->name = ca->name;
368   a->role = ca->role;
369   if (a->description) g_free (a->description);
370   a->description = ca->description;
371   a->states = spi_state_set_cache_new (ca->state_bitflags);
372   g_array_free (ca->interfaces, TRUE);
373   g_array_free (ca->children, TRUE);
374   /* spi_state_set_cache_new frees state_bitflags */
375   /* This is a bit of a hack since ref_accessible sets ref_count to 2
376    * for a new object, one of the refs being for the cache */
377   cspi_object_unref (a);
378 }
379
380 /* Update the cache with added/modified objects and free the array */
381 static void
382 handle_additions (CSpiApplication*app, GArray *additions)
383 {
384   gint i;
385
386   if (!additions)
387   {
388     return;
389   }
390   for (i = 0; i < additions->len; i++)
391   {
392     CACHE_ADDITION *ca = &g_array_index (additions, CACHE_ADDITION, i);
393     handle_addition (app, ca);
394   }
395 }
396
397 static DBusHandlerResult
398 cspi_dbus_handle_remove_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
399 {
400   const char *sender = dbus_message_get_sender (message);
401   CSpiApplication *app = cspi_get_application (sender);
402   const char *path;
403   Accessible *a;
404
405   if (!dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &path, DBUS_TYPE_INVALID))
406   {
407     g_warning ("Received RemoveAccessible with invalid arguments");
408     return;
409   }
410   a = ref_accessible (app, path);
411   if (a->parent && g_list_find (a->parent->children, a))
412   {
413     a->parent->children = g_list_remove (a->parent->children, a);
414     // TODO: Send children-changed:remove event
415     /* Note: children don't hold refs for their parents or vice versa */
416   }
417   g_hash_table_remove (app->hash, &a->v.id);
418   cspi_object_unref_internal (a, TRUE); /* unref our own ref */
419 }
420
421 static gboolean
422 add_app_to_desktop (Accessible *a, const char *bus_name)
423 {
424   DBusError error;
425   char *root_path;
426
427   dbus_error_init (&error);
428   if (dbind_method_call_reentrant (bus, bus_name, "/org/freedesktop/atspi/tree", spi_interface_tree, "getRoot", &error, "=>o", &root_path))
429   {
430     Accessible *obj = cspi_ref_accessible (bus_name, root_path);
431     if (obj)
432     {
433       GList *new_list = g_list_append (a->children, obj);
434       if (new_list)
435       {
436         a->children = new_list;
437         return TRUE;
438       }
439     }
440     g_free (root_path);
441   }
442   else
443   {
444     g_warning ("Error calling getRoot for %s: %s", bus_name, error.message);
445   }
446   return FALSE;
447 }
448
449 static void
450 send_children_changed (Accessible *parent, Accessible *child, gboolean add)
451 {
452   AccessibleEvent e;
453
454   memset (&e, 0, sizeof(e));
455   e.type = (add? "object:children-changed:add": "object:children-changed:remove");
456   e.source = parent;
457   e.detail1 = g_list_index (parent->children, child);
458   cspi_dispatch_event (&e);
459 }
460
461 static void
462 unref_object_and_children (Accessible *obj)
463 {
464   GList *l;
465
466   for (l = obj->children; l; l = l->next)
467   {
468     unref_object_and_children (l->data);
469   }
470   cspi_object_unref_internal (obj, TRUE);
471 }
472
473 static gboolean
474 remove_app_from_desktop (Accessible *a, const char *bus_name)
475 {
476   GList *l;
477   Accessible *child;
478
479   for (l = a->children; l; l = l->next)
480   {
481     child = l->data;
482     if (!strcmp (bus_name, child->app->bus_name)) break;
483   }
484   if (!l)
485   {
486     g_warning ("Removing unregistered app %s; doing nothing\n", bus_name);
487     return FALSE;
488   }
489   send_children_changed (a, child, FALSE);
490   a->children = g_list_remove (a->children, child);
491   unref_object_and_children (child);
492   return TRUE;
493 }
494
495 static Accessible *desktop;
496
497 static Accessible *
498 ref_accessible_desktop (CSpiApplication *app)
499 {
500   DBusError error;
501   GArray *apps = NULL;
502   GArray *additions;
503   gint i;
504
505   if (desktop)
506   {
507     cspi_object_ref (desktop);
508     return desktop;
509   }
510   desktop = g_new0 (Accessible, 1);
511   if (!desktop)
512   {
513     return NULL;
514   }
515   g_hash_table_insert (app->hash, "", desktop);
516   desktop->app = app;
517   desktop->ref_count = 2;       /* one for the caller, one for the hash */
518   desktop->name = g_strdup ("");
519   dbus_error_init (&error);
520   if (!dbind_method_call_reentrant (bus, spi_bus_registry, spi_path_registry, spi_interface_registry, "getApplications", &error, "=>as", &apps))
521   {
522     g_error ("Couldn't get application list: %s", error.message);
523   }
524   for (i = 0; i < apps->len; i++)
525   {
526     const char *app_name = g_array_index (apps, char *, i);
527     if (app_name[0] == '\0')
528     {
529       g_warning ("Got empty app name");
530       continue;
531     }
532     CSpiApplication *app = cspi_get_application (app_name);
533     additions = NULL;
534     dbus_error_init (&error);
535     dbind_method_call_reentrant (bus, app_name, "/org/freedesktop/atspi/tree", spi_interface_tree, "getTree", &error, "=>a(ooaoassusau)", &additions);
536     if (error.message)
537     {
538       g_warning ("getTree (%s): %s", app_name, error.message);
539     }
540     handle_additions (app, additions);
541     add_app_to_desktop (desktop, app_name);
542   }
543   g_array_free (apps, TRUE);
544   return desktop;
545 }
546
547 Accessible *
548 cspi_ref_accessible (const char *app, const char *path)
549 {
550   CSpiApplication *a = cspi_get_application (app);
551   if (!a) return NULL;
552   if ( APP_IS_REGISTRY(a))
553   {
554     return ref_accessible_desktop (a);
555   }
556   return ref_accessible (a, path);
557 }
558
559 Accessible *
560 cspi_ref_related_accessible (Accessible *obj, const char *path)
561 {
562   return ref_accessible (obj->app, path);
563 }
564
565 static const char *cacheSignalType = "(ooaoassusau)";
566
567 static DBusHandlerResult
568 cspi_dbus_handle_update_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
569 {
570   DBusMessageIter iter;
571   CACHE_ADDITION ca;
572   void *p = &ca;
573   const char *sender = dbus_message_get_sender (message);
574   CSpiApplication *app = cspi_get_application (sender);
575   const char *type = cacheSignalType;
576
577   if (!app)
578   {
579     g_warning ("UpdateAccessible from unknown app.  Should we add it?", sender);
580     return DBUS_HANDLER_RESULT_HANDLED;
581   }
582   dbus_message_iter_init (message, &iter);
583   // TODO: Check signature
584   dbind_any_demarshal (&iter, &type, &p);       /* additions */
585   handle_addition (app, &ca);
586 }
587
588 static DBusHandlerResult
589 cspi_dbus_handle_register_application (DBusConnection *bus, DBusMessage *message, void *user_data)
590 {
591   DBusError error;
592   dbus_uint32_t v;
593   Accessible *a;
594   char *bus_name;
595
596   dbus_error_init (&error);
597   a = cspi_ref_accessible (spi_bus_registry, spi_path_registry);
598   if (add_app_to_desktop (a, dbus_message_get_sender (message)))
599   {
600     send_children_changed (a, g_list_last (a->children)->data, TRUE);
601   }
602   cspi_object_unref (a);
603   return DBUS_HANDLER_RESULT_HANDLED;
604 }
605
606 static DBusHandlerResult
607 cspi_dbus_handle_deregister_application (DBusConnection *bus, DBusMessage *message, void *user_data)
608 {
609   Accessible *a;
610   DBusError error;
611   char *bus_name;
612  
613   dbus_error_init (&error);
614   if (!dbus_message_get_args (message, &error, DBUS_TYPE_STRING, &bus_name, DBUS_TYPE_INVALID))
615   {
616     g_warning ("Error processing %s: %s\n", dbus_message_get_member(message), error.message);
617     dbus_error_free (&error);
618     return DBUS_HANDLER_RESULT_HANDLED;
619   }
620
621   a = cspi_ref_accessible (spi_bus_registry, spi_path_registry);
622   remove_app_from_desktop (a, bus_name);
623   cspi_object_unref (a);
624   return DBUS_HANDLER_RESULT_HANDLED;
625 }
626
627
628 static DBusHandlerResult
629 cspi_dbus_filter (DBusConnection *bus, DBusMessage *message, void *data)
630 {
631   int type = dbus_message_get_type (message);
632   const char *interface = dbus_message_get_interface (message);
633   const char *member = dbus_message_get_member (message); 
634   dbus_uint32_t v;
635   char *bus_name;
636
637   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
638       !strncmp (interface, "org.freedesktop.atspi.Event.", 28))
639   {
640     return cspi_dbus_handle_event (bus, message, data);
641   }
642   if (dbus_message_is_method_call (message, spi_interface_device_event_listener, "notifyEvent"))
643   {
644     return cspi_dbus_handle_deviceEvent (bus, message, data);
645   }
646   if (dbus_message_is_signal (message, spi_interface_tree, "updateAccessible"))
647   {
648     return cspi_dbus_handle_update_accessible (bus, message, data);
649   }
650   if (dbus_message_is_signal (message, spi_interface_tree, "removeAccessible"))
651   {
652     return cspi_dbus_handle_remove_accessible (bus, message, data);
653   }
654   if (dbus_message_is_method_call (message, spi_interface_registry, "registerApplication"))
655   {
656     return cspi_dbus_handle_register_application (bus, message, data);
657   }
658   if (dbus_message_is_method_call (message, spi_interface_registry, "deregisterApplication"))
659   {
660     return cspi_dbus_handle_deregister_application (bus, message, data);
661   }
662   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
663 }
664
665 static const char *signal_interfaces[] =
666 {
667   "org.freedesktop.atspi.Event.Object",
668   "org.freedesktop.atspi.Event.Window",
669   "org.freedesktop.atspi.Event.Mouse",
670   "org.freedesktop.atspi.Event.Terminal",
671   "org.freedesktop.atspi.Event.Document",
672   "org.freedesktop.atspi.Event.Focus",
673   NULL
674 };
675
676 /**
677  * SPI_init:
678  *
679  * Connects to the accessibility registry and initializes the SPI.
680  *
681  * Returns: 0 on success, otherwise an integer error code.  
682  **/
683 int
684 SPI_init (void)
685 {
686   DBusError error;
687   char *match;
688   int i;
689
690   if (SPI_inited)
691     {
692       return 1;
693     }
694
695   SPI_inited = TRUE;
696
697   g_type_init ();
698
699   cspi_get_live_refs();
700   g_atexit (cspi_cleanup);
701
702   dbus_error_init (&error);
703   bus = dbus_bus_get (DBUS_BUS_SESSION, &error);
704   if (!bus)
705   {
706     g_error ("Couldn't get session bus");
707     return 2;
708   }
709   dbus_bus_register (bus, &error);
710   dbus_connection_setup_with_g_main(bus, g_main_context_default());
711   dbus_connection_add_filter (bus, cspi_dbus_filter, NULL, NULL);
712   match = g_strdup_printf ("type='signal',interface='%s',member='updateAccessible'", spi_interface_tree);
713   dbus_error_init (&error);
714   dbus_bus_add_match (bus, match, &error);
715   g_free (match);
716   match = g_strdup_printf ("type='signal',interface='%s',member='removeAccessible'", spi_interface_tree);
717   dbus_error_init (&error);
718   dbus_bus_add_match (bus, match, &error);
719   g_free (match);
720   match = g_strdup_printf ("type='method_call',interface='%s'", spi_interface_registry);
721   dbus_bus_add_match (bus, match, &error);
722   g_free (match);
723   for (i = 0; signal_interfaces[i]; i++)
724   {
725     match = g_strdup_printf ("type='signal',interface='%s'", signal_interfaces[i]);
726     dbus_bus_add_match (bus, match, &error);
727     g_free (match);
728   }
729   return 0;
730 }
731
732   static GMainLoop *mainloop;
733
734 /**
735  * SPI_event_main:
736  *
737  * Starts/enters the main event loop for the SPI services.
738  *
739  * (NOTE: This method does not return control, it is exited via a call to
740  *  SPI_event_quit () from within an event handler).
741  *
742  **/
743 void
744 SPI_event_main (void)
745 {
746
747   mainloop = g_main_loop_new (NULL, FALSE);
748   g_main_loop_run (mainloop);
749 }
750
751 /**
752  * SPI_event_quit:
753  *
754  * Quits the last main event loop for the SPI services,
755  * see SPI_event_main
756  **/
757 void
758 SPI_event_quit (void)
759 {
760   g_main_loop_quit (mainloop);
761 }
762
763 /**
764  * SPI_eventIsReady:
765  *
766  * Checks to see if an SPI event is waiting in the event queue.
767  * Used by clients that don't wish to use SPI_event_main().
768  *
769  * Not Yet Implemented.
770  *
771  * Returns: #TRUE if an event is waiting, otherwise #FALSE.
772  *
773  **/
774 SPIBoolean
775 SPI_eventIsReady (void)
776 {
777   return FALSE;
778 }
779
780 /**
781  * SPI_nextEvent:
782  * @waitForEvent: a #SPIBoolean indicating whether to block or not.
783  *
784  * Gets the next event in the SPI event queue; blocks if no event
785  * is pending and @waitForEvent is #TRUE.
786  * Used by clients that don't wish to use SPI_event_main().
787  *
788  * Not Yet Implemented.
789  *
790  * Returns: the next #AccessibleEvent in the SPI event queue.
791  **/
792 AccessibleEvent *
793 SPI_nextEvent (SPIBoolean waitForEvent)
794 {
795   return NULL;
796 }
797
798 #ifdef PRINT_LEAKS
799 static void
800 report_leaked_ref (gpointer key, gpointer val, gpointer user_data)
801 {
802   char *name, *role;
803   Accessible *a = (Accessible *) val;
804   
805   name = Accessible_getName (a);
806   if (cspi_exception ())
807     {
808       name = NULL;
809     }
810
811   role = Accessible_getRoleName (a);
812   if (cspi_exception ())
813     {
814       role = NULL;
815     }
816
817   fprintf (stderr, "leaked %d references to object %s, role %s %p\n",
818            a->ref_count, name ? name : "<?>", role ? role : "<?>", a);
819
820   SPI_freeString (name);
821 }
822 #endif
823
824 /**
825  * SPI_exit:
826  *
827  * Disconnects from the Accessibility Registry and releases 
828  * any floating resources. Call only once at exit.
829  *
830  * Returns: 0 if there were no leaks, otherwise non zero.
831  **/
832 int
833 SPI_exit (void)
834 {
835   int leaked;
836
837   if (!SPI_inited)
838     {
839       return 0;
840     }
841
842   SPI_inited = FALSE;
843
844   if (live_refs)
845     {
846       leaked = g_hash_table_size (live_refs);
847 #ifdef DEBUG_OBJECTS
848       fprintf (stderr, "Leaked %d SPI handles\n", leaked);
849
850 #define PRINT_LEAKS
851 #ifdef PRINT_LEAKS
852       g_hash_table_foreach (live_refs, report_leaked_ref, NULL);
853 #endif
854
855 #endif
856     }
857   else
858     {
859       leaked = 0;
860     }
861
862   cspi_cleanup ();
863
864   return leaked;
865 }
866
867 /**
868  * SPI_freeString:
869  * @s: a character string returned from another at-spi call.
870  *
871  * Free a character string returned from an at-spi call.  Clients of
872  * at-spi should use this function instead of free () or g_free().
873  * A NULL string @s will be silently ignored.
874  * This API should not be used to free strings
875  * from other libraries or allocated by the client.
876  **/
877 void
878 SPI_freeString (char *s)
879 {
880   if (s)
881     {
882       g_free (s);
883     }
884 }
885
886 /**
887  * SPI_freeRect:
888  * @r: a pointer to an SPIRect returned from another at-spi call.
889  *
890  * Free a SPIRect structure returned from an at-spi call.  Clients of
891  * at-spi should use this function instead of free () or g_free().
892  * A NULL rect @r will be silently ignored.
893  * This API should not be used to free data
894  * from other libraries or allocated by the client.
895  *
896  * @Since: AT-SPI 1.6
897  **/
898 void
899 SPI_freeRect (SPIRect *r)
900 {
901   if (r)
902     {
903       /* err, okay, in this case the client _could_ 
904          have called g_free, but we don't want to guarantee it */
905       g_free (r);
906     }
907 }
908
909 /**
910  * SPI_dupString:
911  * @s: a UTF-8 string to be duplicated
912  * 
913  * @Since: AT-SPI 1.4
914  *
915  * Returns: a duplicate of the string passed as a parameter, which should
916  * be freed via SPI_freeString after use.
917  **/
918 char *
919 SPI_dupString (char *s)
920 {
921   if (s)
922     {
923       return g_strdup (s);
924     }
925   else 
926     return NULL;
927 }
928
929 /**
930  * SPI_exceptionHandlerPush:
931  * @handler: an #SPIExceptionHandler to install as the first code to deal with exceptions.
932  *
933  * Install a client-side handler for #SPIException instances, which can see and handle any
934  * exceptions before chaining them to the next exception handler in the stack.
935  *
936  * @Since: AT-SPI 1.4
937  *
938  * Returns %TRUE if the result succeeded, %FALSE if @hander could not be registered.
939  **/
940 SPIBoolean SPI_exceptionHandlerPush (SPIExceptionHandler *handler)
941 {
942   if (!exception_handlers)
943     exception_handlers = g_queue_new ();
944   g_queue_push_head (exception_handlers, handler);
945   return TRUE;
946 }
947
948 /**
949  * SPI_exceptionHandlerPop:
950  * 
951  * Remove/pop an #SPIExceptionHandler off the error handler stack and return the new handler.
952  *
953  * @Since: AT-SPI 1.4
954  *
955  * Returns the #SPIExceptionHandler which is now at the top of the error handler stack after the call.
956  **/
957 SPIExceptionHandler* SPI_exceptionHandlerPop (void)
958 {
959   return (SPIExceptionHandler *) g_queue_pop_head (exception_handlers);
960 }
961
962 /**
963  * SPIException_getSourceType:
964  * @err: the exception being queried
965  *
966  * Get the #SPIExceptionType of an exception which has been thrown.
967  *
968  * @Since: AT-SPI 1.4
969  *
970  * Returns: the #SPIExceptionType corresponding to exception @err.
971  **/
972 SPIExceptionType SPIException_getSourceType (SPIException *err)
973 {
974   if (err)
975     return err->type;
976   else
977     return SPI_EXCEPTION_SOURCE_UNSPECIFIED;
978 }
979
980 /**
981  * SPIException_getExceptionCode:
982  * @err: the #SPIException being queried.
983  *
984  * Get the #SPIExceptionCode telling what type of exception condition has occurred.
985  *
986  * @Since: AT-SPI 1.4
987  *
988  * Returns: the #SPIExceptionCode corresponding to exception @err.
989  **/
990 SPIExceptionCode SPIException_getExceptionCode (SPIException *err)
991 {  
992   return err->code;
993 }
994
995 /**
996  * SPIAccessibleException_getSource:
997  * @err: the #SPIException being queried.
998  *
999  * Get the identity of the object which threw an exception.
1000  *
1001  * @Since: AT-SPI 1.4
1002  *
1003  * Returns: a pointer to the #Accessible object which threw the exception.
1004  **/
1005 Accessible* SPIAccessibleException_getSource (SPIException *err)
1006 {
1007   if (err->type == SPI_EXCEPTION_SOURCE_ACCESSIBLE)
1008     cspi_object_ref (err->source);
1009     return err->source;
1010   return NULL;
1011 }
1012
1013 /**
1014  * SPIException_getDescription:
1015  * @err: the #SPIException being queried.
1016  *
1017  * Get a text description of the exception that has been thrown.
1018  * Unfortunately these descriptions tend to be terse and limited in
1019  * the detail which they can provide.
1020  *
1021  * Returns: a brief character string describing the exception.
1022  **/
1023 char* SPIException_getDescription (SPIException *err)
1024 {
1025   /* TODO: friendlier error messages? */
1026   if (err->error)
1027     return err->error->message;
1028   return NULL;
1029 }
1030
1031 static char *
1032 get_path (Accessible *obj)
1033 {
1034   if (APP_IS_REGISTRY (obj->app))
1035   {
1036     return g_strdup_printf (SPI_DBUS_PATH_REGISTRY);
1037   }
1038   return g_strdup_printf ("/org/freedesktop/atspi/accessible/%d", obj->v.id);
1039 }
1040
1041 dbus_bool_t
1042 cspi_dbus_call (Accessible *obj, const char *interface, const char *method, DBusError *error, const char *type, ...)
1043 {
1044   va_list args;
1045   char *path = get_path (obj);
1046   dbus_bool_t retval;
1047   DBusError err;
1048
1049   if (!error) error = &err;
1050   dbus_error_init (error);
1051   va_start (args, type);
1052   retval = dbind_method_call_reentrant_va (SPI_bus(), obj->app->bus_name, path, interface, method, error, type, args);
1053   va_end (args);
1054   g_free (path);
1055   if (dbus_error_is_set (error))
1056   {
1057     if (!dbus_error_is_set (&exception))
1058     {
1059       // TODO: Should we call cspi_exception_throw?
1060       dbus_move_error (error, &exception);
1061     }
1062     else if (error == &err) dbus_error_free (error);
1063   }
1064   return retval;
1065 }
1066
1067 dbus_bool_t
1068 cspi_dbus_get_property (Accessible *obj, const char *interface, const char *name, DBusError *error, const char *type, void *data)
1069 {
1070   DBusMessage *message, *reply;
1071   char *path = get_path (obj);
1072   DBusMessageIter iter, iter_variant;
1073   DBusError err;
1074   dbus_bool_t retval = FALSE;
1075
1076   message = dbus_message_new_method_call (obj->app->bus_name, path, "org.freedesktop.DBus.Properties", "Get");
1077   if (!message)
1078   {
1079     // TODO: throw exception
1080     goto done;
1081   }
1082   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1083   if (!error) error = &err;
1084   dbus_error_init (error);
1085   reply = dbus_connection_send_with_reply_and_block (SPI_bus(), message, 1000, error);
1086   dbus_message_unref (message);
1087   if (!reply)
1088   {
1089     // TODO: throw exception
1090     goto done;
1091   }
1092   dbus_message_iter_init (reply, &iter);
1093   dbus_message_iter_recurse (&iter, &iter_variant);
1094   if (dbus_message_iter_get_arg_type (&iter_variant) != type[0])
1095   {
1096     g_warning ("cspi_dbus_get_property: Wrong type: expected %s, got %c\n", type, dbus_message_iter_get_arg_type (&iter_variant));
1097     goto done;
1098   }
1099   dbus_message_iter_get_basic (&iter_variant, data);
1100   dbus_message_unref (reply);
1101   if (type[0] == 's') *(char **)data = g_strdup (*(char **)data);
1102   retval = TRUE;
1103 done:
1104   g_free (path);
1105   return retval;
1106 }