Merge branch 'master' of ssh://git.codethink.co.uk/git/atspi-dbus
[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     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   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
659 }
660
661 /**
662  * SPI_init:
663  *
664  * Connects to the accessibility registry and initializes the SPI.
665  *
666  * Returns: 0 on success, otherwise an integer error code.  
667  **/
668 int
669 SPI_init (void)
670 {
671   DBusError error;
672   char *match;
673
674   if (SPI_inited)
675     {
676       return 1;
677     }
678
679   SPI_inited = TRUE;
680
681   g_type_init ();
682
683   cspi_get_live_refs();
684   g_atexit (cspi_cleanup);
685
686   dbus_error_init (&error);
687   bus = dbus_bus_get (DBUS_BUS_SESSION, &error);
688   if (!bus)
689   {
690     g_error ("Couldn't get session bus");
691     return 2;
692   }
693   dbus_bus_register (bus, &error);
694   dbus_connection_setup_with_g_main(bus, g_main_context_default());
695   dbus_connection_add_filter (bus, cspi_dbus_filter, NULL, NULL);
696   match = g_strdup_printf ("type='signal',interface='%s',member='updateTree'", spi_interface_tree);
697   dbus_error_init (&error);
698   dbus_bus_add_match (bus, match, &error);
699   g_free (match);
700   match = g_strdup_printf ("type='signal',sender='%s'", spi_bus_registry);
701   dbus_bus_add_match (bus, match, &error);
702   g_free (match);
703   return 0;
704 }
705
706   static GMainLoop *mainloop;
707
708 /**
709  * SPI_event_main:
710  *
711  * Starts/enters the main event loop for the SPI services.
712  *
713  * (NOTE: This method does not return control, it is exited via a call to
714  *  SPI_event_quit () from within an event handler).
715  *
716  **/
717 void
718 SPI_event_main (void)
719 {
720
721   mainloop = g_main_loop_new (NULL, FALSE);
722   g_main_loop_run (mainloop);
723 }
724
725 /**
726  * SPI_event_quit:
727  *
728  * Quits the last main event loop for the SPI services,
729  * see SPI_event_main
730  **/
731 void
732 SPI_event_quit (void)
733 {
734   g_main_loop_quit (mainloop);
735 }
736
737 /**
738  * SPI_eventIsReady:
739  *
740  * Checks to see if an SPI event is waiting in the event queue.
741  * Used by clients that don't wish to use SPI_event_main().
742  *
743  * Not Yet Implemented.
744  *
745  * Returns: #TRUE if an event is waiting, otherwise #FALSE.
746  *
747  **/
748 SPIBoolean
749 SPI_eventIsReady (void)
750 {
751   return FALSE;
752 }
753
754 /**
755  * SPI_nextEvent:
756  * @waitForEvent: a #SPIBoolean indicating whether to block or not.
757  *
758  * Gets the next event in the SPI event queue; blocks if no event
759  * is pending and @waitForEvent is #TRUE.
760  * Used by clients that don't wish to use SPI_event_main().
761  *
762  * Not Yet Implemented.
763  *
764  * Returns: the next #AccessibleEvent in the SPI event queue.
765  **/
766 AccessibleEvent *
767 SPI_nextEvent (SPIBoolean waitForEvent)
768 {
769   return NULL;
770 }
771
772 #ifdef PRINT_LEAKS
773 static void
774 report_leaked_ref (gpointer key, gpointer val, gpointer user_data)
775 {
776   char *name, *role;
777   Accessible *a = (Accessible *) val;
778   
779   name = Accessible_getName (a);
780   if (cspi_exception ())
781     {
782       name = NULL;
783     }
784
785   role = Accessible_getRoleName (a);
786   if (cspi_exception ())
787     {
788       role = NULL;
789     }
790
791   fprintf (stderr, "leaked %d references to object %s, role %s %p\n",
792            a->ref_count, name ? name : "<?>", role ? role : "<?>", a);
793
794   SPI_freeString (name);
795 }
796 #endif
797
798 /**
799  * SPI_exit:
800  *
801  * Disconnects from the Accessibility Registry and releases 
802  * any floating resources. Call only once at exit.
803  *
804  * Returns: 0 if there were no leaks, otherwise non zero.
805  **/
806 int
807 SPI_exit (void)
808 {
809   int leaked;
810
811   if (!SPI_inited)
812     {
813       return 0;
814     }
815
816   SPI_inited = FALSE;
817
818   if (live_refs)
819     {
820       leaked = g_hash_table_size (live_refs);
821 #ifdef DEBUG_OBJECTS
822       fprintf (stderr, "Leaked %d SPI handles\n", leaked);
823
824 #define PRINT_LEAKS
825 #ifdef PRINT_LEAKS
826       g_hash_table_foreach (live_refs, report_leaked_ref, NULL);
827 #endif
828
829 #endif
830     }
831   else
832     {
833       leaked = 0;
834     }
835
836   cspi_cleanup ();
837
838   return leaked;
839 }
840
841 /**
842  * SPI_freeString:
843  * @s: a character string returned from another at-spi call.
844  *
845  * Free a character string returned from an at-spi call.  Clients of
846  * at-spi should use this function instead of free () or g_free().
847  * A NULL string @s will be silently ignored.
848  * This API should not be used to free strings
849  * from other libraries or allocated by the client.
850  **/
851 void
852 SPI_freeString (char *s)
853 {
854   if (s)
855     {
856       g_free (s);
857     }
858 }
859
860 /**
861  * SPI_freeRect:
862  * @r: a pointer to an SPIRect returned from another at-spi call.
863  *
864  * Free a SPIRect structure returned from an at-spi call.  Clients of
865  * at-spi should use this function instead of free () or g_free().
866  * A NULL rect @r will be silently ignored.
867  * This API should not be used to free data
868  * from other libraries or allocated by the client.
869  *
870  * @Since: AT-SPI 1.6
871  **/
872 void
873 SPI_freeRect (SPIRect *r)
874 {
875   if (r)
876     {
877       /* err, okay, in this case the client _could_ 
878          have called g_free, but we don't want to guarantee it */
879       g_free (r);
880     }
881 }
882
883 /**
884  * SPI_dupString:
885  * @s: a UTF-8 string to be duplicated
886  * 
887  * @Since: AT-SPI 1.4
888  *
889  * Returns: a duplicate of the string passed as a parameter, which should
890  * be freed via SPI_freeString after use.
891  **/
892 char *
893 SPI_dupString (char *s)
894 {
895   if (s)
896     {
897       return g_strdup (s);
898     }
899   else 
900     return NULL;
901 }
902
903 /**
904  * SPI_exceptionHandlerPush:
905  * @handler: an #SPIExceptionHandler to install as the first code to deal with exceptions.
906  *
907  * Install a client-side handler for #SPIException instances, which can see and handle any
908  * exceptions before chaining them to the next exception handler in the stack.
909  *
910  * @Since: AT-SPI 1.4
911  *
912  * Returns %TRUE if the result succeeded, %FALSE if @hander could not be registered.
913  **/
914 SPIBoolean SPI_exceptionHandlerPush (SPIExceptionHandler *handler)
915 {
916   if (!exception_handlers)
917     exception_handlers = g_queue_new ();
918   g_queue_push_head (exception_handlers, handler);
919   return TRUE;
920 }
921
922 /**
923  * SPI_exceptionHandlerPop:
924  * 
925  * Remove/pop an #SPIExceptionHandler off the error handler stack and return the new handler.
926  *
927  * @Since: AT-SPI 1.4
928  *
929  * Returns the #SPIExceptionHandler which is now at the top of the error handler stack after the call.
930  **/
931 SPIExceptionHandler* SPI_exceptionHandlerPop (void)
932 {
933   return (SPIExceptionHandler *) g_queue_pop_head (exception_handlers);
934 }
935
936 /**
937  * SPIException_getSourceType:
938  * @err: the exception being queried
939  *
940  * Get the #SPIExceptionType of an exception which has been thrown.
941  *
942  * @Since: AT-SPI 1.4
943  *
944  * Returns: the #SPIExceptionType corresponding to exception @err.
945  **/
946 SPIExceptionType SPIException_getSourceType (SPIException *err)
947 {
948   if (err)
949     return err->type;
950   else
951     return SPI_EXCEPTION_SOURCE_UNSPECIFIED;
952 }
953
954 /**
955  * SPIException_getExceptionCode:
956  * @err: the #SPIException being queried.
957  *
958  * Get the #SPIExceptionCode telling what type of exception condition has occurred.
959  *
960  * @Since: AT-SPI 1.4
961  *
962  * Returns: the #SPIExceptionCode corresponding to exception @err.
963  **/
964 SPIExceptionCode SPIException_getExceptionCode (SPIException *err)
965 {  
966   return err->code;
967 }
968
969 /**
970  * SPIAccessibleException_getSource:
971  * @err: the #SPIException being queried.
972  *
973  * Get the identity of the object which threw an exception.
974  *
975  * @Since: AT-SPI 1.4
976  *
977  * Returns: a pointer to the #Accessible object which threw the exception.
978  **/
979 Accessible* SPIAccessibleException_getSource (SPIException *err)
980 {
981   if (err->type == SPI_EXCEPTION_SOURCE_ACCESSIBLE)
982     cspi_object_ref (err->source);
983     return err->source;
984   return NULL;
985 }
986
987 /**
988  * SPIException_getDescription:
989  * @err: the #SPIException being queried.
990  *
991  * Get a text description of the exception that has been thrown.
992  * Unfortunately these descriptions tend to be terse and limited in
993  * the detail which they can provide.
994  *
995  * Returns: a brief character string describing the exception.
996  **/
997 char* SPIException_getDescription (SPIException *err)
998 {
999   /* TODO: friendlier error messages? */
1000   if (err->error)
1001     return err->error->message;
1002   return NULL;
1003 }
1004
1005 static char *
1006 get_path (Accessible *obj)
1007 {
1008   if (APP_IS_REGISTRY (obj->app))
1009   {
1010     return g_strdup_printf (SPI_DBUS_PATH_DESKTOP);
1011   }
1012   return g_strdup_printf ("/org/freedesktop/atspi/accessible/%d", obj->v.id);
1013 }
1014
1015 dbus_bool_t
1016 cspi_dbus_call (Accessible *obj, const char *interface, const char *method, DBusError *error, const char *type, ...)
1017 {
1018   va_list args;
1019   char *path = get_path (obj);
1020   dbus_bool_t retval;
1021   DBusError err;
1022
1023   if (!error) error = &err;
1024   dbus_error_init (error);
1025   va_start (args, type);
1026   retval = dbind_connection_method_call_va (SPI_bus(), obj->app->bus_name, path, interface, method, error, type, args);
1027   va_end (args);
1028   g_free (path);
1029   if (dbus_error_is_set (error))
1030   {
1031     if (!dbus_error_is_set (&exception))
1032     {
1033       // TODO: Should we call cspi_exception_throw?
1034       dbus_move_error (error, &exception);
1035     }
1036     else if (error == &err) dbus_error_free (error);
1037   }
1038   return retval;
1039 }
1040
1041 dbus_bool_t
1042 cspi_dbus_get_property (Accessible *obj, const char *interface, const char *name, DBusError *error, const char *type, void *data)
1043 {
1044   DBusMessage *message, *reply;
1045   char *path = get_path (obj);
1046   DBusMessageIter iter, iter_variant;
1047   DBusError err;
1048   dbus_bool_t retval = FALSE;
1049
1050   message = dbus_message_new_method_call (obj->app->bus_name, path, "org.freedesktop.DBus.Properties", "Get");
1051   if (!message)
1052   {
1053     // TODO: throw exception
1054     goto done;
1055   }
1056   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1057   if (!error) error = &err;
1058   dbus_error_init (error);
1059   reply = dbus_connection_send_with_reply_and_block (SPI_bus(), message, 1000, error);
1060   dbus_message_unref (message);
1061   if (!reply)
1062   {
1063     // TODO: throw exception
1064     goto done;
1065   }
1066   dbus_message_iter_init (reply, &iter);
1067   dbus_message_iter_recurse (&iter, &iter_variant);
1068   if (dbus_message_iter_get_arg_type (&iter_variant) != type[0])
1069   {
1070     g_warning ("cspi_dbus_get_property: Wrong type: expected %s, got %c\n", type, dbus_message_iter_get_arg_type (&iter_variant));
1071     goto done;
1072   }
1073   dbus_message_iter_get_basic (&iter_variant, data);
1074   dbus_message_unref (reply);
1075   if (type[0] == 's') *(char **)data = g_strdup (*(char **)data);
1076   retval = TRUE;
1077 done:
1078   g_free (path);
1079   return retval;
1080 }