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