add screen-reader dead tracker to at-spi-bus-launcher
[platform/upstream/at-spi2-core.git] / bus / at-spi-bus-launcher.c
index 76b7060..87b2da7 100644 (file)
@@ -1,6 +1,6 @@
 /* -*- mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
- * 
- * at-spi-bus-launcher: Manage the a11y bus as a child process 
+ *
+ * at-spi-bus-launcher: Manage the a11y bus as a child process
  *
  * Copyright 2011 Red Hat, Inc.
  *
 #include <stdio.h>
 
 #include <gio/gio.h>
+#ifdef HAVE_X11
 #include <X11/Xlib.h>
 #include <X11/Xatom.h>
+#endif
+
+#define APP_CONTROL_OPERATION_SCREEN_READ "http://tizen.org/appcontrol/operation/read_screen"
+#include <appsvc.h>
+#include <vconf.h>
+
+//uncomment if you want debug
+//#ifndef TIZEN_ENGINEER_MODE
+//#define TIZEN_ENGINEER_MODE
+//#endif
+#ifdef LOG_TAG
+#undef LOG_TAG
+#endif
+
+#define LOG_TAG "ATSPI_BUS_LAUNCHER"
+
+#include <dlog.h>
+#include <aul.h>
+
+//uncomment this if you want log suring startup
+//seems like dlog is not working at startup time
+#define ATSPI_BUS_LAUNCHER_LOG_TO_FILE
+
+#ifdef ATSPI_BUS_LAUNCHER_LOG_TO_FILE
+FILE *log_file;
+#ifdef LOGD
+#undef LOGD
+#endif
+#define LOGD(arg...) do {if (log_file) {fprintf(log_file, ##arg);fprintf(log_file, "\n"); fflush(log_file);}} while(0)
+#endif
+
+static gboolean _launch_screen_reader_repeat_until_success(gpointer user_data);
 
 typedef enum {
   A11Y_BUS_STATE_IDLE = 0,
@@ -43,9 +76,18 @@ typedef enum {
 typedef struct {
   GMainLoop *loop;
   gboolean launch_immediately;
+  gboolean a11y_enabled;
+  gboolean screen_reader_enabled;
   GDBusConnection *session_bus;
+  GSettings *a11y_schema;
+  GSettings *interface_schema;
+
+  int launch_screen_reader_repeats;
+  gboolean screen_reader_needed;
+  int pid;
 
   A11yBusState state;
+
   /* -1 == error, 0 == pending, > 0 == running */
   int a11y_bus_pid;
   char *a11y_bus_address;
@@ -63,7 +105,8 @@ static const gchar introspection_xml[] =
   "    </method>"
   "  </interface>"
   "<interface name='org.a11y.Status'>"
-  "<property name='IsEnabled' type='b' access='read'/>"
+  "<property name='IsEnabled' type='b' access='readwrite'/>"
+  "<property name='ScreenReaderEnabled' type='b' access='readwrite'/>"
   "</interface>"
   "</node>";
 static GDBusNodeInfo *introspection_data = NULL;
@@ -82,7 +125,7 @@ setup_bus_child (gpointer data)
 #ifdef __linux
 #include <sys/prctl.h>
   prctl (PR_SET_PDEATHSIG, 15);
-#endif  
+#endif
 }
 
 /**
@@ -114,7 +157,7 @@ on_bus_exited (GPid     pid,
                gpointer data)
 {
   A11yBusLauncher *app = data;
-  
+
   app->a11y_bus_pid = -1;
   app->state = A11Y_BUS_STATE_ERROR;
   if (app->a11y_launch_error_message == NULL)
@@ -127,9 +170,9 @@ on_bus_exited (GPid     pid,
         app->a11y_launch_error_message = g_strdup_printf ("Bus stopped by signal %d", WSTOPSIG (status));
     }
   g_main_loop_quit (app->loop);
-} 
+}
 
-static void
+static gboolean
 ensure_a11y_bus (A11yBusLauncher *app)
 {
   GPid pid;
@@ -138,13 +181,13 @@ ensure_a11y_bus (A11yBusLauncher *app)
   GError *error = NULL;
 
   if (app->a11y_bus_pid != 0)
-    return;
-  
+    return FALSE;
+
   argv[1] = g_strdup_printf ("--config-file=%s/at-spi2/accessibility.conf", SYSCONFDIR);
 
   if (pipe (app->pipefd) < 0)
     g_error ("Failed to create pipe: %s", strerror (errno));
-  
+
   if (!g_spawn_async (NULL,
                       argv,
                       NULL,
@@ -167,7 +210,7 @@ ensure_a11y_bus (A11yBusLauncher *app)
 
   app->state = A11Y_BUS_STATE_READING_ADDRESS;
   app->a11y_bus_pid = pid;
-  g_debug ("Launched a11y bus, child is %ld", (long) pid);
+  LOGD("Launched a11y bus, child is %ld", (long) pid);
   if (!unix_read_all_fd_to_string (app->pipefd[0], addr_buf, sizeof (addr_buf)))
     {
       app->a11y_launch_error_message = g_strdup_printf ("Failed to read address: %s", strerror (errno));
@@ -180,8 +223,9 @@ ensure_a11y_bus (A11yBusLauncher *app)
 
   /* Trim the trailing newline */
   app->a11y_bus_address = g_strchomp (g_strdup (addr_buf));
