gboolean
xdg_app_builtin_run (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  g_autoptr(GOptionContext) context = NULL;
  g_autoptr(XdgAppDeploy) app_deploy = NULL;
  g_autoptr(XdgAppDeploy) runtime_deploy = NULL;
  g_autoptr(GFile) app_files = NULL;
  g_autoptr(GFile) runtime_files = NULL;
  g_autoptr(GFile) app_id_dir = NULL;
  g_autoptr(GFile) app_cache_dir = NULL;
  g_autoptr(GFile) app_data_dir = NULL;
  g_autoptr(GFile) app_config_dir = NULL;
  g_autoptr(GFile) home = NULL;
  g_autoptr(GFile) user_font1 = NULL;
  g_autoptr(GFile) user_font2 = NULL;
  g_autoptr(XdgAppSessionHelper) session_helper = NULL;
  g_autofree char *runtime = NULL;
  g_autofree char *default_command = NULL;
  g_autofree char *runtime_ref = NULL;
  g_autofree char *app_ref = NULL;
  g_autofree char *doc_mount_path = NULL;
  g_autoptr(GKeyFile) metakey = NULL;
  g_autoptr(GKeyFile) runtime_metakey = NULL;
  g_autoptr(GPtrArray) argv_array = NULL;
  g_auto(GStrv) envp = NULL;
  g_autoptr(GPtrArray) dbus_proxy_argv = NULL;
  g_autofree char *monitor_path = NULL;
  const char *app;
  const char *branch = "master";
  const char *command = "/bin/sh";
  int i;
  int rest_argv_start, rest_argc;
  int sync_proxy_pipes[2];
  g_autoptr(XdgAppContext) arg_context = NULL;
  g_autoptr(XdgAppContext) app_context = NULL;
  g_autoptr(XdgAppContext) overrides = NULL;
  g_autoptr(GDBusConnection) session_bus = NULL;

  context = g_option_context_new ("APP [args...] - Run an app");

  rest_argc = 0;
  for (i = 1; i < argc; i++)
    {
      /* The non-option is the command, take it out of the arguments */
      if (argv[i][0] != '-')
        {
          rest_argv_start = i;
          rest_argc = argc - i;
          argc = i;
          break;
        }
    }

  arg_context = xdg_app_context_new ();
  g_option_context_add_group (context, xdg_app_context_get_options (arg_context));

  if (!xdg_app_option_context_parse (context, options, &argc, &argv, XDG_APP_BUILTIN_FLAG_NO_DIR, NULL, cancellable, error))
    return FALSE;

  if (rest_argc == 0)
    return usage_error (context, "APP must be specified", error);

  app = argv[rest_argv_start];

  if (opt_branch)
    branch = opt_branch;

  if (!xdg_app_is_valid_name (app))
    return xdg_app_fail (error, "'%s' is not a valid application name", app);

  if (!xdg_app_is_valid_branch (branch))
    return xdg_app_fail (error, "'%s' is not a valid branch name", branch);

  app_ref = xdg_app_build_app_ref (app, branch, opt_arch);

  app_deploy = xdg_app_find_deploy_for_ref (app_ref, cancellable, error);
  if (app_deploy == NULL)
    return FALSE;

  metakey = xdg_app_deploy_get_metadata (app_deploy);

  argv_array = g_ptr_array_new_with_free_func (g_free);
  dbus_proxy_argv = g_ptr_array_new_with_free_func (g_free);
  g_ptr_array_add (argv_array, g_strdup (HELPER));
  g_ptr_array_add (argv_array, g_strdup ("-l"));

  if (!xdg_app_run_add_extension_args (argv_array, metakey, app_ref, cancellable, error))
    return FALSE;

  if (opt_runtime)
    runtime = opt_runtime;
  else
    {
      runtime = g_key_file_get_string (metakey, "Application", opt_devel ? "sdk" : "runtime", error);
      if (*error)
        return FALSE;
    }

  runtime_ref = g_build_filename ("runtime", runtime, NULL);

  runtime_deploy = xdg_app_find_deploy_for_ref (runtime_ref, cancellable, error);
  if (runtime_deploy == NULL)
    return FALSE;

  runtime_metakey = xdg_app_deploy_get_metadata (runtime_deploy);

  app_context = xdg_app_context_new ();
  if (!xdg_app_context_load_metadata (app_context, runtime_metakey, error))
    return FALSE;
  if (!xdg_app_context_load_metadata (app_context, metakey, error))
    return FALSE;

  overrides = xdg_app_deploy_get_overrides (app_deploy);
  xdg_app_context_merge (app_context, overrides);

  xdg_app_context_merge (app_context, arg_context);

  if (!xdg_app_run_add_extension_args (argv_array, runtime_metakey, runtime_ref, cancellable, error))
    return FALSE;

  if ((app_id_dir = xdg_app_ensure_data_dir (app, cancellable, error)) == NULL)
      return FALSE;

  app_cache_dir = g_file_get_child (app_id_dir, "cache");
  g_ptr_array_add (argv_array, g_strdup ("-B"));
  g_ptr_array_add (argv_array, g_strdup_printf ("/var/cache=%s", gs_file_get_path_cached (app_cache_dir)));

  app_data_dir = g_file_get_child (app_id_dir, "data");
  g_ptr_array_add (argv_array, g_strdup ("-B"));
  g_ptr_array_add (argv_array, g_strdup_printf ("/var/data=%s", gs_file_get_path_cached (app_data_dir)));

  app_config_dir = g_file_get_child (app_id_dir, "config");
  g_ptr_array_add (argv_array, g_strdup ("-B"));
  g_ptr_array_add (argv_array, g_strdup_printf ("/var/config=%s", gs_file_get_path_cached (app_config_dir)));

  app_files = xdg_app_deploy_get_files (app_deploy);
  runtime_files = xdg_app_deploy_get_files (runtime_deploy);

  default_command = g_key_file_get_string (metakey, "Application", "command", error);
  if (*error)
    return FALSE;
  if (opt_command)
    command = opt_command;
  else
    command = default_command;

  session_helper = xdg_app_session_helper_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
								  G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
								  "org.freedesktop.XdgApp",
								  "/org/freedesktop/XdgApp/SessionHelper",
								  NULL, NULL);
  if (session_helper &&
      xdg_app_session_helper_call_request_monitor_sync (session_helper,
                                                        &monitor_path,
                                                        NULL, NULL))
    {
      g_ptr_array_add (argv_array, g_strdup ("-m"));
      g_ptr_array_add (argv_array, monitor_path);
    }
  else
    g_ptr_array_add (argv_array, g_strdup ("-r"));

  session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
  if (session_bus)
    {
      g_autoptr (GError) local_error = NULL;
      g_autoptr (GDBusMessage) reply = NULL;
      g_autoptr (GDBusMessage) msg = g_dbus_message_new_method_call ("org.freedesktop.portal.Documents",
                                                                     "/org/freedesktop/portal/documents",
                                                                     "org.freedesktop.portal.Documents",
                                                                     "GetMountPoint");
      g_dbus_message_set_body (msg, g_variant_new ("()"));
      reply = g_dbus_connection_send_message_with_reply_sync (session_bus, msg,
                                                              G_DBUS_SEND_MESSAGE_FLAGS_NONE,
                                                              30000,
                                                              NULL,
                                                              NULL,
                                                              NULL);
      if (reply)
        {
          if (g_dbus_message_to_gerror (reply, &local_error))
            {
              g_warning ("Can't get document portal: %s\n", local_error->message);
            }
          else
            g_variant_get (g_dbus_message_get_body (reply),
                           "(^ay)", &doc_mount_path);
        }
    }

  xdg_app_run_add_environment_args (argv_array, dbus_proxy_argv, doc_mount_path,
                                    app, app_context, app_id_dir);

  g_ptr_array_add (argv_array, g_strdup ("-b"));
  g_ptr_array_add (argv_array, g_strdup_printf ("/run/host/fonts=%s", SYSTEM_FONTS_DIR));

  if (opt_devel)
    g_ptr_array_add (argv_array, g_strdup ("-c"));

  home = g_file_new_for_path (g_get_home_dir ());
  user_font1 = g_file_resolve_relative_path (home, ".local/share/fonts");
  user_font2 = g_file_resolve_relative_path (home, ".fonts");

  if (g_file_query_exists (user_font1, NULL))
    {
      g_autofree char *path = g_file_get_path (user_font1);
      g_ptr_array_add (argv_array, g_strdup ("-b"));
      g_ptr_array_add (argv_array, g_strdup_printf ("/run/host/user-fonts=%s", path));
    }
  else if (g_file_query_exists (user_font2, NULL))
    {
      g_autofree char *path = g_file_get_path (user_font2);
      g_ptr_array_add (argv_array, g_strdup ("-b"));
      g_ptr_array_add (argv_array, g_strdup_printf ("/run/host/user-fonts=%s", path));
    }

  /* Must run this before spawning the dbus proxy, to ensure it
     ends up in the app cgroup */
  xdg_app_run_in_transient_unit (app);

  if (dbus_proxy_argv->len > 0)
    {
      char x;

      if (pipe (sync_proxy_pipes) < 0)
	{
	  g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "Unable to create sync pipe");
	  return FALSE;
	}

      g_ptr_array_insert (dbus_proxy_argv, 0, g_strdup (DBUSPROXY));
      g_ptr_array_insert (dbus_proxy_argv, 1, g_strdup_printf ("--fd=%d", sync_proxy_pipes[1]));

      g_ptr_array_add (dbus_proxy_argv, NULL); /* NULL terminate */

      if (!g_spawn_async (NULL,
			  (char **)dbus_proxy_argv->pdata,
			  NULL,
			  G_SPAWN_SEARCH_PATH,
			  dbus_spawn_child_setup,
			  GINT_TO_POINTER (sync_proxy_pipes[1]),
			  NULL, error))
	return FALSE;

      close (sync_proxy_pipes[1]);

      /* Sync with proxy, i.e. wait until its listening on the sockets */
      if (read (sync_proxy_pipes[0], &x, 1) != 1)
	{
	  g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "Failed to sync with dbus proxy");
	  return FALSE;
	}

      g_ptr_array_add (argv_array, g_strdup ("-S"));
      g_ptr_array_add (argv_array, g_strdup_printf ("%d", sync_proxy_pipes[0]));
    }

  g_ptr_array_add (argv_array, g_strdup ("-a"));
  g_ptr_array_add (argv_array, g_file_get_path (app_files));
  g_ptr_array_add (argv_array, g_strdup ("-I"));
  g_ptr_array_add (argv_array, g_strdup (app));
  g_ptr_array_add (argv_array, g_file_get_path (runtime_files));

  g_ptr_array_add (argv_array, g_strdup (command));
  for (i = 1; i < rest_argc; i++)
    g_ptr_array_add (argv_array, g_strdup (argv[rest_argv_start + i]));

  g_ptr_array_add (argv_array, NULL);

  envp = g_get_environ ();
  envp = xdg_app_run_apply_env_default (envp);

  envp = xdg_app_run_apply_env_vars (envp, app_context);

  envp = xdg_app_run_apply_env_appid (envp, app_id_dir);

  if (execvpe (HELPER, (char **)argv_array->pdata, envp) == -1)
    {
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno), "Unable to start app");
      return FALSE;
    }

  /* Not actually reached... */
  return TRUE;
}
/**
 * nautilus_get_gmc_desktop_directory:
 * 
 * Get the path for the directory containing the legacy gmc desktop.
 *
 * Return value: the directory path.
 **/
char *
nautilus_get_gmc_desktop_directory (void)
{
	return g_build_filename (g_get_home_dir (), LEGACY_DESKTOP_DIRECTORY_NAME, NULL);
}
Example #3
0
/**
 * caja_get_user_directory:
 *
 * Get the path for the directory containing caja settings.
 *
 * Return value: the directory path.
 **/
