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