-  g_debug ("a11y bus address: %s", app->a11y_bus_address);
+  LOGD("a11y bus address: %s", app->a11y_bus_address);
 
+#ifdef HAVE_X11
   {
     Display *display = XOpenDisplay (NULL);
     if (display)
@@ -196,13 +240,19 @@ ensure_a11y_bus (A11yBusLauncher *app)
         XCloseDisplay (display);
       }
   }
+#endif
+
+  if (argv[1]) g_free(argv[1]);
+
+  return TRUE;
 
-  return;
-  
  error:
+  if (argv[1]) g_free(argv[1]);
   close (app->pipefd[0]);
   close (app->pipefd[1]);
   app->state = A11Y_BUS_STATE_ERROR;
+
+  return FALSE;
 }
 
 static void
@@ -242,12 +292,127 @@ handle_get_property  (GDBusConnection       *connection,
   A11yBusLauncher *app = user_data;
 
   if (g_strcmp0 (property_name, "IsEnabled") == 0)
+    return g_variant_new ("b", app->a11y_enabled);
+  else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
+    return g_variant_new ("b", app->screen_reader_enabled);
+  else
+    return NULL;
+}
+
+static void
+handle_a11y_enabled_change (A11yBusLauncher *app, gboolean enabled,
+                               gboolean notify_gsettings)
+{
+  GVariantBuilder builder;
+  GVariantBuilder invalidated_builder;
+
+  if (enabled == app->a11y_enabled)
+    return;
+
+  app->a11y_enabled = enabled;
+
+  if (notify_gsettings && app->interface_schema)
     {
-      gboolean result = (app->a11y_bus_pid > 0);
-      return g_variant_new ("(b)", result);
+      g_settings_set_boolean (app->interface_schema, "toolkit-accessibility",
+                              enabled);
+      g_settings_sync ();
+    }
+
+  g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
+  g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
+  g_variant_builder_add (&builder, "{sv}", "IsEnabled",
+                         g_variant_new_boolean (enabled));
+
+  g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
+                                 "org.freedesktop.DBus.Properties",
+                                 "PropertiesChanged",
+                                 g_variant_new ("(sa{sv}as)", "org.a11y.Status",
+                                                &builder,
+                                                &invalidated_builder),
+                                 NULL);
+  g_variant_builder_clear (&builder);
+  g_variant_builder_clear (&invalidated_builder);
+}
+
+static void
+handle_screen_reader_enabled_change (A11yBusLauncher *app, gboolean enabled,
+                               gboolean notify_gsettings)
+{
+  GVariantBuilder builder;
+  GVariantBuilder invalidated_builder;
+
+  if (enabled == app->screen_reader_enabled)
+    return;
+
+  /* If the screen reader is being enabled, we should enable accessibility
+   * if it isn't enabled already */
+  if (enabled)
+    handle_a11y_enabled_change (app, enabled, notify_gsettings);
+
+  app->screen_reader_enabled = enabled;
+
+  if (notify_gsettings && app->a11y_schema)
+    {
+      g_settings_set_boolean (app->a11y_schema, "screen-reader-enabled",
+                              enabled);
+      g_settings_sync ();
+    }
+
+  g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
+  g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
+  g_variant_builder_add (&builder, "{sv}", "ScreenReaderEnabled",
+                         g_variant_new_boolean (enabled));
+
+  g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
+                                 "org.freedesktop.DBus.Properties",
+                                 "PropertiesChanged",
+                                 g_variant_new ("(sa{sv}as)", "org.a11y.Status",
+                                                &builder,
+                                                &invalidated_builder),
+                                 NULL);
+  g_variant_builder_clear (&builder);
+  g_variant_builder_clear (&invalidated_builder);
+}
+
+static gboolean
+handle_set_property  (GDBusConnection       *connection,
+                      const gchar           *sender,
+                      const gchar           *object_path,
+                      const gchar           *interface_name,
+                      const gchar           *property_name,
+                      GVariant *value,
+                    GError **error,
+                    gpointer               user_data)
+{
+  A11yBusLauncher *app = user_data;
+  const gchar *type = g_variant_get_type_string (value);
+  gboolean enabled;
+
+  if (g_strcmp0 (type, "b") != 0)
+    {
+      g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
+                       "org.a11y.Status.%s expects a boolean but got %s", property_name, type);
+      return FALSE;
+    }
+
+  enabled = g_variant_get_boolean (value);
+
+  if (g_strcmp0 (property_name, "IsEnabled") == 0)
+    {
+      handle_a11y_enabled_change (app, enabled, TRUE);
+      return TRUE;
+    }
+  else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
+    {
+      handle_screen_reader_enabled_change (app, enabled, TRUE);
+      return TRUE;
     }
   else