char* caja_get_user_directory(void)
{
	/* FIXME bugzilla.gnome.org 41286:
	 * How should we handle the case where this mkdir fails?
	 * Note that caja_application_startup will refuse to launch if this
	 * directory doesn't get created, so that case is OK. But the directory
	 * could be deleted after Caja was launched, and perhaps
	 * there is some bad side-effect of not handling that case.
	 * <<<
	 * Si alguien tiene tiempo, puede enviar este codigo a Nautilus.
	 * Obviamente, con los comentarios traducidos al Inglés.
	 */
	char* user_directory = g_build_filename(g_get_user_config_dir(), "caja", NULL);
	/* Se necesita que esta dirección sea una carpeta, con los permisos
	 * DEFAULT_CAJA_DIRECTORY_MODE. Pero si es un archivo, el programa intentará
	 * eliminar el archivo silenciosamente. */
	if (g_file_test(user_directory, G_FILE_TEST_IS_DIR) == FALSE ||
		g_access(user_directory, DEFAULT_CAJA_DIRECTORY_MODE) == -1)
	{
		/* Se puede obtener un enlace simbolico a una carpeta */
		if (g_file_test(user_directory, G_FILE_TEST_IS_SYMLINK) == TRUE)
		{
			/* intentaremos saber si el enlace es una carpeta, y tiene los
			 * permisos adecuados */
			char* link = g_file_read_link(user_directory, NULL);

			if (link)
			{
				/* Si el enlace no es un directorio, o si falla al hacer chmod,
				 * se borra el enlace y se crea la carpeta */
				if (g_file_test(link, G_FILE_TEST_IS_DIR) != TRUE ||
					g_chmod(link, DEFAULT_CAJA_DIRECTORY_MODE) != 0)
				{
					/* podemos borrar el enlace y crear la carpeta */
					g_unlink(user_directory);
					g_mkdir(user_directory, DEFAULT_CAJA_DIRECTORY_MODE);
				}

				g_free(link);
			}
		}
		else if (g_file_test(user_directory, G_FILE_TEST_IS_DIR) == TRUE)
		{
			g_chmod(user_directory, DEFAULT_CAJA_DIRECTORY_MODE);
		}
		else if (g_file_test(user_directory, G_FILE_TEST_EXISTS) == TRUE)
		{
			/* podemos borrar el enlace y crear la carpeta */
			g_unlink(user_directory);
			g_mkdir(user_directory, DEFAULT_CAJA_DIRECTORY_MODE);
		}
		else
		{
			/* Si no existe ningun archivo, se crea la carpeta */
			g_mkdir_with_parents(user_directory, DEFAULT_CAJA_DIRECTORY_MODE);
		}

		/* Faltan permisos */
		if (g_chmod(user_directory, DEFAULT_CAJA_DIRECTORY_MODE) != 0)
		{
			GtkWidget* dialog = gtk_message_dialog_new(
				NULL,
				GTK_DIALOG_DESTROY_WITH_PARENT,
				GTK_MESSAGE_ERROR,
				GTK_BUTTONS_CLOSE,
				"The path for the directory containing caja settings need read and write permissions: %s",
				user_directory);

			gtk_dialog_run(GTK_DIALOG(dialog));
			gtk_widget_destroy(dialog);

			exit(0);
		}
	}

	return user_directory;
}
Example #4
0
gboolean
purple_core_migrate(void)
{
    const char *user_dir = purple_user_dir();
    char *old_user_dir = g_strconcat(purple_home_dir(),
                                     G_DIR_SEPARATOR_S ".gaim", NULL);
    char *status_file;
    FILE *fp;
    GDir *dir;
    GError *err;
    const char *entry;
#ifndef _WIN32
    char *logs_dir;
#endif
    char *old_icons_dir;

    if (!g_file_test(old_user_dir, G_FILE_TEST_EXISTS))
    {
        /* ~/.gaim doesn't exist, so there's nothing to migrate. */
        g_free(old_user_dir);
        return TRUE;
    }

    status_file = g_strconcat(user_dir, G_DIR_SEPARATOR_S "migrating", NULL);

    if (g_file_test(user_dir, G_FILE_TEST_EXISTS))
    {
        /* If we're here, we have both ~/.gaim and .purple. */

        if (!g_file_test(status_file, G_FILE_TEST_EXISTS))
        {
            /* There's no "migrating" status file,
             * so ~/.purple is all up to date. */
            g_free(status_file);
            g_free(old_user_dir);
            return TRUE;
        }
    }

    /* If we're here, it's time to migrate from ~/.gaim to ~/.purple. */

    /* Ensure the user directory exists */
    if (!g_file_test(user_dir, G_FILE_TEST_IS_DIR))
    {
        if (g_mkdir(user_dir, S_IRUSR | S_IWUSR | S_IXUSR) == -1)
        {
            purple_debug_error("core", "Error creating directory %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                               user_dir, g_strerror(errno));
            g_free(status_file);
            g_free(old_user_dir);
            return FALSE;
        }
    }

    /* This writes ~/.purple/migrating, which allows us to detect
     * incomplete migrations and properly retry. */
    if (!(fp = g_fopen(status_file, "w")))
    {
        purple_debug_error("core", "Error opening file %s for writing: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                           status_file, g_strerror(errno));
        g_free(status_file);
        g_free(old_user_dir);
        return FALSE;
    }
    fclose(fp);

    /* Open ~/.gaim so we can loop over its contents. */
    err = NULL;
    if (!(dir = g_dir_open(old_user_dir, 0, &err)))
    {
        purple_debug_error("core", "Error opening directory %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                           status_file,
                           (err ? err->message : "Unknown error"));
        if (err)
            g_error_free(err);
        g_free(status_file);
        g_free(old_user_dir);
        return FALSE;
    }

    /* Loop over the contents of ~/.gaim */
    while ((entry = g_dir_read_name(dir)))
    {
        char *name = g_build_filename(old_user_dir, entry, NULL);

#ifndef _WIN32
        /* Deal with symlinks... */
        if (g_file_test(name, G_FILE_TEST_IS_SYMLINK))
        {
            /* We're only going to duplicate a logs symlink. */
            if (!strcmp(entry, "logs"))
            {
                char *link;
#if GLIB_CHECK_VERSION(2,4,0)
                GError *err = NULL;

                if ((link = g_file_read_link(name, &err)) == NULL)
                {
                    char *name_utf8 = g_filename_to_utf8(name, -1, NULL, NULL, NULL);
                    purple_debug_error("core", "Error reading symlink %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                       name_utf8 ? name_utf8 : name, err->message);
                    g_free(name_utf8);
                    g_error_free(err);
                    g_free(name);
                    g_dir_close(dir);
                    g_free(status_file);
                    g_free(old_user_dir);
                    return FALSE;
                }
#else
                char buf[MAXPATHLEN];
                size_t linklen;

                if ((linklen = readlink(name, buf, sizeof(buf) - 1) == -1))
                {
                    char *name_utf8 = g_filename_to_utf8(name, -1, NULL, NULL, NULL);
                    purple_debug_error("core", "Error reading symlink %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                       name_utf8, g_strerror(errno));
                    g_free(name_utf8);
                    g_free(name);
                    g_dir_close(dir);
                    g_free(status_file);
                    g_free(old_user_dir);
                    return FALSE;
                }
                buf[linklen] = '\0';

                /* This way we don't have to GLIB_VERSION_CHECK every g_free(link) below. */
                link = g_strdup(buf);
#endif

                logs_dir = g_build_filename(user_dir, "logs", NULL);

                if (!strcmp(link, "../.purple/logs") || !strcmp(link, logs_dir))
                {
                    /* If the symlink points to the new directory, we're
                     * likely just trying again after a failed migration,
                     * so there's no need to fail here. */
                    g_free(link);
                    g_free(logs_dir);
                    continue;
                }

                /* In case we are trying again after a failed migration, we need
                 * to unlink any existing symlink.  If it's a directory, this
                 * will fail, and so will the symlink below, which is good
                 * because the user should sort things out. */
                g_unlink(logs_dir);

                /* Relative links will most likely still be
                 * valid from ~/.purple, though it's not
                 * guaranteed.  Oh well. */
                if (symlink(link, logs_dir))
                {
                    purple_debug_error("core", "Error symlinking %s to %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                       logs_dir, link, g_strerror(errno));
                    g_free(link);
                    g_free(name);
                    g_free(logs_dir);
                    g_dir_close(dir);
                    g_free(status_file);
                    g_free(old_user_dir);
                    return FALSE;
                }

                g_free(link);
                g_free(logs_dir);
                continue;
            }

            /* Ignore all other symlinks. */
            continue;
        }
#endif

        /* Deal with directories... */
        if (g_file_test(name, G_FILE_TEST_IS_DIR))
        {
            if (!strcmp(entry, "icons"))
            {
                /* This is a special case for the Album plugin, which
                 * stores data in the icons folder.  We're not copying
                 * the icons directory over because previous bugs
                 * meant that it filled up with junk for many users.
                 * This is a great time to purge it. */

                GDir *icons_dir;
                char *new_icons_dir;
                const char *icons_entry;

                err = NULL;
                if (!(icons_dir = g_dir_open(name, 0, &err)))
                {
                    purple_debug_error("core", "Error opening directory %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                       name,
                                       (err ? err->message : "Unknown error"));
                    if (err)
                        g_error_free(err);
                    g_free(name);
                    g_dir_close(dir);
                    g_free(status_file);
                    g_free(old_user_dir);
                    return FALSE;
                }

                new_icons_dir = g_build_filename(user_dir, "icons", NULL);
                /* Ensure the new icon directory exists */
                if (!g_file_test(new_icons_dir, G_FILE_TEST_IS_DIR))
                {
                    if (g_mkdir(new_icons_dir, S_IRUSR | S_IWUSR | S_IXUSR) == -1)
                    {
                        purple_debug_error("core", "Error creating directory %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                           new_icons_dir, g_strerror(errno));
                        g_free(new_icons_dir);
                        g_dir_close(icons_dir);
                        g_free(name);
                        g_dir_close(dir);
                        g_free(status_file);
                        g_free(old_user_dir);
                        return FALSE;
                    }
                }

                while ((icons_entry = g_dir_read_name(icons_dir)))
                {
                    char *icons_name = g_build_filename(name, icons_entry, NULL);

                    if (g_file_test(icons_name, G_FILE_TEST_IS_DIR))
                    {
                        if (!move_and_symlink_dir(icons_name, icons_entry,
                                                  name, new_icons_dir, "../../.purple/icons"))
                        {
                            g_free(icons_name);
                            g_free(new_icons_dir);
                            g_dir_close(icons_dir);
                            g_free(name);
                            g_dir_close(dir);
                            g_free(status_file);
                            g_free(old_user_dir);
                            return FALSE;
                        }
                    }
                    g_free(icons_name);
                }

                g_dir_close(icons_dir);
            }
            else if (!strcmp(entry, "plugins"))
            {
                /* Do nothing, because we broke plugin compatibility.
                 * This means that the plugins directory gets left behind. */
            }
            else
            {
                /* All other directories are moved and symlinked. */
                if (!move_and_symlink_dir(name, entry, old_user_dir, user_dir, "../.purple"))
                {
                    g_free(name);
                    g_dir_close(dir);
                    g_free(status_file);
                    g_free(old_user_dir);
                    return FALSE;
                }
            }
        }
        else if (g_file_test(name, G_FILE_TEST_IS_REGULAR))
        {
            /* Regular files are copied. */

            char *new_name;
            FILE *new_file;

            if (!(fp = g_fopen(name, "rb")))
            {
                purple_debug_error("core", "Error opening file %s for reading: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                   name, g_strerror(errno));
                g_free(name);
                g_dir_close(dir);
                g_free(status_file);
                g_free(old_user_dir);
                return FALSE;
            }

            new_name = g_build_filename(user_dir, entry, NULL);
            if (!(new_file = g_fopen(new_name, "wb")))
            {
                purple_debug_error("core", "Error opening file %s for writing: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                   new_name, g_strerror(errno));
                fclose(fp);
                g_free(new_name);
                g_free(name);
                g_dir_close(dir);
                g_free(status_file);
                g_free(old_user_dir);
                return FALSE;
            }

            while (!feof(fp))
            {
                unsigned char buf[256];
                size_t size;

                size = fread(buf, 1, sizeof(buf), fp);
                if (size != sizeof(buf) && !feof(fp))
                {
                    purple_debug_error("core", "Error reading %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                       name, g_strerror(errno));
                    fclose(new_file);
                    fclose(fp);
                    g_free(new_name);
                    g_free(name);
                    g_dir_close(dir);
                    g_free(status_file);
                    g_free(old_user_dir);
                    return FALSE;
                }

                if (!fwrite(buf, size, 1, new_file) && ferror(new_file) != 0)
                {
                    purple_debug_error("core", "Error writing %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                       new_name, g_strerror(errno));
                    fclose(new_file);
                    fclose(fp);
                    g_free(new_name);
                    g_free(name);
                    g_dir_close(dir);
                    g_free(status_file);
                    g_free(old_user_dir);
                    return FALSE;
                }
            }

            if (fclose(new_file))
            {
                purple_debug_error("core", "Error writing: %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                                   new_name, g_strerror(errno));
            }
            if (fclose(fp))
            {
                purple_debug_warning("core", "Error closing %s: %s\n",
                                     name, g_strerror(errno));
            }
            g_free(new_name);
        }
        else
            purple_debug_warning("core", "Not a regular file or directory: %s\n", name);

        g_free(name);
    }

    /* The migration was successful, so delete the status file. */
    if (g_unlink(status_file))
    {
        purple_debug_error("core", "Error unlinking file %s: %s. Please report this at " PURPLE_DEVEL_WEBSITE "\n",
                           status_file, g_strerror(errno));
        g_free(status_file);
        return FALSE;
    }

    old_icons_dir = g_build_filename(old_user_dir, "icons", NULL);
    _purple_buddy_icon_set_old_icons_dir(old_icons_dir);
    g_free(old_icons_dir);

    g_free(old_user_dir);

    g_free(status_file);
    return TRUE;
}
Example #5
0
static gboolean
charpicker_applet_fill (MatePanelApplet *applet)
{
  MatePanelAppletOrient orientation;
  charpick_data *curr_data;
  GdkAtom utf8_atom;
  GList *list;
  gchar *string;
  GtkActionGroup *action_group;
  gchar *ui_path;

  g_set_application_name (_("Character Palette"));
  
  gtk_window_set_default_icon_name ("accessories-character-map");

  mate_panel_applet_set_background_widget (applet, GTK_WIDGET (applet));

  mate_panel_applet_set_flags (applet, MATE_PANEL_APPLET_EXPAND_MINOR);
   
  curr_data = g_new0 (charpick_data, 1);
  curr_data->last_index = NO_LAST_INDEX;
  curr_data->applet = GTK_WIDGET (applet);
  curr_data->about_dialog = NULL;
  curr_data->add_edit_dialog = NULL;
  curr_data->settings = mate_panel_applet_settings_new (applet, "org.mate.panel.applet.charpick");
 
  get_chartable (curr_data);
  
  string  = g_settings_get_string (curr_data->settings, "current-list");
  if (string) {
  	list = curr_data->chartable;
  	while (list) {
  		if (g_ascii_strcasecmp (list->data, string) == 0)
  			curr_data->charlist = list->data;
  		list = g_list_next (list);
  	}
	/* FIXME: yeah leak, but this code is full of leaks and evil
	   point shuffling.  This should really be rewritten
	   -George */
	if (curr_data->charlist == NULL)
		curr_data->charlist = string;
	else
		g_free (string);
  } else {
  	curr_data->charlist = curr_data->chartable->data;  
  }
 
  curr_data->panel_size = mate_panel_applet_get_size (applet);
  
  orientation = mate_panel_applet_get_orient (applet);
  curr_data->panel_vertical = (orientation == MATE_PANEL_APPLET_ORIENT_LEFT) 
                              || (orientation == MATE_PANEL_APPLET_ORIENT_RIGHT);
  build_table (curr_data);
    
  g_signal_connect (G_OBJECT (curr_data->applet), "key_press_event",
		             G_CALLBACK (key_press_event), curr_data);

  utf8_atom = gdk_atom_intern ("UTF8_STRING", FALSE);
  gtk_selection_add_target (curr_data->applet, 
			    GDK_SELECTION_PRIMARY,
                            utf8_atom,
			    0);
  gtk_selection_add_target (curr_data->applet, 
			    GDK_SELECTION_CLIPBOARD,
                            utf8_atom,
			    0);
  g_signal_connect (GTK_OBJECT (curr_data->applet), "selection_get",
		      G_CALLBACK (charpick_selection_handler),
		      curr_data);
  g_signal_connect (GTK_OBJECT (curr_data->applet), "selection_clear_event",
		      G_CALLBACK (selection_clear_cb),
		      curr_data);
 
  make_applet_accessible (GTK_WIDGET (applet));

  /* session save signal */ 
  g_signal_connect (G_OBJECT (applet), "change_orient",
		    G_CALLBACK (applet_change_orient), curr_data);

  g_signal_connect (G_OBJECT (applet), "size_allocate",
		    G_CALLBACK (applet_size_allocate), curr_data);
		    
  g_signal_connect (G_OBJECT (applet), "destroy",
  		    G_CALLBACK (applet_destroy), curr_data);
  
  gtk_widget_show_all (GTK_WIDGET (applet));

  action_group = gtk_action_group_new ("Charpicker Applet Actions");
  gtk_action_group_set_translation_domain (action_group, GETTEXT_PACKAGE);
  gtk_action_group_add_actions (action_group,
				charpick_applet_menu_actions,
				G_N_ELEMENTS (charpick_applet_menu_actions),
				curr_data);
  ui_path = g_build_filename (CHARPICK_MENU_UI_DIR, "charpick-applet-menu.xml", NULL);
  mate_panel_applet_setup_menu_from_file (MATE_PANEL_APPLET (applet),
                                     ui_path, action_group);
  g_free (ui_path);

  if (mate_panel_applet_get_locked_down (MATE_PANEL_APPLET (applet))) {
	  GtkAction *action;

	  action = gtk_action_group_get_action (action_group, "Preferences");
	  gtk_action_set_visible (action, FALSE);
  }
  g_object_unref (action_group);

  register_stock_for_edit ();			             
  populate_menu (curr_data);
  
  return TRUE;
}
Example #6
0
int
main (int argc, char **argv)
{
  GtkWidget *w1;
  gchar *path;

  gtk_init (&argc, &argv);

  toplevel = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  grid = gtk_grid_new ();

  w1 = gtk_label_new ("File:");
  gtk_widget_set_halign (w1, GTK_ALIGN_START);
  gtk_grid_attach (GTK_GRID (grid),
                   w1, 0, 0, 1, 1);

  file_l = gtk_button_new ();
  path = g_build_filename (g_get_current_dir (), "apple-red.png", NULL);
  file = g_file_new_for_path (path);
  gtk_button_set_label (GTK_BUTTON (file_l), path);
  g_free (path);

  gtk_widget_set_halign (file_l, GTK_ALIGN_START);
  gtk_grid_attach_next_to (GTK_GRID (grid), file_l,
                           w1, GTK_POS_RIGHT, 3, 1);
  g_signal_connect (file_l, "clicked",
                    G_CALLBACK (button_clicked), NULL);

  radio_file = gtk_radio_button_new_with_label (NULL, "Use GFile");
  radio_content = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (radio_file),
                                                               "Use content type");

  gtk_grid_attach (GTK_GRID (grid), radio_file,
                   0, 1, 1, 1);
  gtk_grid_attach_next_to (GTK_GRID (grid), radio_content,
                           radio_file, GTK_POS_BOTTOM, 1, 1);

  open = gtk_button_new_with_label ("Trigger App Chooser dialog");
  gtk_grid_attach_next_to (GTK_GRID (grid), open,
                           radio_content, GTK_POS_BOTTOM, 1, 1);

  recommended = gtk_check_button_new_with_label ("Show recommended");
  gtk_grid_attach_next_to (GTK_GRID (grid), recommended,
                           open, GTK_POS_BOTTOM, 1, 1);
  g_object_set (recommended, "active", TRUE, NULL);

  fallback = gtk_check_button_new_with_label ("Show fallback");
  gtk_grid_attach_next_to (GTK_GRID (grid), fallback,
                           recommended, GTK_POS_RIGHT, 1, 1);

  other = gtk_check_button_new_with_label ("Show other");
  gtk_grid_attach_next_to (GTK_GRID (grid), other,
                           fallback, GTK_POS_RIGHT, 1, 1);

  all = gtk_check_button_new_with_label ("Show all");
  gtk_grid_attach_next_to (GTK_GRID (grid), all,
                           other, GTK_POS_RIGHT, 1, 1);

  def = gtk_check_button_new_with_label ("Show default");
  gtk_grid_attach_next_to (GTK_GRID (grid), def,
                           all, GTK_POS_RIGHT, 1, 1);

  g_object_set (recommended, "active", TRUE, NULL);
  prepare_dialog ();
  g_signal_connect (open, "clicked",
                    G_CALLBACK (display_dialog), NULL);

  gtk_container_add (GTK_CONTAINER (toplevel), grid);

  gtk_widget_show_all (toplevel);
  g_signal_connect (toplevel, "delete-event",
                    G_CALLBACK (gtk_main_quit), NULL);

  gtk_main ();

  return EXIT_SUCCESS;
}
Example #7
0
/**
 * cockpit_web_response_file:
 * @response: the response
 * @path: escaped path, or NULL to get from response
 * @roots: directories to look for file in
 *
 * Serve a file from disk as an HTTP response.
 */
void
cockpit_web_response_file (CockpitWebResponse *response,
                           const gchar *escaped,
                           gboolean cache_forever,
                           const gchar **roots)
{
  const gchar *cache_control;
  GError *error = NULL;
  gchar *unescaped = NULL;
  gchar *path = NULL;
  GMappedFile *file = NULL;
  const gchar *root;
  GBytes *body;

  g_return_if_fail (COCKPIT_IS_WEB_RESPONSE (response));

  if (!escaped)
    escaped = cockpit_web_response_get_path (response);

  g_return_if_fail (escaped != NULL);

  /* Someone is trying to escape the root directory, or access hidden files? */
  unescaped = g_uri_unescape_string (escaped, NULL);
  if (strstr (unescaped, "/.") || strstr (unescaped, "../") || strstr (unescaped, "//"))
    {
      g_debug ("%s: invalid path request", escaped);
      cockpit_web_response_error (response, 404, NULL, "Not Found");
      goto out;
    }

again:
  root = *(roots++);
  if (root == NULL)
    {
      cockpit_web_response_error (response, 404, NULL, "Not Found");
      goto out;
    }

  g_free (path);
  path = g_build_filename (root, unescaped, NULL);

  if (g_file_test (path, G_FILE_TEST_IS_DIR))
    {
      cockpit_web_response_error (response, 403, NULL, "Directory Listing Denied");
      goto out;
    }

  /* As a double check of above behavior */
  g_assert (path_has_prefix (path, root));

  g_clear_error (&error);
  file = g_mapped_file_new (path, FALSE, &error);
  if (file == NULL)
    {
      if (g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT) ||
          g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NAMETOOLONG))
        {
          g_debug ("%s: file not found in root: %s", escaped, root);
          goto again;
        }
      else if (g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_PERM) ||
               g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_ACCES) ||
               g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_ISDIR))
        {
          cockpit_web_response_error (response, 403, NULL, "Access denied");
          goto out;
        }
      else
        {
          g_warning ("%s: %s", path, error->message);
          cockpit_web_response_error (response, 500, NULL, "Internal server error");
          goto out;
        }
    }

  body = g_mapped_file_get_bytes (file);

  cache_control = cache_forever ? "max-age=31556926, public" : NULL;
  cockpit_web_response_headers (response, 200, "OK", g_bytes_get_size (body),
                                "Cache-Control", cache_control,
                                NULL);

  if (cockpit_web_response_queue (response, body))
    cockpit_web_response_complete (response);

  g_bytes_unref (body);

out:
  g_free (unescaped);
  g_clear_error (&error);
  g_free (path);
  if (file)
    g_mapped_file_unref (file);
}
Example #8
0
static gboolean
_create_settings_dialog (MexInfoBar *self)
{
  MexInfoBarPrivate *priv = self->priv;

  ClutterActor *dialog, *network_graphic;
  ClutterActor *network_tile, *dialog_layout, *dialog_label;
  ClutterActor *network_button;

  MxAction *close_dialog, *network_settings;

  dialog = mx_dialog_new ();
  mx_stylable_set_style_class (MX_STYLABLE (dialog), "MexInfoBarDialog");

  dialog_label = mx_label_new_with_text (_("Settings"));
  mx_stylable_set_style_class (MX_STYLABLE (dialog_label), "DialogHeader");

  /* Create actions for settings dialog */
  network_settings =
    _action_new_from_desktop_file ("mex-networks.desktop");

  close_dialog = mx_action_new_full ("close", _("Close"),
                                     G_CALLBACK (_close_dialog_cb), self);

  dialog_layout = mx_table_new ();
  mx_table_set_column_spacing (MX_TABLE (dialog_layout), 10);
  mx_table_set_row_spacing (MX_TABLE (dialog_layout), 30);

  mx_table_add_actor (MX_TABLE (dialog_layout),
                      CLUTTER_ACTOR (dialog_label), 0, 0);

  if (network_settings)
    {
      gchar *tmp;
      network_graphic = mx_image_new ();
      mx_stylable_set_style_class (MX_STYLABLE (network_graphic),
                                   "NetworkGraphic");

      tmp = g_build_filename (mex_get_data_dir (), "style",
                              "graphic-network.png", NULL);
      mx_image_set_from_file (MX_IMAGE (network_graphic), tmp, NULL);
      g_free (tmp);

      network_tile = mex_tile_new ();
      mex_tile_set_label (MEX_TILE (network_tile), _("Network"));
      mex_tile_set_important (MEX_TILE (network_tile), TRUE);

      network_button = mx_button_new ();

      mx_button_set_action (MX_BUTTON (network_button), network_settings);

      mx_bin_set_child (MX_BIN (network_tile), network_button);
      mx_bin_set_child (MX_BIN (network_button), network_graphic);

      mx_table_add_actor (MX_TABLE (dialog_layout),
                          CLUTTER_ACTOR (network_tile), 1, 1);
    }

  if (!network_settings)
    {
      ClutterActor *no_settings;
      no_settings = mx_label_new_with_text (_("No settings helpers installed"));

      clutter_actor_destroy (priv->settings_button);

      mx_table_add_actor (MX_TABLE (dialog_layout),
                          CLUTTER_ACTOR (no_settings), 1, 0);
    }


  clutter_container_add_actor (CLUTTER_CONTAINER (dialog), dialog_layout);
  mx_dialog_add_action (MX_DIALOG (dialog), close_dialog);

  priv->settings_dialog = g_object_ref (dialog);

  return TRUE;
}
Example #9
0
int
main (int argc, char** argv)
{
    xmlDocPtr doc;
    xmlNodePtr root, node;
    GdaSqlParser *parser;
    gint failures = 0;
    gint ntests = 0;
    gchar *fname;
    GHashTable *parsers_hash;
    GdaDataModel *providers_model;
    gint i;

    gda_init ();

    /* load file */
    fname = g_build_filename (ROOT_DIR, "tests", "parser", "testdata.xml", NULL);
    if (! g_file_test (fname, G_FILE_TEST_EXISTS)) {
        g_print ("File '%s' does not exist\n", fname);
        exit (1);
    }

    /* create parsers */
    parsers_hash = g_hash_table_new (g_str_hash, g_str_equal);
    providers_model = gda_config_list_providers ();
    for (i = 0; i < gda_data_model_get_n_rows (providers_model); i++) {
        const GValue *pname;
        GError *lerror = NULL;
        pname = gda_data_model_get_value_at (providers_model, 0, i, &lerror);
        if (!pname) {
            g_print ("Can't get data model's value: %s",
                     lerror && lerror->message ? lerror->message : "No detail");
            exit (1);
        }
        parser = create_parser_for_provider (g_value_get_string (pname));
        g_hash_table_insert (parsers_hash, g_strdup (g_value_get_string (pname)), parser);
        g_print ("Created parser for provider %s\n", g_value_get_string (pname));
    }
    g_object_unref (providers_model);
    g_hash_table_insert (parsers_hash, "", gda_sql_parser_new ());

    /* use test data */
    doc = xmlParseFile (fname);
    g_free (fname);
    g_assert (doc);
    root = xmlDocGetRootElement (doc);
    g_assert (!strcmp ((gchar*) root->name, "testdata"));
    for (node = root->children; node; node = node->next) {
        if (strcmp ((gchar*) node->name, "test"))
            continue;
        xmlNodePtr snode;
        xmlChar *sql = NULL;
        xmlChar *id;
        xmlChar *prov_name;

        prov_name = xmlGetProp (node, BAD_CAST "provider");
        if (prov_name) {
            parser = g_hash_table_lookup (parsers_hash, (gchar *) prov_name);
            xmlFree (prov_name);
        }
        else
            parser = g_hash_table_lookup (parsers_hash, "");
        if (!parser)
            continue;

        id = xmlGetProp (node, BAD_CAST "id");
        for (snode = node->children; snode; snode = snode->next) {
            if (!strcmp ((gchar*) snode->name, "sql"))
                sql = xmlNodeGetContent (snode);
            else if (!strcmp ((gchar*) snode->name, "expected")) {
                xmlChar *expected;
                xmlChar *mode;

                expected = xmlNodeGetContent (snode);
                mode = xmlGetProp (snode, BAD_CAST "mode");
                if (sql) {
                    g_object_set (G_OBJECT (parser), "mode",
                                  mode && !strcmp ((gchar *) mode, "delim") ?
                                  GDA_SQL_PARSER_MODE_DELIMIT : GDA_SQL_PARSER_MODE_PARSE,
                                  NULL);
                    failures += do_test (parser, id,  sql, expected, NULL, NULL);
                    ntests++;
                }
                else
                    g_print ("===== Test '%s' doe not have any <sql> tag!\n", id);
                if (expected) xmlFree (expected);
                if (mode) xmlFree (mode);
            }
            else if (!strcmp ((gchar*) snode->name, "error")) {
                xmlChar *error_line, *error_col;
                xmlChar *mode;
                mode = xmlGetProp (snode, BAD_CAST "mode");
                error_line = xmlGetProp (snode, BAD_CAST "line");
                error_col = xmlGetProp (snode, BAD_CAST "col");
                if (sql) {
                    g_object_set (G_OBJECT (parser), "mode",
                                  mode && !strcmp ((gchar *) mode, "delim") ?
                                  GDA_SQL_PARSER_MODE_DELIMIT : GDA_SQL_PARSER_MODE_PARSE,
                                  NULL);
                    failures += do_test (parser, id, sql, NULL, error_line, error_col);
                    ntests++;
                }
                else
                    g_print ("===== Test '%s' doe not have any <sql> tag!\n", id);

                if (mode) xmlFree (mode);
                if (error_line)	xmlFree (error_line);
                if (error_col) xmlFree (error_col);
            }
        }

        /* mem free */
        if (sql) xmlFree (sql);
        if (id)	xmlFree (id);
    }
    xmlFreeDoc (doc);

    g_print ("TESTS COUNT: %d\n", ntests);
    g_print ("FAILURES: %d\n", failures);

    return failures != 0 ? 1 : 0;
}
Example #10
0
/*
 * render SQL
 */
static gboolean
test2 (GError **error)
{
	GdaSqlParser *parser = NULL;
	GHashTable *parsers_hash;
	GdaDataModel *providers_model;
	gint i;

	/* create parsers */
	parsers_hash = g_hash_table_new (g_str_hash, g_str_equal);
	providers_model = gda_config_list_providers ();
	for (i = 0; i < gda_data_model_get_n_rows (providers_model); i++) {
		const GValue *pname;
		pname = gda_data_model_get_value_at (providers_model, 0, i, error);
		if (!pname)
			return FALSE;
		parser = create_parser_for_provider (g_value_get_string (pname));
		g_hash_table_insert (parsers_hash, g_strdup (g_value_get_string (pname)), parser);
		g_print ("Created parser for provider %s\n", g_value_get_string (pname));
	}
	g_object_unref (providers_model);
	g_hash_table_insert (parsers_hash, "", gda_sql_parser_new ());
	
	xmlDocPtr doc;
        xmlNodePtr root, node;
	gchar *fname;
	
	fname = g_build_filename (ROOT_DIR, "tests", "parser", "testdata.xml", NULL);
	if (! g_file_test (fname, G_FILE_TEST_EXISTS)) {
                g_set_error (error, TEST_ERROR, TEST_ERROR_GENERIC, "File '%s' does not exist\n", fname);
		return FALSE;
        }
	doc = xmlParseFile (fname);
        g_free (fname);
        g_assert (doc);
        root = xmlDocGetRootElement (doc);
	g_assert (!strcmp ((gchar*) root->name, "testdata"));
        for (node = root->children; node; node = node->next) {
		if (strcmp ((gchar*) node->name, "test"))
                        continue;
		xmlNodePtr snode;
                xmlChar *sql = NULL;
                xmlChar *id;
                xmlChar *prov_name;

		prov_name = xmlGetProp (node, BAD_CAST "provider");
		if (prov_name) {
			parser = g_hash_table_lookup (parsers_hash, (gchar *) prov_name);
			xmlFree (prov_name);
		}
		else
			parser = g_hash_table_lookup (parsers_hash, "");
		if (!parser)
			continue;

		for (snode = node->children; snode && strcmp ((gchar*) snode->name, "sql"); snode = snode->next);
		if (!snode)
			continue;
		sql = xmlNodeGetContent (snode);
		if (!sql)
			continue;
		
		GdaStatement *stmt;
		GError *lerror = NULL;
		
		stmt = gda_sql_parser_parse_string (parser, sql, NULL, &lerror);
		xmlFree (sql);
		id = xmlGetProp (node, BAD_CAST "id");
		g_print ("===== TEST %s\n", id);

		if (!stmt) {
			/* skip that SQL if it can't be parsed */
			g_error_free (lerror);
			continue;
		}
		else { 
			GdaStatement *stmt2;
			gchar *rsql;
			gchar *ser1, *ser2;
			
			rsql = gda_statement_to_sql_extended (stmt, NULL, NULL, 0, NULL, &lerror);
			if (!rsql) {
				g_print ("REM: test '%s' can't be rendered: %s\n", id,
					 lerror && lerror->message ? lerror->message : "No detail");
				xmlFree (id);
				continue;
			}
			
			/*g_print ("--> rendered SQL: %s\n", rsql);*/
			stmt2 = gda_sql_parser_parse_string (parser, rsql, NULL, error);
			if (!stmt2) 
				return FALSE;
			
			GdaSqlStatement *sqlst;
			
			g_object_get (G_OBJECT (stmt), "structure", &sqlst, NULL);
			g_free (sqlst->sql);
			sqlst->sql = NULL;
			ser1 = gda_sql_statement_serialize (sqlst);
			gda_sql_statement_free (sqlst);
			
			g_object_get (G_OBJECT (stmt2), "structure", &sqlst, NULL);
			g_free (sqlst->sql);
			sqlst->sql = NULL;
			ser2 = gda_sql_statement_serialize (sqlst);
			gda_sql_statement_free (sqlst);
			
			if (strcmp (ser1, ser2)) {
				g_set_error (error, TEST_ERROR, TEST_ERROR_GENERIC,
					     "Statement failed, ID: %s\nSQL: %s\nSER1: %s\nSER2 :%s", 
					     id, rsql, ser1, ser2);
				g_free (ser1);
				g_free (ser2);
				return FALSE;
			}
			
			g_free (rsql);
			g_free (ser1);
			g_free (ser2);
			g_object_unref (stmt);
			g_object_unref (stmt2);
		}
		
		xmlFree (id);

		if (lerror)
			g_error_free (lerror);
	}

	g_object_unref (parser);

	return TRUE;
}
Example #11
0
File: subshell.c Project: artzub/mc
static void
init_subshell_child (const char *pty_name)
{
    char *init_file = NULL;
    pid_t mc_sid;

    (void) pty_name;
    setsid ();                  /* Get a fresh terminal session */

    /* Make sure that it has become our controlling terminal */

    /* Redundant on Linux and probably most systems, but just in case: */

#ifdef TIOCSCTTY
    ioctl (subshell_pty_slave, TIOCSCTTY, 0);
#endif

    /* Configure its terminal modes and window size */

    /* Set up the pty with the same termios flags as our own tty */
    if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
    {
        fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
        _exit (FORK_FAILURE);
    }

    /* Set the pty's size (80x25 by default on Linux) according to the */
    /* size of the real terminal as calculated by ncurses, if possible */
    tty_resize (subshell_pty_slave);

    /* Set up the subshell's environment and init file name */

    /* It simplifies things to change to our home directory here, */
    /* and the user's startup file may do a `cd' command anyway   */
    {
        int ret;
        ret = chdir (mc_config_get_home_dir ());        /* FIXME? What about when we re-run the subshell? */
    }

    /* Set MC_SID to prevent running one mc from another */
    mc_sid = getsid (0);
    if (mc_sid != -1)
    {
        char sid_str[BUF_SMALL];
        g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
        putenv (g_strdup (sid_str));
    }

    switch (subshell_type)
    {
    case BASH:
        init_file = g_build_filename (mc_config_get_path (), "bashrc", NULL);

        if (access (init_file, R_OK) == -1)
        {
            g_free (init_file);
            init_file = g_strdup (".bashrc");
        }

        /* Make MC's special commands not show up in bash's history */
        putenv ((char *) "HISTCONTROL=ignorespace");

        /* Allow alternative readline settings for MC */
        {
            char *input_file = g_build_filename (mc_config_get_path (), "inputrc", NULL);
            if (access (input_file, R_OK) == 0)
            {
                char *putenv_str = g_strconcat ("INPUTRC=", input_file, NULL);
                putenv (putenv_str);
                g_free (putenv_str);
            }
            g_free (input_file);
        }

        break;

    /* TODO: Find a way to pass initfile to TCSH and ZSH */
    case TCSH:
    case ZSH:
    case FISH:
        break;

    default:
        fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
        _exit (FORK_FAILURE);
    }

    /* Attach all our standard file descriptors to the pty */

    /* This is done just before the fork, because stderr must still      */
    /* be connected to the real tty during the above error messages; */
    /* otherwise the user will never see them.                   */

    dup2 (subshell_pty_slave, STDIN_FILENO);
    dup2 (subshell_pty_slave, STDOUT_FILENO);
    dup2 (subshell_pty_slave, STDERR_FILENO);

    close (subshell_pipe[READ]);
    close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
    /* Close master side of pty.  This is important; apart from */
    /* freeing up the descriptor for use in the subshell, it also       */
    /* means that when MC exits, the subshell will get a SIGHUP and     */
    /* exit too, because there will be no more descriptors pointing     */
    /* at the master side of the pty and so it will disappear.  */
    close (mc_global.tty.subshell_pty);

    /* Execute the subshell at last */

    switch (subshell_type)
    {
    case BASH:
        execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
        break;

    case TCSH:
        execl (shell, "tcsh", (char *) NULL);
        break;

    case ZSH:
        /* Use -g to exclude cmds beginning with space from history
         * and -Z to use the line editor on non-interactive term */
        execl (shell, "zsh", "-Z", "-g", (char *) NULL);

        break;

    case FISH:
        execl (shell, "fish", (char *) NULL);
        break;
    }

    /* If we get this far, everything failed miserably */
    g_free (init_file);
    _exit (FORK_FAILURE);
}
Example #12
0
/**
 * e_xml_save_file:
 * @filename: path to a file to save to
 * @doc: an XML document structure
 *
 * Writes the given XML document structure to the file given by @filename.
 * If an error occurs while saving, the function returns -1 and sets errno.
 *
 * Returns: 0 on success, -1 on failure
 **/
gint
e_xml_save_file (const gchar *filename,
                 xmlDocPtr doc)
{
    gchar *filesave;
    xmlChar *xmlbuf;
    gsize n, written = 0;
    gint ret, fd, size;
    gint errnosave;
    gssize w;
    gchar *dirname = g_path_get_dirname (filename);
    gchar *basename = g_path_get_basename (filename);
    gchar *savebasename = g_strconcat (".#", basename, NULL);

    g_free (basename);
    filesave = g_build_filename (dirname, savebasename, NULL);
    g_free (savebasename);
    g_free (dirname);

    fd = g_open (filesave, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0600);
    if (fd == -1) {
        g_free (filesave);
        return -1;
    }

    xmlDocDumpFormatMemory (doc, &xmlbuf, &size, TRUE);
    if (size <= 0) {
        close (fd);
        g_unlink (filesave);
        g_free (filesave);
        errno = ENOMEM;
        return -1;
    }

    n = (gsize) size;
    do {
        do {
            w = write (fd, xmlbuf + written, n - written);
        } while (w == -1 && errno == EINTR);

        if (w > 0)
            written += w;
    } while (w != -1 && written < n);

    xmlFree (xmlbuf);

    if (written < n || fsync (fd) == -1) {
        errnosave = errno;
        close (fd);
        g_unlink (filesave);
        g_free (filesave);
        errno = errnosave;
        return -1;
    }

    while ((ret = close (fd)) == -1 && errno == EINTR)
        ;

    if (ret == -1) {
        g_free (filesave);
        return -1;
    }

    if (g_rename (filesave, filename) == -1) {
        errnosave = errno;
        g_unlink (filesave);
        g_free (filesave);
        errno = errnosave;
        return -1;
    }
    g_free (filesave);

    return 0;
}
Example #13
0
void inititializeFontConfigSetting()
{
    FcInit();

    // If a test resulted a font being added or removed via the @font-face rule, then
    // we want to reset the FontConfig configuration to prevent it from affecting other tests.
    static int numFonts = 0;
    FcFontSet* appFontSet = FcConfigGetFonts(0, FcSetApplication);
    if (appFontSet && numFonts && appFontSet->nfont == numFonts)
        return;

    // Load our configuration file, which sets up proper aliases for family
    // names like sans, serif and monospace.
    FcConfig* config = FcConfigCreate();
    GOwnPtr<gchar> fontConfigFilename(g_build_filename(FONTS_CONF_DIR, "fonts.conf", NULL));
    if (!g_file_test(fontConfigFilename.get(), G_FILE_TEST_IS_REGULAR))
        g_error("Cannot find fonts.conf at %s\n", fontConfigFilename.get());
    if (!FcConfigParseAndLoad(config, reinterpret_cast<FcChar8*>(fontConfigFilename.get()), true))
        g_error("Couldn't load font configuration file from: %s", fontConfigFilename.get());

    static const char *const fontDirectories[] = {
        "/usr/share/fonts/truetype/liberation",
        "/usr/share/fonts/truetype/ttf-liberation",
        "/usr/share/fonts/liberation",
        "/usr/share/fonts/truetype/ttf-dejavu",
        "/usr/share/fonts/dejavu",
        "/usr/share/fonts/opentype/stix",
        "/usr/share/fonts/stix"
    };

    static const char *const fontPaths[] = {
        "LiberationMono-BoldItalic.ttf",
        "LiberationMono-Bold.ttf",
        "LiberationMono-Italic.ttf",
        "LiberationMono-Regular.ttf",
        "LiberationSans-BoldItalic.ttf",
        "LiberationSans-Bold.ttf",
        "LiberationSans-Italic.ttf",
        "LiberationSans-Regular.ttf",
        "LiberationSerif-BoldItalic.ttf",
        "LiberationSerif-Bold.ttf",
        "LiberationSerif-Italic.ttf",
        "LiberationSerif-Regular.ttf",
        "DejaVuSans.ttf",
        "DejaVuSerif.ttf",

        // MathML tests require the STIX fonts.
        "STIXGeneral.otf",
        "STIXGeneralBolIta.otf",
        "STIXGeneralBol.otf",
        "STIXGeneralItalic.otf"
    };

    // TODO: Some tests use Lucida. We should load these as well, once it becomes
    // clear how to install these fonts easily on Fedora.
    for (size_t font = 0; font < G_N_ELEMENTS(fontPaths); font++) {
        bool found = false;
        for (size_t path = 0; path < G_N_ELEMENTS(fontDirectories); path++) {
            GOwnPtr<gchar> fullPath(g_build_filename(fontDirectories[path], fontPaths[font], NULL));
            if (g_file_test(fullPath.get(), G_FILE_TEST_EXISTS)) {
                found = true;
                if (!FcConfigAppFontAddFile(config, reinterpret_cast<const FcChar8*>(fullPath.get())))
                    g_error("Could not load font at %s!", fullPath.get());
                else
                    break;
            }
        }

        if (!found) {
            GOwnPtr<gchar> directoriesDescription;
            for (size_t path = 0; path < G_N_ELEMENTS(fontDirectories); path++)
                directoriesDescription.set(g_strjoin(":", directoriesDescription.release(), fontDirectories[path], NULL));
            g_error("Could not find font %s in %s. Either install this font or file a bug "
                    "at http://bugs.webkit.org if it is installed in another location.",
                    fontPaths[font], directoriesDescription.get());
        }
    }

    // Ahem is used by many layout tests.
    GOwnPtr<gchar> ahemFontFilename(g_build_filename(FONTS_CONF_DIR, "AHEM____.TTF", NULL));
    if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(ahemFontFilename.get())))
        g_error("Could not load font at %s!", ahemFontFilename.get()); 

    static const char* fontFilenames[] = {
        "WebKitWeightWatcher100.ttf",
        "WebKitWeightWatcher200.ttf",
        "WebKitWeightWatcher300.ttf",
        "WebKitWeightWatcher400.ttf",
        "WebKitWeightWatcher500.ttf",
        "WebKitWeightWatcher600.ttf",
        "WebKitWeightWatcher700.ttf",
        "WebKitWeightWatcher800.ttf",
        "WebKitWeightWatcher900.ttf",
        0
    };

    for (size_t i = 0; fontFilenames[i]; ++i) {
        GOwnPtr<gchar> fontFilename(g_build_filename(FONTS_CONF_DIR, "..", "..", "fonts", fontFilenames[i], NULL));
        if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(fontFilename.get())))
            g_error("Could not load font at %s!", fontFilename.get()); 
    }

    // A font with no valid Fontconfig encoding to test https://bugs.webkit.org/show_bug.cgi?id=47452
    GOwnPtr<gchar> fontWithNoValidEncodingFilename(g_build_filename(FONTS_CONF_DIR, "FontWithNoValidEncoding.fon", NULL));
    if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(fontWithNoValidEncodingFilename.get())))
        g_error("Could not load font at %s!", fontWithNoValidEncodingFilename.get()); 

    if (!FcConfigSetCurrent(config))
        g_error("Could not set the current font configuration!");

    numFonts = FcConfigGetFonts(config, FcSetApplication)->nfont;
}
Example #14
0
int
main (int argc, char *argv[])
{
  GError *error = NULL;
  GOptionContext *context;
  GMainLoop *loop;
  GInetAddress *inet;
  GSocketAddress *address;
  GSocketService *listener;
  char *path, *basename;
  char *http_address = NULL;
  int http_port = 0;
  char *display;
  int port = 0;
  const GOptionEntry entries[] = {
    { "port", 'p', 0, G_OPTION_ARG_INT, &http_port, "Httpd port", "PORT" },
    { "address", 'a', 0, G_OPTION_ARG_STRING, &http_address, "Ip address to bind to ", "ADDRESS" },
    { NULL }
  };

  context = g_option_context_new ("[:DISPLAY] - broadway display daemon");
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("option parsing failed: %s\n", error->message);
      exit (1);
    }

  display = NULL;
  if (argc > 1)
    {
      if (*argv[1] != ':')
	{
	  g_printerr ("Usage broadwayd [:DISPLAY]\n");
	  exit (1);
	}
      display = argv[1];
    }

  if (display == NULL)
    {
#ifdef G_OS_UNIX
      display = ":0";
#else
      display = ":tcp";
#endif
    }

  if (g_str_has_prefix (display, ":tcp"))
    {
      port = strtol (display + strlen (":tcp"), NULL, 10);

      inet = g_inet_address_new_from_string ("127.0.0.1");
      g_print ("Listening on 127.0.0.1:%d\n", port + 9090);
      address = g_inet_socket_address_new (inet, port + 9090);
      g_object_unref (inet);
    }
