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