-    return NULL;
+    {
+      g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
+                       "Unknown property '%s'", property_name);
+      return FALSE;
+    }
 }
 
 static const GDBusInterfaceVTable bus_vtable =
@@ -261,7 +426,7 @@ static const GDBusInterfaceVTable status_vtable =
 {
   NULL, /* handle_method_call */
   handle_get_property,
-  NULL  /* handle_set_property */
+  handle_set_property
 };
 
 static void
@@ -272,7 +437,7 @@ on_bus_acquired (GDBusConnection *connection,
   A11yBusLauncher *app = user_data;
   GError *error;
   guint registration_id;
-  
+
   if (connection == NULL)
     {
       g_main_loop_quit (app->loop);
@@ -299,15 +464,18 @@ on_bus_acquired (GDBusConnection *connection,
                                                        NULL,
                                                        &error);
   if (registration_id == 0)
-    g_error ("%s", error->message);
+    {
+      g_error ("%s", error->message);
+      g_clear_error (&error);
+    }
 
   g_dbus_connection_register_object (connection,
-                                                       "/org/a11y/bus",
-                                                       introspection_data->interfaces[1],
-                                                       &status_vtable,
-                                                       _global_app,
-                                                       NULL,
-                                                       &error);
+                                     "/org/a11y/bus",
+                                     introspection_data->interfaces[1],
+                                     &status_vtable,
+                                     _global_app,
+                                     NULL,
+                                     NULL);
 }
 
 static void