#ifdef G_OS_UNIX
  else if (display[0] == ':' && g_ascii_isdigit(display[1]))
    {
      port = strtol (display + strlen (":"), NULL, 10);
      basename = g_strdup_printf ("broadway%d.socket", port + 1);
      path = g_build_filename (g_get_user_runtime_dir (), basename, NULL);
      g_free (basename);

      g_print ("Listening on %s\n", path);
      address = g_unix_socket_address_new_with_type (path, -1,
						     G_UNIX_SOCKET_ADDRESS_ABSTRACT);
      g_free (path);
    }
#endif
  else
    {
      g_printerr ("Failed to parse display %s\n", display);
      exit (1);
    }

  if (http_port == 0)
    http_port = 8080 + port;

  server = broadway_server_new (http_address, http_port, &error);
  if (server == NULL)
    {
      g_printerr ("%s\n", error->message);
      return 1;
    }

  listener = g_socket_service_new ();
  if (!g_socket_listener_add_address (G_SOCKET_LISTENER (listener),
				      address,
				      G_SOCKET_TYPE_STREAM,
				      G_SOCKET_PROTOCOL_DEFAULT,
				      G_OBJECT (server),
				      NULL,
				      &error))
    {
      g_printerr ("Can't listen: %s\n", error->message);
      return 1;
    }
  g_object_unref (address);
  g_signal_connect (listener, "incoming", G_CALLBACK (incoming_client), NULL);

  g_socket_service_start (G_SOCKET_SERVICE (listener));

  loop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (loop);
  
  return 0;
}
static void
migrate_to_user_cache_dir (const gchar *old_base_dir)
{
	const gchar *new_cache_dir;
	gchar *old_cache_dir;
	gchar *src_directory;
	gchar *dst_directory;

	old_cache_dir = g_build_filename (old_base_dir, "cache", NULL);
	new_cache_dir = e_get_user_cache_dir ();

	g_print ("Migrating cached backend data\n");

	/* We don't want to move the source directory directly because the
	 * destination directory may already exist with content.  Instead
	 * we want to merge the content of the source directory into the
	 * destination directory.
	 *
	 * For example, given:
	 *
	 *    $(src_directory)/A   and   $(dst_directory)/B
	 *    $(src_directory)/C
	 *
	 * we want to end up with:
	 *
	 *    $(dst_directory)/A
	 *    $(dst_directory)/B
	 *    $(dst_directory)/C
	 *
	 * Any name collisions will be left in the source directory.
	 */

	src_directory = g_build_filename (old_cache_dir, "calendar", NULL);
	dst_directory = g_build_filename (new_cache_dir, "calendar", NULL);

	migrate_move_contents (src_directory, dst_directory);
	migrate_rmdir (src_directory);

	g_free (src_directory);
	g_free (dst_directory);

	src_directory = g_build_filename (old_cache_dir, "memos", NULL);
	dst_directory = g_build_filename (new_cache_dir, "memos", NULL);

	migrate_move_contents (src_directory, dst_directory);
	migrate_rmdir (src_directory);

	g_free (src_directory);
	g_free (dst_directory);

	src_directory = g_build_filename (old_cache_dir, "tasks", NULL);
	dst_directory = g_build_filename (new_cache_dir, "tasks", NULL);

	migrate_move_contents (src_directory, dst_directory);
	migrate_rmdir (src_directory);

	g_free (src_directory);
	g_free (dst_directory);

	/* Try to remove the old cache directory.  Good chance this will
	 * fail on the first try, since Evolution puts stuff here too. */
	migrate_rmdir (old_cache_dir);

	g_free (old_cache_dir);
}
Example #16
0
void
dialog_search (WBCGtk *wbcg)
{
	GtkBuilder *gui;
	GtkDialog *dialog;
	DialogState *dd;
	GtkTable *table;
	char *f;

	g_return_if_fail (wbcg != NULL);

#ifdef USE_GURU
	/* Only one guru per workbook. */
	if (wbc_gtk_get_guru (wbcg))
		return;
#endif

	f = g_build_filename (gnm_sys_data_dir (), "ui", "search.ui", NULL);
	gui = go_gtk_builder_new (f, NULL, GO_CMD_CONTEXT (wbcg));
	g_free (f);
        if (gui == NULL)
                return;

	dialog = GTK_DIALOG (gtk_builder_get_object (gui, "search_dialog"));

	dd = g_new (DialogState, 1);
	dd->wbcg = wbcg;
	dd->gui = gui;
	dd->dialog = dialog;
	dd->matches = g_ptr_array_new ();

	dd->prev_button = go_gtk_builder_get_widget (gui, "prev_button");
	dd->next_button = go_gtk_builder_get_widget (gui, "next_button");

	dd->notebook = GTK_NOTEBOOK (gtk_builder_get_object (gui, "notebook"));
	dd->notebook_matches_page =
		gtk_notebook_page_num (dd->notebook,
				       go_gtk_builder_get_widget (gui, "matches_tab"));

	dd->rangetext = gnm_expr_entry_new (wbcg, TRUE);
	gnm_expr_entry_set_flags (dd->rangetext, 0, GNM_EE_MASK);
	table = GTK_TABLE (gtk_builder_get_object (gui, "page1-table"));
	gtk_table_attach (table, GTK_WIDGET (dd->rangetext),
			  1, 2, 6, 7,
			  GTK_EXPAND | GTK_FILL, 0,
			  0, 0);
	{
		char *selection_text =
			selection_to_string (
				wb_control_cur_sheet_view (WORKBOOK_CONTROL (wbcg)),
				TRUE);
		gnm_expr_entry_load_from_text  (dd->rangetext, selection_text);
		g_free (selection_text);
	}

	dd->gentry = GTK_ENTRY (gtk_entry_new ());
	gtk_table_attach (table, GTK_WIDGET (dd->gentry),
			  1, 2, 0, 1,
			  GTK_EXPAND | GTK_FILL, 0,
			  0, 0);
	gtk_widget_grab_focus (GTK_WIDGET (dd->gentry));
	gnumeric_editable_enters (GTK_WINDOW (dialog), GTK_WIDGET (dd->gentry));

	dd->matches_table = make_matches_table (dd);

	{
		GtkWidget *scrolled_window =
			gtk_scrolled_window_new (NULL, NULL);
		gtk_container_add (GTK_CONTAINER (scrolled_window),
				   GTK_WIDGET (dd->matches_table));
		gtk_box_pack_start (GTK_BOX (gtk_builder_get_object (gui, "matches_vbox")),
				    scrolled_window,
				    TRUE, TRUE, 0);
		gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
						GTK_POLICY_NEVER,
						GTK_POLICY_ALWAYS);
	}

	/* Set sensitivity of buttons.  */
	cursor_change (dd->matches_table, dd);

	g_signal_connect (G_OBJECT (dd->matches_table), "cursor_changed",
		G_CALLBACK (cursor_change), dd);
	g_signal_connect (G_OBJECT (dd->matches_table), "select_cursor_row",
		G_CALLBACK (cb_next), dd);
	go_gtk_builder_signal_connect (gui, "search_button", "clicked",
		G_CALLBACK (search_clicked), dd);
	g_signal_connect (G_OBJECT (dd->prev_button), "clicked",
		G_CALLBACK (prev_clicked), dd);
	g_signal_connect (G_OBJECT (dd->next_button), "clicked",
		G_CALLBACK (next_clicked), dd);
	go_gtk_builder_signal_connect_swapped (gui, "close_button", "clicked",
		G_CALLBACK (gtk_widget_destroy), dd->dialog);
	g_signal_connect (G_OBJECT (gnm_expr_entry_get_entry (dd->rangetext)), "focus-in-event",
		G_CALLBACK (range_focused), dd);
	go_gtk_builder_signal_connect (gui, "scope_range", "toggled",
		G_CALLBACK (cb_focus_on_entry), dd->rangetext);

