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