@@ -346,7 +514,7 @@ on_sigterm_pipe (GIOChannel  *channel,
                  gpointer     data)
 {
   A11yBusLauncher *app = data;
-  
+
   g_main_loop_quit (app->loop);
 
   return FALSE;
@@ -371,6 +539,7 @@ init_sigterm_handling (A11yBusLauncher *app)
 static gboolean
 already_running ()
 {
+#ifdef HAVE_X11
   Atom AT_SPI_BUS;
   Atom actual_type;
   Display *bridge_display;
@@ -383,7 +552,7 @@ already_running ()
   bridge_display = XOpenDisplay (NULL);
   if (!bridge_display)
              return FALSE;
-      
+
   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
   XGetWindowProperty (bridge_display,
                      XDefaultRootWindow (bridge_display),
@@ -395,39 +564,271 @@ already_running ()
   if (data)
   {
     GDBusConnection *bus;
-    GError *error = NULL;
-    const gchar *old_session = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
-    /* TODO: Is there a better way to connect? This is really hacky */
-    g_setenv ("DBUS_SESSION_BUS_ADDRESS", data, TRUE);
-    bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
-    g_setenv ("DBUS_SESSION_BUS_ADDRESS", old_session, TRUE);
+    bus = g_dbus_connection_new_for_address_sync ((const gchar *)data, 0,
+                                                  NULL, NULL, NULL);
     if (bus != NULL)
-      result = TRUE;
-    g_object_unref (bus);
+      {
+        result = TRUE;
+        g_object_unref (bus);
+      }
   }
 
   XCloseDisplay (bridge_display);
   return result;
+#else
+  return FALSE;
+#endif
+}
+
+static GSettings *
+get_schema (const gchar *name)
+{
+  const char * const *schemas = NULL;
+  gint i;
+
+  schemas = g_settings_list_schemas ();
+  for (i = 0; schemas[i]; i++)
+  {
+    if (!strcmp (schemas[i], name))
+      return g_settings_new (schemas[i]);
+  }
+
+  return NULL;
+}
+
+static void
+gsettings_key_changed (GSettings *gsettings, const gchar *key, void *user_data)
+{
+  gboolean new_val = g_settings_get_boolean (gsettings, key);
+  A11yBusLauncher *app = user_data;
+
+  if (!strcmp (key, "toolkit-accessibility"))
+    handle_a11y_enabled_change (_global_app, new_val, FALSE);
+  else if (!strcmp (key, "screen-reader-enabled"))
+    handle_screen_reader_enabled_change (_global_app, new_val, FALSE);
+}
+
+static int
+_screen_reader_dead_tracker (int pid, void *data)
+{
+  A11yBusLauncher *app = data;
+
+  if (app->pid > 0 && pid == app->pid)
+    {
+      LOGE("screen reader is dead, pid: %d, restarting", pid);
+      app->pid = 0;
+      g_timeout_add_seconds (2, _launch_screen_reader_repeat_until_success, app);
+    }
+  return 0;
+}
+
+static gboolean
+_launch_screen_reader(gpointer user_data, gboolean by_vconf_change)
+{
+   A11yBusLauncher *bl = user_data;
+   LOGD("Launching screen reader");
+
+   bundle *kb = NULL;
+   gboolean ret = FALSE;
+
+   kb = bundle_create();
+
+   if (kb == NULL)
+     {
+        LOGD("Can't create bundle");
+        return FALSE;
+     }
+
+   if (by_vconf_change)
+     {
+        if (bundle_add_str(kb, "by_vconf_change", "yes") != BUNDLE_ERROR_NONE)
+          {
+             LOGD("Can't add information to bundle");
+          }
+     }
+
+   int operation_error = appsvc_set_operation(kb, APP_CONTROL_OPERATION_SCREEN_READ);
+   LOGD("appsvc_set_operation: %i", operation_error);
+
+   bl->pid = appsvc_run_service(kb, 0, NULL, NULL);
+
+   if (bl->pid > 0)
+     {
+        LOGD("Screen reader launched with pid: %i", bl->pid);
+        LOGD("registering screen reader dead tracker");
+        aul_listen_app_dead_signal(_screen_reader_dead_tracker, bl);
+        ret = TRUE;
+     }
+   else
+     {
+        LOGD("Can't start screen-reader - error code: %i", bl->pid);
+     }
+
+
+   bundle_free(kb);
+   return ret;
 }
 
+static gboolean
+_launch_screen_reader_repeat_until_success(gpointer user_data) {
+    A11yBusLauncher *bl = user_data;
+
+    if (bl->launch_screen_reader_repeats > 100 || bl->pid > 0)
+      {
+         //do not try anymore
+         return FALSE;
+      }
+
+    gboolean ret = _launch_screen_reader(user_data, FALSE);
+
+    if (ret)
+      {
+         //we managed to
+         bl->launch_screen_reader_repeats = 0;
+         return FALSE;
+      }
+    //try again
+    return TRUE;
+}
+
+static gboolean
+_terminate_screen_reader(A11yBusLauncher *bl)
+{
+   LOGD("Terminating screen reader");
+   int ret;
+   int ret_aul;
+   if (bl->pid <= 0)
+     return FALSE;
+
+
+   LOGD("unregistering screen reader dead tracker");
+   aul_listen_app_dead_signal(NULL, NULL);
+
+   int status = aul_app_get_status_bypid(bl->pid);
+
+   if (status < 0)
+     {
+       LOGD("App with pid %d already terminated", bl->pid);
+       bl->pid = 0;
+       return TRUE;
+     }
+
+   LOGD("terminate process with pid %d", bl->pid);
+   ret_aul = aul_terminate_pid(bl->pid);
+   if (ret_aul >= 0)
+     {
+        LOGD("Terminating with aul_terminate_pid: return is %d", ret_aul);
+        bl->pid = 0;
+        return TRUE;
+     }
+   else
+     LOGD("aul_terminate_pid failed: return is %d", ret_aul);
+
+   LOGD("Unable to terminate process using aul api. Sending SIGTERM signal");
+   ret = kill(bl->pid, SIGTERM);
+   if (!ret)
+     {
+        bl->pid = 0;
+        return TRUE;
+     }
+
+   LOGD("Unable to terminate process: %d with api or signal.", bl->pid);
+   return FALSE;
+}
+
+void screen_reader_cb(keynode_t *node, void *user_data)
+{
+   A11yBusLauncher *bl = user_data;
+   int ret;
+
+   ret = vconf_keynode_get_bool(node);
+   LOGD("vconf_keynode_get_bool(node): %i", ret);
+   if (ret < 0)
+     return;
+
+   //check if process really exists (e.g didn't crash)
+   if (bl->pid > 0)
+     {
+        int err = kill(bl->pid,0);
+        //process doesn't exist
+        if (err == ESRCH)
+          bl->pid = 0;
+     }
+
+   bl->screen_reader_needed = ret;
+   LOGD("bl->screen_reader_needed: %i, bl->pid: %i", ret, bl->pid);
+   if (!bl->screen_reader_needed && (bl->pid > 0))
+     _terminate_screen_reader(bl);
+   else if (bl->screen_reader_needed && (bl->pid <= 0))
+     _launch_screen_reader(bl, TRUE);
+}
 
 int
 main (int    argc,
       char **argv)
 {
+#ifdef ATSPI_BUS_LAUNCHER_LOG_TO_FILE
+  log_file = fopen("/tmp/at-spi-bus-launcher.log", "a");
+#endif
+
+  LOGD("Starting atspi bus launcher");
   GError *error = NULL;
   GMainLoop *loop;
   GDBusConnection *session_bus;
   int name_owner_id;
-
-  g_type_init ();
+  gboolean a11y_set = FALSE;
+  gboolean screen_reader_set = FALSE;
+  gint i;
 
   if (already_running ())
-    return 0;
+    {
+       LOGD("atspi bus launcher is already running");
+       return 0;
+    }
 
   _global_app = g_slice_new0 (A11yBusLauncher);
   _global_app->loop = g_main_loop_new (NULL, FALSE);
-  _global_app->launch_immediately = (argc == 2 && strcmp (argv[1], "--launch-immediately") == 0);
+  _global_app->launch_screen_reader_repeats = 0;
+
+  for (i = 1; i < argc; i++)
+    {
+      if (!strcmp (argv[i], "--launch-immediately"))
+        _global_app->launch_immediately = TRUE;
+      else if (sscanf (argv[i], "--a11y=%d", &_global_app->a11y_enabled) == 2)
+        a11y_set = TRUE;
+      else if (sscanf (argv[i], "--screen-reader=%d",
+                       &_global_app->screen_reader_enabled) == 2)
+        screen_reader_set = TRUE;
+    else
+      g_error ("usage: %s [--launch-immediately] [--a11y=0|1] [--screen-reader=0|1]", argv[0]);
+    }
+
+  _global_app->interface_schema = get_schema ("org.gnome.desktop.interface");
+  _global_app->a11y_schema = get_schema ("org.gnome.desktop.a11y.applications");
+
+  if (!a11y_set)
+    {
+      _global_app->a11y_enabled = _global_app->interface_schema
+                                  ? g_settings_get_boolean (_global_app->interface_schema, "toolkit-accessibility")
+                                  : _global_app->launch_immediately;
+    }
+
+  if (!screen_reader_set)
+    {
+      _global_app->screen_reader_enabled = _global_app->a11y_schema
+                                  ? g_settings_get_boolean (_global_app->a11y_schema, "screen-reader-enabled")
+                                  : FALSE;
+    }
+
+  if (_global_app->interface_schema)
+    g_signal_connect (_global_app->interface_schema,
+                      "changed::toolkit-accessibility",
+                      G_CALLBACK (gsettings_key_changed), _global_app);
+
+  if (_global_app->a11y_schema)
+    g_signal_connect (_global_app->a11y_schema,
+                      "changed::screen-reader-enabled",
+                      G_CALLBACK (gsettings_key_changed), _global_app);
 
   init_sigterm_handling (_global_app);
 
@@ -443,15 +844,31 @@ main (int    argc,
                                   _global_app,
                                   NULL);
 
+  int ret = vconf_get_bool(VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &_global_app->screen_reader_needed);
+  if (ret != 0)
+    {
+      LOGD("Could not read VCONFKEY_SETAPPL_ACCESSIBILITY_TTS key value.\n");
+      return FALSE;
+    }
+  ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, screen_reader_cb, _global_app);
+  if(ret != 0)
+    {
+      LOGD("Could not add information level callback\n");
+      return FALSE;
+    }
+  if (_global_app->screen_reader_needed)
+    g_timeout_add_seconds(2,_launch_screen_reader_repeat_until_success, _global_app);
+
   g_main_loop_run (_global_app->loop);
 
   if (_global_app->a11y_bus_pid > 0)
     kill (_global_app->a11y_bus_pid, SIGTERM);
 
-  /* Clear the X property if our bus is gone; in the case where e.g. 
+  /* Clear the X property if our bus is gone; in the case where e.g.
    * GDM is launching a login on an X server it was using before,
    * we don't want early login processes to pick up the stale address.
    */
+#ifdef HAVE_X11
   {
     Display *display = XOpenDisplay (NULL);
     if (display)
@@ -465,6 +882,7 @@ main (int    argc,
         XCloseDisplay (display);
       }
   }
+#endif
 
   if (_global_app->a11y_launch_error_message)
     {