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