Fix a critical when processing deferred messages
[platform/upstream/at-spi2-core.git] / atspi / atspi-misc.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  * Copyright 2010, 2011 Novell, Inc.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 /*
26  *
27  * Basic SPI initialization and event loop function prototypes
28  *
29  */
30
31 #include "atspi-private.h"
32 #ifdef HAVE_X11
33 #include "X11/Xlib.h"
34 #endif
35 #include "atspi-gmain.h"
36 #include <stdio.h>
37 #include <string.h>
38
39 static void handle_get_items (DBusPendingCall *pending, void *user_data);
40
41 static DBusConnection *bus = NULL;
42 static GHashTable *live_refs = NULL;
43 static gint method_call_timeout = 800;
44 static gint app_startup_time = 15000;
45 static gboolean allow_sync = TRUE;
46
47 GMainLoop *atspi_main_loop;
48 GMainContext *atspi_main_context;
49 gboolean atspi_no_cache;
50
51 const char *atspi_path_dec = ATSPI_DBUS_PATH_DEC;
52 const char *atspi_path_registry = ATSPI_DBUS_PATH_REGISTRY;
53 const char *atspi_path_root = ATSPI_DBUS_PATH_ROOT;
54 const char *atspi_bus_registry = ATSPI_DBUS_NAME_REGISTRY;
55 const char *atspi_interface_accessible = ATSPI_DBUS_INTERFACE_ACCESSIBLE;
56 const char *atspi_interface_action = ATSPI_DBUS_INTERFACE_ACTION;
57 const char *atspi_interface_application = ATSPI_DBUS_INTERFACE_APPLICATION;
58 const char *atspi_interface_collection = ATSPI_DBUS_INTERFACE_COLLECTION;
59 const char *atspi_interface_component = ATSPI_DBUS_INTERFACE_COMPONENT;
60 const char *atspi_interface_dec = ATSPI_DBUS_INTERFACE_DEC;
61 const char *atspi_interface_device_event_listener = ATSPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER;
62 const char *atspi_interface_document = ATSPI_DBUS_INTERFACE_DOCUMENT;
63 const char *atspi_interface_editable_text = ATSPI_DBUS_INTERFACE_EDITABLE_TEXT;
64 const char *atspi_interface_event_object = ATSPI_DBUS_INTERFACE_EVENT_OBJECT;
65 const char *atspi_interface_hyperlink = ATSPI_DBUS_INTERFACE_HYPERLINK;
66 const char *atspi_interface_hypertext = ATSPI_DBUS_INTERFACE_HYPERTEXT;
67 const char *atspi_interface_image = ATSPI_DBUS_INTERFACE_IMAGE;
68 const char *atspi_interface_registry = ATSPI_DBUS_INTERFACE_REGISTRY;
69 const char *atspi_interface_selection = ATSPI_DBUS_INTERFACE_SELECTION;
70 const char *atspi_interface_table = ATSPI_DBUS_INTERFACE_TABLE;
71 const char *atspi_interface_text = ATSPI_DBUS_INTERFACE_TEXT;
72 const char *atspi_interface_cache = ATSPI_DBUS_INTERFACE_CACHE;
73 const char *atspi_interface_value = ATSPI_DBUS_INTERFACE_VALUE;
74
75 static const char *interfaces[] =
76 {
77   ATSPI_DBUS_INTERFACE_ACCESSIBLE,
78   ATSPI_DBUS_INTERFACE_ACTION,
79   ATSPI_DBUS_INTERFACE_APPLICATION,
80   ATSPI_DBUS_INTERFACE_COLLECTION,
81   ATSPI_DBUS_INTERFACE_COMPONENT,
82   ATSPI_DBUS_INTERFACE_DOCUMENT,
83   ATSPI_DBUS_INTERFACE_EDITABLE_TEXT,
84   ATSPI_DBUS_INTERFACE_HYPERLINK,
85   ATSPI_DBUS_INTERFACE_HYPERTEXT,
86   ATSPI_DBUS_INTERFACE_IMAGE,
87   "org.a11y.atspi.LoginHelper",
88   ATSPI_DBUS_INTERFACE_SELECTION,
89   ATSPI_DBUS_INTERFACE_TABLE,
90   ATSPI_DBUS_INTERFACE_TEXT,
91   ATSPI_DBUS_INTERFACE_VALUE,
92   NULL
93 };
94
95 gint
96 _atspi_get_iface_num (const char *iface)
97 {
98   /* TODO: Use a binary search or hash to improve performance */
99   int i;
100
101   for (i = 0; interfaces[i]; i++)
102   {
103     if (!strcmp(iface, interfaces[i])) return i;
104   }
105   return -1;
106 }
107
108 GHashTable *
109 _atspi_get_live_refs (void)
110 {
111   if (!live_refs) 
112     {
113       live_refs = g_hash_table_new (g_direct_hash, g_direct_equal);
114     }
115   return live_refs;
116 }
117
118 /* TODO: Add an application parameter */
119 DBusConnection *
120 _atspi_bus ()
121 {
122   if (!bus)
123     atspi_init ();
124   if (!bus)
125     g_error ("AT-SPI: COuldn't connect to accessibility bus. Is at-spi-bus-launcher running?");
126   return bus;
127 }
128
129 #define APP_IS_REGISTRY(app) (!strcmp (app->bus_name, atspi_bus_registry))
130
131 static AtspiAccessible *desktop;
132
133 static void
134 cleanup ()
135 {
136   GHashTable *refs;
137   GList *l;
138
139   refs = live_refs;
140   live_refs = NULL;
141   if (refs)
142     {
143       g_hash_table_destroy (refs);
144     }
145
146   if (bus)
147     {
148       dbus_connection_close (bus);
149       dbus_connection_unref (bus);
150       bus = NULL;
151     }
152
153   if (!desktop)
154     return;
155   for (l = desktop->children; l;)
156   {
157     GList *next = l->next;
158     AtspiAccessible *child = l->data;
159     g_object_run_dispose (G_OBJECT (child->parent.app));
160     g_object_run_dispose (G_OBJECT (child));
161     l = next;
162   }
163   g_object_run_dispose (G_OBJECT (desktop->parent.app));
164   g_object_unref (desktop);
165   desktop = NULL;
166 }
167
168 static gboolean atspi_inited = FALSE;
169
170 static GHashTable *app_hash = NULL;
171
172 static void
173 handle_get_bus_address (DBusPendingCall *pending, void *user_data)
174 {
175   AtspiApplication *app = user_data;
176   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
177   DBusMessage *message;
178   const char *address;
179   DBusPendingCall *new_pending;
180
181   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_METHOD_RETURN)
182   {
183     if (dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &address,
184                                DBUS_TYPE_INVALID) && address [0])
185     {
186       DBusError error;
187       DBusConnection *bus;
188
189       dbus_error_init (&error);
190       bus = dbus_connection_open_private (address, &error);
191       if (bus)
192       {
193         if (app->bus)
194           {
195             dbus_connection_unref (app->bus);
196           }
197         app->bus = bus;
198       }
199       else
200       {
201         g_warning ("Unable to open bus connection: %s", error.message);
202         dbus_error_free (&error);
203       }
204     }
205   }
206   dbus_message_unref (reply);
207   dbus_pending_call_unref (pending);
208
209   if (!app->bus)
210     return; /* application has gone away / been disposed */
211
212   message = dbus_message_new_method_call (app->bus_name,
213                                           "/org/a11y/atspi/cache",
214                                           atspi_interface_cache, "GetItems");
215
216    dbus_connection_send_with_reply (app->bus, message, &new_pending, 2000);
217   dbus_pending_call_set_notify (new_pending, handle_get_items, app, NULL);
218   dbus_message_unref (message);
219 }
220
221 static AtspiApplication *
222 get_application (const char *bus_name)
223 {
224   AtspiApplication *app = NULL;
225   char *bus_name_dup;
226   DBusMessage *message;
227   DBusPendingCall *pending = NULL;
228
229   if (!app_hash)
230   {
231     app_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_object_unref);
232     if (!app_hash) return NULL;
233   }
234   app = g_hash_table_lookup (app_hash, bus_name);
235   if (app) return app;
236   bus_name_dup = g_strdup (bus_name);
237   if (!bus_name_dup) return NULL;
238   // TODO: change below to something that will send state-change:defunct notification if necessary */
239   app = _atspi_application_new (bus_name);
240   app->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
241   app->bus = dbus_connection_ref (_atspi_bus ());
242   gettimeofday (&app->time_added, NULL);
243   app->cache = ATSPI_CACHE_UNDEFINED;
244   g_hash_table_insert (app_hash, bus_name_dup, app);
245   message = dbus_message_new_method_call (bus_name, atspi_path_root,
246                                           atspi_interface_application, "GetApplicationBusAddress");
247
248    dbus_connection_send_with_reply (app->bus, message, &pending, 2000);
249   dbus_pending_call_set_notify (pending, handle_get_bus_address, app, NULL);
250   dbus_message_unref (message);
251   return app;
252 }
253
254 static AtspiAccessible *
255 ref_accessible (const char *app_name, const char *path)
256 {
257   AtspiApplication *app;
258   AtspiAccessible *a;
259
260   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
261     return NULL;
262
263   app = get_application (app_name);
264
265   if (!strcmp (path, "/org/a11y/atspi/accessible/root"))
266   {
267     if (!app->root)
268     {
269       app->root = _atspi_accessible_new (app, atspi_path_root);
270       app->root->accessible_parent = atspi_get_desktop (0);
271       app->root->accessible_parent->children = g_list_append (app->root->accessible_parent->children, g_object_ref (app->root));
272     }
273     return g_object_ref (app->root);
274   }
275
276   a = g_hash_table_lookup (app->hash, path);
277   if (a)
278   {
279     return g_object_ref (a);
280   }
281   a = _atspi_accessible_new (app, path);
282   if (!a)
283     return NULL;
284   g_hash_table_insert (app->hash, g_strdup (a->parent.path), g_object_ref (a));
285   return a;
286 }
287
288 static AtspiHyperlink *
289 ref_hyperlink (const char *app_name, const char *path)
290 {
291   AtspiApplication *app = get_application (app_name);
292   AtspiHyperlink *hyperlink;
293
294   if (!strcmp (path, ATSPI_DBUS_PATH_NULL))
295     return NULL;
296
297   hyperlink = g_hash_table_lookup (app->hash, path);
298   if (hyperlink)
299   {
300     return g_object_ref (hyperlink);
301   }
302   hyperlink = _atspi_hyperlink_new (app, path);
303   g_hash_table_insert (app->hash, g_strdup (hyperlink->parent.path), hyperlink);
304   /* TODO: This should be a weak ref */
305   g_object_ref (hyperlink);     /* for the hash */
306   return hyperlink;
307 }
308
309 typedef struct
310 {
311   char *path;
312   char *parent;
313   GArray *children;
314   GArray *interfaces;
315   char *name;
316   dbus_uint32_t role;
317   char *description;
318   GArray *state_bitflags;
319 } CACHE_ADDITION;
320
321 static DBusHandlerResult
322 handle_remove_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
323 {
324   const char *sender = dbus_message_get_sender (message);
325   AtspiApplication *app;
326   const char *path;
327   DBusMessageIter iter, iter_struct;
328   const char *signature = dbus_message_get_signature (message);
329   AtspiAccessible *a;
330
331   if (strcmp (signature, "(so)") != 0)
332   {
333     g_warning ("AT-SPI: Unknown signature %s for RemoveAccessible", signature);
334     return DBUS_HANDLER_RESULT_HANDLED;
335   }
336
337   dbus_message_iter_init (message, &iter);
338   dbus_message_iter_recurse (&iter, &iter_struct);
339   dbus_message_iter_get_basic (&iter_struct, &sender);
340   dbus_message_iter_next (&iter_struct);
341   dbus_message_iter_get_basic (&iter_struct, &path);
342   app = get_application (sender);
343   a = ref_accessible (sender, path);
344   if (!a)
345     return DBUS_HANDLER_RESULT_HANDLED;
346   g_object_run_dispose (G_OBJECT (a));
347   g_hash_table_remove (app->hash, a->parent.path);
348   g_object_unref (a);   /* unref our own ref */
349   return DBUS_HANDLER_RESULT_HANDLED;
350 }
351
352 static DBusHandlerResult
353 handle_name_owner_changed (DBusConnection *bus, DBusMessage *message, void *user_data)
354 {
355   const char *name, *new, *old;
356   static gboolean registry_lost = FALSE;
357
358   if (!dbus_message_get_args (message, NULL,
359                               DBUS_TYPE_STRING, &name,
360                               DBUS_TYPE_STRING, &old,
361                               DBUS_TYPE_STRING, &new,
362                               DBUS_TYPE_INVALID))
363   {
364     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
365   }
366
367   if (!strcmp (name, "org.a11y.atspi.Registry"))
368   {
369     if (registry_lost && !old[0])
370     {
371       _atspi_reregister_event_listeners ();
372       _atspi_reregister_device_listeners ();
373       registry_lost = FALSE;
374     }
375     else if (!new[0])
376       registry_lost = TRUE;
377   }
378   else
379   {
380     AtspiAccessible *desktop = atspi_get_desktop (0);
381     GList *l;
382     for (l = desktop->children; l; l = l->next)
383     {
384       AtspiAccessible *child = l->data;
385       if (!strcmp (child->parent.app->bus_name, old))
386         g_object_run_dispose (G_OBJECT (child->parent.app));
387     }
388     g_object_unref (desktop);
389   }
390   return DBUS_HANDLER_RESULT_HANDLED;
391 }
392
393 static gboolean
394 add_app_to_desktop (AtspiAccessible *a, const char *bus_name)
395 {
396   AtspiAccessible *obj = ref_accessible (bus_name, atspi_path_root);
397   /* The app will be added to the desktop as a side-effect of calling
398    * ref_accessible */
399   g_object_unref (obj);
400   return (obj != NULL);
401 }
402
403 void
404 get_reference_from_iter (DBusMessageIter *iter, const char **app_name, const char **path)
405 {
406   DBusMessageIter iter_struct;
407
408   dbus_message_iter_recurse (iter, &iter_struct);
409   dbus_message_iter_get_basic (&iter_struct, app_name);
410   dbus_message_iter_next (&iter_struct);
411   dbus_message_iter_get_basic (&iter_struct, path);
412   dbus_message_iter_next (iter);
413 }
414
415 static void
416 add_accessible_from_iter (DBusMessageIter *iter)
417 {
418   DBusMessageIter iter_struct, iter_array;
419   const char *app_name, *path;
420   AtspiAccessible *accessible;
421   const char *name, *description;
422   dbus_uint32_t role;
423
424   dbus_message_iter_recurse (iter, &iter_struct);
425
426   /* get accessible */
427   get_reference_from_iter (&iter_struct, &app_name, &path);
428   accessible = ref_accessible (app_name, path);
429   if (!accessible)
430     return;
431
432   /* Get application: TODO */
433   dbus_message_iter_next (&iter_struct);
434
435   /* get parent */
436   get_reference_from_iter (&iter_struct, &app_name, &path);
437   if (accessible->accessible_parent)
438     g_object_unref (accessible->accessible_parent);
439   accessible->accessible_parent = ref_accessible (app_name, path);
440
441   /* Get children */
442   while (accessible->children)
443   {
444     g_object_unref (accessible->children->data);
445     accessible->children = g_list_remove (accessible->children, accessible->children->data);
446   }
447   dbus_message_iter_recurse (&iter_struct, &iter_array);
448   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
449   {
450     AtspiAccessible *child;
451     get_reference_from_iter (&iter_array, &app_name, &path);
452     child = ref_accessible (app_name, path);
453     accessible->children = g_list_append (accessible->children, child);
454   }
455
456   /* interfaces */
457   dbus_message_iter_next (&iter_struct);
458   _atspi_dbus_set_interfaces (accessible, &iter_struct);
459   dbus_message_iter_next (&iter_struct);
460
461   /* name */
462   if (accessible->name)
463     g_free (accessible->name);
464   dbus_message_iter_get_basic (&iter_struct, &name);
465   accessible->name = g_strdup (name);
466   dbus_message_iter_next (&iter_struct);
467
468   /* role */
469   dbus_message_iter_get_basic (&iter_struct, &role);
470   accessible->role = role;
471   dbus_message_iter_next (&iter_struct);
472
473   /* description */
474   if (accessible->description)
475     g_free (accessible->description);
476   dbus_message_iter_get_basic (&iter_struct, &description);
477   accessible->description = g_strdup (description);
478   dbus_message_iter_next (&iter_struct);
479
480   _atspi_dbus_set_state (accessible, &iter_struct);
481   dbus_message_iter_next (&iter_struct);
482
483   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_NAME | ATSPI_CACHE_ROLE |
484                                ATSPI_CACHE_PARENT | ATSPI_CACHE_DESCRIPTION);
485   if (!atspi_state_set_contains (accessible->states,
486                                        ATSPI_STATE_MANAGES_DESCENDANTS))
487     _atspi_accessible_add_cache (accessible, ATSPI_CACHE_CHILDREN);
488
489   /* This is a bit of a hack since the cache holds a ref, so we don't need
490    * the one provided for us anymore */
491   g_object_unref (accessible);
492 }
493
494 static void
495 handle_get_items (DBusPendingCall *pending, void *user_data)
496 {
497   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
498   DBusMessageIter iter, iter_array;
499
500   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
501   {
502     const char *sender = dbus_message_get_sender (reply);
503     const char *error = NULL;
504     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &error,
505                            DBUS_TYPE_INVALID);
506     g_warning ("AT-SPI: Error in GetItems, sender=%s, error=%s", sender, error);
507     dbus_message_unref (reply);
508     dbus_pending_call_unref (pending);
509     return;
510   }
511
512   dbus_message_iter_init (reply, &iter);
513   dbus_message_iter_recurse (&iter, &iter_array);
514   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
515   {
516     add_accessible_from_iter (&iter_array);
517     dbus_message_iter_next (&iter_array);
518   }
519   dbus_message_unref (reply);
520   dbus_pending_call_unref (pending);
521 }
522
523 /* TODO: Do we stil need this function? */
524 static AtspiAccessible *
525 ref_accessible_desktop (AtspiApplication *app)
526 {
527   GError *error;
528   DBusMessage *message, *reply;
529   DBusMessageIter iter, iter_array;
530   gchar *bus_name_dup;
531
532   if (desktop)
533   {
534     g_object_ref (desktop);
535     return desktop;
536   }
537   desktop = _atspi_accessible_new (app, atspi_path_root);
538   if (!desktop)
539   {
540     return NULL;
541   }
542   g_hash_table_insert (app->hash, g_strdup (desktop->parent.path),
543                        g_object_ref (desktop));
544   app->root = g_object_ref (desktop);
545   desktop->name = g_strdup ("main");
546   message = dbus_message_new_method_call (atspi_bus_registry,
547         atspi_path_root,
548         atspi_interface_accessible,
549         "GetChildren");
550   if (!message)
551     return NULL;
552   error = NULL;
553   reply = _atspi_dbus_send_with_reply_and_block (message, &error);
554   if (!reply || strcmp (dbus_message_get_signature (reply), "a(so)") != 0)
555   {
556     if (error != NULL)
557     {
558       g_warning ("Couldn't get application list: %s", error->message);
559       g_clear_error (&error);
560     }
561     if (reply)
562       dbus_message_unref (reply);
563     return NULL;
564   }
565   dbus_message_iter_init (reply, &iter);
566   dbus_message_iter_recurse (&iter, &iter_array);
567   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
568   {
569     const char *app_name, *path;
570     get_reference_from_iter (&iter_array, &app_name, &path);
571     add_app_to_desktop (desktop, app_name);
572   }
573   dbus_message_unref (reply);
574
575   /* Record the alternate name as an alias for org.a11y.atspi.Registry */
576   bus_name_dup = g_strdup (dbus_message_get_sender (reply));
577   if (bus_name_dup)
578     g_hash_table_insert (app_hash, bus_name_dup, app);
579
580   return g_object_ref (desktop);
581 }
582
583 AtspiAccessible *
584 _atspi_ref_accessible (const char *app, const char *path)
585 {
586   AtspiApplication *a = get_application (app);
587   if (!a)
588     return NULL;
589   if ( APP_IS_REGISTRY(a))
590   {
591     if (!a->root)
592       g_object_unref (ref_accessible_desktop (a));      /* sets a->root */
593     return g_object_ref (a->root);
594   }
595   return ref_accessible (app, path);
596 }
597
598 AtspiAccessible *
599 _atspi_dbus_return_accessible_from_message (DBusMessage *message)
600 {
601   DBusMessageIter iter;
602   AtspiAccessible *retval = NULL;
603   const char *signature;
604
605   if (!message)
606     return NULL;
607
608   signature = dbus_message_get_signature (message);
609   if (!strcmp (signature, "(so)"))
610   {
611     dbus_message_iter_init (message, &iter);
612     retval =  _atspi_dbus_return_accessible_from_iter (&iter);
613   }
614   else
615   {
616     g_warning ("AT-SPI: Called _atspi_dbus_return_accessible_from_message with strange signature %s", signature);
617   }
618   dbus_message_unref (message);
619   return retval;
620 }
621
622 AtspiAccessible *
623 _atspi_dbus_return_accessible_from_iter (DBusMessageIter *iter)
624 {
625   const char *app_name, *path;
626
627   get_reference_from_iter (iter, &app_name, &path);
628   return ref_accessible (app_name, path);
629 }
630
631 AtspiHyperlink *
632 _atspi_dbus_return_hyperlink_from_message (DBusMessage *message)
633 {
634   DBusMessageIter iter;
635   AtspiHyperlink *retval = NULL;
636   const char *signature;
637    
638   if (!message)
639     return NULL;
640
641   signature = dbus_message_get_signature (message);
642   if (!strcmp (signature, "(so)"))
643   {
644     dbus_message_iter_init (message, &iter);
645     retval =  _atspi_dbus_return_hyperlink_from_iter (&iter);
646   }
647   else
648   {
649     g_warning ("AT-SPI: Called _atspi_dbus_return_hyperlink_from_message with strange signature %s", signature);
650   }
651   dbus_message_unref (message);
652   return retval;
653 }
654
655 AtspiHyperlink *
656 _atspi_dbus_return_hyperlink_from_iter (DBusMessageIter *iter)
657 {
658   const char *app_name, *path;
659
660   get_reference_from_iter (iter, &app_name, &path);
661   return ref_hyperlink (app_name, path);
662 }
663
664 const char *cache_signal_type = "((so)(so)(so)a(so)assusau)";
665
666 static DBusHandlerResult
667 handle_add_accessible (DBusConnection *bus, DBusMessage *message, void *user_data)
668 {
669   DBusMessageIter iter;
670
671   if (strcmp (dbus_message_get_signature (message), cache_signal_type) != 0)
672   {
673     g_warning ("AT-SPI: AddAccessible with unknown signature %s\n",
674                dbus_message_get_signature (message));
675     return DBUS_HANDLER_RESULT_HANDLED;
676   }
677
678   dbus_message_iter_init (message, &iter);
679   add_accessible_from_iter (&iter);
680   return DBUS_HANDLER_RESULT_HANDLED;
681 }
682
683 typedef struct
684 {
685   DBusConnection *bus;
686   DBusMessage *message;
687   void *data;
688 } BusDataClosure;
689
690 static GSource *process_deferred_messages_source = NULL;
691
692 static void
693 process_deferred_message (BusDataClosure *closure)
694 {
695   int type = dbus_message_get_type (closure->message);
696   const char *interface = dbus_message_get_interface (closure->message);
697
698   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
699       !strncmp (interface, "org.a11y.atspi.Event.", 21))
700   {
701     _atspi_dbus_handle_event (closure->bus, closure->message, closure->data);
702   }
703   if (dbus_message_is_method_call (closure->message, atspi_interface_device_event_listener, "NotifyEvent"))
704   {
705     _atspi_dbus_handle_DeviceEvent (closure->bus,
706                                    closure->message, closure->data);
707   }
708   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "AddAccessible"))
709   {
710     handle_add_accessible (closure->bus, closure->message, closure->data);
711   }
712   if (dbus_message_is_signal (closure->message, atspi_interface_cache, "RemoveAccessible"))
713   {
714     handle_remove_accessible (closure->bus, closure->message, closure->data);
715   }
716   if (dbus_message_is_signal (closure->message, "org.freedesktop.DBus", "NameOwnerChanged"))
717   {
718     handle_name_owner_changed (closure->bus, closure->message, closure->data);
719   }
720 }
721
722 static GQueue *deferred_messages = NULL;
723
724 static gboolean
725 process_deferred_messages (void)
726 {
727   static int in_process_deferred_messages = 0;
728   BusDataClosure *closure;
729
730   if (in_process_deferred_messages)
731     return TRUE;
732   in_process_deferred_messages = 1;
733   while ((closure = g_queue_pop_head (deferred_messages)))
734   {
735     process_deferred_message (closure);
736     dbus_message_unref (closure->message);
737     dbus_connection_unref (closure->bus);
738     g_free (closure);
739   }
740   in_process_deferred_messages = 0;
741   return FALSE;
742 }
743
744 static gboolean
745 process_deferred_messages_callback (gpointer data)
746 {
747   if (process_deferred_messages ())
748     return G_SOURCE_CONTINUE;
749
750   process_deferred_messages_source = NULL;
751   return G_SOURCE_REMOVE;
752 }
753
754 static DBusHandlerResult
755 defer_message (DBusConnection *connection, DBusMessage *message, void *user_data)
756 {
757   BusDataClosure *closure = g_new (BusDataClosure, 1);
758
759   closure->bus = dbus_connection_ref (bus);
760   closure->message = dbus_message_ref (message);
761   closure->data = user_data;
762
763   g_queue_push_tail (deferred_messages, closure);
764
765   if (process_deferred_messages_source == NULL)
766   {
767     process_deferred_messages_source = g_idle_source_new ();
768     g_source_set_callback (process_deferred_messages_source,
769                            process_deferred_messages_callback, NULL, NULL);
770     g_source_attach (process_deferred_messages_source, atspi_main_context);
771     g_source_unref (process_deferred_messages_source);
772   }
773
774   return DBUS_HANDLER_RESULT_HANDLED;
775 }
776
777 static DBusHandlerResult
778 atspi_dbus_filter (DBusConnection *bus, DBusMessage *message, void *data)
779 {
780   int type = dbus_message_get_type (message);
781   const char *interface = dbus_message_get_interface (message);
782
783   if (type == DBUS_MESSAGE_TYPE_SIGNAL &&
784       !strncmp (interface, "org.a11y.atspi.Event.", 21))
785   {
786     return defer_message (bus, message, data);
787   }
788   if (dbus_message_is_method_call (message, atspi_interface_device_event_listener, "NotifyEvent"))
789   {
790     return defer_message (bus, message, data);
791   }
792   if (dbus_message_is_signal (message, atspi_interface_cache, "AddAccessible"))
793   {
794     return defer_message (bus, message, data);
795   }
796   if (dbus_message_is_signal (message, atspi_interface_cache, "RemoveAccessible"))
797   {
798     return defer_message (bus, message, data);
799   }
800   if (dbus_message_is_signal (message, "org.freedesktop.DBus", "NameOwnerChanged"))
801   {
802     defer_message (bus, message, data);
803     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
804   }
805   return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
806 }
807
808 /*
809  * Returns a 'canonicalized' value for DISPLAY,
810  * with the screen number stripped off if present.
811  *
812  * TODO: Avoid having duplicate functions for this here and in at-spi2-atk
813  */
814 static gchar *
815 spi_display_name (void)
816 {
817   char *canonical_display_name = NULL;
818   const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
819
820   if (!display_env)
821     {
822       display_env = g_getenv ("DISPLAY");
823       if (!display_env || !display_env[0])
824         return NULL;
825       else
826         {
827           gchar *display_p, *screen_p;
828           canonical_display_name = g_strdup (display_env);
829           display_p = g_utf8_strrchr (canonical_display_name, -1, ':');
830           screen_p = g_utf8_strrchr (canonical_display_name, -1, '.');
831           if (screen_p && display_p && (screen_p > display_p))
832             {
833               *screen_p = '\0';
834             }
835         }
836     }
837   else
838     {
839       canonical_display_name = g_strdup (display_env);
840     }
841
842   return canonical_display_name;
843 }
844
845 /**
846  * atspi_init:
847  *
848  * Connects to the accessibility registry and initializes the SPI.
849  *
850  * Returns: 0 on success, 1 if already initialized, or an integer error code.  
851  **/
852 int
853 atspi_init (void)
854 {
855   char *match;
856   const gchar *no_cache;
857
858   if (atspi_inited)
859     {
860       return 1;
861     }
862
863   atspi_inited = TRUE;
864
865   _atspi_get_live_refs();
866
867   bus = atspi_get_a11y_bus ();
868   if (!bus)
869     return 2;
870   dbus_bus_register (bus, NULL);
871   atspi_dbus_connection_setup_with_g_main(bus, g_main_context_default());
872   dbus_connection_add_filter (bus, atspi_dbus_filter, NULL, NULL);
873   match = g_strdup_printf ("type='signal',interface='%s',member='AddAccessible'", atspi_interface_cache);
874   dbus_bus_add_match (bus, match, NULL);
875   g_free (match);
876   match = g_strdup_printf ("type='signal',interface='%s',member='RemoveAccessible'", atspi_interface_cache);
877   dbus_bus_add_match (bus, match, NULL);
878   g_free (match);
879   match = g_strdup_printf ("type='signal',interface='%s',member='ChildrenChanged'", atspi_interface_event_object);
880   dbus_bus_add_match (bus, match, NULL);
881   g_free (match);
882   match = g_strdup_printf ("type='signal',interface='%s',member='PropertyChange'", atspi_interface_event_object);
883   dbus_bus_add_match (bus, match, NULL);
884   g_free (match);
885   match = g_strdup_printf ("type='signal',interface='%s',member='StateChanged'", atspi_interface_event_object);
886   dbus_bus_add_match (bus, match, NULL);
887   g_free (match);
888
889   dbus_bus_add_match (bus,
890                       "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged'",
891                       NULL);
892
893   no_cache = g_getenv ("ATSPI_NO_CACHE");
894   if (no_cache && g_strcmp0 (no_cache, "0") != 0)
895     atspi_no_cache = TRUE;
896
897   deferred_messages = g_queue_new ();
898
899   return 0;
900 }
901
902 /**
903  * atspi_is_initialized:
904  *
905  * Indicates whether AT-SPI has been initialized.
906  *
907  * Returns: %True if initialized; %False otherwise.
908  */
909 gboolean
910 atspi_is_initialized ()
911 {
912   return atspi_inited;
913 }
914
915 /**
916  * atspi_event_main:
917  *
918  * Starts/enters the main event loop for the AT-SPI services.
919  *
920  * NOTE: This method does not return control; it is exited via a call to
921  * #atspi_event_quit from within an event handler.
922  *
923  **/
924 void
925 atspi_event_main (void)
926 {
927   atspi_main_loop = g_main_loop_new (NULL, FALSE);
928   g_main_loop_run (atspi_main_loop);
929   atspi_main_loop = NULL;
930 }
931
932 /**
933  * atspi_event_quit:
934  *
935  * Quits the last main event loop for the AT-SPI services,
936  * See: #atspi_event_main
937  **/
938 void
939 atspi_event_quit (void)
940 {
941   g_main_loop_quit (atspi_main_loop);
942 }
943
944 /**
945  * atspi_exit:
946  *
947  * Disconnects from #AtspiRegistry instances and releases 
948  * any floating resources. Call only once at exit.
949  *
950  * Returns: 0 if there were no leaks, otherwise other integer values.
951  **/
952 int
953 atspi_exit (void)
954 {
955   int leaked;
956
957   if (!atspi_inited)
958     {
959       return 0;
960     }
961
962   atspi_inited = FALSE;
963
964   if (live_refs)
965     {
966       leaked = g_hash_table_size (live_refs);
967     }
968   else
969     {
970       leaked = 0;
971     }
972
973   cleanup ();
974
975   return leaked;
976 }
977
978 static GSList *hung_processes;
979
980 static void
981 remove_hung_process (DBusPendingCall *pending, void *data)
982 {
983
984   hung_processes = g_slist_remove (hung_processes, data);
985   g_free (data);
986   dbus_pending_call_unref (pending);
987 }
988
989 static void
990 check_for_hang (DBusMessage *message, DBusError *error, DBusConnection *bus, const char *bus_name)
991 {
992   if (!message && error->name &&
993       !strcmp (error->name, "org.freedesktop.DBus.Error.NoReply"))
994   {
995     GSList *l;
996     DBusMessage *message;
997     gchar *bus_name_dup;
998     DBusPendingCall *pending = NULL;
999     for (l = hung_processes; l; l = l->next)
1000       if (!strcmp (l->data, bus_name))
1001         return;
1002     message = dbus_message_new_method_call (bus_name, "/",
1003                                             "org.freedesktop.DBus.Peer",
1004                                             "Ping");
1005     if (!message)
1006       return;
1007     dbus_connection_send_with_reply (bus, message, &pending, -1);
1008     dbus_message_unref (message);
1009     if (!pending)
1010       return;
1011     bus_name_dup = g_strdup (bus_name);
1012     hung_processes = g_slist_append (hung_processes, bus_name_dup);
1013     dbus_pending_call_set_notify (pending, remove_hung_process, bus_name_dup, NULL);
1014   }
1015 }
1016
1017 static gboolean
1018 connection_is_hung (const char *bus_name)
1019 {
1020   GSList *l;
1021
1022   for (l = hung_processes; l; l = l->next)
1023     if (!strcmp (l->data, bus_name))
1024       return TRUE;
1025   return FALSE;
1026 }
1027
1028 static gboolean
1029 check_app (AtspiApplication *app, GError **error)
1030 {
1031   if (!app || !app->bus)
1032   {
1033     g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_APPLICATION_GONE,
1034                           _("The application no longer exists"));
1035     return FALSE;
1036   }
1037
1038   if (atspi_main_loop && connection_is_hung (app->bus_name))
1039   {
1040       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC,
1041                            "The process appears to be hung.");
1042     return FALSE;
1043   }
1044
1045   return TRUE;
1046 }
1047
1048 static void
1049 set_timeout (AtspiApplication *app)
1050 {
1051   struct timeval tv;
1052   int diff;
1053
1054   if (app && app_startup_time > 0)
1055   {
1056     gettimeofday (&tv, NULL);
1057     diff = (tv.tv_sec - app->time_added.tv_sec) * 1000 + (tv.tv_usec - app->time_added.tv_usec) / 1000;
1058     dbind_set_timeout (MAX(method_call_timeout, app_startup_time - diff));
1059   }
1060   else
1061     dbind_set_timeout (method_call_timeout);
1062 }
1063
1064 dbus_bool_t
1065 _atspi_dbus_call (gpointer obj, const char *interface, const char *method, GError **error, const char *type, ...)
1066 {
1067   va_list args;
1068   dbus_bool_t retval;
1069   DBusError err;
1070   AtspiObject *aobj = ATSPI_OBJECT (obj);
1071
1072   if (!check_app (aobj->app, error))
1073     return FALSE;
1074
1075   if (!allow_sync)
1076   {
1077     _atspi_set_error_no_sync (error);
1078     return FALSE;
1079   }
1080
1081   va_start (args, type);
1082   dbus_error_init (&err);
1083   set_timeout (aobj->app);
1084   retval = dbind_method_call_reentrant_va (aobj->app->bus, aobj->app->bus_name,
1085                                            aobj->path, interface, method, &err,
1086                                            type, args);
1087   va_end (args);
1088   check_for_hang (NULL, &err, aobj->app->bus, aobj->app->bus_name);
1089   process_deferred_messages ();
1090   if (dbus_error_is_set (&err))
1091   {
1092     g_set_error(error, ATSPI_ERROR, ATSPI_ERROR_IPC, "%s", err.message);
1093     dbus_error_free (&err);
1094   }
1095   return retval;
1096 }
1097
1098 DBusMessage *
1099 _atspi_dbus_call_partial (gpointer obj,
1100                           const char *interface,
1101                           const char *method,
1102                           GError **error,
1103                           const char *type, ...)
1104 {
1105   va_list args;
1106
1107   va_start (args, type);
1108   return _atspi_dbus_call_partial_va (obj, interface, method, error, type, args);
1109 }
1110
1111
1112 DBusMessage *
1113 _atspi_dbus_call_partial_va (gpointer obj,
1114                           const char *interface,
1115                           const char *method,
1116                           GError **error,
1117                           const char *type,
1118                           va_list args)
1119 {
1120   AtspiObject *aobj = ATSPI_OBJECT (obj);
1121   DBusError err;
1122     DBusMessage *msg = NULL, *reply = NULL;
1123     DBusMessageIter iter;
1124     const char *p;
1125
1126   dbus_error_init (&err);
1127
1128   if (!check_app (aobj->app, error))
1129     goto out;
1130
1131   msg = dbus_message_new_method_call (aobj->app->bus_name, aobj->path, interface, method);
1132   if (!msg)
1133     goto out;
1134
1135   p = type;
1136   dbus_message_iter_init_append (msg, &iter);
1137   dbind_any_marshal_va (&iter, &p, args);
1138
1139   set_timeout (aobj->app);
1140   reply = dbind_send_and_allow_reentry (aobj->app->bus, msg, &err);
1141   check_for_hang (reply, &err, aobj->app->bus, aobj->app->bus_name);
1142 out:
1143   va_end (args);
1144   if (msg)
1145     dbus_message_unref (msg);
1146   process_deferred_messages ();
1147   if (dbus_error_is_set (&err))
1148   {
1149     /* TODO: Set gerror */
1150     dbus_error_free (&err);
1151   }
1152
1153   if (reply && dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
1154   {
1155     const char *err_str = NULL;
1156     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &err_str, DBUS_TYPE_INVALID);
1157     if (err_str)
1158       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err_str);
1159     dbus_message_unref (reply);
1160     return NULL;
1161   }
1162
1163   return reply;
1164 }
1165
1166 dbus_bool_t
1167 _atspi_dbus_get_property (gpointer obj, const char *interface, const char *name, GError **error, const char *type, void *data)
1168 {
1169   DBusMessage *message, *reply;
1170   DBusMessageIter iter, iter_variant;
1171   DBusError err;
1172   dbus_bool_t retval = FALSE;
1173   AtspiObject *aobj = ATSPI_OBJECT (obj);
1174   char expected_type = (type [0] == '(' ? 'r' : type [0]);
1175
1176   if (!aobj)
1177     return FALSE;
1178
1179   if (!check_app (aobj->app, error))
1180     return FALSE;
1181
1182   if (!allow_sync)
1183   {
1184     _atspi_set_error_no_sync (error);
1185     return FALSE;
1186   }
1187
1188   message = dbus_message_new_method_call (aobj->app->bus_name,
1189                                           aobj->path,
1190                                           "org.freedesktop.DBus.Properties",
1191                                           "Get");
1192   if (!message)
1193   {
1194     // TODO: throw exception
1195     return FALSE;
1196   }
1197   dbus_message_append_args (message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1198   dbus_error_init (&err);
1199   set_timeout (aobj->app);
1200   reply = dbind_send_and_allow_reentry (aobj->app->bus, message, &err);
1201   check_for_hang (reply, &err, aobj->app->bus, aobj->app->bus_name);
1202   dbus_message_unref (message);
1203   process_deferred_messages ();
1204   if (!reply)
1205   {
1206     // TODO: throw exception
1207     goto done;
1208   }
1209
1210   if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
1211   {
1212     const char *err_str = NULL;
1213     dbus_message_get_args (reply, NULL, DBUS_TYPE_STRING, &err_str, DBUS_TYPE_INVALID);
1214     if (err_str)
1215       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err_str);
1216     goto done;
1217   }
1218
1219   dbus_message_iter_init (reply, &iter);
1220   if (dbus_message_iter_get_arg_type (&iter) != 'v')
1221   {
1222     g_warning ("AT-SPI: expected a variant when fetching %s from interface %s; got %s\n", name, interface, dbus_message_get_signature (reply));
1223     goto done;
1224   }
1225   dbus_message_iter_recurse (&iter, &iter_variant);
1226   if (dbus_message_iter_get_arg_type (&iter_variant) != expected_type)
1227   {
1228     g_warning ("atspi_dbus_get_property: Wrong type: expected %s, got %c\n", type, dbus_message_iter_get_arg_type (&iter_variant));
1229     goto done;
1230   }
1231   if (!strcmp (type, "(so)"))
1232   {
1233     *((AtspiAccessible **)data) = _atspi_dbus_return_accessible_from_iter (&iter_variant);
1234   }
1235   else
1236   {
1237     dbus_message_iter_get_basic (&iter_variant, data);
1238     if (type [0] == 's')
1239       *(char **)data = g_strdup (*(char **)data);
1240   }
1241   retval = TRUE;
1242 done:
1243   dbus_error_free (&err);
1244   if (reply)
1245     dbus_message_unref (reply);
1246   return retval;
1247 }
1248
1249 DBusMessage *
1250 _atspi_dbus_send_with_reply_and_block (DBusMessage *message, GError **error)
1251 {
1252   DBusMessage *reply;
1253   DBusError err;
1254   AtspiApplication *app;
1255   DBusConnection *bus;
1256
1257   app = get_application (dbus_message_get_destination (message));
1258
1259   if (app && !app->bus)
1260     return NULL;        /* will fail anyway; app has been disposed */
1261
1262   bus = (app ? app->bus : _atspi_bus());
1263   dbus_error_init (&err);
1264   set_timeout (app);
1265   reply = dbind_send_and_allow_reentry (bus, message, &err);
1266   process_deferred_messages ();
1267   dbus_message_unref (message);
1268   if (dbus_error_is_set (&err))
1269   {
1270     if (error)
1271       g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_IPC, err.message);
1272     dbus_error_free (&err);
1273   }
1274   return reply;
1275 }
1276
1277 GHashTable *
1278 _atspi_dbus_return_hash_from_message (DBusMessage *message)
1279 {
1280   DBusMessageIter iter;
1281   GHashTable *ret;
1282
1283   if (!message)
1284     return NULL;
1285
1286   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1287
1288   dbus_message_iter_init (message, &iter);
1289   ret = _atspi_dbus_hash_from_iter (&iter);
1290   dbus_message_unref (message);
1291   return ret;
1292 }
1293
1294 GHashTable *
1295 _atspi_dbus_hash_from_iter (DBusMessageIter *iter)
1296 {
1297   GHashTable *hash = g_hash_table_new_full (g_str_hash, g_str_equal,
1298                                             (GDestroyNotify) g_free,
1299                                             (GDestroyNotify) g_free);
1300   DBusMessageIter iter_array, iter_dict;
1301
1302   dbus_message_iter_recurse (iter, &iter_array);
1303   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1304   {
1305     const char *name, *value;
1306     dbus_message_iter_recurse (&iter_array, &iter_dict);
1307     dbus_message_iter_get_basic (&iter_dict, &name);
1308     dbus_message_iter_next (&iter_dict);
1309     dbus_message_iter_get_basic (&iter_dict, &value);
1310     g_hash_table_insert (hash, g_strdup (name), g_strdup (value));
1311     dbus_message_iter_next (&iter_array);
1312   }
1313   return hash;
1314 }
1315
1316 GArray *
1317 _atspi_dbus_return_attribute_array_from_message (DBusMessage *message)
1318 {
1319   DBusMessageIter iter;
1320   GArray *ret;
1321
1322   if (!message)
1323     return NULL;
1324
1325   _ATSPI_DBUS_CHECK_SIG (message, "a{ss}", NULL, NULL);
1326
1327   dbus_message_iter_init (message, &iter);
1328
1329   ret = _atspi_dbus_attribute_array_from_iter (&iter);
1330   dbus_message_unref (message);
1331   return ret;
1332 }
1333
1334 GArray *
1335 _atspi_dbus_attribute_array_from_iter (DBusMessageIter *iter)
1336 {
1337   DBusMessageIter iter_array, iter_dict;
1338   GArray *array = g_array_new (TRUE, TRUE, sizeof (gchar *));
1339
1340   dbus_message_iter_recurse (iter, &iter_array);
1341   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1342   {
1343     const char *name, *value;
1344     gchar *str;
1345     dbus_message_iter_recurse (&iter_array, &iter_dict);
1346     dbus_message_iter_get_basic (&iter_dict, &name);
1347     dbus_message_iter_next (&iter_dict);
1348     dbus_message_iter_get_basic (&iter_dict, &value);
1349     str = g_strdup_printf ("%s:%s", name, value);
1350     array = g_array_append_val (array, str);
1351     dbus_message_iter_next (&iter_array);;
1352   }
1353   return array;
1354 }
1355
1356 void
1357 _atspi_dbus_set_interfaces (AtspiAccessible *accessible, DBusMessageIter *iter)
1358 {
1359   DBusMessageIter iter_array;
1360
1361   accessible->interfaces = 0;
1362   if (strcmp (dbus_message_iter_get_signature (iter), "as") != 0)
1363   {
1364     g_warning ("_atspi_dbus_set_interfaces: Passed iterator with invalid signature %s", dbus_message_iter_get_signature (iter));
1365     return;
1366   }
1367   dbus_message_iter_recurse (iter, &iter_array);
1368   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
1369   {
1370     const char *iface;
1371     gint n;
1372     dbus_message_iter_get_basic (&iter_array, &iface);
1373     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable")) continue;
1374     n = _atspi_get_iface_num (iface);
1375     if (n == -1)
1376     {
1377       g_warning ("AT-SPI: Unknown interface %s", iface);
1378     }
1379     else
1380       accessible->interfaces |= (1 << n);
1381     dbus_message_iter_next (&iter_array);
1382   }
1383   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_INTERFACES);
1384 }
1385
1386 void
1387 _atspi_dbus_set_state (AtspiAccessible *accessible, DBusMessageIter *iter)
1388 {
1389   DBusMessageIter iter_array;
1390   gint count;
1391   dbus_uint32_t *states;
1392
1393   dbus_message_iter_recurse (iter, &iter_array);
1394   dbus_message_iter_get_fixed_array (&iter_array, &states, &count);
1395   if (count != 2)
1396   {
1397     g_warning ("AT-SPI: expected 2 values in states array; got %d\n", count);
1398     if (!accessible->states)
1399       accessible->states = _atspi_state_set_new_internal (accessible, 0);
1400   }
1401   else
1402   {
1403     guint64 val = ((guint64)states [1]) << 32;
1404     val += states [0];
1405     if (!accessible->states)
1406       accessible->states = _atspi_state_set_new_internal (accessible, val);
1407     else
1408       accessible->states->states = val;
1409   }
1410   _atspi_accessible_add_cache (accessible, ATSPI_CACHE_STATES);
1411 }
1412
1413 GQuark
1414 _atspi_error_quark (void)
1415 {
1416   return g_quark_from_static_string ("atspi_error");
1417 }
1418
1419 /*
1420  * Gets the IOR from the XDisplay.
1421  */
1422 #ifdef HAVE_X11
1423 static char *
1424 get_accessibility_bus_address_x11 (void)
1425 {
1426   Atom AT_SPI_BUS;
1427   Atom actual_type;
1428   Display *bridge_display = NULL;
1429   int actual_format;
1430   char *data;
1431   unsigned char *data_x11 = NULL;
1432   unsigned long nitems;
1433   unsigned long leftover;
1434   char *display_name;
1435
1436   display_name = spi_display_name ();
1437   if (!display_name)
1438     return NULL;
1439
1440   bridge_display = XOpenDisplay (display_name);
1441   g_free (display_name);
1442
1443   if (!bridge_display)
1444     {
1445       g_warning ("Could not open X display");
1446       return NULL;
1447     }
1448       
1449   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
1450   XGetWindowProperty (bridge_display,
1451                       XDefaultRootWindow (bridge_display),
1452                       AT_SPI_BUS, 0L,
1453                       (long) BUFSIZ, False,
1454                       (Atom) 31, &actual_type, &actual_format,
1455                       &nitems, &leftover, &data_x11);
1456   XCloseDisplay (bridge_display);
1457
1458   data = g_strdup ((gchar *)data_x11);
1459   XFree (data_x11);
1460   return data;
1461 }
1462 #endif
1463
1464 static char *
1465 get_accessibility_bus_address_dbus (void)
1466 {
1467   DBusConnection *session_bus = NULL;
1468   DBusMessage *message;
1469   DBusMessage *reply;
1470   DBusError error;
1471   char *address = NULL;
1472
1473   session_bus = dbus_bus_get (DBUS_BUS_SESSION, NULL);
1474   if (!session_bus)
1475     return NULL;
1476
1477   message = dbus_message_new_method_call ("org.a11y.Bus",
1478                                           "/org/a11y/bus",
1479                                           "org.a11y.Bus",
1480                                           "GetAddress");
1481
1482   dbus_error_init (&error);
1483   reply = dbus_connection_send_with_reply_and_block (session_bus,
1484                                                      message,
1485                                                      -1,
1486                                                      &error);
1487   dbus_message_unref (message);
1488
1489   if (!reply)
1490   {
1491     g_warning ("Error retrieving accessibility bus address: %s: %s",
1492                error.name, error.message);
1493     dbus_error_free (&error);
1494     return NULL;
1495   }
1496   
1497   {
1498     const char *tmp_address;
1499     if (!dbus_message_get_args (reply,
1500                                 NULL,
1501                                 DBUS_TYPE_STRING,
1502                                 &tmp_address,
1503                                 DBUS_TYPE_INVALID))
1504       {
1505         dbus_message_unref (reply);
1506         return NULL;
1507       }
1508     address = g_strdup (tmp_address);
1509     dbus_message_unref (reply);
1510   }
1511   
1512   return address;
1513 }
1514
1515 static DBusConnection *a11y_bus;
1516 static dbus_int32_t a11y_dbus_slot = -1;
1517
1518 static void
1519 a11y_bus_free (void *data)
1520 {
1521   if (data == a11y_bus)
1522     {
1523       a11y_bus = NULL;
1524       dbus_connection_free_data_slot (&a11y_dbus_slot);
1525     }
1526 }
1527
1528 /**
1529  * atspi_get_a11y_bus: (skip)
1530  */
1531 DBusConnection *
1532 atspi_get_a11y_bus (void)
1533 {
1534   DBusError error;
1535   char *address = NULL;
1536
1537   if (a11y_bus && dbus_connection_get_is_connected (a11y_bus))
1538     return a11y_bus;
1539
1540   if (a11y_dbus_slot == -1)
1541     if (!dbus_connection_allocate_data_slot (&a11y_dbus_slot))
1542       g_warning ("at-spi: Unable to allocate D-Bus slot");
1543
1544 #ifdef HAVE_X11
1545   address = get_accessibility_bus_address_x11 ();
1546 #endif
1547   if (!address)
1548     address = get_accessibility_bus_address_dbus ();
1549   if (!address)
1550     return NULL;
1551
1552   dbus_error_init (&error);
1553   a11y_bus = dbus_connection_open_private (address, &error);
1554   g_free (address);
1555
1556   if (!a11y_bus)
1557     {
1558       g_warning ("Couldn't connect to accessibility bus: %s", error.message);
1559       dbus_error_free (&error);
1560       return NULL;
1561     }
1562   else
1563     {
1564       if (!dbus_bus_register (a11y_bus, &error))
1565         {
1566           g_warning ("Couldn't register with accessibility bus: %s", error.message);
1567           dbus_error_free (&error);
1568           dbus_connection_close (a11y_bus);
1569           dbus_connection_unref (a11y_bus);
1570           a11y_bus = NULL;
1571           return NULL;
1572         }
1573     }
1574   
1575   /* Simulate a weak ref on the bus */
1576   dbus_connection_set_data (a11y_bus, a11y_dbus_slot, a11y_bus, a11y_bus_free);
1577
1578   return a11y_bus;
1579 }
1580
1581 /**
1582  * atspi_set_timeout:
1583  *  @val: The timeout value, in milliseconds, or -1 to disable the timeout.
1584  *  @startup_time: The amount of time, in milliseconds, to allow to pass
1585  *  before enforcing timeouts on an application. Can be used to prevent
1586  *  timeout exceptions if an application is likely to block for an extended
1587  *  period of time on initialization. -1 can be passed to disable this
1588  *  behavior.
1589  *
1590  *  Set the timeout used for method calls. If this is not set explicitly,
1591  *  a default of 0.8 ms is used.
1592  *  Note that at-spi2-registryd currently uses a timeout of 3 seconds when
1593  *  sending a keyboard event notification. This means that, if an AT makes
1594  *  a call in response to the keyboard notification and the application
1595  *  being called does not respond before the timeout is reached,
1596  *  at-spi2-registryd will time out on the keyboard event notification and
1597  *  pass the key onto the application (ie, reply to indicate that the key
1598  *  was not consumed), so this may make it undesirable to set a timeout
1599  *  larger than 3 seconds.
1600  *
1601  * By default, the normal timeout is set to 800 ms, and the application startup
1602  * timeout is set to 15 seconds.
1603  */
1604 void
1605 atspi_set_timeout (gint val, gint startup_time)
1606 {
1607   method_call_timeout = val;
1608   app_startup_time = startup_time;
1609 }
1610
1611 /**
1612  * atspi_set_main_context:
1613  * @cnx: The #GMainContext to use.
1614  *
1615  * Sets the main loop context that AT-SPI should assume is in use when
1616  * setting an idle callback.
1617  * This function should be called by application-side implementors (ie,
1618  * at-spi2-atk) when it is desirable to re-enter the main loop.
1619  */
1620 void
1621 atspi_set_main_context (GMainContext *cnx)
1622 {
1623   if (atspi_main_context == cnx)
1624     return;
1625   if (process_deferred_messages_source != NULL)
1626   {
1627     g_source_destroy (process_deferred_messages_source);
1628     process_deferred_messages_source = g_idle_source_new ();
1629     g_source_set_callback (process_deferred_messages_source,
1630                            process_deferred_messages_callback, NULL, NULL);
1631     g_source_attach (process_deferred_messages_source, cnx);
1632     g_source_unref (process_deferred_messages_source);
1633   }
1634   atspi_main_context = cnx;
1635   atspi_dbus_connection_setup_with_g_main (atspi_get_a11y_bus (), cnx);
1636 }
1637
1638 #ifdef DEBUG_REF_COUNTS
1639 static void
1640 print_disposed (gpointer key, gpointer value, gpointer data)
1641 {
1642   AtspiAccessible *accessible = key;
1643   if (accessible->parent.app)
1644     return;
1645   g_print ("disposed: %s %d\n", accessible->name, accessible->role);
1646 }
1647
1648 void
1649 debug_disposed ()
1650 {
1651   g_hash_table_foreach (live_refs, print_disposed, NULL);
1652 }
1653 #endif
1654
1655 gchar *
1656 _atspi_name_compat (gchar *name)
1657 {
1658   gchar *p = name;
1659
1660   while (*p)
1661   {
1662     if (*p == '-')
1663       *p = ' ';
1664     p++;
1665   }
1666   return name;
1667 }
1668
1669 /**
1670  * atspi_role_get_name:
1671  * @role: an #AtspiRole object to query.
1672  *
1673  * Gets a localizable string that indicates the name of an #AtspiRole.
1674  * <em>DEPRECATED.</em>
1675  *
1676  * Returns: a localizable string name for an #AtspiRole enumerated type.
1677  **/
1678 gchar *
1679 atspi_role_get_name (AtspiRole role)
1680 {
1681   gchar *retval = NULL;
1682   GTypeClass *type_class;
1683   GEnumValue *value;
1684
1685   type_class = g_type_class_ref (ATSPI_TYPE_ROLE);
1686   g_return_val_if_fail (G_IS_ENUM_CLASS (type_class), NULL);
1687
1688   value = g_enum_get_value (G_ENUM_CLASS (type_class), role);
1689
1690   if (value)
1691     {
1692       retval = g_strdup (value->value_nick);
1693     }
1694
1695   if (retval)
1696     return _atspi_name_compat (retval);
1697
1698   return NULL;
1699 }
1700
1701 void
1702 _atspi_dbus_update_cache_from_dict (AtspiAccessible *accessible, DBusMessageIter *iter)
1703 {
1704   GHashTable *cache = _atspi_accessible_ref_cache (accessible);
1705   DBusMessageIter iter_dict, iter_dict_entry, iter_struct, iter_variant;
1706
1707   dbus_message_iter_recurse (iter, &iter_dict);
1708   while (dbus_message_iter_get_arg_type (&iter_dict) != DBUS_TYPE_INVALID)
1709   {
1710     const char *key;
1711     GValue *val = NULL;
1712     dbus_message_iter_recurse (&iter_dict, &iter_dict_entry);
1713     dbus_message_iter_get_basic (&iter_dict_entry, &key);
1714     dbus_message_iter_next (&iter_dict_entry);
1715     dbus_message_iter_recurse (&iter_dict_entry, &iter_variant);
1716     if (!strcmp (key, "interfaces"))
1717     {
1718       _atspi_dbus_set_interfaces (accessible, &iter_variant);
1719     }
1720     else if (!strcmp (key, "Attributes"))
1721     {
1722       val = g_new0 (GValue, 1);;
1723       g_value_init (val, G_TYPE_HASH_TABLE);
1724       if (strcmp (dbus_message_iter_get_signature (&iter_variant),
1725                                                    "a{ss}") != 0)
1726         break;
1727       g_value_take_boxed (val, _atspi_dbus_hash_from_iter (&iter_variant));
1728     }
1729     else if (!strcmp (key, "Component.ScreenExtents"))
1730     {
1731       dbus_int32_t d_int;
1732       AtspiRect extents;
1733       val = g_new0 (GValue, 1);;
1734       g_value_init (val, ATSPI_TYPE_RECT);
1735       if (strcmp (dbus_message_iter_get_signature (&iter_variant),
1736                                                    "(iiii)") != 0)
1737         break;
1738       dbus_message_iter_recurse (&iter_variant, &iter_struct);
1739       dbus_message_iter_get_basic (&iter_struct, &d_int);
1740       extents.x = d_int;
1741       dbus_message_iter_next (&iter_struct);
1742       dbus_message_iter_get_basic (&iter_struct, &d_int);
1743       extents.y = d_int;
1744       dbus_message_iter_next (&iter_struct);
1745       dbus_message_iter_get_basic (&iter_struct, &d_int);
1746       extents.width = d_int;
1747       dbus_message_iter_next (&iter_struct);
1748       dbus_message_iter_get_basic (&iter_struct, &d_int);
1749       extents.height = d_int;
1750       g_value_set_boxed (val, &extents);
1751     }
1752     if (val)
1753       g_hash_table_insert (cache, g_strdup (key), val); 
1754     dbus_message_iter_next (&iter_dict);
1755   }
1756 }
1757
1758 gboolean
1759 _atspi_get_allow_sync ()
1760 {
1761   return allow_sync;
1762 }
1763
1764 gboolean
1765 _atspi_set_allow_sync (gboolean val)
1766 {
1767   gboolean ret = allow_sync;
1768
1769   allow_sync = val;
1770   return ret;
1771 }
1772
1773 void
1774 _atspi_set_error_no_sync (GError **error)
1775 {
1776   g_set_error_literal (error, ATSPI_ERROR, ATSPI_ERROR_SYNC_NOT_ALLOWED,
1777                         _("Attempted synchronous call where prohibited"));
1778 }