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