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