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