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