Have adaptor_init() return -1 on error and not consider itself initialized
[platform/core/uifw/at-spi2-atk.git] / atk-adaptor / bridge.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2008, 2009 Codethink Ltd.
6  * Copyright 2001, 2002, 2003 Sun Microsystems Inc.,
7  * Copyright 2001, 2002, 2003 Ximian, 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 #include "config.h"
26 #include "dbus/dbus-glib-lowlevel.h"
27
28 #include <X11/Xlib.h>
29 #include <X11/Xatom.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <atk/atk.h>
36
37 #include <droute/droute.h>
38
39 #include "bridge.h"
40 #include "event.h"
41 #include "adaptors.h"
42 #include "object.h"
43
44 #include "accessible-register.h"
45 #include "accessible-leasing.h"
46 #include "accessible-cache.h"
47
48 #include "common/spi-dbus.h"
49
50 /*---------------------------------------------------------------------------*/
51
52 SpiBridge *spi_global_app_data = NULL;
53
54 static const AtkMisc *atk_misc = NULL;
55
56 /*static Display *bridge_display = NULL;*/
57
58 /*---------------------------------------------------------------------------*/
59
60 /*
61  * Returns a 'canonicalized' value for DISPLAY,
62  * with the screen number stripped off if present.
63  *
64  */
65 static const gchar *
66 spi_display_name (void)
67 {
68   static const char *canonical_display_name = NULL;
69   if (!canonical_display_name)
70     {
71       const gchar *display_env = g_getenv ("AT_SPI_DISPLAY");
72       if (!display_env)
73         {
74           display_env = g_getenv ("DISPLAY");
75           if (!display_env || !display_env[0])
76             canonical_display_name = ":0";
77           else
78             {
79               gchar *display_p, *screen_p;
80               canonical_display_name = g_strdup (display_env);
81               display_p = strrchr (canonical_display_name, ':');
82               screen_p = strrchr (canonical_display_name, '.');
83               if (screen_p && display_p && (screen_p > display_p))
84                 {
85                   *screen_p = '\0';
86                 }
87             }
88         }
89       else
90         {
91           canonical_display_name = display_env;
92         }
93     }
94   return canonical_display_name;
95 }
96
97 /*---------------------------------------------------------------------------*/
98
99 /*
100  * Gets the IOR from the XDisplay.
101  * Not currently used in D-Bus version, but something similar
102  * may be employed in the future for accessing the registry daemon
103  * bus name.
104  */
105
106 static DBusConnection *
107 spi_atk_bridge_get_bus (void)
108 {
109   Atom AT_SPI_BUS;
110   Atom actual_type;
111   Display *bridge_display;
112   int actual_format;
113   unsigned char *data = NULL;
114   unsigned long nitems;
115   unsigned long leftover;
116
117   DBusConnection *bus = NULL;
118   DBusError error;
119
120   bridge_display = XOpenDisplay (spi_display_name ());
121   if (!bridge_display)
122     {
123       g_warning ("AT_SPI: Could not get the display\n");
124       return NULL;
125     }
126
127   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
128   XGetWindowProperty (bridge_display,
129                       XDefaultRootWindow (bridge_display),
130                       AT_SPI_BUS, 0L,
131                       (long) BUFSIZ, False,
132                       (Atom) 31, &actual_type, &actual_format,
133                       &nitems, &leftover, &data);
134
135   dbus_error_init (&error);
136
137   if (data == NULL)
138     {
139       g_warning
140         ("AT-SPI: Accessibility bus not found - Using session bus.\n");
141       bus = dbus_bus_get (DBUS_BUS_SESSION, &error);
142       if (!bus)
143         {
144           g_warning ("AT-SPI: Couldn't connect to bus: %s\n", error.message);
145           return NULL;
146         }
147     }
148   else
149     {
150       bus = dbus_connection_open (data, &error);
151       if (!bus)
152         {
153           g_warning ("AT-SPI: Couldn't connect to bus: %s\n", error.message);
154           return NULL;
155         }
156       else
157         {
158           if (!dbus_bus_register (bus, &error))
159             {
160               g_warning ("AT-SPI: Couldn't register with bus: %s\n", error.message);
161               return NULL;
162             }
163         }
164     }
165
166   return bus;
167 }
168
169 static void
170 set_reply (DBusPendingCall *pending, void *user_data)
171 {
172     void **replyptr = (void **)user_data;
173
174     *replyptr = dbus_pending_call_steal_reply (pending);
175 }
176
177 static DBusMessage *
178 send_and_allow_reentry (DBusConnection *bus, DBusMessage *message, DBusError *error)
179 {
180     DBusPendingCall *pending;
181     DBusMessage *reply = NULL;
182
183     if (!dbus_connection_send_with_reply (bus, message, &pending, -1))
184     {
185         return NULL;
186     }
187     dbus_pending_call_set_notify (pending, set_reply, (void *)&reply, NULL);
188     while (!reply)
189     {
190       if (!dbus_connection_read_write_dispatch (bus, -1)) return NULL;
191     }
192     return reply;
193 }
194 /*---------------------------------------------------------------------------*/
195
196 static void
197 register_reply (DBusPendingCall *pending, void *user_data)
198 {
199   DBusMessage *reply;
200   SpiBridge *app = user_data;
201
202     reply = dbus_pending_call_steal_reply (pending);
203   if (reply)
204     {
205       DBusMessageIter iter, iter_struct;
206       gchar *app_name, *obj_path;
207
208       if (strcmp (dbus_message_get_signature (reply), "(so)") != 0)
209         {
210           g_warning ("AT-SPI: Could not obtain desktop path or name\n");
211           dbus_message_unref (reply);
212           return;
213         }
214
215       dbus_message_iter_init (reply, &iter);
216       dbus_message_iter_recurse (&iter, &iter_struct);
217       dbus_message_iter_get_basic (&iter_struct, &app_name);
218       dbus_message_iter_next (&iter_struct);
219       dbus_message_iter_get_basic (&iter_struct, &obj_path);
220
221       app->desktop_name = g_strdup (app_name);
222       app->desktop_path = g_strdup (obj_path);
223     }
224   else
225     {
226       g_warning ("AT-SPI: Could not embed inside desktop");
227       return;
228     }
229   dbus_message_unref (reply);
230 }
231
232 static gboolean
233 register_application (SpiBridge * app)
234 {
235   DBusMessage *message, *reply;
236   DBusMessageIter iter;
237   DBusError error;
238   DBusPendingCall *pending;
239
240   dbus_error_init (&error);
241
242   /* These will be overridden when we get a reply, but in practice these
243      defaults should always be correct */
244   app->desktop_name = SPI_DBUS_NAME_REGISTRY;
245   app->desktop_path = SPI_DBUS_PATH_ROOT;
246
247   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
248                                           SPI_DBUS_PATH_ROOT,
249                                           SPI_DBUS_INTERFACE_SOCKET,
250                                           "Embed");
251
252   dbus_message_iter_init_append (message, &iter);
253   spi_object_append_reference (&iter, app->root);
254   
255     if (!dbus_connection_send_with_reply (app->bus, message, &pending, -1))
256     {
257         return FALSE;
258     }
259
260     dbus_pending_call_set_notify (pending, register_reply, app, NULL);
261
262   if (message)
263     dbus_message_unref (message);
264
265   return TRUE;
266 }
267
268 /*---------------------------------------------------------------------------*/
269
270 static void
271 deregister_application (SpiBridge * app)
272 {
273   DBusMessage *message;
274   DBusMessageIter iter;
275   DBusError error;
276   const char *uname;
277
278   dbus_error_init (&error);
279
280   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
281                                           SPI_DBUS_PATH_REGISTRY,
282                                           SPI_DBUS_INTERFACE_REGISTRY,
283                                           "DeregisterApplication");
284   dbus_message_set_no_reply (message, TRUE);
285
286   uname = dbus_bus_get_unique_name (app->bus);
287
288   dbus_message_iter_init_append (message, &iter);
289   dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &uname);
290   dbus_connection_send (app->bus, message, NULL);
291   if (message)
292     dbus_message_unref (message);
293 }
294
295 /*---------------------------------------------------------------------------*/
296
297 static void
298 exit_func (void)
299 {
300   if (!spi_global_app_data)
301     {
302       return;
303     }
304
305   spi_atk_tidy_windows ();
306   spi_atk_deregister_event_listeners ();
307   deregister_application (spi_global_app_data);
308
309   g_free (spi_global_app_data);
310   spi_global_app_data = NULL;
311
312   /* Not currently creating an XDisplay */
313 #if 0
314   if (bridge_display)
315     XCloseDisplay (bridge_display);
316 #endif
317 }
318
319 /*---------------------------------------------------------------------------*/
320
321 static AtkPlugClass *plug_class;
322 static AtkSocketClass *socket_class;
323
324 static gchar *
325 get_plug_id (AtkPlug * plug)
326 {
327   const char *uname = dbus_bus_get_unique_name (spi_global_app_data->bus);
328   gchar *path;
329   GString *str = g_string_new (NULL);
330
331   path = spi_register_object_to_path (spi_global_register, G_OBJECT (plug));
332   g_string_printf (str, "%s:%s", uname, path);
333   g_free (path);
334   return g_string_free (str, FALSE);
335 }
336
337 AtkStateSet *
338 socket_ref_state_set (AtkObject *accessible)
339 {
340   char *child_name, *child_path;
341   AtkSocket *socket = ATK_SOCKET (accessible);
342   int count = 0;
343   int j;
344   int v;
345   DBusMessage *message, *reply;
346   DBusMessageIter iter, iter_array;
347   AtkStateSet *set;
348
349   if (!socket->embedded_plug_id)
350     return NULL;
351
352   child_name = g_strdup (socket->embedded_plug_id);
353   if (!child_name)
354     return NULL;
355   child_path = g_utf8_strchr (child_name + 1, -1, ':');
356   if (!child_path)
357     {
358       g_free (child_name);
359       return NULL;
360     }
361   *(child_path++) = '\0';
362   message = dbus_message_new_method_call (child_name, child_path, SPI_DBUS_INTERFACE_ACCESSIBLE, "GetState");
363   g_free (child_name);
364   reply = dbus_connection_send_with_reply_and_block (spi_global_app_data->bus, message, 1, NULL);
365   dbus_message_unref (message);
366   if (reply == NULL)
367     return NULL;
368   if (strcmp (dbus_message_get_signature (reply), "au") != 0)
369     {
370       dbus_message_unref (reply);
371       return NULL;
372     }
373   set = atk_state_set_new ();
374   if (!set)
375     return  NULL;
376   dbus_message_iter_init (reply, &iter);
377   dbus_message_iter_recurse (&iter, &iter_array);
378   do
379     {
380       dbus_message_iter_get_basic (&iter_array, &v);
381       for (j = 0; j < 32; j++)
382         {
383           if (v & (1 << j))
384             {
385               AtkState state = spi_atk_state_from_spi_state ((count << 5) + j);
386               atk_state_set_add_state (set, state);
387             }
388         }
389       count++;
390     }
391   while (dbus_message_iter_next (&iter_array));
392   dbus_message_unref (reply);
393   return set;
394 }
395
396 static void
397 socket_embed_hook (AtkSocket * socket, gchar * plug_id)
398 {
399   AtkObject *accessible = ATK_OBJECT(socket);
400   gchar *plug_name, *plug_path;
401   AtkObjectClass *klass;
402
403   /* Force registration */
404   gchar *path = spi_register_object_to_path (spi_global_register, G_OBJECT (accessible));
405   /* Let the plug know that it has been embedded */
406   plug_name = g_strdup (plug_id);
407   if (!plug_name)
408     {
409       g_free (path);
410       return;
411     }
412   plug_path = g_utf8_strchr (plug_name + 1, -1, ':');
413   if (plug_path)
414     {
415       DBusMessage *message;
416       *(plug_path++) = '\0';
417       message = dbus_message_new_method_call (plug_name, plug_path, SPI_DBUS_INTERFACE_SOCKET, "Embedded");
418       dbus_message_append_args (message, DBUS_TYPE_STRING, &path, DBUS_TYPE_INVALID);
419       dbus_connection_send (spi_global_app_data->bus, message, NULL);
420     }
421   g_free (plug_name);
422   g_free (path);
423
424   klass = ATK_OBJECT_GET_CLASS (accessible);
425   klass->ref_state_set = socket_ref_state_set;
426 }
427
428 static void
429 install_plug_hooks ()
430 {
431   gpointer data;
432
433   data = g_type_class_ref (ATK_TYPE_PLUG);
434   plug_class = ATK_PLUG_CLASS (data);
435   data = g_type_class_ref (ATK_TYPE_SOCKET);
436   socket_class = ATK_SOCKET_CLASS (data);
437   plug_class->get_object_id = get_plug_id;
438   socket_class->embed = socket_embed_hook;
439 }
440
441 gchar *atspi_dbus_name = NULL;
442 static gboolean atspi_no_register = FALSE;
443
444 static GOptionEntry atspi_option_entries[] = {
445   {"atspi-dbus-name", 0, 0, G_OPTION_ARG_STRING, &atspi_dbus_name,
446    "D-Bus bus name to register as", NULL},
447   {"atspi-no-register", 0, 0, G_OPTION_ARG_NONE, &atspi_no_register,
448    "Do not register with Registry Daemon", NULL},
449   {NULL}
450 };
451
452 static gchar *
453 introspect_children_cb (const char *path, void *data)
454 {
455   if (!strcmp (path, "/org/a11y/atspi/accessible"))
456     {
457       return g_strdup ("<node name=\"root\"/>\n");
458       /* TODO: Should we place the whole hierarchy here? */
459     }
460   return NULL;
461 }
462
463 /*
464  * spi_app_init
465  *
466  * The following needs to be initialized.
467  *
468  * - DRoute for routing message to their accessible objects.
469  * - Event handlers for emmitting signals on specific ATK events.
470  * - Application registration with the AT-SPI registry.
471  *
472  */
473 static int
474 adaptor_init (gint * argc, gchar ** argv[])
475 {
476   GOptionContext *opt;
477   GError *err = NULL;
478   DBusError error;
479   DBusConnection *bus;
480   AtkObject *root;
481   gchar *introspection_directory;
482   static gboolean inited = FALSE;
483
484   if (inited)
485     return 0;
486
487   inited = TRUE;
488
489   DRoutePath *treepath, *accpath;
490
491   root = atk_get_root ();
492   g_warn_if_fail (root);
493   if (!root)
494     {
495       inited = FALSE;
496       return -1;
497     }
498
499   /* Parse command line options */
500   opt = g_option_context_new (NULL);
501   g_option_context_add_main_entries (opt, atspi_option_entries, NULL);
502   g_option_context_set_ignore_unknown_options (opt, TRUE);
503   if (!g_option_context_parse (opt, argc, argv, &err))
504     g_warning ("AT-SPI Option parsing failed: %s\n", err->message);
505
506   /* Allocate global data and do ATK initializations */
507   spi_global_app_data = g_new0 (SpiBridge, 1);
508   atk_misc = atk_misc_get_instance ();
509   spi_global_app_data->root = g_object_ref (root);
510
511   /* Set up D-Bus connection and register bus name */
512   dbus_error_init (&error);
513   spi_global_app_data->bus = spi_atk_bridge_get_bus ();
514   if (!spi_global_app_data->bus)
515     {
516       g_free (spi_global_app_data);
517       spi_global_app_data = NULL;
518       inited = FALSE;
519       return -1;
520     }
521
522   if (atspi_dbus_name != NULL)
523     {
524       if (dbus_bus_request_name
525           (spi_global_app_data->bus, atspi_dbus_name, 0, &error))
526         {
527           g_print ("AT-SPI Recieved D-Bus name - %s\n", atspi_dbus_name);
528         }
529       else
530         {
531           g_print
532             ("AT-SPI D-Bus name requested but could not be allocated - %s\n",
533              atspi_dbus_name);
534         }
535     }
536
537   dbus_connection_setup_with_g_main (spi_global_app_data->bus,
538                                      g_main_context_default ());
539
540   /* Hook our plug-and socket functions */
541   install_plug_hooks ();
542
543   /* 
544    * Create the leasing, register and cache objects.
545    * The order is important here, the cache depends on the
546    * register object.
547    */
548   spi_global_register = g_object_new (SPI_REGISTER_TYPE, NULL);
549   spi_global_leasing  = g_object_new (SPI_LEASING_TYPE, NULL);
550   spi_global_cache    = g_object_new (SPI_CACHE_TYPE, NULL);
551
552   /* Register droute for routing AT-SPI messages */
553   spi_global_app_data->droute =
554     droute_new (spi_global_app_data->bus);
555
556   treepath = droute_add_one (spi_global_app_data->droute,
557                              "/org/a11y/atspi/cache", spi_global_cache);
558
559   if (!treepath)
560     {
561       g_warning ("atk-bridge: Error in droute_add_one().  Already running?");
562       return -1;
563     }
564
565   accpath = droute_add_many (spi_global_app_data->droute,
566                              "/org/a11y/atspi/accessible",
567                              NULL,
568                              introspect_children_cb,
569                              NULL,
570                              (DRouteGetDatumFunction)
571                              spi_global_register_path_to_object);
572
573
574   /* Register all interfaces with droute and set up application accessible db */
575   spi_initialize_cache (treepath);
576   spi_initialize_accessible (accpath);
577   spi_initialize_application (accpath);
578   spi_initialize_action (accpath);
579   spi_initialize_collection (accpath);
580   spi_initialize_component (accpath);
581   spi_initialize_document (accpath);
582   spi_initialize_editabletext (accpath);
583   spi_initialize_hyperlink (accpath);
584   spi_initialize_hypertext (accpath);
585   spi_initialize_image (accpath);
586   spi_initialize_selection (accpath);
587   spi_initialize_socket (accpath);
588   spi_initialize_table (accpath);
589   spi_initialize_text (accpath);
590   spi_initialize_value (accpath);
591
592   /* Register methods to send D-Bus signals on certain ATK events */
593   spi_atk_register_event_listeners ();
594
595   /* Register this app by sending a signal out to AT-SPI registry daemon */
596   if (!atspi_no_register && (!root || !ATK_IS_PLUG (root)))
597     register_application (spi_global_app_data);
598
599   g_atexit (exit_func);
600
601   return 0;
602 }
603
604 /*---------------------------------------------------------------------------*/
605
606 int
607 gtk_module_init (gint * argc, gchar ** argv[])
608 {
609   const gchar *load_bridge = g_getenv ("NO_AT_BRIDGE");
610
611   if (!load_bridge || g_ascii_strtod (load_bridge, NULL) == 0)
612     {
613       return adaptor_init (argc, argv);
614     }
615   return 0;
616 }
617
618 void
619 gnome_accessibility_module_init (void)
620 {
621   const gchar *load_bridge = g_getenv ("NO_AT_BRIDGE");
622
623   if (!load_bridge || g_ascii_strtod (load_bridge, NULL) == 0)
624     {
625       adaptor_init (NULL, NULL);
626
627       if (g_getenv ("AT_SPI_DEBUG"))
628         {
629           g_print ("Atk Accessibility bridge initialized\n");
630         }
631     }
632 }
633
634 void
635 gnome_accessibility_module_shutdown (void)
636 {
637   spi_atk_deregister_event_listeners ();
638   exit_func ();
639 }
640
641 /*END------------------------------------------------------------------------*/