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