For IsScreenReaderEnabled, listen for the correct gsettings change signal
[platform/upstream/at-spi2-core.git] / bus / at-spi-bus-launcher.c
1 /* -*- mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2  * 
3  * at-spi-bus-launcher: Manage the a11y bus as a child process 
4  *
5  * Copyright 2011 Red Hat, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 #include "config.h"
24
25 #include <unistd.h>
26 #include <string.h>
27 #include <signal.h>
28 #include <sys/wait.h>
29 #include <errno.h>
30 #include <stdio.h>
31
32 #include <gio/gio.h>
33 #include <X11/Xlib.h>
34 #include <X11/Xatom.h>
35
36 typedef enum {
37   A11Y_BUS_STATE_IDLE = 0,
38   A11Y_BUS_STATE_READING_ADDRESS,
39   A11Y_BUS_STATE_RUNNING,
40   A11Y_BUS_STATE_ERROR
41 } A11yBusState;
42
43 typedef struct {
44   GMainLoop *loop;
45   gboolean launch_immediately;
46   gboolean a11y_enabled;
47   gboolean screen_reader_enabled;
48   GDBusConnection *session_bus;
49   GSettings *a11y_schema;
50   GSettings *interface_schema;
51
52   A11yBusState state;
53   /* -1 == error, 0 == pending, > 0 == running */
54   int a11y_bus_pid;
55   char *a11y_bus_address;
56   int pipefd[2];
57   char *a11y_launch_error_message;
58 } A11yBusLauncher;
59
60 static A11yBusLauncher *_global_app = NULL;
61
62 static const gchar introspection_xml[] =
63   "<node>"
64   "  <interface name='org.a11y.Bus'>"
65   "    <method name='GetAddress'>"
66   "      <arg type='s' name='address' direction='out'/>"
67   "    </method>"
68   "  </interface>"
69   "<interface name='org.a11y.Status'>"
70   "<property name='IsEnabled' type='b' access='readwrite'/>"
71   "<property name='ScreenReaderEnabled' type='b' access='readwrite'/>"
72   "</interface>"
73   "</node>";
74 static GDBusNodeInfo *introspection_data = NULL;
75
76 static void
77 setup_bus_child (gpointer data)
78 {
79   A11yBusLauncher *app = data;
80   (void) app;
81
82   close (app->pipefd[0]);
83   dup2 (app->pipefd[1], 3);
84   close (app->pipefd[1]);
85
86   /* On Linux, tell the bus process to exit if this process goes away */
87 #ifdef __linux
88 #include <sys/prctl.h>
89   prctl (PR_SET_PDEATHSIG, 15);
90 #endif  
91 }
92
93 /**
94  * unix_read_all_fd_to_string:
95  *
96  * Read all data from a file descriptor to a C string buffer.
97  */
98 static gboolean
99 unix_read_all_fd_to_string (int      fd,
100                             char    *buf,
101                             ssize_t  max_bytes)
102 {
103   ssize_t bytes_read;
104
105   while (max_bytes > 1 && (bytes_read = read (fd, buf, MAX (4096, max_bytes - 1))))
106     {
107       if (bytes_read < 0)
108         return FALSE;
109       buf += bytes_read;
110       max_bytes -= bytes_read;
111     }
112   *buf = '\0';
113   return TRUE;
114 }
115
116 static void
117 on_bus_exited (GPid     pid,
118                gint     status,
119                gpointer data)
120 {
121   A11yBusLauncher *app = data;
122   
123   app->a11y_bus_pid = -1;
124   app->state = A11Y_BUS_STATE_ERROR;
125   if (app->a11y_launch_error_message == NULL)
126     {
127       if (WIFEXITED (status))
128         app->a11y_launch_error_message = g_strdup_printf ("Bus exited with code %d", WEXITSTATUS (status));
129       else if (WIFSIGNALED (status))
130         app->a11y_launch_error_message = g_strdup_printf ("Bus killed by signal %d", WTERMSIG (status));
131       else if (WIFSTOPPED (status))
132         app->a11y_launch_error_message = g_strdup_printf ("Bus stopped by signal %d", WSTOPSIG (status));
133     }
134   g_main_loop_quit (app->loop);
135
136
137 static gboolean
138 ensure_a11y_bus (A11yBusLauncher *app)
139 {
140   GPid pid;
141   char *argv[] = { DBUS_DAEMON, NULL, "--nofork", "--print-address", "3", NULL };
142   char addr_buf[2048];
143   GError *error = NULL;
144
145   if (app->a11y_bus_pid != 0)
146     return FALSE;
147   
148   argv[1] = g_strdup_printf ("--config-file=%s/at-spi2/accessibility.conf", SYSCONFDIR);
149
150   if (pipe (app->pipefd) < 0)
151     g_error ("Failed to create pipe: %s", strerror (errno));
152   
153   if (!g_spawn_async (NULL,
154                       argv,
155                       NULL,
156                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
157                       setup_bus_child,
158                       app,
159                       &pid,
160                       &error))
161     {
162       app->a11y_bus_pid = -1;
163       app->a11y_launch_error_message = g_strdup (error->message);
164       g_clear_error (&error);
165       goto error;
166     }
167
168   close (app->pipefd[1]);
169   app->pipefd[1] = -1;
170
171   g_child_watch_add (pid, on_bus_exited, app);
172
173   app->state = A11Y_BUS_STATE_READING_ADDRESS;
174   app->a11y_bus_pid = pid;
175   g_debug ("Launched a11y bus, child is %ld", (long) pid);
176   if (!unix_read_all_fd_to_string (app->pipefd[0], addr_buf, sizeof (addr_buf)))
177     {
178       app->a11y_launch_error_message = g_strdup_printf ("Failed to read address: %s", strerror (errno));
179       kill (app->a11y_bus_pid, SIGTERM);
180       goto error;
181     }
182   close (app->pipefd[0]);
183   app->pipefd[0] = -1;
184   app->state = A11Y_BUS_STATE_RUNNING;
185
186   /* Trim the trailing newline */
187   app->a11y_bus_address = g_strchomp (g_strdup (addr_buf));
188   g_debug ("a11y bus address: %s", app->a11y_bus_address);
189
190   {
191     Display *display = XOpenDisplay (NULL);
192     if (display)
193       {
194         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
195         XChangeProperty (display,
196                          XDefaultRootWindow (display),
197                          bus_address_atom,
198                          XA_STRING, 8, PropModeReplace,
199                          (guchar *) app->a11y_bus_address, strlen (app->a11y_bus_address));
200         XFlush (display);
201         XCloseDisplay (display);
202       }
203   }
204
205   return TRUE;
206   
207  error:
208   close (app->pipefd[0]);
209   close (app->pipefd[1]);
210   app->state = A11Y_BUS_STATE_ERROR;
211
212   return FALSE;
213 }
214
215 static void
216 handle_method_call (GDBusConnection       *connection,
217                     const gchar           *sender,
218                     const gchar           *object_path,
219                     const gchar           *interface_name,
220                     const gchar           *method_name,
221                     GVariant              *parameters,
222                     GDBusMethodInvocation *invocation,
223                     gpointer               user_data)
224 {
225   A11yBusLauncher *app = user_data;
226
227   if (g_strcmp0 (method_name, "GetAddress") == 0)
228     {
229       ensure_a11y_bus (app);
230       if (app->a11y_bus_pid > 0)
231         g_dbus_method_invocation_return_value (invocation,
232                                                g_variant_new ("(s)", app->a11y_bus_address));
233       else
234         g_dbus_method_invocation_return_dbus_error (invocation,
235                                                     "org.a11y.Bus.Error",
236                                                     app->a11y_launch_error_message);
237     }
238 }
239
240 static GVariant *
241 handle_get_property  (GDBusConnection       *connection,
242                       const gchar           *sender,
243                       const gchar           *object_path,
244                       const gchar           *interface_name,
245                       const gchar           *property_name,
246                     GError **error,
247                     gpointer               user_data)
248 {
249   A11yBusLauncher *app = user_data;
250
251   if (g_strcmp0 (property_name, "IsEnabled") == 0)
252     return g_variant_new ("b", app->a11y_enabled);
253   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
254     return g_variant_new ("b", app->screen_reader_enabled);
255   else
256     return NULL;
257 }
258
259 static void
260 handle_a11y_enabled_change (A11yBusLauncher *app, gboolean enabled,
261                                gboolean notify_gsettings)
262 {
263   GVariantBuilder *builder;
264   GVariantBuilder *invalidated_builder;
265
266   if (enabled == app->a11y_enabled)
267     return;
268
269   app->a11y_enabled = enabled;
270
271   if (notify_gsettings && app->interface_schema)
272     {
273       g_settings_set_boolean (app->interface_schema, "toolkit-accessibility",
274                               enabled);
275       g_settings_sync ();
276     }
277
278   builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
279   invalidated_builder = g_variant_builder_new (G_VARIANT_TYPE ("as"));
280   g_variant_builder_add (builder, "{sv}", "IsEnabled",
281                          g_variant_new_boolean (enabled));
282
283   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
284                                  "org.freedesktop.DBus", "PropertiesChanged",
285                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
286                                                 builder,
287                                                 invalidated_builder),
288                                  NULL);
289 }
290
291 static void
292 handle_screen_reader_enabled_change (A11yBusLauncher *app, gboolean enabled,
293                                gboolean notify_gsettings)
294 {
295   GVariantBuilder *builder;
296   GVariantBuilder *invalidated_builder;
297
298   if (enabled == app->screen_reader_enabled)
299     return;
300
301   /* If the screen reader is being enabled, we should enable accessibility
302    * if it isn't enabled already */
303   if (enabled)
304     handle_a11y_enabled_change (app, enabled, notify_gsettings);
305
306   app->screen_reader_enabled = enabled;
307
308   if (notify_gsettings && app->a11y_schema)
309     {
310       g_settings_set_boolean (app->a11y_schema, "screen-reader-enabled",
311                               enabled);
312       g_settings_sync ();
313     }
314
315   builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
316   invalidated_builder = g_variant_builder_new (G_VARIANT_TYPE ("as"));
317   g_variant_builder_add (builder, "{sv}", "ScreenReaderEnabled",
318                          g_variant_new_boolean (enabled));
319
320   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
321                                  "org.freedesktop.DBus", "PropertiesChanged",
322                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
323                                                 builder,
324                                                 invalidated_builder),
325                                  NULL);
326 }
327
328 static gboolean
329 handle_set_property  (GDBusConnection       *connection,
330                       const gchar           *sender,
331                       const gchar           *object_path,
332                       const gchar           *interface_name,
333                       const gchar           *property_name,
334                       GVariant *value,
335                     GError **error,
336                     gpointer               user_data)
337 {
338   A11yBusLauncher *app = user_data;
339   const gchar *type = g_variant_get_type_string (value);
340   gboolean enabled;
341   
342   if (g_strcmp0 (type, "b") != 0)
343     {
344       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
345                        "org.a11y.Status.%s expects a boolean but got %s", property_name, type);
346       return FALSE;
347     }
348
349   enabled = g_variant_get_boolean (value);
350
351   if (g_strcmp0 (property_name, "IsEnabled") == 0)
352     {
353       handle_a11y_enabled_change (app, enabled, TRUE);
354       return TRUE;
355     }
356   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
357     {
358       handle_screen_reader_enabled_change (app, enabled, TRUE);
359       return TRUE;
360     }
361   else
362     {
363       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
364                        "Unknown property '%s'", property_name);
365       return FALSE;
366     }
367 }
368
369 static const GDBusInterfaceVTable bus_vtable =
370 {
371   handle_method_call,
372   NULL, /* handle_get_property, */
373   NULL  /* handle_set_property */
374 };
375
376 static const GDBusInterfaceVTable status_vtable =
377 {
378   NULL, /* handle_method_call */
379   handle_get_property,
380   handle_set_property
381 };
382
383 static void
384 on_bus_acquired (GDBusConnection *connection,
385                  const gchar     *name,
386                  gpointer         user_data)
387 {
388   A11yBusLauncher *app = user_data;
389   GError *error;
390   guint registration_id;
391   
392   if (connection == NULL)
393     {
394       g_main_loop_quit (app->loop);
395       return;
396     }
397   app->session_bus = connection;
398
399   if (app->launch_immediately)
400     {
401       ensure_a11y_bus (app);
402       if (app->state == A11Y_BUS_STATE_ERROR)
403         {
404           g_main_loop_quit (app->loop);
405           return;
406         }
407     }
408
409   error = NULL;
410   registration_id = g_dbus_connection_register_object (connection,
411                                                        "/org/a11y/bus",
412                                                        introspection_data->interfaces[0],
413                                                        &bus_vtable,
414                                                        _global_app,
415                                                        NULL,
416                                                        &error);
417   if (registration_id == 0)
418     g_error ("%s", error->message);
419
420   g_dbus_connection_register_object (connection,
421                                                        "/org/a11y/bus",
422                                                        introspection_data->interfaces[1],
423                                                        &status_vtable,
424                                                        _global_app,
425                                                        NULL,
426                                                        &error);
427 }
428
429 static void
430 on_name_lost (GDBusConnection *connection,
431               const gchar     *name,
432               gpointer         user_data)
433 {
434   A11yBusLauncher *app = user_data;
435   if (app->session_bus == NULL
436       && connection == NULL
437       && app->a11y_launch_error_message == NULL)
438     app->a11y_launch_error_message = g_strdup ("Failed to connect to session bus");
439   g_main_loop_quit (app->loop);
440 }
441
442 static void
443 on_name_acquired (GDBusConnection *connection,
444                   const gchar     *name,
445                   gpointer         user_data)
446 {
447   A11yBusLauncher *app = user_data;
448   (void) app;
449 }
450
451 static int sigterm_pipefd[2];
452
453 static void
454 sigterm_handler (int signum)
455 {
456   write (sigterm_pipefd[1], "X", 1);
457 }
458
459 static gboolean
460 on_sigterm_pipe (GIOChannel  *channel,
461                  GIOCondition condition,
462                  gpointer     data)
463 {
464   A11yBusLauncher *app = data;
465   
466   g_main_loop_quit (app->loop);
467
468   return FALSE;
469 }
470
471 static void
472 init_sigterm_handling (A11yBusLauncher *app)
473 {
474   GIOChannel *sigterm_channel;
475
476   if (pipe (sigterm_pipefd) < 0)
477     g_error ("Failed to create pipe: %s", strerror (errno));
478   signal (SIGTERM, sigterm_handler);
479
480   sigterm_channel = g_io_channel_unix_new (sigterm_pipefd[0]);
481   g_io_add_watch (sigterm_channel,
482                   G_IO_IN | G_IO_ERR | G_IO_HUP,
483                   on_sigterm_pipe,
484                   app);
485 }
486
487 static gboolean
488 already_running ()
489 {
490   Atom AT_SPI_BUS;
491   Atom actual_type;
492   Display *bridge_display;
493   int actual_format;
494   unsigned char *data = NULL;
495   unsigned long nitems;
496   unsigned long leftover;
497   gboolean result = FALSE;
498
499   bridge_display = XOpenDisplay (NULL);
500   if (!bridge_display)
501               return FALSE;
502       
503   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
504   XGetWindowProperty (bridge_display,
505                       XDefaultRootWindow (bridge_display),
506                       AT_SPI_BUS, 0L,
507                       (long) BUFSIZ, False,
508                       (Atom) 31, &actual_type, &actual_format,
509                       &nitems, &leftover, &data);
510
511   if (data)
512   {
513     GDBusConnection *bus;
514     GError *error = NULL;
515     const gchar *old_session = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
516     /* TODO: Is there a better way to connect? This is really hacky */
517     g_setenv ("DBUS_SESSION_BUS_ADDRESS", data, TRUE);
518     bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
519     g_setenv ("DBUS_SESSION_BUS_ADDRESS", old_session, TRUE);
520     if (bus != NULL)
521       {
522         result = TRUE;
523         g_object_unref (bus);
524       }
525   }
526
527   XCloseDisplay (bridge_display);
528   return result;
529 }
530
531 static GSettings *
532 get_schema (const gchar *name)
533 {
534   const char * const *schemas = NULL;
535   gint i;
536
537   schemas = g_settings_list_schemas ();
538   for (i = 0; schemas[i]; i++)
539   {
540     if (!strcmp (schemas[i], name))
541       return g_settings_new (schemas[i]);
542   }
543
544   return NULL;
545 }
546
547 static void
548 gsettings_key_changed (GSettings *gsettings, const gchar *key, void *user_data)
549 {
550   gboolean new_val = g_settings_get_boolean (gsettings, key);
551   A11yBusLauncher *app = user_data;
552
553   if (!strcmp (key, "toolkit-accessibility"))
554     handle_a11y_enabled_change (_global_app, new_val, FALSE);
555   else if (!strcmp (key, "screen-reader-enabled"))
556     handle_screen_reader_enabled_change (_global_app, new_val, FALSE);
557 }
558
559 int
560 main (int    argc,
561       char **argv)
562 {
563   GError *error = NULL;
564   GMainLoop *loop;
565   GDBusConnection *session_bus;
566   int name_owner_id;
567   gboolean a11y_set = FALSE;
568   gboolean screen_reader_set = FALSE;
569   gint i;
570
571   g_type_init ();
572
573   if (already_running ())
574     return 0;
575
576   _global_app = g_slice_new0 (A11yBusLauncher);
577   _global_app->loop = g_main_loop_new (NULL, FALSE);
578
579   for (i = 1; i < argc; i++)
580     {
581       if (!strcmp (argv[i], "--launch-immediately"))
582         _global_app->launch_immediately = TRUE;
583       else if (sscanf (argv[i], "--a11y=%d", &_global_app->a11y_enabled) == 2)
584         a11y_set = TRUE;
585       else if (sscanf (argv[i], "--screen-reader=%d",
586                        &_global_app->screen_reader_enabled) == 2)
587         screen_reader_set = TRUE;
588     else
589       g_error ("usage: %s [--launch-immediately] [--a11y=0|1] [--screen-reader=0|1]", argv[0]);
590     }
591
592   _global_app->interface_schema = get_schema ("org.gnome.desktop.interface");
593   _global_app->a11y_schema = get_schema ("org.gnome.desktop.a11y.applications");
594
595   if (!a11y_set)
596     {
597       _global_app->a11y_enabled = _global_app->interface_schema
598                                   ? g_settings_get_boolean (_global_app->interface_schema, "toolkit-accessibility")
599                                   : _global_app->launch_immediately;
600     }
601
602   if (!screen_reader_set)
603     {
604       _global_app->screen_reader_enabled = _global_app->a11y_schema
605                                   ? g_settings_get_boolean (_global_app->a11y_schema, "screen-reader-enabled")
606                                   : FALSE;
607     }
608
609   if (_global_app->interface_schema)
610     g_signal_connect (_global_app->interface_schema,
611                       "changed::toolkit-accessibility",
612                       G_CALLBACK (gsettings_key_changed), _global_app);
613
614   if (_global_app->a11y_schema)
615     g_signal_connect (_global_app->a11y_schema,
616                       "changed::screen-reader-enabled",
617                       G_CALLBACK (gsettings_key_changed), _global_app);
618
619   init_sigterm_handling (_global_app);
620
621   introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
622   g_assert (introspection_data != NULL);
623
624   name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
625                                   "org.a11y.Bus",
626                                   G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT,
627                                   on_bus_acquired,
628                                   on_name_acquired,
629                                   on_name_lost,
630                                   _global_app,
631                                   NULL);
632
633   g_main_loop_run (_global_app->loop);
634
635   if (_global_app->a11y_bus_pid > 0)
636     kill (_global_app->a11y_bus_pid, SIGTERM);
637
638   /* Clear the X property if our bus is gone; in the case where e.g. 
639    * GDM is launching a login on an X server it was using before,
640    * we don't want early login processes to pick up the stale address.
641    */
642   {
643     Display *display = XOpenDisplay (NULL);
644     if (display)
645       {
646         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
647         XDeleteProperty (display,
648                          XDefaultRootWindow (display),
649                          bus_address_atom);
650
651         XFlush (display);
652         XCloseDisplay (display);
653       }
654   }
655
656   if (_global_app->a11y_launch_error_message)
657     {
658       g_printerr ("Failed to launch bus: %s", _global_app->a11y_launch_error_message);
659       return 1;
660     }
661   return 0;
662 }