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