#ifdef USE_GURU
	wbc_gtk_attach_guru_with_unfocused_rs (wbcg, GTK_WIDGET (dialog), dd->rangetext);
#endif
	g_object_set_data_full (G_OBJECT (dialog),
		"state", dd, (GDestroyNotify) free_state);
	gnm_dialog_setup_destroy_handlers (dialog, wbcg,
		GNM_DIALOG_DESTROY_SHEET_REMOVED);
	gnumeric_init_help_button (
		go_gtk_builder_get_widget (gui, "help_button"),
		GNUMERIC_HELP_LINK_SEARCH);
	gnumeric_restore_window_geometry (GTK_WINDOW (dialog), SEARCH_KEY);

	go_gtk_nonmodal_dialog (wbcg_toplevel (wbcg), GTK_WINDOW (dialog));
	gtk_widget_show_all (GTK_WIDGET (dialog));
}
static void
migrate_to_user_data_dir (const gchar *old_base_dir)
{
	const gchar *new_data_dir;
	gchar *src_directory;
	gchar *dst_directory;

	new_data_dir = e_get_user_data_dir ();

	g_print ("Migrating local backend data\n");

	/* We don't want to move the source directory directly because the
	 * destination directory may already exist with content.  Instead
	 * we want to merge the content of the source directory into the
	 * destination directory.
	 *
	 * For example, given:
	 *
	 *    $(src_directory)/A   and   $(dst_directory)/B
	 *    $(src_directory)/C
	 *
	 * we want to end up with:
	 *
	 *    $(dst_directory)/A
	 *    $(dst_directory)/B
	 *    $(dst_directory)/C
	 *
	 * Any name collisions will be left in the source directory.
	 */

	src_directory = g_build_filename (old_base_dir, "calendar", "local", NULL);
	dst_directory = g_build_filename (new_data_dir, "calendar", NULL);

	migrate_move_contents (src_directory, dst_directory);
	migrate_rmdir (src_directory);

	g_free (src_directory);
	g_free (dst_directory);

	src_directory = g_build_filename (old_base_dir, "memos", "local", NULL);
	dst_directory = g_build_filename (new_data_dir, "memos", NULL);

	migrate_move_contents (src_directory, dst_directory);
	migrate_rmdir (src_directory);

	g_free (src_directory);
	g_free (dst_directory);

	src_directory = g_build_filename (old_base_dir, "tasks", "local", NULL);
	dst_directory = g_build_filename (new_data_dir, "tasks", NULL);

	migrate_move_contents (src_directory, dst_directory);
	migrate_rmdir (src_directory);

	g_free (src_directory);
	g_free (dst_directory);

	/* XXX This is not really the right place to be migrating
	 *     exchange data, but since we already cleaned out the
	 *     cached attachment files from this directory, may as
	 *     well move the user accounts too while we're at it. */

	src_directory = g_build_filename (old_base_dir, "exchange", NULL);
	dst_directory = g_build_filename (new_data_dir, "exchange", NULL);

	migrate_move_contents (src_directory, dst_directory);
	migrate_rmdir (src_directory);

	g_free (src_directory);
	g_free (dst_directory);
}
/**
 * nautilus_get_scripts_directory_path:
 *
 * Get the path for the directory containing nautilus scripts.
 *
 * Return value: the directory path containing nautilus scripts
 **/
