118379fe6b5f19246a5268501b6f4c50f8d5c8c4
[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 #ifdef HAVE_X11
34 #include <X11/Xlib.h>
35 #include <X11/Xatom.h>
36 #endif
37
38 //TODO: move to vconf/vconf-internal-setting-keys.h?
39 #define VCONFKEY_SETAPPL_ACCESSIBILITY_UNIVERSAL_SWITCH "db/setting/accessibility/universal-switch"
40
41 #define APP_CONTROL_OPERATION_SCREEN_READ "http://tizen.org/appcontrol/operation/read_screen"
42 #define APP_CONTROL_OPERATION_UNIVERSAL_SWITCH "http://tizen.org/appcontrol/operation/universal_switch"
43 #include <appsvc.h>
44 #include <vconf.h>
45
46 //uncomment if you want debug
47 //#ifndef TIZEN_ENGINEER_MODE
48 //#define TIZEN_ENGINEER_MODE
49 //#endif
50 #ifdef LOG_TAG
51 #undef LOG_TAG
52 #endif
53
54 #define LOG_TAG "ATSPI_BUS_LAUNCHER"
55
56 #include <dlog.h>
57 #include <aul.h>
58
59 //uncomment this if you want log suring startup
60 //seems like dlog is not working at startup time
61 #define ATSPI_BUS_LAUNCHER_LOG_TO_FILE
62
63 #ifdef ATSPI_BUS_LAUNCHER_LOG_TO_FILE
64 FILE *log_file;
65 #ifdef LOGD
66 #undef LOGD
67 #endif
68 #define LOGD(arg...) do {if (log_file) {fprintf(log_file, ##arg);fprintf(log_file, "\n"); fflush(log_file);}} while(0)
69 #endif
70
71 static gboolean _launch_process_repeat_until_success(gpointer user_data);
72
73 typedef enum {
74   A11Y_BUS_STATE_IDLE = 0,
75   A11Y_BUS_STATE_READING_ADDRESS,
76   A11Y_BUS_STATE_RUNNING,
77   A11Y_BUS_STATE_ERROR
78 } A11yBusState;
79
80 typedef struct {
81   const char * name;
82   const char * app_control_operation;
83   const char * vconf_key;
84   int launch_repeats;
85   int pid;
86 } A11yBusClient;
87
88 typedef struct {
89   GMainLoop *loop;
90   gboolean launch_immediately;
91   gboolean a11y_enabled;
92   gboolean screen_reader_enabled;
93   GHashTable *client_watcher_id;
94   GDBusConnection *session_bus;
95   GSettings *a11y_schema;
96   GSettings *interface_schema;
97
98   A11yBusClient screen_reader;
99   A11yBusClient universal_switch;
100
101   GDBusProxy *client_proxy;
102
103   A11yBusState state;
104
105   /* -1 == error, 0 == pending, > 0 == running */
106   int a11y_bus_pid;
107   char *a11y_bus_address;
108   int pipefd[2];
109   char *a11y_launch_error_message;
110 } A11yBusLauncher;
111
112 static A11yBusLauncher *_global_app = NULL;
113
114 static const gchar introspection_xml[] =
115   "<node>"
116   "  <interface name='org.a11y.Bus'>"
117   "    <method name='GetAddress'>"
118   "      <arg type='s' name='address' direction='out'/>"
119   "    </method>"
120   "  </interface>"
121   "<interface name='org.a11y.Status'>"
122   "<property name='IsEnabled' type='b' access='readwrite'/>"
123   "<property name='ScreenReaderEnabled' type='b' access='readwrite'/>"
124   "</interface>"
125   "</node>";
126 static GDBusNodeInfo *introspection_data = NULL;
127
128 static void
129 respond_to_end_session (GDBusProxy *proxy)
130 {
131   GVariant *parameters;
132
133   parameters = g_variant_new ("(bs)", TRUE, "");
134
135   g_dbus_proxy_call (proxy,
136                      "EndSessionResponse", parameters,
137                      G_DBUS_CALL_FLAGS_NONE,
138                      -1, NULL, NULL, NULL);
139 }
140
141 static void
142 g_signal_cb (GDBusProxy *proxy,
143              gchar      *sender_name,
144              gchar      *signal_name,
145              GVariant   *parameters,
146              gpointer    user_data)
147 {
148   A11yBusLauncher *app = user_data;
149
150   if (g_strcmp0 (signal_name, "QueryEndSession") == 0)
151     respond_to_end_session (proxy);
152   else if (g_strcmp0 (signal_name, "EndSession") == 0)
153     respond_to_end_session (proxy);
154   else if (g_strcmp0 (signal_name, "Stop") == 0)
155     g_main_loop_quit (app->loop);
156 }
157
158 static void
159 client_proxy_ready_cb (GObject      *source_object,
160                        GAsyncResult *res,
161                        gpointer      user_data)
162 {
163   A11yBusLauncher *app = user_data;
164   GError *error = NULL;
165
166   app->client_proxy = g_dbus_proxy_new_for_bus_finish (res, &error);
167
168   if (error != NULL)
169     {
170       g_warning ("Failed to get a client proxy: %s", error->message);
171       g_error_free (error);
172
173       return;
174     }
175
176   g_signal_connect (app->client_proxy, "g-signal",
177                     G_CALLBACK (g_signal_cb), app);
178 }
179
180 static void
181 register_client (A11yBusLauncher *app)
182 {
183   GDBusProxyFlags flags;
184   GDBusProxy *sm_proxy;
185   GError *error;
186   const gchar *app_id;
187   const gchar *autostart_id;
188   gchar *client_startup_id;
189   GVariant *parameters;
190   GVariant *variant;
191   gchar *object_path;
192
193   flags = G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
194           G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS;
195
196   error = NULL;
197   sm_proxy = g_dbus_proxy_new_sync (app->session_bus, flags, NULL,
198                                     "org.gnome.SessionManager",
199                                     "/org/gnome/SessionManager",
200                                     "org.gnome.SessionManager",
201                                     NULL, &error);
202
203   if (error != NULL)
204     {
205       g_warning ("Failed to get session manager proxy: %s", error->message);
206       g_error_free (error);
207
208       return;
209     }
210
211   app_id = "at-spi-bus-launcher";
212   autostart_id = g_getenv ("DESKTOP_AUTOSTART_ID");
213
214   if (autostart_id != NULL)
215     {
216       client_startup_id = g_strdup (autostart_id);
217       g_unsetenv ("DESKTOP_AUTOSTART_ID");
218     }
219   else
220     {
221       client_startup_id = g_strdup ("");
222     }
223
224   parameters = g_variant_new ("(ss)", app_id, client_startup_id);
225   g_free (client_startup_id);
226
227   error = NULL;
228   variant = g_dbus_proxy_call_sync (sm_proxy,
229                                     "RegisterClient", parameters,
230                                     G_DBUS_CALL_FLAGS_NONE,
231                                     -1, NULL, &error);
232
233   g_object_unref (sm_proxy);
234
235   if (error != NULL)
236     {
237       g_warning ("Failed to register client: %s", error->message);
238       g_error_free (error);
239
240       return;
241     }
242
243   g_variant_get (variant, "(o)", &object_path);
244   g_variant_unref (variant);
245
246   flags = G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES;
247   g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION, flags, NULL,
248                             "org.gnome.SessionManager", object_path,
249                             "org.gnome.SessionManager.ClientPrivate",
250                             NULL, client_proxy_ready_cb, app);
251
252   g_free (object_path);
253 }
254
255 static void
256 name_appeared_handler (GDBusConnection *connection,
257                        const gchar     *name,
258                        const gchar     *name_owner,
259                        gpointer         user_data)
260 {
261   A11yBusLauncher *app = user_data;
262
263   register_client (app);
264 }
265
266 static void
267 setup_bus_child (gpointer data)
268 {
269   A11yBusLauncher *app = data;
270   (void) app;
271
272   close (app->pipefd[0]);
273   dup2 (app->pipefd[1], 3);
274   close (app->pipefd[1]);
275
276   /* On Linux, tell the bus process to exit if this process goes away */
277 #ifdef __linux
278 #include <sys/prctl.h>
279   prctl (PR_SET_PDEATHSIG, 15);
280 #endif
281 }
282
283 /**
284  * unix_read_all_fd_to_string:
285  *
286  * Read all data from a file descriptor to a C string buffer.
287  */
288 static gboolean
289 unix_read_all_fd_to_string (int      fd,
290                             char    *buf,
291                             ssize_t  max_bytes)
292 {
293   ssize_t bytes_read;
294
295   while (max_bytes > 1 && (bytes_read = read (fd, buf, MAX (4096, max_bytes - 1))))
296     {
297       if (bytes_read < 0)
298         return FALSE;
299       buf += bytes_read;
300       max_bytes -= bytes_read;
301     }
302   *buf = '\0';
303   return TRUE;
304 }
305
306 static void
307 on_bus_exited (GPid     pid,
308                gint     status,
309                gpointer data)
310 {
311   A11yBusLauncher *app = data;
312
313   app->a11y_bus_pid = -1;
314   app->state = A11Y_BUS_STATE_ERROR;
315   if (app->a11y_launch_error_message == NULL)
316     {
317       if (WIFEXITED (status))
318         app->a11y_launch_error_message = g_strdup_printf ("Bus exited with code %d", WEXITSTATUS (status));
319       else if (WIFSIGNALED (status))
320         app->a11y_launch_error_message = g_strdup_printf ("Bus killed by signal %d", WTERMSIG (status));
321       else if (WIFSTOPPED (status))
322         app->a11y_launch_error_message = g_strdup_printf ("Bus stopped by signal %d", WSTOPSIG (status));
323     }
324   g_main_loop_quit (app->loop);
325 }
326
327 static gboolean
328 ensure_a11y_bus (A11yBusLauncher *app)
329 {
330   GPid pid;
331   char *argv[] = { DBUS_DAEMON, NULL, "--nofork", "--print-address", "3", NULL };
332   char addr_buf[2048];
333   GError *error = NULL;
334   const char *config_path = NULL;
335
336   if (app->a11y_bus_pid != 0)
337     return FALSE;
338
339   if (g_file_test (SYSCONFDIR"/at-spi2/accessibility.conf", G_FILE_TEST_EXISTS))
340       config_path = "--config-file="SYSCONFDIR"/at-spi2/accessibility.conf";
341   else
342       config_path = "--config-file="DATADIR"/defaults/at-spi2/accessibility.conf";
343
344   argv[1] = (char*)config_path;
345
346   if (pipe (app->pipefd) < 0)
347     g_error ("Failed to create pipe: %s", strerror (errno));
348
349   if (!g_spawn_async (NULL,
350                       argv,
351                       NULL,
352                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
353                       setup_bus_child,
354                       app,
355                       &pid,
356                       &error))
357     {
358       app->a11y_bus_pid = -1;
359       app->a11y_launch_error_message = g_strdup (error->message);
360       g_clear_error (&error);
361       goto error;
362     }
363
364   close (app->pipefd[1]);
365   app->pipefd[1] = -1;
366
367   g_child_watch_add (pid, on_bus_exited, app);
368
369   app->state = A11Y_BUS_STATE_READING_ADDRESS;
370   app->a11y_bus_pid = pid;
371   LOGD("Launched a11y bus, child is %ld", (long) pid);
372   if (!unix_read_all_fd_to_string (app->pipefd[0], addr_buf, sizeof (addr_buf)))
373     {
374       app->a11y_launch_error_message = g_strdup_printf ("Failed to read address: %s", strerror (errno));
375       kill (app->a11y_bus_pid, SIGTERM);
376       goto error;
377     }
378   close (app->pipefd[0]);
379   app->pipefd[0] = -1;
380   app->state = A11Y_BUS_STATE_RUNNING;
381
382   /* Trim the trailing newline */
383   app->a11y_bus_address = g_strchomp (g_strdup (addr_buf));
384   LOGD("a11y bus address: %s", app->a11y_bus_address);
385
386 #ifdef HAVE_X11
387   {
388     Display *display = XOpenDisplay (NULL);
389     if (display)
390       {
391         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
392         XChangeProperty (display,
393                          XDefaultRootWindow (display),
394                          bus_address_atom,
395                          XA_STRING, 8, PropModeReplace,
396                          (guchar *) app->a11y_bus_address, strlen (app->a11y_bus_address));
397         XFlush (display);
398         XCloseDisplay (display);
399       }
400   }
401 #endif
402
403   return TRUE;
404
405  error:
406   close (app->pipefd[0]);
407   close (app->pipefd[1]);
408   app->state = A11Y_BUS_STATE_ERROR;
409
410   return FALSE;
411 }
412
413 static void
414 handle_method_call (GDBusConnection       *connection,
415                     const gchar           *sender,
416                     const gchar           *object_path,
417                     const gchar           *interface_name,
418                     const gchar           *method_name,
419                     GVariant              *parameters,
420                     GDBusMethodInvocation *invocation,
421                     gpointer               user_data)
422 {
423   A11yBusLauncher *app = user_data;
424
425   if (g_strcmp0 (method_name, "GetAddress") == 0)
426     {
427       ensure_a11y_bus (app);
428       if (app->a11y_bus_pid > 0)
429         g_dbus_method_invocation_return_value (invocation,
430                                                g_variant_new ("(s)", app->a11y_bus_address));
431       else
432         g_dbus_method_invocation_return_dbus_error (invocation,
433                                                     "org.a11y.Bus.Error",
434                                                     app->a11y_launch_error_message);
435     }
436 }
437
438 static GVariant *
439 handle_get_property  (GDBusConnection       *connection,
440                       const gchar           *sender,
441                       const gchar           *object_path,
442                       const gchar           *interface_name,
443                       const gchar           *property_name,
444                     GError **error,
445                     gpointer               user_data)
446 {
447   A11yBusLauncher *app = user_data;
448
449   if (g_strcmp0 (property_name, "IsEnabled") == 0)
450     return g_variant_new ("b", app->a11y_enabled);
451   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
452     return g_variant_new ("b", app->screen_reader_enabled);
453   else
454     return NULL;
455 }
456
457 static void
458 handle_a11y_enabled_change (A11yBusLauncher *app, gboolean enabled,
459                                gboolean notify_gsettings)
460 {
461   GVariantBuilder builder;
462   GVariantBuilder invalidated_builder;
463
464   if (enabled == app->a11y_enabled)
465     return;
466
467   app->a11y_enabled = enabled;
468
469   if (notify_gsettings && app->interface_schema)
470     {
471       g_settings_set_boolean (app->interface_schema, "toolkit-accessibility",
472                               enabled);
473       g_settings_sync ();
474     }
475
476   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
477   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
478   g_variant_builder_add (&builder, "{sv}", "IsEnabled",
479                          g_variant_new_boolean (enabled));
480
481   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
482                                  "org.freedesktop.DBus.Properties",
483                                  "PropertiesChanged",
484                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
485                                                 &builder,
486                                                 &invalidated_builder),
487                                  NULL);
488
489   g_variant_builder_clear (&builder);
490   g_variant_builder_clear (&invalidated_builder);
491 }
492
493 static void
494 handle_screen_reader_enabled_change (A11yBusLauncher *app, gboolean enabled,
495                                gboolean notify_gsettings)
496 {
497   GVariantBuilder builder;
498   GVariantBuilder invalidated_builder;
499
500   if (enabled == app->screen_reader_enabled)
501     return;
502
503   app->screen_reader_enabled = enabled;
504
505   if (notify_gsettings && app->a11y_schema)
506     {
507       g_settings_set_boolean (app->a11y_schema, "screen-reader-enabled",
508                               enabled);
509       g_settings_sync ();
510     }
511
512   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
513   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
514   g_variant_builder_add (&builder, "{sv}", "ScreenReaderEnabled",
515                          g_variant_new_boolean (enabled));
516
517   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
518                                  "org.freedesktop.DBus.Properties",
519                                  "PropertiesChanged",
520                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
521                                                 &builder,
522                                                 &invalidated_builder),
523                                  NULL);
524   g_variant_builder_clear (&builder);
525   g_variant_builder_clear (&invalidated_builder);
526 }
527
528 static gboolean
529 is_client_connected(A11yBusLauncher *app)
530 {
531   guint watchers = g_hash_table_size(app->client_watcher_id);
532   LOGD("clients connected: %d", watchers);
533   return watchers > 0;
534 }
535
536 static void
537 remove_client_watch(A11yBusLauncher *app,
538                                   const gchar     *sender)
539 {
540   LOGD("Remove client watcher for %s", sender);
541   guint watcher_id = GPOINTER_TO_UINT(g_hash_table_lookup(app->client_watcher_id, sender));
542   if (watcher_id)
543     g_bus_unwatch_name(watcher_id);
544
545   g_hash_table_remove(app->client_watcher_id, sender);
546   if (!is_client_connected(app))
547     handle_a11y_enabled_change (app, FALSE, TRUE);
548 }
549
550 static void
551 on_client_name_vanished (GDBusConnection *connection,
552                                        const gchar     *name,
553                                        gpointer         user_data)
554 {
555   A11yBusLauncher *app = user_data;
556   remove_client_watch(app, name);
557 }
558
559 static void
560 add_client_watch(A11yBusLauncher *app,
561                                const gchar     *sender)
562 {
563   LOGD("Add client watcher for %s", sender);
564
565   if (g_hash_table_contains(app->client_watcher_id, sender))
566     {
567       LOGI("Watcher for %s already registered", sender);
568       return;
569     }
570
571   guint watcher_id = g_bus_watch_name(G_BUS_TYPE_SESSION,
572                      sender,
573                      G_BUS_NAME_WATCHER_FLAGS_NONE,
574                      NULL,
575                      on_client_name_vanished,
576                      app,
577                      NULL);
578
579   g_hash_table_insert(app->client_watcher_id, g_strdup(sender), GUINT_TO_POINTER(watcher_id));
580   handle_a11y_enabled_change (app, TRUE, TRUE);
581 }
582
583 static gboolean
584 handle_set_property  (GDBusConnection       *connection,
585                       const gchar           *sender,
586                       const gchar           *object_path,
587                       const gchar           *interface_name,
588                       const gchar           *property_name,
589                       GVariant *value,
590                     GError **error,
591                     gpointer               user_data)
592 {
593   A11yBusLauncher *app = user_data;
594   const gchar *type = g_variant_get_type_string (value);
595   gboolean enabled;
596
597   if (g_strcmp0 (type, "b") != 0)
598     {
599       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
600                        "org.a11y.Status.%s expects a boolean but got %s", property_name, type);
601       return FALSE;
602     }
603
604   enabled = g_variant_get_boolean (value);
605
606   if (g_strcmp0 (property_name, "IsEnabled") == 0)
607     {
608       if (enabled)
609         add_client_watch(app, sender);
610       else
611         remove_client_watch(app, sender);
612       return TRUE;
613     }
614   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
615     {
616       handle_screen_reader_enabled_change (app, enabled, TRUE);
617       return TRUE;
618     }
619   else
620     {
621       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
622                        "Unknown property '%s'", property_name);
623       return FALSE;
624     }
625 }
626
627 static const GDBusInterfaceVTable bus_vtable =
628 {
629   handle_method_call,
630   NULL, /* handle_get_property, */
631   NULL  /* handle_set_property */
632 };
633
634 static const GDBusInterfaceVTable status_vtable =
635 {
636   NULL, /* handle_method_call */
637   handle_get_property,
638   handle_set_property
639 };
640
641 static void
642 on_bus_acquired (GDBusConnection *connection,
643                  const gchar     *name,
644                  gpointer         user_data)
645 {
646   A11yBusLauncher *app = user_data;
647   GError *error;
648   guint registration_id;
649
650   if (connection == NULL)
651     {
652       g_main_loop_quit (app->loop);
653       return;
654     }
655   app->session_bus = connection;
656
657   if (app->launch_immediately)
658     {
659       ensure_a11y_bus (app);
660       if (app->state == A11Y_BUS_STATE_ERROR)
661         {
662           g_main_loop_quit (app->loop);
663           return;
664         }
665     }
666
667   error = NULL;
668   registration_id = g_dbus_connection_register_object (connection,
669                                                        "/org/a11y/bus",
670                                                        introspection_data->interfaces[0],
671                                                        &bus_vtable,
672                                                        _global_app,
673                                                        NULL,
674                                                        &error);
675   if (registration_id == 0)
676     {
677       g_error ("%s", error->message);
678       g_clear_error (&error);
679     }
680
681   g_dbus_connection_register_object (connection,
682                                      "/org/a11y/bus",
683                                      introspection_data->interfaces[1],
684                                      &status_vtable,
685                                      _global_app,
686                                      NULL,
687                                      NULL);
688 }
689
690 static void
691 on_name_lost (GDBusConnection *connection,
692               const gchar     *name,
693               gpointer         user_data)
694 {
695   A11yBusLauncher *app = user_data;
696   if (app->session_bus == NULL
697       && connection == NULL
698       && app->a11y_launch_error_message == NULL)
699     app->a11y_launch_error_message = g_strdup ("Failed to connect to session bus");
700   g_main_loop_quit (app->loop);
701 }
702
703 static void
704 on_name_acquired (GDBusConnection *connection,
705                   const gchar     *name,
706                   gpointer         user_data)
707 {
708   g_bus_watch_name (G_BUS_TYPE_SESSION,
709                     "org.gnome.SessionManager",
710                     G_BUS_NAME_WATCHER_FLAGS_NONE,
711                     name_appeared_handler, NULL,
712                     user_data, NULL);
713 }
714
715 static int sigterm_pipefd[2];
716
717 static void
718 sigterm_handler (int signum)
719 {
720   write (sigterm_pipefd[1], "X", 1);
721 }
722
723 static gboolean
724 on_sigterm_pipe (GIOChannel  *channel,
725                  GIOCondition condition,
726                  gpointer     data)
727 {
728   A11yBusLauncher *app = data;
729
730   g_main_loop_quit (app->loop);
731
732   return FALSE;
733 }
734
735 static void
736 init_sigterm_handling (A11yBusLauncher *app)
737 {
738   GIOChannel *sigterm_channel;
739
740   if (pipe (sigterm_pipefd) < 0)
741     g_error ("Failed to create pipe: %s", strerror (errno));
742   signal (SIGTERM, sigterm_handler);
743
744   sigterm_channel = g_io_channel_unix_new (sigterm_pipefd[0]);
745   g_io_add_watch (sigterm_channel,
746                   G_IO_IN | G_IO_ERR | G_IO_HUP,
747                   on_sigterm_pipe,
748                   app);
749 }
750
751 static gboolean
752 already_running ()
753 {
754 #ifdef HAVE_X11
755   Atom AT_SPI_BUS;
756   Atom actual_type;
757   Display *bridge_display;
758   int actual_format;
759   unsigned char *data = NULL;
760   unsigned long nitems;
761   unsigned long leftover;
762   gboolean result = FALSE;
763
764   bridge_display = XOpenDisplay (NULL);
765   if (!bridge_display)
766               return FALSE;
767
768   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
769   XGetWindowProperty (bridge_display,
770                       XDefaultRootWindow (bridge_display),
771                       AT_SPI_BUS, 0L,
772                       (long) BUFSIZ, False,
773                       (Atom) 31, &actual_type, &actual_format,
774                       &nitems, &leftover, &data);
775
776   if (data)
777   {
778     GDBusConnection *bus;
779     bus = g_dbus_connection_new_for_address_sync ((const gchar *)data, 0,
780                                                   NULL, NULL, NULL);
781     if (bus != NULL)
782       {
783         result = TRUE;
784         g_object_unref (bus);
785       }
786   }
787
788   XCloseDisplay (bridge_display);
789   return result;
790 #else
791   return FALSE;
792 #endif
793 }
794
795 static GSettings *
796 get_schema (const gchar *name)
797 {
798   const char * const *schemas = NULL;
799   gint i;
800
801   schemas = g_settings_list_schemas ();
802   for (i = 0; schemas[i]; i++)
803   {
804     if (!strcmp (schemas[i], name))
805       return g_settings_new (schemas[i]);
806   }
807
808   return NULL;
809 }
810
811 static void
812 gsettings_key_changed (GSettings *gsettings, const gchar *key, void *user_data)
813 {
814   gboolean new_val = g_settings_get_boolean (gsettings, key);
815
816   if (!strcmp (key, "toolkit-accessibility"))
817     handle_a11y_enabled_change (_global_app, new_val, FALSE);
818   else if (!strcmp (key, "screen-reader-enabled"))
819     handle_screen_reader_enabled_change (_global_app, new_val, FALSE);
820 }
821
822 static int
823 _process_dead_tracker (int pid, void *data)
824 {
825   A11yBusLauncher *app = data;
826
827   if (app->screen_reader.pid > 0 && pid == app->screen_reader.pid)
828     {
829       LOGE("screen reader is dead, pid: %d, restarting", pid);
830       app->screen_reader.pid = 0;
831       g_timeout_add_seconds (2, _launch_process_repeat_until_success, &app->screen_reader);
832     }
833
834   if (app->universal_switch.pid > 0 && pid == app->universal_switch.pid)
835     {
836       LOGE("universal switch is dead, pid: %d, restarting", pid);
837       app->universal_switch.pid = 0;
838       g_timeout_add_seconds (2, _launch_process_repeat_until_success, &app->universal_switch);
839     }
840   return 0;
841 }
842
843 static void
844 _register_process_dead_tracker ()
845 {
846         if(_global_app->screen_reader.pid > 0 || _global_app->universal_switch.pid > 0) {
847                 LOGD("registering process dead tracker");
848                 aul_listen_app_dead_signal(_process_dead_tracker, _global_app);
849         } else {
850                 LOGD("unregistering process dead tracker");
851                 aul_listen_app_dead_signal(NULL, NULL);
852         }
853 }
854
855
856 static gboolean
857 _launch_client(A11yBusClient *client, gboolean by_vconf_change)
858 {
859    LOGD("Launching %s", client->name);
860
861    bundle *kb = NULL;
862    gboolean ret = FALSE;
863
864    kb = bundle_create();
865
866    if (kb == NULL)
867      {
868         LOGD("Can't create bundle");
869         return FALSE;
870      }
871
872    if (by_vconf_change)
873      {
874         if (bundle_add_str(kb, "by_vconf_change", "yes") != BUNDLE_ERROR_NONE)
875           {
876              LOGD("Can't add information to bundle");
877           }
878      }
879
880    int operation_error = appsvc_set_operation(kb, client->app_control_operation);
881    LOGD("appsvc_set_operation: %i", operation_error);
882
883    client->pid = appsvc_run_service(kb, 0, NULL, NULL);
884
885    if (client->pid > 0)
886      {
887         LOGD("Process launched with pid: %i", client->pid);
888         _register_process_dead_tracker();
889         ret = TRUE;
890      }
891    else
892      {
893         LOGD("Can't start %s - error code: %i", client->name, client->pid);
894      }
895
896    bundle_free(kb);
897    return ret;
898 }
899
900 static gboolean
901 _launch_process_repeat_until_success(gpointer user_data) {
902     A11yBusClient *client = user_data;
903
904     if (client->launch_repeats > 100 || client->pid > 0)
905       {
906          //do not try anymore
907          return FALSE;
908       }
909
910     gboolean ret = _launch_client(client, FALSE);
911
912     if (ret)
913       {
914          //we managed to
915          client->launch_repeats = 0;
916          return FALSE;
917       }
918     client->launch_repeats++;
919     //try again
920     return TRUE;
921 }
922
923 static gboolean
924 _terminate_process(int pid)
925 {
926    int ret;
927    int ret_aul;
928    if (pid <= 0)
929      return FALSE;
930
931    int status = aul_app_get_status_bypid(pid);
932
933    if (status < 0)
934      {
935        LOGD("App with pid %d already terminated", pid);
936        return TRUE;
937      }
938
939    LOGD("terminate process with pid %d", pid);
940    ret_aul = aul_terminate_pid(pid);
941    if (ret_aul >= 0)
942      {
943         LOGD("Terminating with aul_terminate_pid: return is %d", ret_aul);
944         return TRUE;
945      }
946    else
947      LOGD("aul_terminate_pid failed: return is %d", ret_aul);
948
949    LOGD("Unable to terminate process using aul api. Sending SIGTERM signal");
950    ret = kill(pid, SIGTERM);
951    if (!ret)
952      {
953         return TRUE;
954      }
955
956    LOGD("Unable to terminate process: %d with api or signal.", pid);
957    return FALSE;
958 }
959
960 static gboolean
961 _terminate_client(A11yBusClient *client)
962 {
963    LOGD("Terminating %s", client->name);
964    int pid = client->pid;
965    client->pid = 0;
966    _register_process_dead_tracker();
967    gboolean ret = _terminate_process(pid);
968    return ret;
969 }
970
971 void vconf_client_cb(keynode_t *node, void *user_data)
972 {
973    A11yBusClient *client = user_data;
974    int client_needed = vconf_keynode_get_bool(node);
975    LOGD("vconf_keynode_get_bool(node): %i", client_needed);
976    if (client_needed < 0)
977      return;
978
979    //check if process really exists (e.g didn't crash)
980    if (client->pid > 0)
981      {
982         int err = kill(client->pid,0);
983         //process doesn't exist
984         if (err == ESRCH)
985           client->pid = 0;
986      }
987
988    LOGD("client_needed: %i, client->pid: %i", client_needed, client->pid);
989    if (!client_needed && (client->pid > 0))
990            _terminate_client(client);
991    else if (client_needed && (client->pid <= 0))
992      _launch_client(client, TRUE);
993 }
994
995
996 static gboolean register_executable(A11yBusClient *client)
997 {
998   gboolean client_needed = FALSE;
999
1000   if(!client->vconf_key) {
1001           LOGE("Vconf_key missing for client: %s \n", client->vconf_key);
1002           return FALSE;
1003   }
1004
1005   int ret = vconf_get_bool(client->vconf_key, &client_needed);
1006   if (ret != 0)
1007         {
1008           LOGD("Could not read %s key value.\n", client->vconf_key);
1009           return FALSE;
1010         }
1011   ret = vconf_notify_key_changed(client->vconf_key, vconf_client_cb, client);
1012   if(ret != 0)
1013         {
1014           LOGD("Could not add information level callback\n");
1015           return FALSE;
1016         }
1017
1018   if (client_needed)
1019         g_timeout_add_seconds(2,_launch_process_repeat_until_success, client);
1020   return TRUE;
1021 }
1022
1023 int
1024 main (int    argc,
1025       char **argv)
1026 {
1027 #ifdef ATSPI_BUS_LAUNCHER_LOG_TO_FILE
1028   log_file = fopen("/tmp/at-spi-bus-launcher.log", "a");
1029 #endif
1030
1031   LOGD("Starting atspi bus launcher");
1032   gboolean a11y_set = FALSE;
1033   gboolean screen_reader_set = FALSE;
1034   gint i;
1035
1036   if (already_running ())
1037     {
1038        LOGD("atspi bus launcher is already running");
1039        return 0;
1040     }
1041
1042   _global_app = g_slice_new0 (A11yBusLauncher);
1043   _global_app->loop = g_main_loop_new (NULL, FALSE);
1044   _global_app->client_watcher_id = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
1045
1046   _global_app->screen_reader.name = "screen-reader";
1047   _global_app->screen_reader.app_control_operation = APP_CONTROL_OPERATION_SCREEN_READ;
1048   _global_app->screen_reader.vconf_key = VCONFKEY_SETAPPL_ACCESSIBILITY_TTS;
1049
1050   _global_app->universal_switch.name = "universal-switch";
1051   _global_app->universal_switch.app_control_operation = APP_CONTROL_OPERATION_UNIVERSAL_SWITCH;
1052   _global_app->universal_switch.vconf_key = VCONFKEY_SETAPPL_ACCESSIBILITY_UNIVERSAL_SWITCH;
1053
1054   for (i = 1; i < argc; i++)
1055     {
1056       if (!strcmp (argv[i], "--launch-immediately"))
1057         _global_app->launch_immediately = TRUE;
1058       else if (sscanf (argv[i], "--a11y=%d", &_global_app->a11y_enabled) == 1)
1059         a11y_set = TRUE;
1060       else if (sscanf (argv[i], "--screen-reader=%d",
1061                        &_global_app->screen_reader_enabled) == 1)
1062         screen_reader_set = TRUE;
1063     else
1064       g_error ("usage: %s [--launch-immediately] [--a11y=0|1] [--screen-reader=0|1]", argv[0]);
1065     }
1066
1067   _global_app->interface_schema = get_schema ("org.gnome.desktop.interface");
1068   _global_app->a11y_schema = get_schema ("org.gnome.desktop.a11y.applications");
1069
1070   if (!a11y_set)
1071     {
1072       _global_app->a11y_enabled = _global_app->interface_schema
1073                                   ? g_settings_get_boolean (_global_app->interface_schema, "toolkit-accessibility")
1074                                   : _global_app->launch_immediately;
1075     }
1076
1077   if (!screen_reader_set)
1078     {
1079       _global_app->screen_reader_enabled = _global_app->a11y_schema
1080                                   ? g_settings_get_boolean (_global_app->a11y_schema, "screen-reader-enabled")
1081                                   : FALSE;
1082     }
1083
1084   if (_global_app->interface_schema)
1085     g_signal_connect (_global_app->interface_schema,
1086                       "changed::toolkit-accessibility",
1087                       G_CALLBACK (gsettings_key_changed), _global_app);
1088
1089   if (_global_app->a11y_schema)
1090     g_signal_connect (_global_app->a11y_schema,
1091                       "changed::screen-reader-enabled",
1092                       G_CALLBACK (gsettings_key_changed), _global_app);
1093
1094   init_sigterm_handling (_global_app);
1095
1096   introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
1097   g_assert (introspection_data != NULL);
1098
1099   g_bus_own_name (G_BUS_TYPE_SESSION,
1100                                   "org.a11y.Bus",
1101                                   G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT,
1102                                   on_bus_acquired,
1103                                   on_name_acquired,
1104                                   on_name_lost,
1105                                   _global_app,
1106                                   NULL);
1107
1108   register_executable (&_global_app->screen_reader);
1109   register_executable (&_global_app->universal_switch);
1110
1111   g_main_loop_run (_global_app->loop);
1112
1113   if (_global_app->a11y_bus_pid > 0)
1114     kill (_global_app->a11y_bus_pid, SIGTERM);
1115
1116   /* Clear the X property if our bus is gone; in the case where e.g.
1117    * GDM is launching a login on an X server it was using before,
1118    * we don't want early login processes to pick up the stale address.
1119    */
1120 #ifdef HAVE_X11
1121   {
1122     Display *display = XOpenDisplay (NULL);
1123     if (display)
1124       {
1125         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
1126         XDeleteProperty (display,
1127                          XDefaultRootWindow (display),
1128                          bus_address_atom);
1129
1130         XFlush (display);
1131         XCloseDisplay (display);
1132       }
1133   }
1134 #endif
1135
1136   if (_global_app->a11y_launch_error_message)
1137     {
1138       g_printerr ("Failed to launch bus: %s", _global_app->a11y_launch_error_message);
1139       return 1;
1140     }
1141   return 0;
1142 }