char *
nautilus_get_scripts_directory_path (void)
{
	return g_build_filename (g_get_user_data_dir (), "nautilus", "scripts", NULL);
}
Example #19
0
G_MODULE_EXPORT gint
test_texture_quality_main (int argc, char *argv[])
{
  ClutterTimeline  *timeline;
  ClutterAlpha     *alpha;
  ClutterBehaviour *depth_behavior;
  ClutterActor     *stage;
  ClutterActor     *image;
  ClutterColor      stage_color = { 0x12, 0x34, 0x56, 0xff };
  ClutterFog        stage_fog = { 10.0, -50.0 };
  GError           *error;
  gchar            *file;

  clutter_init (&argc, &argv);

  stage = clutter_stage_get_default ();
  clutter_stage_set_color (CLUTTER_STAGE (stage), &stage_color);
  clutter_stage_set_use_fog (CLUTTER_STAGE (stage), TRUE);
  clutter_stage_set_fog (CLUTTER_STAGE (stage), &stage_fog);

  g_signal_connect (stage,
                    "button-press-event", G_CALLBACK (clutter_main_quit),
                    NULL);

  if (argc < 2)
    g_print ("Hint: the redhand.png isn't a good test image for this test.\n"
             "This test can take any image file as an argument\n");

  file = (argc > 1)
       ? g_strdup (argv[1])
       : g_build_filename (TESTS_DATADIR, "redhand.png", NULL);

  error = NULL;
  image = clutter_texture_new_from_file (file, &error);
  if (error)
    g_error ("Unable to load image: %s", error->message);

  g_free (file);

  /* center the image */
  clutter_actor_set_position (image, 
    (clutter_actor_get_width (stage) - clutter_actor_get_width (image))/2,
    (clutter_actor_get_height (stage) - clutter_actor_get_height (image))/2);
  clutter_container_add (CLUTTER_CONTAINER (stage), image, NULL);

  timeline = clutter_timeline_new (5000);
  g_signal_connect (timeline,
                    "completed", G_CALLBACK (timeline_completed),
                    NULL);

  alpha = clutter_alpha_new_full (timeline, CLUTTER_LINEAR);
  depth_behavior = clutter_behaviour_depth_new (alpha, -2500, 400);
  clutter_behaviour_apply (depth_behavior, image);

  clutter_actor_show (stage);
  clutter_timeline_start (timeline);

  g_timeout_add (10000, change_filter, image);

  clutter_main ();

  g_object_unref (depth_behavior);
  g_object_unref (timeline);

  return EXIT_SUCCESS;
}
Example #20
0
int main(int argc, char *argv[])
#endif
{
	gboolean opt_force_online = FALSE;
	gboolean opt_help = FALSE;
	gboolean opt_login = FALSE;
	gboolean opt_nologin = FALSE;
	gboolean opt_version = FALSE;
	gboolean opt_si = TRUE;     /* Check for single instance? */
	char *opt_config_dir_arg = NULL;
	char *opt_login_arg = NULL;
	char *opt_session_arg = NULL;
	char *search_path;
	GList *accounts;
#ifdef HAVE_SIGNAL_H
	int sig_indx;	/* for setting up signal catching */
	sigset_t sigset;
	RETSIGTYPE (*prev_sig_disp)(int);
	char errmsg[BUFSIZ];
	GIOChannel *signal_channel;
	GIOStatus signal_status;
	guint signal_channel_watcher;
#ifndef DEBUG
	char *segfault_message_tmp;
#endif
	GError *error;
#endif
	int opt;
	gboolean gui_check;
	gboolean debug_enabled;
	gboolean migration_failed = FALSE;
	GList *active_accounts;
	struct stat st;

	struct option long_options[] = {
		{"config",       required_argument, NULL, 'c'},
		{"debug",        no_argument,       NULL, 'd'},
		{"force-online", no_argument,       NULL, 'f'},
		{"help",         no_argument,       NULL, 'h'},
		{"login",        optional_argument, NULL, 'l'},
		{"multiple",     no_argument,       NULL, 'm'},
		{"nologin",      no_argument,       NULL, 'n'},
		{"session",      required_argument, NULL, 's'},
		{"version",      no_argument,       NULL, 'v'},
		{"display",      required_argument, NULL, 'D'},
		{"sync",         no_argument,       NULL, 'S'},
		{0, 0, 0, 0}
	};

#ifdef DEBUG
	debug_enabled = TRUE;
#else
	debug_enabled = FALSE;
#endif

	/* Initialize GThread before calling any Glib or GTK+ functions. */
	g_thread_init(NULL);

	g_set_prgname("Carrier");

#ifdef ENABLE_NLS
	bindtextdomain(PACKAGE, LOCALEDIR);
	bind_textdomain_codeset(PACKAGE, "UTF-8");
	textdomain(PACKAGE);
#endif

#ifdef HAVE_SETLOCALE
	/* Locale initialization is not complete here.  See gtk_init_check() */
	setlocale(LC_ALL, "");
#endif

#ifdef HAVE_SIGNAL_H

#ifndef DEBUG
		/* We translate this here in case the crash breaks gettext. */
		segfault_message_tmp = g_strdup_printf(_(
			"%s %s has segfaulted and attempted to dump a core file.\n"
			"This is a bug in the software and has happened through\n"
			"no fault of your own.\n\n"
			"If you can reproduce the crash, please notify the developers\n"
			"by reporting a bug at:\n"
			"%ssimpleticket/\n\n"
			"Please make sure to specify what you were doing at the time\n"
			"and post the backtrace from the core file.  If you do not know\n"
			"how to get the backtrace, please read the instructions at\n"
			"%swiki/GetABacktrace\n"),
			PIDGIN_NAME, DISPLAY_VERSION, PURPLE_DEVEL_WEBSITE, PURPLE_DEVEL_WEBSITE
		);

		/* we have to convert the message (UTF-8 to console
		   charset) early because after a segmentation fault
		   it's not a good practice to allocate memory */
		error = NULL;
		segfault_message = g_locale_from_utf8(segfault_message_tmp,
						      -1, NULL, NULL, &error);
		if (segfault_message != NULL) {
			g_free(segfault_message_tmp);
		}
		else {
			/* use 'segfault_message_tmp' (UTF-8) as a fallback */
			g_warning("%s\n", error->message);
			g_error_free(error);
			segfault_message = segfault_message_tmp;
		}
#else
		/* Don't mark this for translation. */
		segfault_message = g_strdup(
			"Hi, user.  We need to talk.\n"
			"I think something's gone wrong here.  It's probably my fault.\n"
			"No, really, it's not you... it's me... no no no, I think we get along well\n"
			"it's just that.... well, I want to see other people.  I... what?!?  NO!  I \n"
			"haven't been cheating on you!!  How many times do you want me to tell you?!  And\n"
			"for the last time, it's just a rash!\n"
		);
#endif

	/*
	 * Create a socket pair for receiving unix signals from a signal
	 * handler.
	 */
	if (socketpair(AF_UNIX, SOCK_STREAM, 0, signal_sockets) < 0) {
		perror("Failed to create sockets for GLib signal handling");
		exit(1);
	}
	signal_channel = g_io_channel_unix_new(signal_sockets[1]);

	/*
	 * Set the channel encoding to raw binary instead of the default of
	 * UTF-8, because we'll be sending integers across instead of strings.
	 */
	error = NULL;
	signal_status = g_io_channel_set_encoding(signal_channel, NULL, &error);
	if (signal_status != G_IO_STATUS_NORMAL) {
		fprintf(stderr, "Failed to set the signal channel to raw "
				"binary: %s", error->message);
		exit(1);
	}
	signal_channel_watcher = g_io_add_watch(signal_channel, G_IO_IN, mainloop_sighandler, NULL);
	g_io_channel_unref(signal_channel);

	/* Let's not violate any PLA's!!!! */
	/* jseymour: whatever the fsck that means */
	/* Robot101: for some reason things like gdm like to block     *
	 * useful signals like SIGCHLD, so we unblock all the ones we  *
	 * declare a handler for. thanks JSeymour and Vann.            */
	if (sigemptyset(&sigset)) {
		snprintf(errmsg, sizeof(errmsg), "Warning: couldn't initialise empty signal set");
		perror(errmsg);
	}
	for(sig_indx = 0; catch_sig_list[sig_indx] != -1; ++sig_indx) {
		if((prev_sig_disp = signal(catch_sig_list[sig_indx], sighandler)) == SIG_ERR) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't set signal %d for catching",
				catch_sig_list[sig_indx]);
			perror(errmsg);
		}
		if(sigaddset(&sigset, catch_sig_list[sig_indx])) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't include signal %d for unblocking",
				catch_sig_list[sig_indx]);
			perror(errmsg);
		}
	}
	for(sig_indx = 0; ignore_sig_list[sig_indx] != -1; ++sig_indx) {
		if((prev_sig_disp = signal(ignore_sig_list[sig_indx], SIG_IGN)) == SIG_ERR) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't set signal %d to ignore",
				ignore_sig_list[sig_indx]);
			perror(errmsg);
		}
	}

	if (sigprocmask(SIG_UNBLOCK, &sigset, NULL)) {
		snprintf(errmsg, sizeof(errmsg), "Warning: couldn't unblock signals");
		perror(errmsg);
	}
#endif

	/* scan command-line options */
	opterr = 1;
	while ((opt = getopt_long(argc, argv,
#ifndef _WIN32
				  "c:dfhmnl::s:v",
#else
				  "c:dfhmnl::v",
#endif
				  long_options, NULL)) != -1) {
		switch (opt) {
		case 'c':	/* config dir */
			g_free(opt_config_dir_arg);
			opt_config_dir_arg = g_strdup(optarg);
			break;
		case 'd':	/* debug */
			debug_enabled = TRUE;
			break;
		case 'f':	/* force-online */
			opt_force_online = TRUE;
			break;
		case 'h':	/* help */
			opt_help = TRUE;
			break;
		case 'n':	/* no autologin */
			opt_nologin = TRUE;
			break;
		case 'l':	/* login, option username */
			opt_login = TRUE;
			g_free(opt_login_arg);
			if (optarg != NULL)
				opt_login_arg = g_strdup(optarg);
			break;
		case 's':	/* use existing session ID */
			g_free(opt_session_arg);
			opt_session_arg = g_strdup(optarg);
			break;
		case 'v':	/* version */
			opt_version = TRUE;
			break;
		case 'm':   /* do not ensure single instance. */
			opt_si = FALSE;
			break;
		case 'D':   /* --display */
		case 'S':   /* --sync */
			/* handled by gtk_init_check below */
			break;
		case '?':	/* show terse help */
		default:
			show_usage(argv[0], TRUE);
#ifdef HAVE_SIGNAL_H
			g_free(segfault_message);
#endif
			return 0;
			break;
		}
	}

	/* show help message */
	if (opt_help) {
		show_usage(argv[0], FALSE);
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}
	/* show version message */
	if (opt_version) {
		printf("%s %s (libpurple %s)\n", PIDGIN_NAME, DISPLAY_VERSION,
		                                 purple_core_get_version());
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	/* set a user-specified config directory */
	if (opt_config_dir_arg != NULL) {
		purple_util_set_user_dir(opt_config_dir_arg);
	}

	/*
	 * We're done piddling around with command line arguments.
	 * Fire up this baby.
	 */

	purple_debug_set_enabled(debug_enabled);

	/* If we're using a custom configuration directory, we
	 * do NOT want to migrate, or weird things will happen. */
	if (opt_config_dir_arg == NULL)
	{
		if (!purple_core_migrate())
		{
			migration_failed = TRUE;
		}
	}

	search_path = g_build_filename(purple_user_dir(), "gtkrc-2.0", NULL);
	gtk_rc_add_default_file(search_path);
	g_free(search_path);

	gui_check = gtk_init_check(&argc, &argv);
	if (!gui_check) {
		char *display = gdk_get_display();

		printf("%s %s\n", PIDGIN_NAME, DISPLAY_VERSION);

		g_warning("cannot open display: %s", display ? display : "unset");
		g_free(display);
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif

		return 1;
	}

	g_set_application_name(PIDGIN_NAME);

#ifdef _WIN32
	winpidgin_init(hint);
#endif

	if (migration_failed)
	{
		char *old = g_strconcat(purple_home_dir(),
		                        G_DIR_SEPARATOR_S ".gaim", NULL);
		const char *text = _(
			"%s encountered errors migrating your settings "
			"from %s to %s. Please investigate and complete the "
			"migration by hand. Please report this error at http://developer.pidgin.im");
		GtkWidget *dialog;

		dialog = gtk_message_dialog_new(NULL,
		                                0,
		                                GTK_MESSAGE_ERROR,
		                                GTK_BUTTONS_CLOSE,
		                                text, PIDGIN_NAME,
		                                old, purple_user_dir());
		g_free(old);

		g_signal_connect_swapped(dialog, "response",
		                         G_CALLBACK(gtk_main_quit), NULL);

		gtk_widget_show_all(dialog);

		gtk_main();

#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	purple_core_set_ui_ops(pidgin_core_get_ui_ops());
	purple_eventloop_set_ui_ops(pidgin_eventloop_get_ui_ops());

	/*
	 * Set plugin search directories. Give priority to the plugins
	 * in user's home directory.
	 */
	search_path = g_build_filename(purple_user_dir(), "plugins", NULL);
	if (!g_stat(search_path, &st))
		g_mkdir(search_path, S_IRUSR | S_IWUSR | S_IXUSR);
	purple_plugins_add_search_path(search_path);
	g_free(search_path);
	purple_plugins_add_search_path(LIBDIR);

	if (!purple_core_init(PIDGIN_UI)) {
		fprintf(stderr,
				"Initialization of the libpurple core failed. Dumping core.\n"
				"Please report this!\n");
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		abort();
	}

	if (opt_si && !purple_core_ensure_single_instance()) {
#ifdef HAVE_DBUS
		DBusConnection *conn = purple_dbus_get_connection();
		DBusMessage *message = dbus_message_new_method_call(DBUS_SERVICE_PURPLE, DBUS_PATH_PURPLE,
				DBUS_INTERFACE_PURPLE, "PurpleBlistSetVisible");
		gboolean tr = TRUE;
		dbus_message_append_args(message, DBUS_TYPE_INT32, &tr, DBUS_TYPE_INVALID);
		dbus_connection_send_with_reply_and_block(conn, message, -1, NULL);
		dbus_message_unref(message);
#endif
		gdk_notify_startup_complete();
		purple_core_quit();
		g_printerr(_("Exiting because another libpurple client is already running.\n"));
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	/* TODO: Move blist loading into purple_blist_init() */
	purple_set_blist(purple_blist_new());
	purple_blist_load();

	/* load plugins we had when we quit */
	purple_plugins_load_saved(PIDGIN_PREFS_ROOT "/plugins/loaded");

	/* TODO: Move pounces loading into purple_pounces_init() */
	purple_pounces_load();

	ui_main();

#ifdef USE_SM
	pidgin_session_init(argv[0], opt_session_arg, opt_config_dir_arg);
#endif
	if (opt_session_arg != NULL) {
		g_free(opt_session_arg);
		opt_session_arg = NULL;
	}
	if (opt_config_dir_arg != NULL) {
		g_free(opt_config_dir_arg);
		opt_config_dir_arg = NULL;
	}

	/* This needs to be before purple_blist_show() so the
	 * statusbox gets the forced online status. */
	if (opt_force_online)
		purple_network_force_online();

	/*
	 * We want to show the blist early in the init process so the
	 * user feels warm and fuzzy (not cold and prickley).
	 */
	purple_blist_show();

	if (purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/debug/enabled"))
		pidgin_debug_window_show();

	if (opt_login) {
		/* disable all accounts */
		for (accounts = purple_accounts_get_all(); accounts != NULL; accounts = accounts->next) {
			PurpleAccount *account = accounts->data;
			purple_account_set_enabled(account, PIDGIN_UI, FALSE);
		}
		/* honor the startup status preference */
		if (!purple_prefs_get_bool("/purple/savedstatus/startup_current_status"))
			purple_savedstatus_activate(purple_savedstatus_get_startup());
		/* now enable the requested ones */
		dologin_named(opt_login_arg);
		if (opt_login_arg != NULL) {
			g_free(opt_login_arg);
			opt_login_arg = NULL;
		}
	} else if (opt_nologin)	{
		/* Set all accounts to "offline" */
		PurpleSavedStatus *saved_status;

		/* If we've used this type+message before, lookup the transient status */
		saved_status = purple_savedstatus_find_transient_by_type_and_message(
							PURPLE_STATUS_OFFLINE, NULL);

		/* If this type+message is unique then create a new transient saved status */
		if (saved_status == NULL)
			saved_status = purple_savedstatus_new(NULL, PURPLE_STATUS_OFFLINE);

		/* Set the status for each account */
		purple_savedstatus_activate(saved_status);
	} else {
		/* Everything is good to go--sign on already */
		if (!purple_prefs_get_bool("/purple/savedstatus/startup_current_status"))
			purple_savedstatus_activate(purple_savedstatus_get_startup());
		purple_accounts_restore_current_statuses();
	}

	if ((active_accounts = purple_accounts_get_all_active()) == NULL)
	{
		pidgin_accounts_window_show();
	}
	else
	{
		g_list_free(active_accounts);
	}

	/* GTK clears the notification for us when opening the first window,
	 * but we may have launched with only a status icon, so clear the it
	 * just in case. */
	gdk_notify_startup_complete();

#ifdef _WIN32
	winpidgin_post_init();
#endif

	gtk_main();

#ifdef HAVE_SIGNAL_H
	g_free(segfault_message);
	g_source_remove(signal_channel_watcher);
	close(signal_sockets[0]);
	close(signal_sockets[1]);
#endif

#ifdef _WIN32
	winpidgin_cleanup();
#endif

	return 0;
}
Example #21
0
void
libgoffice_init (void)
{
	if (initialized++)
		return;

#ifdef G_OS_WIN32
	{
	gchar *dir;

#define S(s)	#s
	char const *module_name =
		"libgoffice-" S(GO_VERSION_EPOCH) "-" S(GO_VERSION_MAJOR) ".dll";
#undef S
	wchar_t *wc_module_name = g_utf8_to_utf16 (module_name, -1, NULL, NULL, NULL);
	HMODULE hmodule = GetModuleHandleW (wc_module_name);
	g_free (wc_module_name);
	dir = g_win32_get_package_installation_directory_of_module (hmodule);

	libgoffice_data_dir = g_build_filename (dir,
		"share", "goffice", GOFFICE_VERSION, NULL);
	libgoffice_icon_dir = g_build_filename (dir,
		"share", "pixmaps", "goffice", GOFFICE_VERSION, NULL);
	libgoffice_locale_dir = g_build_filename (dir,
		"share", "locale", NULL);
	libgoffice_lib_dir = g_build_filename (dir,
		"lib", "goffice", GOFFICE_VERSION, NULL);
	g_free (dir);
	}
#else
#ifdef GTKOSXAPPLICATION
    if (quartz_application_get_bundle_id ())
    {
        gchar *dir;

        dir = quartz_application_get_resource_path ();
	libgoffice_data_dir = g_build_filename (dir,
		"share", "goffice", GOFFICE_VERSION, NULL);
	libgoffice_icon_dir = g_build_filename (dir,
		"share", "pixmaps", "goffice", GOFFICE_VERSION, NULL);
	libgoffice_locale_dir = g_build_filename (dir,
		"share", "locale", NULL);
	libgoffice_lib_dir = g_build_filename (dir,
		"lib", "goffice", GOFFICE_VERSION, NULL);
	g_free (dir);
    }
#endif /* GTKOSXAPPLICATION */
#endif

	bindtextdomain (GETTEXT_PACKAGE, libgoffice_locale_dir);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	gsf_init ();

	_go_string_init ();
	_go_conf_init ();
	_go_fonts_init ();
	_go_math_init ();
	_go_rsm_init ();
	go_register_ui_files ();

	/* keep trigger happy linkers from leaving things out */
	_go_plugin_services_init ();
	_gog_plugin_services_init ();
#ifdef GOFFICE_WITH_GTK
	_goc_plugin_services_init ();
	install_icons ();
#endif
	g_type_ensure (GO_TYPE_PLUGIN_LOADER_MODULE);
	g_type_ensure (GOG_TYPE_GRAPH);
	g_type_ensure (GOG_TYPE_CHART);
	g_type_ensure (GOG_TYPE_PLOT);
	g_type_ensure (GOG_TYPE_SERIES);
	g_type_ensure (GOG_TYPE_SERIES_ELEMENT);
	g_type_ensure (GOG_TYPE_LEGEND);
	g_type_ensure (GOG_TYPE_AXIS);
	g_type_ensure (GOG_TYPE_AXIS_LINE);
	g_type_ensure (GOG_TYPE_COLOR_SCALE);
	g_type_ensure (GOG_TYPE_LABEL);
	g_type_ensure (GOG_TYPE_GRID);
	g_type_ensure (GOG_TYPE_GRID_LINE);
#ifdef GOFFICE_WITH_LASEM
	g_type_ensure (GOG_TYPE_EQUATION);
#endif
	g_type_ensure (GOG_TYPE_ERROR_BAR);
	g_type_ensure (GOG_TYPE_REG_EQN);
	g_type_ensure (GOG_TYPE_SERIES_LABELS);
	g_type_ensure (GOG_TYPE_DATA_LABEL);
	g_type_ensure (GOG_TYPE_SERIES_LINES);
	g_type_ensure (GO_TYPE_DATA_SCALAR_VAL);
	g_type_ensure (GO_TYPE_DATA_SCALAR_STR);
	g_type_ensure (GOG_3D_BOX_TYPE);
	g_type_ensure (GO_TYPE_EMF);
	g_type_ensure (GO_TYPE_PIXBUF);
	g_type_ensure (GO_TYPE_SPECTRE);
	g_type_ensure (GO_TYPE_SVG);

	_gog_themes_init ();
	_go_number_format_init ();
	_go_currency_date_format_init ();
	_go_distributions_init ();
	initialized = TRUE;
}
Example #22
0
/*
 * "force" implies here to change the brush even if it was the same.
 * It is used for the initialization of the preview.
 * */
static void
brush_select (GtkTreeSelection *selection, gboolean force)
{
  GtkTreeIter   iter;
  GtkTreeModel *model;
  gchar        *fname = NULL;
  gchar        *brush = NULL;

  if (brush_dont_update)
    goto cleanup;

  if (brush_from_file == 0)
    {
      update_brush_preview (NULL);
      goto cleanup;
    }

  if (gtk_tree_selection_get_selected (selection, &model, &iter))
    {
      gtk_tree_model_get (model, &iter, 0, &brush, -1);

      /* Check if the same brush was selected twice, and if so
       * break. Otherwise, the brush gamma and stuff would have been
       * reset.
       * */
      if (last_selected_brush == NULL)
        {
          last_selected_brush = g_strdup (brush);
        }
      else
        {
          if (!strcmp (last_selected_brush, brush))
            {
              if (!force)
                {
                  goto cleanup;
                }
            }
          else
            {
              g_free (last_selected_brush);
              last_selected_brush = g_strdup (brush);
            }
        }

      brush_dont_update = TRUE;
      gtk_adjustment_set_value (brush_gamma_adjust, 1.0);
      gtk_adjustment_set_value (brush_aspect_adjust, 0.0);
      brush_dont_update = FALSE;

      if (brush)
        {
          fname = g_build_filename ("Brushes", brush, NULL);

          g_strlcpy (pcvals.selected_brush,
                     fname, sizeof (pcvals.selected_brush));

          update_brush_preview (fname);

        }
    }
cleanup:
  g_free (fname);
  g_free (brush);
}
Example #23
0
G_MODULE_EXPORT int
test_shader_effects_main (int argc, char *argv[])
{
  ClutterTimeline *timeline;
  ClutterActor *stage, *hand, *label, *rect;
  gchar *file;

  clutter_init (&argc, &argv);

  /* Make a timeline */
  timeline = clutter_timeline_new (7692);
  clutter_timeline_set_loop (timeline, TRUE);

  stage = clutter_stage_new ();
  clutter_stage_set_title (CLUTTER_STAGE (stage), "Rotations");
  clutter_stage_set_color (CLUTTER_STAGE (stage), CLUTTER_COLOR_Aluminium3);
  g_signal_connect (stage, "destroy", G_CALLBACK (clutter_main_quit), NULL);

  /* Make a hand */
  file = g_build_filename (TESTS_DATADIR, "redhand.png", NULL);
  hand = clutter_texture_new_from_file (file, NULL);
  if (!hand)
    g_error("Unable to load '%s'", file);

  g_free (file);

  clutter_actor_set_position (hand, 326, 265);
  clutter_actor_add_effect_with_name (hand, "desaturate", clutter_desaturate_effect_new (0.75));
  clutter_actor_add_effect_with_name (hand, "blur", clutter_blur_effect_new ());
  clutter_actor_animate_with_timeline (hand, CLUTTER_LINEAR, timeline,
                                       "@effects.desaturate.factor", 1.0,
                                       "rotation-angle-z", 360.0,
                                       "fixed::anchor-x", 86.0,
                                       "fixed::anchor-y", 125.0,
                                       "opacity", 128,
                                       NULL);

  rect = clutter_rectangle_new_with_color (CLUTTER_COLOR_DarkOrange);
  clutter_actor_add_effect_with_name (rect, "blur", clutter_blur_effect_new ());
  clutter_actor_set_position (rect, 415, 215);
  clutter_actor_set_size (rect, 150, 150);
  clutter_actor_animate_with_timeline (rect, CLUTTER_LINEAR, timeline,
                                       "rotation-angle-z", 360.0,
                                       "fixed::anchor-x", 75.0,
                                       "fixed::anchor-y", 75.0,
                                       NULL);

  label = clutter_text_new_with_text ("Mono 16",
                                      "The Wonder\n"
                                      "of the\n"
                                      "Spinning Hand");
  clutter_text_set_line_alignment (CLUTTER_TEXT (label), PANGO_ALIGN_CENTER);
  clutter_actor_set_position (label, 336, 275);
  clutter_actor_set_size (label, 500, 100);
  clutter_actor_animate_with_timeline (label, CLUTTER_LINEAR, timeline,
                                       "rotation-angle-z", 360.0,
                                       "fixed::anchor-x", 86.0,
                                       "fixed::anchor-y", 125.0,
                                       NULL);

  clutter_container_add (CLUTTER_CONTAINER (stage), rect, hand, label, NULL);
  
  /* start the timeline and thus the animations */
  clutter_timeline_start (timeline);

  clutter_actor_show_all (stage);

  clutter_main();

  g_object_unref (timeline);

  return 0;
}
Example #24
0
gchar *
nemo_action_manager_get_user_directory_path (void)
{
    return g_build_filename (g_get_user_data_dir (), "nemo", "actions", NULL);
}
static XdgDirEntry *
parse_xdg_dirs (const char *config_file)
{
  GArray *array;
  char *config_file_free = NULL;
  XdgDirEntry dir;
  char *data;
  char **lines;
  char *p, *d;
  int i;
  char *type_start, *type_end;
  char *value, *unescaped;
  gboolean relative;

  array = g_array_new (TRUE, TRUE, sizeof (XdgDirEntry));
  
  if (config_file == NULL)
    {
      config_file_free = g_build_filename (g_get_user_config_dir (),
					   "user-dirs.dirs", NULL);
      config_file = (const char *)config_file_free;
    }

  if (g_file_get_contents (config_file, &data, NULL, NULL))
    {
      lines = g_strsplit (data, "\n", 0);
      g_free (data);
      for (i = 0; lines[i] != NULL; i++)
	{
	  p = lines[i];
	  while (g_ascii_isspace (*p))
	    p++;
      
	  if (*p == '#')
	    continue;
      
	  value = strchr (p, '=');
	  if (value == NULL)
	    continue;
	  *value++ = 0;
      
	  g_strchug (g_strchomp (p));
	  if (!g_str_has_prefix (p, "XDG_"))
	    continue;
	  if (!g_str_has_suffix (p, "_DIR"))
	    continue;
	  type_start = p + 4;
	  type_end = p + strlen (p) - 4;
      
	  while (g_ascii_isspace (*value))
	    value++;
      
	  if (*value != '"')
	    continue;
	  value++;
      
	  relative = FALSE;
	  if (g_str_has_prefix (value, "$HOME"))
	    {
	      relative = TRUE;
	      value += 5;
	      while (*value == '/')
		      value++;
	    }
	  else if (*value != '/')
	    continue;
	  
	  d = unescaped = g_malloc (strlen (value) + 1);
	  while (*value && *value != '"')
	    {
	      if ((*value == '\\') && (*(value + 1) != 0))
		value++;
	      *d++ = *value++;
	    }
	  *d = 0;
      
	  *type_end = 0;
	  dir.type = g_strdup (type_start);
	  if (relative)
	    {
	      dir.path = g_build_filename (g_get_home_dir (), unescaped, NULL);
	      g_free (unescaped);
	    }
	  else 
	    dir.path = unescaped;
      
	  g_array_append_val (array, dir);
	}
      
      g_strfreev (lines);
    }
  
  g_free (config_file_free);
  
  return (XdgDirEntry *)g_array_free (array, FALSE);
}
int
main (int argc, char **argv)
{
  GError *error;
  GHashTable *table;
  gchar *srcfile;
  gchar *target = NULL;
  gchar *binary_target = NULL;
  gboolean generate_automatic = FALSE;
  gboolean generate_source = FALSE;
  gboolean generate_header = FALSE;
  gboolean manual_register = FALSE;
  gboolean internal = FALSE;
  gboolean generate_dependencies = FALSE;
  char *c_name = NULL;
  char *c_name_no_underscores;
  const char *linkage = "extern";
  GOptionContext *context;
  GOptionEntry entries[] = {
    { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
    { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &sourcedirs, N_("The directories where files are to be read from (default to current directory)"), N_("DIRECTORY") },
    { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
    { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
    { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
    { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
    { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
    { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don't export functions; declare them G_GNUC_INTERNAL"), NULL },
    { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
    { NULL }
  };

#ifdef G_OS_WIN32
  gchar *tmp;
#endif

  setlocale (LC_ALL, "");
  textdomain (GETTEXT_PACKAGE);

#ifdef G_OS_WIN32
  tmp = _glib_get_locale_dir ();
  bindtextdomain (GETTEXT_PACKAGE, tmp);
  g_free (tmp);
#else
  bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
#endif

#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif

  context = g_option_context_new (N_("FILE"));
  g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
  g_option_context_set_summary (context,
    N_("Compile a resource specification into a resource file.\n"
       "Resource specification files have the extension .gresource.xml,\n"
       "and the resource file have the extension called .gresource."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

  error = NULL;
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s\n", error->message);
      return 1;
    }

  g_option_context_free (context);

  if (argc != 2)
    {
      g_printerr (_("You should give exactly one file name\n"));
      return 1;
    }

  if (internal)
    linkage = "G_GNUC_INTERNAL";

  srcfile = argv[1];

  xmllint = g_strdup (g_getenv ("XMLLINT"));
  if (xmllint == NULL)
    xmllint = g_find_program_in_path ("xmllint");
  if (xmllint == NULL)
    g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");

  gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
  if (gdk_pixbuf_pixdata == NULL)
    gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");

  if (target == NULL)
    {
      char *dirname = g_path_get_dirname (srcfile);
      char *base = g_path_get_basename (srcfile);
      char *target_basename;
      if (g_str_has_suffix (base, ".xml"))
	base[strlen(base) - strlen (".xml")] = 0;

      if (generate_source)
	{
	  if (g_str_has_suffix (base, ".gresource"))
	    base[strlen(base) - strlen (".gresource")] = 0;
	  target_basename = g_strconcat (base, ".c", NULL);
	}
      else
	{
	  if (g_str_has_suffix (base, ".gresource"))
	    target_basename = g_strdup (base);
	  else
	    target_basename = g_strconcat (base, ".gresource", NULL);
	}

      target = g_build_filename (dirname, target_basename, NULL);
      g_free (target_basename);
      g_free (dirname);
      g_free (base);
    }
  else if (generate_automatic)
    {
      if (g_str_has_suffix (target, ".c"))
        generate_source = TRUE;
      else if (g_str_has_suffix (target, ".h"))
        generate_header = TRUE;
      else if (g_str_has_suffix (target, ".gresource"))
        ;
    }

  if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
    {
      g_free (target);
      return 1;
    }

  if (generate_dependencies)
    {
      GHashTableIter iter;
      gpointer key, data;
      FileData *file_data;

      g_hash_table_iter_init (&iter, table);
      while (g_hash_table_iter_next (&iter, &key, &data))
        {
          file_data = data;
          g_print ("%s\n",file_data->filename);
        }
    }
  else if (generate_source || generate_header)
    {
      if (generate_source)
	{
	  int fd = g_file_open_tmp (NULL, &binary_target, NULL);
	  if (fd == -1)
	    {
	      g_printerr ("Can't open temp file\n");
	      return 1;
	    }
	  close (fd);
	}

      if (c_name == NULL)
	{
	  char *base = g_path_get_basename (srcfile);
	  GString *s;
	  char *dot;
	  int i;

	  /* Remove extensions */
	  dot = strchr (base, '.');
	  if (dot)
	    *dot = 0;

	  s = g_string_new ("");

	  for (i = 0; base[i] != 0; i++)
	    {
	      const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
	      const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
	      if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
		g_string_append_c (s, base[i]);
	      else if (base[i] == '-')
		g_string_append_c (s, '_');

	    }

	  c_name = g_string_free (s, FALSE);
	}
    }
  else
    binary_target = g_strdup (target);

  c_name_no_underscores = c_name;
  while (c_name_no_underscores && *c_name_no_underscores == '_')
    c_name_no_underscores++;

  if (binary_target != NULL &&
      !write_to_file (table, binary_target, &error))
    {
      g_printerr ("%s\n", error->message);
      g_free (target);
      return 1;
    }

  if (generate_header)
    {
      FILE *file;

      file = fopen (target, "w");
      if (file == NULL)
	{
	  g_printerr ("can't write to file %s", target);
	  return 1;
	}

      fprintf (file,
	       "#ifndef __RESOURCE_%s_H__\n"
	       "#define __RESOURCE_%s_H__\n"
	       "\n"
	       "#include <gio/gio.h>\n"
	       "\n"
	       "%s GResource *%s_get_resource (void);\n",
	       c_name, c_name, linkage, c_name);

      if (manual_register)
	fprintf (file,
		 "\n"
		 "%s void %s_register_resource (void);\n"
		 "%s void %s_unregister_resource (void);\n"
		 "\n",
		 linkage, c_name, linkage, c_name);

      fprintf (file,
	       "#endif\n");

      fclose (file);
    }
  else if (generate_source)
    {
      FILE *file;
      guint8 *data;
      gsize data_size;
      gsize i;

      if (!g_file_get_contents (binary_target, (char **)&data,
				&data_size, NULL))
	{
	  g_printerr ("can't read back temporary file");
	  return 1;
	}
      g_unlink (binary_target);

      file = fopen (target, "w");
      if (file == NULL)
	{
	  g_printerr ("can't write to file %s", target);
	  return 1;
	}

      fprintf (file,
	       "#include <gio/gio.h>\n"
	       "\n"
	       "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
	       "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
	       "#else\n"
	       "# define SECTION\n"
	       "#endif\n"
	       "\n"
	       "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;}  %s_resource_data = { {\n",
	       c_name_no_underscores, data_size, c_name);

      for (i = 0; i < data_size; i++) {
	if (i % 8 == 0)
	  fprintf (file, "  ");
	fprintf (file, "0x%2.2x", (int)data[i]);
	if (i != data_size - 1)
	  fprintf (file, ", ");
	if ((i % 8 == 7) || (i == data_size - 1))
	  fprintf (file, "\n");
      }

      fprintf (file, "} };\n");

      fprintf (file,
	       "\n"
	       "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data), NULL, NULL, NULL };\n"
	       "%s GResource *%s_get_resource (void);\n"
	       "GResource *%s_get_resource (void)\n"
	       "{\n"
	       "  return g_static_resource_get_resource (&static_resource);\n"
	       "}\n",
	       c_name, c_name, linkage, c_name, c_name);


      if (manual_register)
	{
	  fprintf (file,
		   "\n"
		   "%s void %s_unregister_resource (void);\n"
		   "void %s_unregister_resource (void)\n"
		   "{\n"
		   "  g_static_resource_fini (&static_resource);\n"
		   "}\n"
		   "\n"
		   "%s void %s_register_resource (void);\n"
		   "void %s_register_resource (void)\n"
		   "{\n"
		   "  g_static_resource_init (&static_resource);\n"
		   "}\n",
		   linkage, c_name, c_name, linkage, c_name, c_name);
	}
      else
	{
	  fprintf (file, "%s", gconstructor_code);
	  fprintf (file,
		   "\n"
		   "#ifdef G_HAS_CONSTRUCTORS\n"
		   "\n"
		   "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
		   "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
		   "#endif\n"
		   "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
		   "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
		   "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
		   "#endif\n"
		   "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
		   "\n"
		   "#else\n"
		   "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
		   "#endif\n"
		   "\n"
		   "static void resource_constructor (void)\n"
		   "{\n"
		   "  g_static_resource_init (&static_resource);\n"
		   "}\n"
		   "\n"
		   "static void resource_destructor (void)\n"
		   "{\n"
		   "  g_static_resource_fini (&static_resource);\n"
		   "}\n");
	}

      fclose (file);

      g_free (data);
    }

  g_free (binary_target);
  g_free (target);
  g_hash_table_destroy (table);
  g_free (xmllint);

  return 0;
}
Example #27
0
SeafileSession *
seafile_session_new(const char *central_config_dir,
                    const char *seafile_dir,
                    CcnetClient *ccnet_session)
{
    char *abs_central_config_dir = NULL;
    char *abs_seafile_dir;
    char *tmp_file_dir;
    char *config_file_path;
    GKeyFile *config;
    SeafileSession *session = NULL;

    if (!ccnet_session)
        return NULL;

    abs_seafile_dir = ccnet_expand_path (seafile_dir);
    tmp_file_dir = g_build_filename (abs_seafile_dir, "tmpfiles", NULL);
    if (central_config_dir) {
        abs_central_config_dir = ccnet_expand_path (central_config_dir);
    }
    config_file_path = g_build_filename(
        abs_central_config_dir ? abs_central_config_dir : abs_seafile_dir,
        "seafile.conf", NULL);

    if (checkdir_with_mkdir (abs_seafile_dir) < 0) {
        seaf_warning ("Config dir %s does not exist and is unable to create\n",
                   abs_seafile_dir);
        goto onerror;
    }

    if (checkdir_with_mkdir (tmp_file_dir) < 0) {
        seaf_warning ("Temp file dir %s does not exist and is unable to create\n",
                   tmp_file_dir);
        goto onerror;
    }

    GError *error = NULL;
    config = g_key_file_new ();
    if (!g_key_file_load_from_file (config, config_file_path, 
                                    G_KEY_FILE_NONE, &error)) {
        seaf_warning ("Failed to load config file.\n");
        g_key_file_free (config);
        goto onerror;
    }

    session = g_new0(SeafileSession, 1);
    session->seaf_dir = abs_seafile_dir;
    session->tmp_file_dir = tmp_file_dir;
    session->session = ccnet_session;
    session->config = config;

    if (load_database_config (session) < 0) {
        seaf_warning ("Failed to load database config.\n");
        goto onerror;
    }

    if (load_thread_pool_config (session) < 0) {
        seaf_warning ("Failed to load thread pool config.\n");
        goto onerror;
    }

    session->fs_mgr = seaf_fs_manager_new (session, abs_seafile_dir);
    if (!session->fs_mgr)
        goto onerror;
    session->block_mgr = seaf_block_manager_new (session, abs_seafile_dir);
    if (!session->block_mgr)
        goto onerror;
    session->commit_mgr = seaf_commit_manager_new (session);
    if (!session->commit_mgr)
        goto onerror;
    session->repo_mgr = seaf_repo_manager_new (session);
    if (!session->repo_mgr)
        goto onerror;
    session->branch_mgr = seaf_branch_manager_new (session);
    if (!session->branch_mgr)
        goto onerror;

    session->cs_mgr = seaf_cs_manager_new (session);
    if (!session->cs_mgr)
        goto onerror;

    session->share_mgr = seaf_share_manager_new (session);
    if (!session->share_mgr)
        goto onerror;
    
    session->web_at_mgr = seaf_web_at_manager_new (session);
    if (!session->web_at_mgr)
        goto onerror;

    session->token_mgr = seaf_token_manager_new (session);
    if (!session->token_mgr)
        goto onerror;

    session->passwd_mgr = seaf_passwd_manager_new (session);
    if (!session->passwd_mgr)
        goto onerror;

    session->quota_mgr = seaf_quota_manager_new (session);
    if (!session->quota_mgr)
        goto onerror;

    session->listen_mgr = seaf_listen_manager_new (session);
    if (!session->listen_mgr)
        goto onerror;

    session->copy_mgr = seaf_copy_manager_new (session);
    if (!session->copy_mgr)
        goto onerror;

    session->job_mgr = ccnet_job_manager_new (session->sync_thread_pool_size);
    ccnet_session->job_mgr = ccnet_job_manager_new (session->rpc_thread_pool_size);

    session->size_sched = size_scheduler_new (session);

    session->ev_mgr = cevent_manager_new ();
    if (!session->ev_mgr)
        goto onerror;

    session->mq_mgr = seaf_mq_manager_new (session);
    if (!session->mq_mgr)
        goto onerror;

    session->http_server = seaf_http_server_new (session);
    if (!session->http_server)
        goto onerror;

    return session;

onerror:
    free (abs_seafile_dir);
    g_free (tmp_file_dir);
    g_free (config_file_path);
    g_free (session);
    return NULL;    
}
Example #28
0
/*
 * Test 1: gda_connection_open() when there is no error
 */
static guint
test1 (void)
{
	g_print ("============= %s started =============\n", __FUNCTION__);
	GdaConnection *cnc;
	GError *error = NULL;

	gchar *cnc_string, *fname;
        fname = g_build_filename (ROOT_DIR, "data", NULL);
        cnc_string = g_strdup_printf ("DB_DIR=%s;DB_NAME=sales_test", fname);
        g_free (fname);
        cnc = gda_connection_new_from_string ("SQLite", cnc_string, NULL,
					      GDA_CONNECTION_OPTIONS_READ_ONLY, NULL);
	if (!cnc) {
		g_print ("gda_connection_new_from_string([%s]) failed: %s\n", cnc_string,
			 error && error->message ? error->message : "No detail");
		g_free (cnc_string);
		return 1;
	}

	guint counter = 0;
	setup_main_context (cnc, 0, &counter);

	/* connection open */
	if (! gda_connection_open (cnc, &error)) {
		g_print ("gda_connection_open([%s]) failed: %s\n", cnc_string,
			 error && error->message ? error->message : "No detail");
		g_free (cnc_string);
		return 1;
	}
	g_free (cnc_string);

	if (counter == 0 && !connected) {
		g_print ("gda_connection_open() failed: did not make GMainContext 'run'\n");
		return 1;
	}
	else
		g_print ("Counter incremented to %u\n", counter);
	g_print ("Connection %p Opened\n", cnc);
	

	/* SELECT */
	counter = 0;
	GdaDataModel *model;
	model = gda_connection_execute_select_command (cnc, "SELECT * FROM customers", &error);
	if (model) {
		gda_data_model_dump (model, NULL);
		gint expnrows = 5;
		if (gda_data_model_get_n_rows (model) != expnrows) {
			g_print ("SELECT Exec() failed: expected %d and got %d\n", expnrows,
				 gda_data_model_get_n_rows (model));
			g_object_unref (model);
			g_object_unref (cnc);
			return 1;
		}
		g_object_unref (model);
	}
	else {
		g_print ("gda_connection_execute_select_command() failed: %s\n",
			 error && error->message ? error->message : "No detail");
		g_object_unref (cnc);
		return 1;
	}

	if (counter == 0 && !connected) {
		g_print ("gda_connection_open() failed: did not make GMainContext 'run'\n");
		g_object_unref (cnc);
		return 1;
	}
	else
		g_print ("Counter incremented to %u\n", counter);


	g_object_unref (cnc);

	return 0;
}
Example #29
0
int
main(int argc, char **argv)
{
    /* These may be absolute or relative to top_builddir, depending whether
     * GJS_TOP_SRCDIR is absolute or not */
    const char * const path_directories[] = {
        GJS_TOP_SRCDIR"/modules",
        GJS_TOP_SRCDIR"/test/js/modules",
        ".libs:",
        NULL
    };

    char *js_test_dir;
    char *working_dir;
    char *gjs_unit_path;
    char *gjs_unit_dir;
    char *top_builddir;
    char *data_home;
    GString *path;
    size_t i;
    GSList *all_tests, *iter;
    GSList *test_filenames = NULL;
    int retval;

    working_dir = g_get_current_dir();

    gjs_unit_path = build_absolute_filename(argv[0], NULL);

    gjs_unit_dir = g_path_get_dirname(gjs_unit_path);
    g_free(gjs_unit_path);
    /* the gjs-unit executable will be in <top_builddir>/.libs */
    top_builddir = g_path_get_dirname(gjs_unit_dir);
    g_free(gjs_unit_dir);
    top_srcdir = build_absolute_filename(top_builddir, GJS_TOP_SRCDIR, NULL);

    /* Normalize, not strictly necessary */
    g_chdir(top_builddir);
    g_free(top_builddir);
    top_builddir = g_get_current_dir();

    g_chdir(top_srcdir);
    g_free(top_srcdir);
    top_srcdir = g_get_current_dir();

    g_chdir(working_dir);
    g_free(working_dir);

    /* we're always going to use uninstalled files, set up necessary
     * environment variables, but don't overwrite if already set */

    data_home = g_build_filename(top_builddir, "test_user_data", NULL);
    path = g_string_new(NULL);
    for(i = 0; i < G_N_ELEMENTS(path_directories); i++) {
        char *directory;

        if (i != 0)
            g_string_append_c(path, ':');

        directory = build_absolute_filename(top_builddir, path_directories[i], NULL);
        g_string_append(path, directory);
        g_free(directory);
    }

    g_setenv("TOP_SRCDIR", top_srcdir, FALSE);
    g_setenv("BUILDDIR", top_builddir, FALSE);
    g_free(top_builddir);
    g_setenv("XDG_DATA_HOME", data_home, FALSE);
    g_free(data_home);
    g_setenv("GJS_PATH", path->str, FALSE);
    g_string_free(path, TRUE);
    /* The tests are known to fail in the presence of the JIT;
     * we leak objects.
     * https://bugzilla.gnome.org/show_bug.cgi?id=616193
     */
    g_setenv("GJS_DISABLE_JIT", "1", FALSE);

    {
        const char *timeout_str = g_getenv("GJS_TEST_TIMEOUT");
        if (timeout_str != NULL) {
            guint timeout = (guint)g_ascii_strtoull(timeout_str, NULL, 10);
            if (timeout > 0)
                gjs_crash_after_timeout(timeout);
        }
    }

    setlocale(LC_ALL, "");
    g_test_init(&argc, &argv, NULL);

    /* iterate through all 'test*.js' files in ${top_srcdir}/test/js */
    js_test_dir = g_build_filename(top_srcdir, "test", "js", NULL);

    all_tests = read_all_dir_sorted(js_test_dir);
    for (iter = all_tests; iter; iter = iter->next) {
        char *name = iter->data;
        char *test_name;
        char *file_name;

        if (!(g_str_has_prefix(name, "test") &&
              g_str_has_suffix(name, ".js"))) {
            g_free(name);
            continue;
        }
        if (g_str_has_prefix (name, "testCairo") && g_getenv ("GJS_TEST_SKIP_CAIRO"))
            continue;

        /* pretty print, drop 'test' prefix and '.js' suffix from test name */
        test_name = g_strconcat("/js/", name + 4, NULL);
        test_name[strlen(test_name)-3] = '\0';

        file_name = g_build_filename(js_test_dir, name, NULL);
        g_test_add(test_name, GjsTestJSFixture, file_name, setup, test, teardown);
        g_free(name);
        g_free(test_name);
        test_filenames = g_slist_prepend(test_filenames, file_name);
        /* not freeing file_name yet as it's needed while running the test */
    }
    g_free(js_test_dir);
    g_slist_free(all_tests);

    retval =  g_test_run ();
    g_slist_foreach(test_filenames, (GFunc)g_free, test_filenames);
    g_slist_free(test_filenames);
    g_free(top_srcdir);
    return retval;
}
Example #30
0
static gboolean
get_sorted_triggers (GPtrArray       **out_triggers,
                     GCancellable     *cancellable,
                     GError          **error)
{
  gboolean ret = FALSE;
  GError *temp_error = NULL;
  char *triggerdir_path = NULL;
  GFile *triggerdir = NULL;
  GFileInfo *file_info = NULL;
  GFileEnumerator *enumerator = NULL;
  GPtrArray *ret_triggers = NULL;

  ret_triggers = g_ptr_array_new_with_free_func ((GDestroyNotify)g_object_unref);

  triggerdir_path = g_build_filename (LIBEXECDIR, "ostree", "triggers.d", NULL);
  triggerdir = g_file_new_for_path (triggerdir_path);

  enumerator = g_file_enumerate_children (triggerdir, "standard::name,standard::type", 
                                          G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                                          cancellable, 
                                          error);
  if (!enumerator)
    goto out;

  while ((file_info = g_file_enumerator_next_file (enumerator, cancellable, &temp_error)) != NULL)
    {
      const char *name;
      guint32 type;

      name = g_file_info_get_attribute_byte_string (file_info, "standard::name"); 
      type = g_file_info_get_attribute_uint32 (file_info, "standard::type");
      
      if (type == G_FILE_TYPE_REGULAR && g_str_has_suffix (name, ".trigger"))
        {
          char *child_path;
          GFile *child;

          child_path = g_build_filename (triggerdir_path, name, NULL);
          child = g_file_new_for_path (child_path);
          g_free (child_path);

          g_ptr_array_add (ret_triggers, child);
        }
      g_clear_object (&file_info);
    }
  if (file_info == NULL && temp_error != NULL)
    {
      g_propagate_error (error, temp_error);
      goto out;
    }
  
  g_ptr_array_sort (ret_triggers, compare_files_by_basename);

  ret = TRUE;
  if (out_triggers)
    {
      *out_triggers = ret_triggers;
      ret_triggers = NULL;
    }
 out:
  g_free (triggerdir_path);
  g_clear_object (&triggerdir);
  g_clear_object (&enumerator);
  if (ret_triggers)
    g_ptr_array_unref (ret_triggers);
  return ret;
}