Ejemplo n.º 1
0
/**
 * file_plugin_proxy_load:
 * @filename. A file name to load.
 * @mode: Run mode.
 * @error: Return location for a #GError (or %NULL).
 * @name: Plug-in name (i.e. file-loading function) to run.
 *
 * The plug-in proxy itself, runs file-loading plug-in @name to load @filename.
 *
 * Returns: A newly created data container with the contents of @filename,
 *          or %NULL if it fails.
 **/
static GwyContainer*
file_plugin_proxy_load(const gchar *filename,
                       GwyRunType mode,
                       GError **error,
                       const gchar *name)
{
    FilePluginInfo *info;
    GwyContainer *data = NULL;
    GObject *dfield;
    gchar *tmpname = NULL, *buffer = NULL;
    GError *err = NULL;
    gint exit_status;
    gsize size = 0;
    FILE *fh;
    gchar *args[] = { NULL, NULL, NULL, NULL, NULL };
    gboolean ok;

    gwy_debug("called as %s with file `%s'", name, filename);
    if (mode != GWY_RUN_INTERACTIVE) {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_INTERACTIVE,
                    _("Plugin-proxy must be run as interactive."));
        return NULL;
    }
    if (!(info = file_find_plugin(name, GWY_FILE_OPERATION_LOAD))) {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_UNIMPLEMENTED,
                    _("Plug-in `%s' does not implement file loading."), name);
        return NULL;
    }
    if (!(fh = open_temporary_file(&tmpname, error)))
        return NULL;

    args[0] = info->file;
    args[1] = g_strdup(gwy_enum_to_string(GWY_FILE_OPERATION_LOAD,
                                          file_op_names, -1));
    args[2] = tmpname;
    args[3] = decode_glib_encoded_filename(filename);
    gwy_debug("%s %s %s %s", args[0], args[1], args[2], args[3]);
    ok = g_spawn_sync(NULL, args, NULL, 0, NULL, NULL,
                      NULL, NULL, &exit_status, &err);
    if (ok) {
        ok = g_file_get_contents(tmpname, &buffer, &size, &err);
        if (!ok) {
            g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_IO,
                        _("Cannot read temporary file: %s."), err->message);
            g_clear_error(&err);
        }
    }
    else {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_SPECIFIC,
                    _("Cannot execute plug-in `%s': %s."), name, err->message);
        g_clear_error(&err);
    }
    g_unlink(tmpname);
    fclose(fh);
    gwy_debug("ok = %d, exit_status = %d, err = %p", ok, exit_status, err);
    if (ok && exit_status) {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_SPECIFIC,
                    _("Plug-in `%s' returned non-zero exit status: %d."),
                    name, exit_status);
        ok = FALSE;
    }
    if (ok) {
        data = text_dump_import(buffer, size, error);
        if (!data)
            ok = FALSE;
    }
    if (ok
        && (!gwy_container_gis_object_by_name(data, "/0/data", &dfield)
            || !GWY_IS_DATA_FIELD(dfield))) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Plug-in `%s' did not return any meaningful data."),
                    name);
        gwy_object_unref(data);
    }
    g_free(args[1]);
    g_free(args[3]);
    g_free(buffer);
    g_free(tmpname);

    return data;
}
Ejemplo n.º 2
0
void
mex_screensaver_inhibit (MexScreensaver *self)
{
  MexScreensaverPrivate *priv = MEX_SCREENSAVER (self)->priv;

  GDBusProxy *proxy;
  GError *error = NULL;
  GVariant *variant;

  /* If we're already inhibited don't inhibit again */
  if (priv->cookie > 0)
    return;

  if (priv->gnome_version == -1)
    return;

  proxy = connect_gnome_screensaverd (self);

  if (!proxy)
    return;

  /* gnome_version will be 0 if the current version has not been determined */
  if (priv->gnome_version == 0 || priv->gnome_version == 2)
    {

      if ((variant = g_dbus_proxy_call_sync (proxy, "Inhibit",
                                            g_variant_new ("(ss)",
                                                           "Media Explorer",
                                                           "Playing media"),
                                            G_DBUS_CALL_FLAGS_NONE, -1, NULL,
                                            &error)))
        {
          priv->gnome_version = 2;
          g_variant_get (variant, "(u)", &priv->cookie);
          g_object_unref (proxy);
          g_variant_unref (variant);
        }
      else
        {
          if (error->domain == G_DBUS_ERROR &&
              error->code == G_DBUS_ERROR_UNKNOWN_METHOD)
            {
              g_clear_error (&error);
              priv->gnome_version = 3;
              /* the current proxy is useless to us */
              g_object_unref (proxy);
              proxy = NULL;
            }
        }
    }
  /* The code path may originate from the bail out on G_DBUS_ERROR_UNKNOWN_METHOD
   * or if the version has been set by a previous call of the inhibit function
   * which has worked out the version.
   */
  if (priv->gnome_version == 3)
    {
      /* proxy maybe null if the proxy was a gnome 2 proxy */
      if (!proxy)
        proxy = connect_gnome_screensaverd (self);

      /* 8 = GSM_INHIBITOR_FLAG_IDLE */
      if ((variant = g_dbus_proxy_call_sync (proxy, "Inhibit",
                                            g_variant_new ("(susu)",
                                                           "MediaExplorer",
                                                           0, "Playing media", 8),
                                            G_DBUS_CALL_FLAGS_NONE, -1, NULL,
                                            &error)))
        {
          priv->gnome_version = 3;
          g_variant_get (variant, "(u)", &priv->cookie);
          g_object_unref (proxy);
          g_variant_unref (variant);
        }
      else
        {
          if (error->domain == G_DBUS_ERROR &&
              error->code == G_DBUS_ERROR_UNKNOWN_METHOD)
            {
              g_clear_error (&error);
              priv->gnome_version = -1;
              g_object_unref (proxy);
              proxy = NULL;
            }
        }
    }

  if (error)
    {
      g_warning ("Problem inhibiting screensaver: %s", error->message);
      g_error_free (error);
    }
}
Ejemplo n.º 3
0
static gboolean notification_libnotify_add_msg(MsgInfo *msginfo,
					       NotificationFolderType nftype)
{
  gchar *summary;
  gchar *text;
  gboolean retval;
  NotificationPopup *ppopup;
  GdkPixbuf *pixbuf;

  ppopup = &(popup[nftype]);

  if(!ppopup->notification)
    return notification_libnotify_create(msginfo,nftype);

  ppopup->count++;

  if(ppopup->msg_path) {
    g_free(ppopup->msg_path);
    ppopup->msg_path = NULL;
  }

  /* make sure we show a logo on many msg arrival */
  pixbuf = notification_pixbuf_get(NOTIFICATION_CM_LOGO_64x64);
  if(pixbuf)
    notify_notification_set_icon_from_pixbuf(ppopup->notification, pixbuf);

  switch(nftype) {
  case F_TYPE_MAIL:
    summary = _("Mail message");
    text = g_strdup_printf(ngettext("%d new message arrived",
				    "%d new messages arrived",
				    ppopup->count), ppopup->count);
    break;
  case F_TYPE_NEWS:
    summary = _("News message");
    text = g_strdup_printf(ngettext("%d new message arrived",
                                     "%d new messages arrived",
				     ppopup->count), ppopup->count);
    break;
  case F_TYPE_CALENDAR:
    summary = _("Calendar message");
    text = g_strdup_printf(ngettext("%d new calendar message arrived",
                                     "%d new calendar messages arrived",
				     ppopup->count), ppopup->count);
    break;
  case F_TYPE_RSS:
    summary = _("RSS news feed");
    text = g_strdup_printf(ngettext("%d new article in a RSS feed arrived",
                                     "%d new articles in a RSS feed arrived",
				     ppopup->count), ppopup->count);
    break;
  default:
    /* Should not happen */
    debug_print("Notification Plugin: Unknown folder type ignored\n");
    return FALSE;
  }

  retval = notify_notification_update(ppopup->notification, summary,
				      text, NULL);
  g_free(text);
  if(!retval) {
    debug_print("Notification Plugin: Failed to update notification.\n");
    return FALSE;
  }

  /* Show the popup */
  notify_notification_set_hint_string(ppopup->notification, "desktop-entry", "claws-mail");
  if(!notify_notification_show(ppopup->notification, &(ppopup->error))) {
    debug_print("Notification Plugin: Failed to send updated notification: "
		"%s\n",	ppopup->error->message);
    g_clear_error(&(ppopup->error));
    return FALSE;
  }

  debug_print("Notification Plugin: Popup successfully modified "
	      "with libnotify.\n");
  return TRUE;
}
int
rpmostree_compose_builtin_tree (int             argc,
                                char          **argv,
                                GCancellable   *cancellable,
                                GError        **error)
{
  int exit_status = EXIT_FAILURE;
  GError *temp_error = NULL;
  GOptionContext *context = g_option_context_new ("TREEFILE - Run yum and commit the result to an OSTree repository");
  RpmOstreeTreeComposeContext selfdata = { NULL, };
  RpmOstreeTreeComposeContext *self = &selfdata;
  JsonNode *treefile_rootval = NULL;
  JsonObject *treefile = NULL;
  g_autofree char *cachekey = NULL;
  g_autofree char *new_inputhash = NULL;
  g_autoptr(GFile) previous_root = NULL;
  g_autofree char *previous_checksum = NULL;
  g_autoptr(GFile) yumroot = NULL;
  g_autoptr(GFile) yumroot_varcache = NULL;
  glnx_fd_close int rootfs_fd = -1;
  glnx_unref_object OstreeRepo *repo = NULL;
  g_autoptr(GPtrArray) bootstrap_packages = NULL;
  g_autoptr(GPtrArray) packages = NULL;
  g_autoptr(GFile) treefile_path = NULL;
  g_autoptr(GFile) treefile_dirpath = NULL;
  g_autoptr(GFile) repo_path = NULL;
  glnx_unref_object JsonParser *treefile_parser = NULL;
  gs_unref_variant_builder GVariantBuilder *metadata_builder = 
    g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
  g_autoptr(RpmOstreeContext) corectx = NULL;
  g_autoptr(GHashTable) varsubsts = NULL;
  gboolean workdir_is_tmp = FALSE;
  g_autofree char *next_version = NULL;

  self->treefile_context_dirs = g_ptr_array_new_with_free_func ((GDestroyNotify)g_object_unref);
  
  if (!rpmostree_option_context_parse (context,
                                       option_entries,
                                       &argc, &argv,
                                       RPM_OSTREE_BUILTIN_FLAG_LOCAL_CMD,
                                       cancellable,
                                       NULL,
                                       error))
    goto out;

  if (argc < 2)
    {
      rpmostree_usage_error (context, "TREEFILE must be specified", error);
      goto out;
    }
  
  if (!opt_repo)
    {
      rpmostree_usage_error (context, "--repo must be specified", error);
      goto out;
    }

  if (getuid () != 0)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "compose tree must presently be run as uid 0 (root)");
      goto out;
    }

  /* Test whether or not bwrap is going to work - we will fail inside e.g. a Docker
   * container without --privileged or userns exposed.
   */
  if (!rpmostree_bwrap_selftest (error))
    goto out;

  repo_path = g_file_new_for_path (opt_repo);
  repo = self->repo = ostree_repo_new (repo_path);
  if (!ostree_repo_open (repo, cancellable, error))
    goto out;

  treefile_path = g_file_new_for_path (argv[1]);

  if (opt_workdir)
    {
      self->workdir = g_file_new_for_path (opt_workdir);
    }
  else
    {
      g_autofree char *tmpd = NULL;

      if (!rpmostree_mkdtemp ("/var/tmp/rpm-ostree.XXXXXX", &tmpd, NULL, error))
        goto out;

      self->workdir = g_file_new_for_path (tmpd);
      workdir_is_tmp = TRUE;

      if (opt_workdir_tmpfs)
        {
          if (mount ("tmpfs", tmpd, "tmpfs", 0, (const void*)"mode=755") != 0)
            {
              _rpmostree_set_prefix_error_from_errno (error, errno,
                                                      "mount(tmpfs): ");
              goto out;
            }
        }
    }

  if (!glnx_opendirat (AT_FDCWD, gs_file_get_path_cached (self->workdir),
                       FALSE, &self->workdir_dfd, error))
    goto out;

  if (opt_cachedir)
    {
      if (!glnx_opendirat (AT_FDCWD, opt_cachedir, TRUE, &self->cachedir_dfd, error))
        {
          g_prefix_error (error, "Opening cachedir '%s': ", opt_cachedir);
          goto out;
        }
    }
  else
    {
      self->cachedir_dfd = fcntl (self->workdir_dfd, F_DUPFD_CLOEXEC, 3);
      if (self->cachedir_dfd < 0)
        {
          glnx_set_error_from_errno (error);
          goto out;
        }
    }

  if (opt_metadata_strings)
    {
      if (!parse_keyvalue_strings (opt_metadata_strings,
                                   metadata_builder, error))
        goto out;
    }

  if (fchdir (self->workdir_dfd) != 0)
    {
      glnx_set_error_from_errno (error);
      goto out;
    }

  corectx = rpmostree_context_new_compose (self->cachedir_dfd, cancellable, error);
  if (!corectx)
    goto out;

  varsubsts = rpmostree_context_get_varsubsts (corectx);

  treefile_parser = json_parser_new ();
  if (!json_parser_load_from_file (treefile_parser,
                                   gs_file_get_path_cached (treefile_path),
                                   error))
    goto out;

  treefile_rootval = json_parser_get_root (treefile_parser);
  if (!JSON_NODE_HOLDS_OBJECT (treefile_rootval))
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Treefile root is not an object");
      goto out;
    }
  treefile = json_node_get_object (treefile_rootval);

  if (!process_includes (self, treefile_path, 0, treefile,
                         cancellable, error))
    goto out;

  if (opt_print_only)
    {
      glnx_unref_object JsonGenerator *generator = json_generator_new ();
      g_autoptr(GOutputStream) stdout = g_unix_output_stream_new (1, FALSE);

      json_generator_set_pretty (generator, TRUE);
      json_generator_set_root (generator, treefile_rootval);
      (void) json_generator_to_stream (generator, stdout, NULL, NULL);

      exit_status = EXIT_SUCCESS;
      goto out;
    }

  { const char *input_ref = _rpmostree_jsonutil_object_require_string_member (treefile, "ref", error);
    if (!input_ref)
      goto out;
    self->ref = _rpmostree_varsubst_string (input_ref, varsubsts, error);
    if (!self->ref)
      goto out;
  }

  if (!ostree_repo_read_commit (repo, self->ref, &previous_root, &previous_checksum,
                                cancellable, &temp_error))
    {
      if (g_error_matches (temp_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
        { 
          g_clear_error (&temp_error);
          g_print ("No previous commit for %s\n", self->ref);
        }
      else
        {
          g_propagate_error (error, temp_error);
          goto out;
        }
    }
  else
    g_print ("Previous commit: %s\n", previous_checksum);

  self->previous_checksum = previous_checksum;

  yumroot = g_file_get_child (self->workdir, "rootfs.tmp");
  if (!glnx_shutil_rm_rf_at (self->workdir_dfd, "rootfs.tmp", cancellable, error))
    goto out;

  if (json_object_has_member (treefile, "automatic_version_prefix") &&
      !compose_strv_contains_prefix (opt_metadata_strings, "version="))
    {
      g_autoptr(GVariant) variant = NULL;
      g_autofree char *last_version = NULL;
      const char *ver_prefix;

      ver_prefix = _rpmostree_jsonutil_object_require_string_member (treefile,
                                                                     "automatic_version_prefix",
                                                                     error);
      if (!ver_prefix)
          goto out;

      if (previous_checksum)
        {
          if (!ostree_repo_load_variant (repo, OSTREE_OBJECT_TYPE_COMMIT,
                                         previous_checksum, &variant, error))
            goto out;

          last_version = checksum_version (variant);
        }

      next_version = _rpmostree_util_next_version (ver_prefix, last_version);
      g_variant_builder_add (metadata_builder, "{sv}", "version",
                             g_variant_new_string (next_version));
    }

  bootstrap_packages = g_ptr_array_new ();
  packages = g_ptr_array_new ();

  if (json_object_has_member (treefile, "bootstrap_packages"))
    {
      if (!_rpmostree_jsonutil_append_string_array_to (treefile, "bootstrap_packages", packages, error))
        goto out;
    }
  if (!_rpmostree_jsonutil_append_string_array_to (treefile, "packages", packages, error))
    goto out;

  { g_autofree char *thisarch_packages = g_strconcat ("packages-", dnf_context_get_base_arch (rpmostree_context_get_hif (corectx)), NULL);

    if (json_object_has_member (treefile, thisarch_packages))
      {
        if (!_rpmostree_jsonutil_append_string_array_to (treefile, thisarch_packages, packages, error))
          goto out;
      }
  }
  g_ptr_array_add (packages, NULL);

  { glnx_unref_object JsonGenerator *generator = json_generator_new ();
    char *treefile_buf = NULL;
    gsize len;

    json_generator_set_root (generator, treefile_rootval);
    json_generator_set_pretty (generator, TRUE);
    treefile_buf = json_generator_to_data (generator, &len);

    self->serialized_treefile = g_bytes_new_take (treefile_buf, len);
  }

  treefile_dirpath = g_file_get_parent (treefile_path);
  if (TRUE)
    {
      gboolean generate_from_previous = TRUE;

      if (!_rpmostree_jsonutil_object_get_optional_boolean_member (treefile,
                                                                   "preserve-passwd",
                                                                   &generate_from_previous,
                                                                   error))
        goto out;

      if (generate_from_previous)
        {
          if (!rpmostree_generate_passwd_from_previous (repo, yumroot,
                                                        treefile_dirpath,
                                                        previous_root, treefile,
                                                        cancellable, error))
            goto out;
        }
    }

  { gboolean unmodified = FALSE;

    if (!install_packages_in_root (self, corectx, treefile, yumroot,
                                   (char**)packages->pdata,
                                   opt_force_nocache ? NULL : &unmodified,
                                   &new_inputhash,
                                   cancellable, error))
      goto out;

    if (unmodified)
      {
        g_print ("No apparent changes since previous commit; use --force-nocache to override\n");
        exit_status = EXIT_SUCCESS;
        goto out;
      }
    else if (opt_dry_run)
      {
        g_print ("--dry-run complete, exiting\n");
        exit_status = EXIT_SUCCESS;
        goto out;
      }
  }

  if (g_strcmp0 (g_getenv ("RPM_OSTREE_BREAK"), "post-yum") == 0)
    goto out;

  if (!glnx_opendirat (AT_FDCWD, gs_file_get_path_cached (yumroot), TRUE,
                       &rootfs_fd, error))
    goto out;

  if (!rpmostree_treefile_postprocessing (rootfs_fd, self->treefile_context_dirs->pdata[0],
                                          self->serialized_treefile, treefile,
                                          next_version, cancellable, error))
    goto out;

  if (!rpmostree_prepare_rootfs_for_commit (yumroot, treefile, cancellable, error))
    goto out;

  /* Reopen since the prepare renamed */
  (void) close (rootfs_fd);
  if (!glnx_opendirat (AT_FDCWD, gs_file_get_path_cached (yumroot), TRUE,
                       &rootfs_fd, error))
    goto out;

  if (!rpmostree_copy_additional_files (yumroot, self->treefile_context_dirs->pdata[0], treefile, cancellable, error))
    goto out;

  if (!rpmostree_check_passwd (repo, yumroot, treefile_dirpath, treefile,
                               previous_checksum,
                               cancellable, error))
    goto out;

  if (!rpmostree_check_groups (repo, yumroot, treefile_dirpath, treefile,
                               previous_checksum,
                               cancellable, error))
    goto out;

  {
    const char *gpgkey;
    gboolean selinux = TRUE;
    g_autoptr(GVariant) metadata = NULL;

    g_variant_builder_add (metadata_builder, "{sv}",
                           "rpmostree.inputhash",
                           g_variant_new_string (new_inputhash));

    metadata = g_variant_ref_sink (g_variant_builder_end (metadata_builder));

    if (!_rpmostree_jsonutil_object_get_optional_string_member (treefile, "gpg_key", &gpgkey, error))
      goto out;

    if (!_rpmostree_jsonutil_object_get_optional_boolean_member (treefile,
                                                                 "selinux",
                                                                 &selinux,
                                                                 error))
      goto out;

    { g_autofree char *new_revision = NULL;

      if (!rpmostree_commit (rootfs_fd, repo, self->ref, metadata, gpgkey, selinux, NULL,
                             &new_revision,
                             cancellable, error))
        goto out;

      g_print ("%s => %s\n", self->ref, new_revision);

    }
  }

  if (opt_touch_if_changed)
    {
      gs_fd_close int fd = open (opt_touch_if_changed, O_CREAT|O_WRONLY|O_NOCTTY, 0644);
      if (fd == -1)
        {
          gs_set_error_from_errno (error, errno);
          g_prefix_error (error, "Updating '%s': ", opt_touch_if_changed);
          goto out;
        }
      if (futimens (fd, NULL) == -1)
        {
          gs_set_error_from_errno (error, errno);
          goto out;
        }
    }

  exit_status = EXIT_SUCCESS;

 out:
  /* Explicitly close this one now as it may have references to files
   * we delete below.
   */
  g_clear_object (&corectx);
  
  /* Move back out of the workding directory to ensure unmount works */
  (void )chdir ("/");

  if (self->workdir_dfd != -1)
    (void) close (self->workdir_dfd);

  if (workdir_is_tmp)
    {
      if (opt_workdir_tmpfs)
        if (umount (gs_file_get_path_cached (self->workdir)) != 0)
          {
            fprintf (stderr, "warning: umount failed: %m\n");
          }
      (void) gs_shutil_rm_rf (self->workdir, NULL, NULL);
    }
  if (self)
    {
      g_clear_object (&self->workdir);
      g_clear_pointer (&self->serialized_treefile, g_bytes_unref);
      g_ptr_array_unref (self->treefile_context_dirs);
    }

  return exit_status;
}
Ejemplo n.º 5
0
gboolean
ot_admin_builtin_status (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  GOptionContext *context;
  glnx_unref_object OstreeSysroot *sysroot = NULL;
  gboolean ret = FALSE;
  glnx_unref_object OstreeRepo *repo = NULL;
  OstreeDeployment *booted_deployment = NULL;
  g_autoptr(GPtrArray) deployments = NULL;
  guint i;

  context = g_option_context_new ("List deployments");

  if (!ostree_admin_option_context_parse (context, options, &argc, &argv,
                                          OSTREE_ADMIN_BUILTIN_FLAG_NONE,
                                          &sysroot, cancellable, error))
    goto out;

  if (!ostree_sysroot_load (sysroot, cancellable, error))
    goto out;

  if (!ostree_sysroot_get_repo (sysroot, &repo, cancellable, error))
    goto out;

  deployments = ostree_sysroot_get_deployments (sysroot);
  booted_deployment = ostree_sysroot_get_booted_deployment (sysroot);

  if (deployments->len == 0)
    {
      g_print ("No deployments.\n");
    }
  else
    {
      for (i = 0; i < deployments->len; i++)
        {
          OstreeDeployment *deployment = deployments->pdata[i];
          GKeyFile *origin;
          const char *ref = ostree_deployment_get_csum (deployment);
          g_autofree char *version = version_of_commit (repo, ref);
          glnx_unref_object OstreeGpgVerifyResult *result = NULL;
          GString *output_buffer;
          guint jj, n_signatures;
          GError *local_error = NULL;

          g_print ("%c %s %s.%d\n",
                   deployment == booted_deployment ? '*' : ' ',
                   ostree_deployment_get_osname (deployment),
                   ostree_deployment_get_csum (deployment),
                   ostree_deployment_get_deployserial (deployment));
          if (version)
            g_print ("    Version: %s\n", version);
          origin = ostree_deployment_get_origin (deployment);
          if (!origin)
            g_print ("    origin: none\n");
          else
            {
              g_autofree char *origin_refspec = g_key_file_get_string (origin, "origin", "refspec", NULL);
              if (!origin_refspec)
                g_print ("    origin: <unknown origin type>\n");
              else
                g_print ("    origin refspec: %s\n", origin_refspec);
            }

          if (deployment_get_gpg_verify (deployment, repo))
            {
              /* Print any digital signatures on this commit. */

              result = ostree_repo_verify_commit_ext (repo, ref, NULL, NULL,
                                                      cancellable, &local_error);

              /* G_IO_ERROR_NOT_FOUND just means the commit is not signed. */
              if (g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
                {
                  g_clear_error (&local_error);
                  continue;
                }
              else if (local_error != NULL)
                {
                  g_propagate_error (error, local_error);
                  goto out;
                }

              output_buffer = g_string_sized_new (256);
              n_signatures = ostree_gpg_verify_result_count_all (result);

              for (jj = 0; jj < n_signatures; jj++)
                {
                  ostree_gpg_verify_result_describe (result, jj, output_buffer, "    GPG: ",
                                                     OSTREE_GPG_SIGNATURE_FORMAT_DEFAULT);
                }

              g_print ("%s", output_buffer->str);
              g_string_free (output_buffer, TRUE);
            }
        }
    }

  ret = TRUE;
 out:
  if (context)
    g_option_context_free (context);
  return ret;
}
static gboolean
cc_timezone_map_draw (GtkWidget *widget,
                      cairo_t   *cr)
{
  CcTimezoneMapPrivate *priv = CC_TIMEZONE_MAP (widget)->priv;
  GdkPixbuf *hilight, *orig_hilight;
  GtkAllocation alloc;
  gchar *file;
  GError *err = NULL;
  gdouble pointx, pointy;
  char buf[16];
  const char *fmt;

  gtk_widget_get_allocation (widget, &alloc);

  /* paint background */
  gdk_cairo_set_source_pixbuf (cr, priv->background, 0, 0);
  cairo_paint (cr);

  /* paint hilight */
  if (gtk_widget_is_sensitive (widget))
    fmt = DATETIME_RESOURCE_PATH "/timezone_%s.png";
  else
    fmt = DATETIME_RESOURCE_PATH "/timezone_%s_dim.png";

  file = g_strdup_printf (fmt,
                          g_ascii_formatd (buf, sizeof (buf),
                                           "%g", priv->selected_offset));
  orig_hilight = gdk_pixbuf_new_from_resource (file, &err);
  g_free (file);
  file = NULL;

  if (!orig_hilight)
    {
      g_warning ("Could not load hilight: %s",
                 (err) ? err->message : "Unknown Error");
      if (err)
        g_clear_error (&err);
    }
  else
    {

      hilight = gdk_pixbuf_scale_simple (orig_hilight, alloc.width,
                                         alloc.height, GDK_INTERP_BILINEAR);
      gdk_cairo_set_source_pixbuf (cr, hilight, 0, 0);

      cairo_paint (cr);
      g_object_unref (hilight);
      g_object_unref (orig_hilight);
    }

  if (priv->location)
    {
      pointx = convert_longitude_to_x (priv->location->longitude, alloc.width);
      pointy = convert_latitude_to_y (priv->location->latitude, alloc.height);

      pointx = CLAMP (floor (pointx), 0, alloc.width);
      pointy = CLAMP (floor (pointy), 0, alloc.height);

      draw_text_bubble (cr, widget, pointx, pointy);

      if (priv->pin)
        {
          gdk_cairo_set_source_pixbuf (cr, priv->pin,
                                       pointx - PIN_HOT_POINT_X,
                                       pointy - PIN_HOT_POINT_Y);
          cairo_paint (cr);
        }
    }

  return TRUE;
}
Ejemplo n.º 7
0
int
main(int argc, char *argv[])
{
    signal_user_data_t *ud;
    GError *error = NULL;
    GOptionContext *context;

    hb_global_init();

#ifdef ENABLE_NLS
    bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
    bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
    textdomain(GETTEXT_PACKAGE);
#endif

    context = g_option_context_new(_("- Transcode media formats"));
    g_option_context_add_main_entries(context, entries, GETTEXT_PACKAGE);
    g_option_context_add_group(context, gtk_get_option_group(TRUE));
#if defined(_ENABLE_GST)
    g_option_context_add_group(context, gst_init_get_option_group());
#endif
    g_option_context_parse(context, &argc, &argv, &error);
    if (error != NULL)
    {
        g_warning("%s: %s", G_STRFUNC, error->message);
        g_clear_error(&error);
    }
    g_option_context_free(context);

#if defined(_WIN32)
    if (win32_console)
    {
        // Enable console logging
        if(AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){
            close(STDOUT_FILENO);
            freopen("CONOUT$", "w", stdout);
            close(STDERR_FILENO);
            freopen("CONOUT$", "w", stderr);
        }
    }
    else
    {
        // Non-console windows apps do not have a stderr->_file
        // assigned properly
        stderr->_file = STDERR_FILENO;
        stdout->_file = STDOUT_FILENO;
    }
#endif

    if (argc > 1 && dvd_device == NULL && argv[1][0] != '-')
    {
        dvd_device = argv[1];
    }

    gtk_init(&argc, &argv);

    GtkCssProvider *css = gtk_css_provider_new();
    error = NULL;
    gtk_css_provider_load_from_data(css, MyCSS, -1, &error);
    if (error == NULL)
    {
        GdkScreen *ss = gdk_screen_get_default();
        gtk_style_context_add_provider_for_screen(ss, GTK_STYLE_PROVIDER(css),
                                    GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
    }
    else
    {
        g_warning("%s: %s", G_STRFUNC, error->message);
        g_clear_error(&error);
    }

#if !defined(_WIN32)
    notify_init("HandBrake");
#endif
    ghb_resource_init();
    ghb_load_icons();

#if !defined(_WIN32)
    dbus_g_thread_init();
#endif
    ghb_udev_init();

    ghb_write_pid_file();
    ud = g_malloc0(sizeof(signal_user_data_t));
    ud->debug = ghb_debug;
    g_log_set_handler(NULL, G_LOG_LEVEL_DEBUG, debug_log_handler, ud);
    g_log_set_handler("Gtk", G_LOG_LEVEL_WARNING, warn_log_handler, ud);
    //g_log_set_handler("Gtk", G_LOG_LEVEL_CRITICAL, warn_log_handler, ud);

    ud->globals = ghb_dict_new();
    ud->prefs = ghb_dict_new();
    ud->settings_array = ghb_array_new();
    ud->settings = ghb_dict_new();
    ghb_array_append(ud->settings_array, ud->settings);

    ud->builder = create_builder_or_die(BUILDER_NAME);
    // Enable events that alert us to media change events
    watch_volumes(ud);

    //GtkWidget *widget = GHB_WIDGET(ud->builder, "PictureDetelecineCustom");
    //gtk_entry_set_inner_border(widget, 2);

    // Since GtkBuilder no longer assigns object ids to widget names
    // Assign a few that are necessary for style overrides to work
    GtkWidget *widget;
#if defined(_NO_UPDATE_CHECK)
    widget = GHB_WIDGET(ud->builder, "check_updates_box");
    gtk_widget_hide(widget);
#endif

    // Must set the names of the widgets that I want to modify
    // style for.
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_hud"), "preview_hud");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_frame"), "preview_frame");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_preview_play"), "live_preview_play");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_preview_progress"), "live_preview_progress");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_encode_progress"), "live_encode_progress");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "live_duration"), "live_duration");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_show_crop"), "preview_show_crop");
    gtk_widget_set_name(GHB_WIDGET(ud->builder, "preview_fullscreen"), "preview_fullscreen");
    widget = GHB_WIDGET(ud->builder, "preview_hud");
    gtk_widget_set_name(widget, "preview_hud");
    widget = GHB_WIDGET(ud->builder, "preview_window");
    gtk_widget_set_name(widget, "preview_window");

    // Set up the "hud" control overlay for the preview window
    GtkWidget *preview_box, *draw, *hud, *blender;

    preview_box = GHB_WIDGET(ud->builder, "preview_window_box");
    draw = GHB_WIDGET(ud->builder, "preview_image");
    hud = GHB_WIDGET(ud->builder, "preview_hud");

#if 0 // GTK_CHECK_VERSION(3, 0, 0)
    // This uses the new GtkOverlay widget.
    //
    // Unfortunately, GtkOverlay is broken in a couple of ways.
    //
    // First, it doesn't respect gtk_widget_shape_combine_region()
    // on it's child overlays.  It appears to just ignore the clip
    // mask of the child.
    //
    // Second, it doesn't respect window opacity.
    //
    // So for now, I'll just continue using my home-grown overlay
    // widget (GhbCompositor).
    blender = gtk_overlay_new();
    gtk_container_add(GTK_CONTAINER(preview_box), blender);
    gtk_container_add(GTK_CONTAINER(blender), draw);
    gtk_widget_set_valign (hud, GTK_ALIGN_END);
    gtk_widget_set_halign (hud, GTK_ALIGN_CENTER);
    gtk_overlay_add_overlay(GTK_OVERLAY(blender), hud);

    g_signal_connect(G_OBJECT(blender), "get-child-position",
                    G_CALLBACK(position_overlay_cb), ud);

    gtk_widget_show(blender);
#else
    // Set up compositing for hud
    blender = ghb_compositor_new();

    gtk_container_add(GTK_CONTAINER(preview_box), blender);
    ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), draw, 1, 1);
    ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), hud, 2, .85);
    gtk_widget_show(blender);
#endif

    // Redirect stderr to the activity window
    ghb_preview_init(ud);
    IoRedirect(ud);
    ghb_log( "%s - %s - %s",
        HB_PROJECT_TITLE, HB_PROJECT_BUILD_TITLE, HB_PROJECT_URL_WEBSITE );
    ghb_init_dep_map();

    // Need to connect x264_options textview buffer to the changed signal
    // since it can't be done automatically
    GtkTextView *textview;
    GtkTextBuffer *buffer;
    textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "x264Option"));
    buffer = gtk_text_view_get_buffer(textview);
    g_signal_connect(buffer, "changed", (GCallback)x264_entry_changed_cb, ud);

    textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "VideoOptionExtra"));
    buffer = gtk_text_view_get_buffer(textview);
    g_signal_connect(buffer, "changed", (GCallback)video_option_changed_cb, ud);

    textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "MetaLongDescription"));
    buffer = gtk_text_view_get_buffer(textview);
    g_signal_connect(buffer, "changed", (GCallback)plot_changed_cb, ud);

    ghb_combo_init(ud);

    g_debug("ud %p\n", ud);
    g_debug("ud->builder %p\n", ud->builder);

    bind_audio_tree_model(ud);
    bind_subtitle_tree_model(ud);
    bind_presets_tree_model(ud);
    bind_queue_tree_model(ud);
    bind_chapter_tree_model(ud);
    // Connect up the signals to their callbacks
    // I wrote my own connector so that I could pass user data
    // to the callbacks.  Builder's standard autoconnect doesn't all this.
    gtk_builder_connect_signals_full(ud->builder, MyConnect, ud);

    ghb_init_audio_defaults_ui(ud);
    ghb_init_subtitle_defaults_ui(ud);

    // Parsing x264 options "" initializes x264 widgets to proper defaults
    ghb_x264_init(ud);

    // Load prefs before presets.  Some preset defaults may depend
    // on preference settings.
    // First load default values
    ghb_settings_init(ud->prefs, "Preferences");
    ghb_settings_init(ud->globals, "Globals");
    ghb_settings_init(ud->settings, "Initialization");
    ghb_settings_init(ud->settings, "OneTimeInitialization");
    // Load user preferences file
    ghb_prefs_load(ud);
    // Store user preferences into ud->prefs
    ghb_prefs_to_settings(ud->prefs);

    int logLevel = ghb_dict_get_int(ud->prefs, "LoggingLevel");
    ghb_backend_init(logLevel);

    // Load the presets files
    ghb_presets_load(ud);
    // Note that ghb_preset_to_settings(ud->settings) is called when
    // the default preset is selected.

    ghb_settings_to_ui(ud, ud->globals);
    ghb_settings_to_ui(ud, ud->prefs);
    // Note that ghb_settings_to_ui(ud->settings) happens when initial
    // empty title is initialized.


    if (ghb_dict_get_bool(ud->prefs, "hbfd"))
    {
        ghb_hbfd(ud, TRUE);
    }
    const gchar *source = ghb_dict_get_string(ud->prefs, "default_source");
    ghb_dvd_set_current(source, ud);

    // Populate the presets tree view
    ghb_presets_list_init(ud, NULL);
    // Get the first preset name
    if (arg_preset != NULL)
    {
        ghb_select_preset(ud->builder, arg_preset);
    }
    else
    {
        ghb_select_default_preset(ud->builder);
    }

    // Grey out widgets that are dependent on a disabled feature
    ghb_check_all_depencencies(ud);

    if (dvd_device != NULL)
    {
        // Source overridden from command line option
        ghb_dict_set_string(ud->globals, "scan_source", dvd_device);
        g_idle_add((GSourceFunc)ghb_idle_scan, ud);
    }
    else
    {
        GhbValue *gval = ghb_dict_get_value(ud->prefs, "default_source");
        ghb_dict_set(ud->globals, "scan_source", ghb_value_dup(gval));
    }
    // Reload and check status of the last saved queue
    g_idle_add((GSourceFunc)ghb_reload_queue, ud);

    // Start timer for monitoring libhb status, 500ms
    g_timeout_add(200, ghb_timer_cb, (gpointer)ud);

    // Add dvd devices to File menu
    ghb_volname_cache_init();
    GHB_THREAD_NEW("Cache Volume Names", (GThreadFunc)ghb_cache_volnames, ud);

    GtkWidget *ghb_window = GHB_WIDGET(ud->builder, "hb_window");

    gint window_width, window_height;
    GdkGeometry geo = {
        -1, -1, 1920, 768, -1, -1, 10, 10, 0, 0, GDK_GRAVITY_NORTH_WEST
    };
    GdkWindowHints geo_mask;
    geo_mask = GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE | GDK_HINT_BASE_SIZE;
    gtk_window_set_geometry_hints(GTK_WINDOW(ghb_window), ghb_window,
                                  &geo, geo_mask);
    window_width = ghb_dict_get_int(ud->prefs, "window_width");
    window_height = ghb_dict_get_int(ud->prefs, "window_height");

    /*
     * Filter objects in GtkBuilder xml
     * Unfortunately, GtkFilter is poorly supported by GtkBuilder,
     * so a lot of the setup must happen in code.
        SourceFilterAll
        SourceFilterVideo
        SourceFilterTS
        SourceFilterMPG
        SourceFilterEVO
        SourceFilterVOB
        SourceFilterMKV
        SourceFilterMP4
        SourceFilterAVI
        SourceFilterMOV
        SourceFilterOGG
        SourceFilterFLV
        SourceFilterWMV
    */
    // Add filters to source chooser
    GtkFileFilter *filter;
    GtkFileChooser *chooser;
    chooser = GTK_FILE_CHOOSER(GHB_WIDGET(ud->builder, "source_dialog"));
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAll"));
    gtk_file_filter_set_name(filter, _("All"));
    gtk_file_filter_add_pattern(filter, "*");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterVideo"));
    gtk_file_filter_set_name(filter, _("Video"));
    gtk_file_filter_add_mime_type(filter, "video/*");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterTS"));
    gtk_file_filter_set_name(filter, "TS");
    gtk_file_filter_add_pattern(filter, "*.ts");
    gtk_file_filter_add_pattern(filter, "*.TS");
    gtk_file_filter_add_pattern(filter, "*.m2ts");
    gtk_file_filter_add_pattern(filter, "*.M2TS");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMPG"));
    gtk_file_filter_set_name(filter, "MPG");
    gtk_file_filter_add_pattern(filter, "*.mpg");
    gtk_file_filter_add_pattern(filter, "*.MPG");
    gtk_file_filter_add_pattern(filter, "*.mepg");
    gtk_file_filter_add_pattern(filter, "*.MEPG");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterEVO"));
    gtk_file_filter_set_name(filter, "EVO");
    gtk_file_filter_add_pattern(filter, "*.evo");
    gtk_file_filter_add_pattern(filter, "*.EVO");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterVOB"));
    gtk_file_filter_set_name(filter, "VOB");
    gtk_file_filter_add_pattern(filter, "*.vob");
    gtk_file_filter_add_pattern(filter, "*.VOB");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMKV"));
    gtk_file_filter_set_name(filter, "MKV");
    gtk_file_filter_add_pattern(filter, "*.mkv");
    gtk_file_filter_add_pattern(filter, "*.MKV");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMP4"));
    gtk_file_filter_set_name(filter, "MP4");
    gtk_file_filter_add_pattern(filter, "*.mp4");
    gtk_file_filter_add_pattern(filter, "*.MP4");
    gtk_file_filter_add_pattern(filter, "*.m4v");
    gtk_file_filter_add_pattern(filter, "*.M4V");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMOV"));
    gtk_file_filter_set_name(filter, "MOV");
    gtk_file_filter_add_pattern(filter, "*.mov");
    gtk_file_filter_add_pattern(filter, "*.MOV");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAVI"));
    gtk_file_filter_set_name(filter, "AVI");
    gtk_file_filter_add_pattern(filter, "*.avi");
    gtk_file_filter_add_pattern(filter, "*.AVI");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterOGG"));
    gtk_file_filter_set_name(filter, "OGG");
    gtk_file_filter_add_pattern(filter, "*.ogg");
    gtk_file_filter_add_pattern(filter, "*.OGG");
    gtk_file_filter_add_pattern(filter, "*.ogv");
    gtk_file_filter_add_pattern(filter, "*.OGV");
    gtk_file_filter_add_pattern(filter, "*.ogm");
    gtk_file_filter_add_pattern(filter, "*.OGM");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterFLV"));
    gtk_file_filter_set_name(filter, "FLV");
    gtk_file_filter_add_pattern(filter, "*.flv");
    gtk_file_filter_add_pattern(filter, "*.FLV");
    gtk_file_chooser_add_filter(chooser, filter);
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterWMV"));
    gtk_file_filter_set_name(filter, "WMV");
    gtk_file_filter_add_pattern(filter, "*.wmv");
    gtk_file_filter_add_pattern(filter, "*.WMV");
    gtk_file_chooser_add_filter(chooser, filter);

    // Gtk has a really stupid bug.  If the file chooser is showing
    // hidden files AND there is no filter set, it will not select
    // the filename when gtk_file_chooser_set_filename is called.
    // So add a completely unnessary filter to prevent this behavior.
    filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAll"));
    gtk_file_chooser_set_filter(chooser, filter);

    PangoFontDescription *font_desc;
    font_desc = pango_font_description_from_string("monospace 10");
    textview = GTK_TEXT_VIEW(GHB_WIDGET(ud->builder, "activity_view"));
    gtk_widget_override_font(GTK_WIDGET(textview), font_desc);
    pango_font_description_free(font_desc);

    // Grrrr!  Gtk developers !!!hard coded!!! the width of the
    // radio buttons in GtkStackSwitcher to 100!!!
    //
    // Thankfully, GtkStackSwitcher is a regular container object
    // and we can access the buttons to change their width.
    GList *stack_switcher_children, *link;
    GtkContainer * stack_switcher = GTK_CONTAINER(
                            GHB_WIDGET(ud->builder, "SettingsStackSwitcher"));
    link = stack_switcher_children = gtk_container_get_children(stack_switcher);
    while (link != NULL)
    {
        GtkWidget *widget = link->data;
        gtk_widget_set_size_request(widget, -1, -1);
        gtk_widget_set_hexpand(widget, TRUE);
        gtk_widget_set_halign(widget, GTK_ALIGN_FILL);
        link = link->next;
    }
    g_list_free(stack_switcher_children);

    gtk_window_resize(GTK_WINDOW(ghb_window), window_width, window_height);
    gtk_widget_show(ghb_window);

    // Everything should be go-to-go.  Lets rock!

    gtk_main();
    ghb_backend_close();

    ghb_value_free(&ud->queue);
    ghb_value_free(&ud->settings_array);
    ghb_value_free(&ud->prefs);
    ghb_value_free(&ud->globals);
    ghb_value_free(&ud->x264_priv);

    g_io_channel_unref(ud->activity_log);
    ghb_settings_close();
    ghb_resource_free();
#if !defined(_WIN32)
    notify_uninit();
#endif

    g_object_unref(ud->builder);

    g_free(ud->current_dvd_device);
    g_free(ud);

    return 0;
}
Ejemplo n.º 8
0
static gboolean
gimp_unique_dbus_open (const gchar **filenames,
		       gboolean      as_new)
{
#ifndef GIMP_CONSOLE_COMPILATION

/*  for the DBus service names  */
#include "gui/gimpdbusservice.h"

  GDBusConnection *connection;
  GError          *error = NULL;

  connection = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);

  if (connection)
    {
      gboolean success = TRUE;

      if (filenames)
        {
          const gchar *method = as_new ? "OpenAsNew" : "Open";
          gchar       *cwd    = g_get_current_dir ();
          gint         i;

          for (i = 0; filenames[i] && success; i++)
            {
              GError *error = NULL;
	      gchar  *uri   = gimp_unique_filename_to_uri (filenames[i],
                                                           cwd, &error);

              if (uri)
                {
                  GVariant *result;

                  result = g_dbus_connection_call_sync (connection,
                                                        GIMP_DBUS_SERVICE_NAME,
                                                        GIMP_DBUS_SERVICE_PATH,
                                                        GIMP_DBUS_INTERFACE_NAME,
                                                        method,
                                                        g_variant_new ("(s)",
                                                                       uri),
                                                        NULL,
                                                        G_DBUS_CALL_FLAGS_NO_AUTO_START,
                                                        -1,
                                                        NULL, NULL);
                  if (result)
                    g_variant_unref (result);
                  else
                    success = FALSE;

                  g_free (uri);
                }
              else
                {
                  g_printerr ("conversion to uri failed: %s\n", error->message);
                  g_clear_error (&error);
                }
            }

          g_free (cwd);
        }
      else
        {
          GVariant *result;

          result = g_dbus_connection_call_sync (connection,
                                                GIMP_DBUS_SERVICE_NAME,
                                                GIMP_DBUS_SERVICE_PATH,
                                                GIMP_DBUS_INTERFACE_NAME,
                                                "Activate",
                                                NULL,
                                                NULL,
                                                G_DBUS_CALL_FLAGS_NO_AUTO_START,
                                                -1,
                                                NULL, NULL);
          if (result)
            g_variant_unref (result);
          else
            success = FALSE;
        }

      g_object_unref (connection);

      return success;
    }
  else
    {
      g_printerr ("%s\n", error->message);
      g_clear_error (&error);
    }
#endif

  return FALSE;
}
Ejemplo n.º 9
0
int
main (int argc, char **argv)
{
    GstBus *bus;
    GOptionContext *ctx;
    GIOChannel *io_stdin;
    GError *err = NULL;
    gboolean res;
    GOptionEntry options[] = {
        {NULL}
    };
    GThread *rthread;

    /* Clear application state */
    memset (state, 0, sizeof (*state));
    state->animate = TRUE;
    state->current_buffer = NULL;
    state->caps = NULL;

#if !GLIB_CHECK_VERSION (2, 31, 0)
    /* must initialise the threading system before using any other GLib funtion */
    if (!g_thread_supported ())
        g_thread_init (NULL);
#endif

    ctx = g_option_context_new ("[ADDITIONAL ARGUMENTS]");
    g_option_context_add_main_entries (ctx, options, NULL);
    g_option_context_add_group (ctx, gst_init_get_option_group ());
    if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
        g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
        g_option_context_free (ctx);
        g_clear_error (&err);
        exit (1);
    }
    g_option_context_free (ctx);

    if (argc != 2) {
        g_print ("Usage: %s <URI> or <PIPELINE-DESCRIPTION>\n", argv[0]);
        exit (1);
    }

    /* Initialize GStreamer */
    gst_init (&argc, &argv);

    /* initialize inter thread comunnication */
    init_intercom (state);

    TRACE_VC_MEMORY ("state 0");

    if (!(rthread = g_thread_new ("render", (GThreadFunc) render_func, NULL))) {
        g_print ("Render thread create failed\n");
        exit (1);
    }

    /* Initialize player */
    if (gst_uri_is_valid (argv[1])) {
        res = init_playbin_player (state, argv[1]);
    } else {
        res = init_parse_launch_player (state, argv[1]);
    }

    if (!res)
        goto done;

    /* Create a GLib Main Loop and set it to run */
    state->main_loop = g_main_loop_new (NULL, FALSE);

    /* Add a keyboard watch so we get notified of keystrokes */
    io_stdin = g_io_channel_unix_new (fileno (stdin));
    g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc) handle_keyboard, state);
    g_io_channel_unref (io_stdin);

  /* *INDENT-OFF* */
  g_print ("Available commands: \n"
      "  a - Toggle animation \n"
      "  p - Pause playback \n"
      "  r - Resume playback \n"
      "  l - Query position/duration\n"
      "  f - Seek 30 seconds forward \n"
      "  b - Seek 30 seconds backward \n"
      "  q - Quit \n");
  /* *INDENT-ON* */

    /* Connect the bus handlers */
    bus = gst_element_get_bus (state->pipeline);

    gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bus_sync_handler, state,
                              NULL);

    gst_bus_add_signal_watch_full (bus, G_PRIORITY_HIGH);
    gst_bus_enable_sync_message_emission (bus);

    g_signal_connect (G_OBJECT (bus), "message::error", (GCallback) error_cb,
                      state);
    g_signal_connect (G_OBJECT (bus), "message::buffering",
                      (GCallback) buffering_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback) eos_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::qos", (GCallback) qos_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::state-changed",
                      (GCallback) state_changed_cb, state);
    gst_object_unref (bus);

    /* Make player start playing */
    gst_element_set_state (state->pipeline, GST_STATE_PLAYING);

    /* Start the mainloop */
    state->main_loop = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (state->main_loop);

done:
    /* Release pipeline */
    if (state->pipeline) {
        gst_element_set_state (state->pipeline, GST_STATE_NULL);
        if (state->vsink) {
            gst_object_unref (state->vsink);
            state->vsink = NULL;
        }

        gst_object_unref (state->pipeline);
    }

    /* Unref the mainloop */
    if (state->main_loop) {
        g_main_loop_unref (state->main_loop);
    }

    /* Stop rendering thread */
    state->running = FALSE;
    g_thread_join (rthread);

    if (state->caps) {
        gst_caps_unref (state->caps);
        state->caps = NULL;
    }

    terminate_intercom (state);

    TRACE_VC_MEMORY ("at exit");
    return 0;
}
Ejemplo n.º 10
0
void daemon_data_sqlite_data_LogMessageEvent (DaemonDataSqliteData* self, DaemonEventsMessageEvent* event, GError** error) {
	gchar* _tmp0_;
	gchar* commandText;
	sqlite3_stmt* statement = NULL;
	sqlite3_stmt* _tmp1_ = NULL;
	const gchar* _tmp2_ = NULL;
	gchar* _tmp3_;
	const gchar* _tmp4_ = NULL;
	gchar* _tmp5_;
	const gchar* _tmp6_ = NULL;
	gchar* _tmp7_;
	const gchar* _tmp8_ = NULL;
	gchar* _tmp9_;
	gint64 _tmp10_;
	gint _tmp11_;
	GError * _inner_error_ = NULL;
	g_return_if_fail (self != NULL);
	g_return_if_fail (event != NULL);
	_tmp0_ = g_strdup ("INSERT INTO Log (Username, Data, Channel, Server, Timestamp, Type) VAL" \
"UES (@1, @2, @3, @4, @5, @6)");
	commandText = _tmp0_;
	sqlite3_prepare_v2 (self->priv->_database, commandText, -1, &_tmp1_, NULL);
	_sqlite3_finalize0 (statement);
	statement = _tmp1_;
	_tmp2_ = daemon_events_log_event_get_Username ((DaemonEventsLogEvent*) event);
	_tmp3_ = g_strdup (_tmp2_);
	sqlite3_bind_text (statement, 1, _tmp3_, -1, g_free);
	_tmp4_ = daemon_events_message_event_get_Message (event);
	_tmp5_ = g_strdup (_tmp4_);
	sqlite3_bind_text (statement, 2, _tmp5_, -1, g_free);
	_tmp6_ = daemon_events_log_event_get_Channel ((DaemonEventsLogEvent*) event);
	_tmp7_ = g_strdup (_tmp6_);
	sqlite3_bind_text (statement, 3, _tmp7_, -1, g_free);
	_tmp8_ = daemon_events_log_event_get_Server ((DaemonEventsLogEvent*) event);
	_tmp9_ = g_strdup (_tmp8_);
	sqlite3_bind_text (statement, 4, _tmp9_, -1, g_free);
	_tmp10_ = daemon_events_log_event_get_UnixTimestamp ((DaemonEventsLogEvent*) event);
	sqlite3_bind_int64 (statement, 5, _tmp10_);
	sqlite3_bind_int (statement, 6, (gint) DAEMON_DATA_EVENT_TYPES_Message);
	_tmp11_ = sqlite3_step (statement);
	if (_tmp11_ != SQLITE_DONE) {
		const gchar* _tmp12_ = NULL;
		GError* _tmp13_ = NULL;
		_tmp12_ = sqlite3_errmsg (self->priv->_database);
		_tmp13_ = g_error_new_literal (DAEMON_DATA_DATA_ACCESS_ERROR, DAEMON_DATA_DATA_ACCESS_ERROR_WriteError, _tmp12_);
		_inner_error_ = _tmp13_;
		if (_inner_error_->domain == DAEMON_DATA_DATA_ACCESS_ERROR) {
			g_propagate_error (error, _inner_error_);
			_sqlite3_finalize0 (statement);
			_g_free0 (commandText);
			return;
		} else {
			_sqlite3_finalize0 (statement);
			_g_free0 (commandText);
			g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
			g_clear_error (&_inner_error_);
			return;
		}
	}
	_sqlite3_finalize0 (statement);
	_g_free0 (commandText);
}
Ejemplo n.º 11
0
static GList* daemon_data_sqlite_data_real_GetLog (DaemonDataIDataAccess* base, const gchar* channel, const gchar* server, GError** error) {
	DaemonDataSqliteData * self;
	GList* result = NULL;
	gchar* _tmp0_;
	gchar* commandText;
	sqlite3_stmt* statement = NULL;
	sqlite3_stmt* _tmp1_ = NULL;
	gchar* _tmp2_;
	gchar* _tmp3_;
	gint _result_;
	GList* results;
	GError * _inner_error_ = NULL;
	self = (DaemonDataSqliteData*) base;
	g_return_val_if_fail (channel != NULL, NULL);
	g_return_val_if_fail (server != NULL, NULL);
	_tmp0_ = g_strdup ("SELECT * FROM Log WHERE Channel = @1 AND Server = @2 ORDER BY Timestam" \
"p DESC LIMIT 50");
	commandText = _tmp0_;
	sqlite3_prepare_v2 (self->priv->_database, commandText, -1, &_tmp1_, NULL);
	_sqlite3_finalize0 (statement);
	statement = _tmp1_;
	_tmp2_ = g_strdup (channel);
	sqlite3_bind_text (statement, 1, _tmp2_, -1, g_free);
	_tmp3_ = g_strdup (server);
	sqlite3_bind_text (statement, 2, _tmp3_, -1, g_free);
	_result_ = 0;
	results = NULL;
	{
		gboolean _tmp4_;
		_tmp4_ = TRUE;
		while (TRUE) {
			gint _tmp5_;
			if (!_tmp4_) {
				if (!(_result_ == SQLITE_ROW)) {
					break;
				}
			}
			_tmp4_ = FALSE;
			_tmp5_ = sqlite3_step (statement);
			_result_ = _tmp5_;
			switch (_result_) {
				case SQLITE_DONE:
				{
					{
						break;
					}
				}
				case SQLITE_ROW:
				{
					{
						const gchar* _tmp6_ = NULL;
						gchar* _tmp7_;
						gchar* username;
						const gchar* _tmp8_ = NULL;
						gchar* _tmp9_;
						gchar* data;
						const gchar* _tmp10_ = NULL;
						gchar* _tmp11_;
						gchar* eventChannel;
						const gchar* _tmp12_ = NULL;
						gchar* _tmp13_;
						gchar* eventServer;
						gint64 _tmp14_;
						GDateTime* _tmp15_ = NULL;
						GDateTime* timestamp;
						gint _tmp16_;
						DaemonDataEventTypes type;
						DaemonEventsLogEvent* current;
						DaemonEventsLogEvent* _tmp21_;
						_tmp6_ = sqlite3_column_text (statement, 0);
						_tmp7_ = g_strdup (_tmp6_);
						username = _tmp7_;
						_tmp8_ = sqlite3_column_text (statement, 1);
						_tmp9_ = g_strdup (_tmp8_);
						data = _tmp9_;
						_tmp10_ = sqlite3_column_text (statement, 2);
						_tmp11_ = g_strdup (_tmp10_);
						eventChannel = _tmp11_;
						_tmp12_ = sqlite3_column_text (statement, 3);
						_tmp13_ = g_strdup (_tmp12_);
						eventServer = _tmp13_;
						_tmp14_ = sqlite3_column_int64 (statement, 4);
						_tmp15_ = daemon_helpers_date_time_converter_FromUnixTimestamp (_tmp14_);
						timestamp = _tmp15_;
						_tmp16_ = sqlite3_column_int (statement, 5);
						type = (DaemonDataEventTypes) _tmp16_;
						current = NULL;
						switch (type) {
							case DAEMON_DATA_EVENT_TYPES_Joined:
							{
								{
									DaemonEventsStatusEvent* _tmp17_ = NULL;
									_tmp17_ = daemon_events_status_event_new_WithTimestamp (username, DAEMON_EVENTS_STATUS_CHANGE_Join, eventChannel, eventServer, timestamp);
									_g_object_unref0 (current);
									current = (DaemonEventsLogEvent*) _tmp17_;
									break;
								}
							}
							case DAEMON_DATA_EVENT_TYPES_Left:
							{
								{
									DaemonEventsStatusEvent* _tmp18_ = NULL;
									_tmp18_ = daemon_events_status_event_new_WithTimestamp (username, DAEMON_EVENTS_STATUS_CHANGE_Leave, eventChannel, eventServer, timestamp);
									_g_object_unref0 (current);
									current = (DaemonEventsLogEvent*) _tmp18_;
									break;
								}
							}
							case DAEMON_DATA_EVENT_TYPES_ChangedName:
							{
								{
									DaemonEventsChangeNameEvent* _tmp19_ = NULL;
									_tmp19_ = daemon_events_change_name_event_new_WithTimestamp (username, data, eventChannel, eventServer, timestamp);
									_g_object_unref0 (current);
									current = (DaemonEventsLogEvent*) _tmp19_;
									break;
								}
							}
							case DAEMON_DATA_EVENT_TYPES_Message:
							{
								{
									DaemonEventsMessageEvent* _tmp20_ = NULL;
									_tmp20_ = daemon_events_message_event_new_WithTimestamp (username, data, eventChannel, eventServer, timestamp);
									_g_object_unref0 (current);
									current = (DaemonEventsLogEvent*) _tmp20_;
									break;
								}
							}
							default:
							break;
						}
						_tmp21_ = _g_object_ref0 (current);
						results = g_list_append (results, _tmp21_);
						_g_object_unref0 (current);
						_g_date_time_unref0 (timestamp);
						_g_free0 (eventServer);
						_g_free0 (eventChannel);
						_g_free0 (data);
						_g_free0 (username);
						break;
					}
				}
				default:
				{
					{
						const gchar* _tmp22_ = NULL;
						GError* _tmp23_ = NULL;
						_tmp22_ = sqlite3_errmsg (self->priv->_database);
						_tmp23_ = g_error_new_literal (DAEMON_DATA_DATA_ACCESS_ERROR, DAEMON_DATA_DATA_ACCESS_ERROR_ReadError, _tmp22_);
						_inner_error_ = _tmp23_;
						if (_inner_error_->domain == DAEMON_DATA_DATA_ACCESS_ERROR) {
							g_propagate_error (error, _inner_error_);
							__g_list_free__g_object_unref0_0 (results);
							_sqlite3_finalize0 (statement);
							_g_free0 (commandText);
							return NULL;
						} else {
							__g_list_free__g_object_unref0_0 (results);
							_sqlite3_finalize0 (statement);
							_g_free0 (commandText);
							g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
							g_clear_error (&_inner_error_);
							return NULL;
						}
					}
				}
			}
		}
	}
	result = results;
	_sqlite3_finalize0 (statement);
	_g_free0 (commandText);
	return result;
}
Ejemplo n.º 12
0
/* set up server */
static gboolean
gst_tcp_server_src_start (GstBaseSrc * bsrc)
{
  GstTCPServerSrc *src = GST_TCP_SERVER_SRC (bsrc);
  GError *err = NULL;
  GInetAddress *addr;
  GSocketAddress *saddr;
  GResolver *resolver;

  /* look up name if we need to */
  addr = g_inet_address_new_from_string (src->host);
  if (!addr) {
    GList *results;

    resolver = g_resolver_get_default ();

    results =
        g_resolver_lookup_by_name (resolver, src->host, src->cancellable, &err);
    if (!results)
      goto name_resolve;
    addr = G_INET_ADDRESS (g_object_ref (results->data));

    g_resolver_free_addresses (results);
    g_object_unref (resolver);
  }
#ifndef GST_DISABLE_GST_DEBUG
  {
    gchar *ip = g_inet_address_to_string (addr);

    GST_DEBUG_OBJECT (src, "IP address for host %s is %s", src->host, ip);
    g_free (ip);
  }
#endif

  saddr = g_inet_socket_address_new (addr, src->server_port);
  g_object_unref (addr);

  /* create the server listener socket */
  src->server_socket =
      g_socket_new (g_socket_address_get_family (saddr), G_SOCKET_TYPE_STREAM,
      G_SOCKET_PROTOCOL_TCP, &err);
  if (!src->server_socket)
    goto no_socket;

  GST_DEBUG_OBJECT (src, "opened receiving server socket");

  /* bind it */
  GST_DEBUG_OBJECT (src, "binding server socket to address");
  if (!g_socket_bind (src->server_socket, saddr, TRUE, &err))
    goto bind_failed;

  g_object_unref (saddr);

  GST_DEBUG_OBJECT (src, "listening on server socket");

  g_socket_set_listen_backlog (src->server_socket, TCP_BACKLOG);

  if (!g_socket_listen (src->server_socket, &err))
    goto listen_failed;

  GST_OBJECT_FLAG_SET (src, GST_TCP_SERVER_SRC_OPEN);

  return TRUE;

  /* ERRORS */
no_socket:
  {
    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
        ("Failed to create socket: %s", err->message));
    g_clear_error (&err);
    g_object_unref (saddr);
    return FALSE;
  }
name_resolve:
  {
    if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
      GST_DEBUG_OBJECT (src, "Cancelled name resolval");
    } else {
      GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
          ("Failed to resolve host '%s': %s", src->host, err->message));
    }
    g_clear_error (&err);
    g_object_unref (resolver);
    return FALSE;
  }
bind_failed:
  {
    if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
      GST_DEBUG_OBJECT (src, "Cancelled binding");
    } else {
      GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
          ("Failed to bind on host '%s:%d': %s", src->host, src->server_port,
              err->message));
    }
    g_clear_error (&err);
    g_object_unref (saddr);
    gst_tcp_server_src_stop (GST_BASE_SRC (src));
    return FALSE;
  }
listen_failed:
  {
    if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
      GST_DEBUG_OBJECT (src, "Cancelled listening");
    } else {
      GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
          ("Failed to listen on host '%s:%d': %s", src->host, src->server_port,
              err->message));
    }
    g_clear_error (&err);
    gst_tcp_server_src_stop (GST_BASE_SRC (src));
    return FALSE;
  }
}
Ejemplo n.º 13
0
static GstFlowReturn
gst_tcp_server_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
{
  GstTCPServerSrc *src;
  GstFlowReturn ret = GST_FLOW_OK;
  gssize rret, avail;
  gsize read;
  GError *err = NULL;
  GstMapInfo map;

  src = GST_TCP_SERVER_SRC (psrc);

  if (!GST_OBJECT_FLAG_IS_SET (src, GST_TCP_SERVER_SRC_OPEN))
    goto wrong_state;

  if (!src->client_socket) {
    /* wait on server socket for connections */
    src->client_socket =
        g_socket_accept (src->server_socket, src->cancellable, &err);
    if (!src->client_socket)
      goto accept_error;
    /* now read from the socket. */
  }

  /* if we have a client, wait for read */
  GST_LOG_OBJECT (src, "asked for a buffer");

  /* read the buffer header */
  avail = g_socket_get_available_bytes (src->client_socket);
  if (avail < 0) {
    goto get_available_error;
  } else if (avail == 0) {
    GIOCondition condition;

    if (!g_socket_condition_wait (src->client_socket,
            G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP, src->cancellable, &err))
      goto select_error;

    condition =
        g_socket_condition_check (src->client_socket,
        G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP);

    if ((condition & G_IO_ERR)) {
      GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
          ("Socket in error state"));
      *outbuf = NULL;
      ret = GST_FLOW_ERROR;
      goto done;
    } else if ((condition & G_IO_HUP)) {
      GST_DEBUG_OBJECT (src, "Connection closed");
      *outbuf = NULL;
      ret = GST_FLOW_EOS;
      goto done;
    }
    avail = g_socket_get_available_bytes (src->client_socket);
    if (avail < 0)
      goto get_available_error;
  }

  if (avail > 0) {
    read = MIN (avail, MAX_READ_SIZE);
    *outbuf = gst_buffer_new_and_alloc (read);
    gst_buffer_map (*outbuf, &map, GST_MAP_READWRITE);
    rret =
        g_socket_receive (src->client_socket, (gchar *) map.data, read,
        src->cancellable, &err);
  } else {
    /* Connection closed */
    rret = 0;
    *outbuf = NULL;
    read = 0;
  }

  if (rret == 0) {
    GST_DEBUG_OBJECT (src, "Connection closed");
    ret = GST_FLOW_EOS;
    if (*outbuf) {
      gst_buffer_unmap (*outbuf, &map);
      gst_buffer_unref (*outbuf);
    }
    *outbuf = NULL;
  } else if (rret < 0) {
    if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
      ret = GST_FLOW_FLUSHING;
      GST_DEBUG_OBJECT (src, "Cancelled reading from socket");
    } else {
      ret = GST_FLOW_ERROR;
      GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
          ("Failed to read from socket: %s", err->message));
    }
    gst_buffer_unmap (*outbuf, &map);
    gst_buffer_unref (*outbuf);
    *outbuf = NULL;
  } else {
    ret = GST_FLOW_OK;
    gst_buffer_unmap (*outbuf, &map);
    gst_buffer_resize (*outbuf, 0, rret);

    GST_LOG_OBJECT (src,
        "Returning buffer from _get of size %" G_GSIZE_FORMAT ", ts %"
        GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT
        ", offset %" G_GINT64_FORMAT ", offset_end %" G_GINT64_FORMAT,
        gst_buffer_get_size (*outbuf),
        GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (*outbuf)),
        GST_TIME_ARGS (GST_BUFFER_DURATION (*outbuf)),
        GST_BUFFER_OFFSET (*outbuf), GST_BUFFER_OFFSET_END (*outbuf));
  }
  g_clear_error (&err);

done:
  return ret;

wrong_state:
  {
    GST_DEBUG_OBJECT (src, "connection to closed, cannot read data");
    return GST_FLOW_FLUSHING;
  }
accept_error:
  {
    if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
      GST_DEBUG_OBJECT (src, "Cancelled accepting of client");
    } else {
      GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
          ("Failed to accept client: %s", err->message));
    }
    g_clear_error (&err);
    return GST_FLOW_ERROR;
  }
select_error:
  {
    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
        ("Select failed: %s", err->message));
    g_clear_error (&err);
    return GST_FLOW_ERROR;
  }
get_available_error:
  {
    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
        ("Failed to get available bytes from socket"));
    return GST_FLOW_ERROR;
  }
}
Ejemplo n.º 14
0
/**
 * file_plugin_proxy_export:
 * @data: A data container to save.
 * @filename: A file name to save @data to.
 * @mode: Run mode.
 * @error: Return location for a #GError (or %NULL).
 * @name: Plug-in name (i.e. file-saving function) to run.
 *
 * The plug-in proxy itself, runs file-saving plug-in @name to save @filename.
 *
 * Returns: Whether it succeeded saving the data.
 **/
static gboolean
file_plugin_proxy_export(GwyContainer *data,
                         const gchar *filename,
                         GwyRunType mode,
                         GError **error,
                         const gchar *name)
{
    FilePluginInfo *info;
    gchar *tmpname = NULL;
    GError *err = NULL;
    gint exit_status;
    FILE *fh;
    gchar *args[] = { NULL, NULL, NULL, NULL, NULL };
    GQuark dquark, mquark;
    gboolean ok;

    gwy_app_data_browser_get_current(GWY_APP_DATA_FIELD_KEY, &dquark,
                                     GWY_APP_MASK_FIELD_KEY, &mquark,
                                     0);

    gwy_debug("called as %s with file `%s'", name, filename);
    if (mode != GWY_RUN_INTERACTIVE) {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_INTERACTIVE,
                    _("Plugin-proxy must be run as interactive."));
        return FALSE;
    }
    if (!(info = file_find_plugin(name, GWY_FILE_OPERATION_EXPORT))) {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_UNIMPLEMENTED,
                    _("Plug-in `%s' does not implement file saving."), name);
        return FALSE;
    }

    fh = text_dump_export(data, dquark, mquark, &tmpname, error);
    if (!fh)
        return FALSE;

    args[0] = info->file;
    args[1] = g_strdup(gwy_enum_to_string(GWY_FILE_OPERATION_EXPORT,
                                          file_op_names, -1));
    args[2] = tmpname;
    args[3] = decode_glib_encoded_filename(filename);
    gwy_debug("%s %s %s %s", args[0], args[1], args[2], args[3]);
    ok = g_spawn_sync(NULL, args, NULL, 0, NULL, NULL,
                      NULL, NULL, &exit_status, &err);
    if (!ok) {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_SPECIFIC,
                    _("Cannot execute plug-in `%s': %s."), name, err->message);
        g_clear_error(&err);
    }
    g_unlink(tmpname);
    fclose(fh);
    gwy_debug("ok = %d, exit_status = %d, err = %p", ok, exit_status, err);
    if (ok && exit_status) {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_SPECIFIC,
                    _("Plug-in `%s' returned non-zero exit status: %d."),
                    name, exit_status);
        ok = FALSE;
    }
    g_free(args[1]);
    g_free(args[3]);
    g_free(tmpname);

    return ok;
}
Ejemplo n.º 15
0
static void
stroke_dialog_response (GtkWidget  *widget,
                        gint        response_id,
                        GtkWidget  *dialog)
{
  GimpStrokeOptions *options;
  GimpItem          *item;
  GimpImage         *image;
  GimpContext       *context;
  GtkWidget         *combo;

  item    = g_object_get_data (G_OBJECT (dialog), "gimp-item");
  options = g_object_get_data (G_OBJECT (dialog), "gimp-stroke-options");
  combo   = g_object_get_data (G_OBJECT (dialog), "gimp-tool-menu");

  image   = gimp_item_get_image (item);
  context = GIMP_VIEWABLE_DIALOG (dialog)->context;

  switch (response_id)
    {
    case RESPONSE_RESET:
      {
        GimpToolInfo *tool_info = gimp_context_get_tool (context);

        gimp_config_reset (GIMP_CONFIG (options));

        gimp_container_view_select_item (GIMP_CONTAINER_VIEW (combo),
                                         GIMP_VIEWABLE (tool_info->paint_info));

      }
      break;

    case GTK_RESPONSE_OK:
      {
        GimpDrawable      *drawable = gimp_image_get_active_drawable (image);
        GimpStrokeOptions *saved_options;
        GError            *error    = NULL;

        if (! drawable)
          {
            gimp_message_literal (context->gimp, G_OBJECT (widget),
                                  GIMP_MESSAGE_WARNING,
                                  _("There is no active layer or channel "
                                    "to stroke to."));
            return;
          }

        saved_options = g_object_get_data (G_OBJECT (context->gimp),
                                           "saved-stroke-options");

        if (saved_options)
          g_object_ref (saved_options);
        else
          saved_options = gimp_stroke_options_new (context->gimp, context, TRUE);

        gimp_config_sync (G_OBJECT (options), G_OBJECT (saved_options), 0);

        g_object_set_data_full (G_OBJECT (context->gimp), "saved-stroke-options",
                                saved_options,
                                (GDestroyNotify) g_object_unref);

        if (! gimp_item_stroke (item, drawable, context, options, NULL,
                                TRUE, NULL, &error))
          {
            gimp_message_literal (context->gimp,
                                  G_OBJECT (widget),
                                  GIMP_MESSAGE_WARNING,
                                  error ? error->message : "NULL");

            g_clear_error (&error);
            return;
          }

        gimp_image_flush (image);
      }
      /* fallthrough */

    default:
      gtk_widget_destroy (dialog);
      break;
    }
}
Ejemplo n.º 16
0
static void
load_httpserver_config (SeafileSession *session)
{
    GError *error = NULL;
    char *host = NULL;
    int port = 0;
    int max_upload_size_mb;
    int max_download_dir_size_mb;

    host = g_key_file_get_string (session->config, "httpserver", "host", &error);
    if (!error) {
        bind_addr = host;
    } else {
        if (error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND &&
            error->code != G_KEY_FILE_ERROR_GROUP_NOT_FOUND) {
            seaf_warning ("[conf] Error: failed to read the value of 'host'\n");
            exit (1);
        }

        bind_addr = DEFAULT_BIND_HOST;
        g_clear_error (&error);
    }

    port = g_key_file_get_integer (session->config, "httpserver", "port", &error);
    if (!error) {
        bind_port = port;
    } else {
        if (error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND &&
            error->code != G_KEY_FILE_ERROR_GROUP_NOT_FOUND) {
            seaf_warning ("[conf] Error: failed to read the value of 'port'\n");
            exit (1);
        }

        bind_port = DEFAULT_BIND_PORT;
        g_clear_error (&error);
    }

    use_https = g_key_file_get_boolean (session->config,
                                        "httpserver", "https",
                                        &error);
    if (error) {
        if (error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND &&
            error->code != G_KEY_FILE_ERROR_GROUP_NOT_FOUND) {
            seaf_warning ("[conf] Error: failed to read the value of 'https'\n");
            exit (1);
        }

        /* There is no <https> field in seafile.conf, so we use http. */
        g_clear_error (&error);

    } else if (use_https) {
        /* read https config */
        pemfile = g_key_file_get_string (session->config,
                                         "httpserver", "pemfile",
                                         &error);
        if (error) {
            seaf_warning ("[conf] Error: https is true, "
                          "but the value of pemfile is unknown\n");
            exit (1);
        }

        privkey = g_key_file_get_string (session->config,
                                         "httpserver", "privkey",
                                         &error);
        if (error) {
            seaf_warning ("[conf] Error: https is true, "
                          "but the value of privkey is unknown\n");
            exit (1);
        }
    }

    max_upload_size_mb = g_key_file_get_integer (session->config,
                                                 "httpserver",
                                                 "max_upload_size",
                                                 &error);
    if (error) {
        session->max_upload_size = -1; /* no limit */
        g_clear_error (&error);
    } else {
        if (max_upload_size_mb <= 0)
            session->max_upload_size = -1; /* no limit */
        else
            session->max_upload_size = max_upload_size_mb * ((gint64)1 << 20);
    }

    max_download_dir_size_mb = g_key_file_get_integer (session->config,
                                                 "httpserver",
                                                 "max_download_dir_size",
                                                 &error);
    if (error) {
        session->max_download_dir_size = DEFAULT_MAX_DOWNLOAD_DIR_SIZE;
        g_clear_error (&error);
    } else {
        if (max_download_dir_size_mb <= 0)
            session->max_download_dir_size = DEFAULT_MAX_DOWNLOAD_DIR_SIZE;
        else
            session->max_download_dir_size = max_download_dir_size_mb * ((gint64)1 << 20);
    }
}
static void
cc_privacy_panel_init (CcPrivacyPanel *self)
{
  GError    *error;
  GtkWidget *widget;
  GtkWidget *frame;
  guint res;

  self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, CC_TYPE_PRIVACY_PANEL, CcPrivacyPanelPrivate);
  g_resources_register (cc_privacy_get_resource ());

  self->priv->cancellable = g_cancellable_new ();
  self->priv->builder = gtk_builder_new ();

  error = NULL;
  res = gtk_builder_add_from_resource (self->priv->builder,
                                       "/org/gnome/control-center/privacy/privacy.ui",
                                       &error);

  if (res == 0)
    {
      g_warning ("Could not load interface file: %s",
                 (error != NULL) ? error->message : "unknown error");
      g_clear_error (&error);
      return;
    }

  self->priv->recent_dialog = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "recent_dialog"));
  self->priv->screen_lock_dialog = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "screen_lock_dialog"));
  self->priv->location_dialog = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "location_dialog"));
  self->priv->trash_dialog = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "trash_dialog"));
  self->priv->software_dialog = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "software_dialog"));
  self->priv->abrt_dialog = GTK_WIDGET (gtk_builder_get_object (self->priv->builder, "abrt_dialog"));

  frame = WID ("frame");
  widget = gtk_list_box_new ();
  gtk_list_box_set_selection_mode (GTK_LIST_BOX (widget), GTK_SELECTION_NONE);
  gtk_container_add (GTK_CONTAINER (frame), widget);
  self->priv->list_box = widget;
  gtk_widget_show (widget);
  self->priv->location_apps_list_box = WID ("location_apps_list_box");
  gtk_list_box_set_header_func (GTK_LIST_BOX (self->priv->location_apps_list_box),
                                cc_list_box_update_header_func,
                                NULL, NULL);
  self->priv->location_apps_frame = WID ("location_apps_frame");
  self->priv->location_apps_label = WID ("location_apps_label");
  self->priv->location_icon_size_group = gtk_size_group_new (GTK_SIZE_GROUP_BOTH);

  g_signal_connect_swapped (widget, "row-activated",
                            G_CALLBACK (activate_row), self);

  gtk_list_box_set_header_func (GTK_LIST_BOX (widget),
                                cc_list_box_update_header_func,
                                NULL, NULL);

  self->priv->lockdown_settings = g_settings_new ("org.gnome.desktop.lockdown");
  self->priv->lock_settings = g_settings_new ("org.gnome.desktop.screensaver");
  self->priv->privacy_settings = g_settings_new ("org.gnome.desktop.privacy");
  self->priv->notification_settings = g_settings_new ("org.gnome.desktop.notifications");
  self->priv->location_settings = g_settings_new ("org.gnome.system.location");

  add_screen_lock (self);
  add_location (self);
  add_usage_history (self);
  add_trash_temp (self);
  add_software (self);
  add_abrt (self);

  g_signal_connect (self->priv->lockdown_settings, "changed",
                    G_CALLBACK (on_lockdown_settings_changed), self);
  update_lock_screen_sensitivity (self);

  widget = WID ("privacy_vbox");
  gtk_container_add (GTK_CONTAINER (self), widget);
}
Ejemplo n.º 18
0
static gboolean
clutter_backend_real_create_context (ClutterBackend  *backend,
                                     GError         **error)
{
  GError *internal_error = NULL;
  const char *drivers_list;
  char **known_drivers;
  gboolean allow_any;
  int i;

  if (allowed_drivers == NULL)
    allowed_drivers = CLUTTER_DRIVERS;

  allow_any = strstr (allowed_drivers, "*") != NULL;

  drivers_list = g_getenv ("CLUTTER_DRIVER");
  if (drivers_list == NULL)
    drivers_list = allowed_drivers;

  known_drivers = g_strsplit (drivers_list, ",", 0);

  for (i = 0; backend->cogl_context == NULL && known_drivers[i] != NULL; i++)
    {
      const char *driver_name = known_drivers[i];
      gboolean is_any = g_str_equal (driver_name, "*");
      int j;

      for (j = 0; j < G_N_ELEMENTS (all_known_drivers); j++)
        {
          if (!allow_any && !is_any && !strstr (driver_name, all_known_drivers[j].driver_name))
            continue;

          if ((allow_any && is_any) ||
              (is_any && strstr (allowed_drivers, all_known_drivers[j].driver_name)) ||
              g_str_equal (all_known_drivers[j].driver_name, driver_name))
            {
              CLUTTER_NOTE (BACKEND, "Checking for the %s driver", all_known_drivers[j].driver_desc);

              if (clutter_backend_do_real_create_context (backend, all_known_drivers[j].driver_id, &internal_error))
                break;

              if (internal_error)
                {
                  CLUTTER_NOTE (BACKEND, "Unable to use the %s driver: %s",
                                all_known_drivers[j].driver_desc,
                                internal_error->message);
                  g_clear_error (&internal_error);
                }
            }
        }
    }

  g_strfreev (known_drivers);

  if (backend->cogl_context == NULL)
    {
      if (internal_error != NULL)
        g_propagate_error (error, internal_error);
      else
        g_set_error_literal (error, CLUTTER_INIT_ERROR,
                             CLUTTER_INIT_ERROR_BACKEND,
                            _("Unable to initialize the Clutter backend: no available drivers found."));

      return FALSE;
    }

  backend->cogl_source = cogl_glib_source_new (backend->cogl_context, G_PRIORITY_DEFAULT);
  g_source_attach (backend->cogl_source, NULL);

  return TRUE;
}
Ejemplo n.º 19
0
static void
seahorse_generate_select_constructed (GObject *obj)
{
	SeahorseGenerateSelect *self = SEAHORSE_GENERATE_SELECT (obj);
	gchar *text;
	GtkCellRenderer *pixcell;
	GtkTreeSelection *selection;
	GtkTreeIter iter;
	GList *actions;
	GList *l, *k;
	GIcon *icon;
	GtkBuilder *builder;
	const gchar *path;
	GError *error = NULL;
	const gchar *icon_name;
	GtkAction *action;

	G_OBJECT_CLASS (seahorse_generate_select_parent_class)->constructed (obj);

	self->store = gtk_list_store_new (COLUMN_N_COLUMNS, G_TYPE_ICON, G_TYPE_STRING, GTK_TYPE_ACTION);
	gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (self->store), on_list_sort, NULL, NULL);
	gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (self->store), GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, GTK_SORT_ASCENDING);

	self->action_groups = seahorse_registry_object_instances ("generator");
	for (l = self->action_groups; l != NULL; l = g_list_next (l)) {
		actions = gtk_action_group_list_actions (l->data);
		for (k = actions; k != NULL; k = g_list_next (k)) {
			action = k->data;

			text = g_strdup_printf (TEMPLATE, gtk_action_get_label (action),
			                        gtk_action_get_tooltip (action));

			icon = gtk_action_get_gicon (action);
			if (icon == NULL) {
				icon_name = gtk_action_get_icon_name (action);
				if (icon_name)
					icon = g_themed_icon_new (icon_name);
				gtk_action_get_stock_id (action);
			} else {
				g_object_ref (icon);
			}

			gtk_list_store_append (self->store, &iter);
			gtk_list_store_set (self->store, &iter,
			                    COLUMN_TEXT, text, 
			                    COLUMN_ICON, icon, 
			                    COLUMN_ACTION, k->data,
			                    -1);
			g_clear_object (&icon);
		}

		g_list_free (actions);
	}

	builder = gtk_builder_new ();
	path = "/org/gnome/Seahorse/seahorse-generate-select.xml";
	gtk_builder_add_from_resource (builder, path, &error);
	if (error != NULL) {
		g_warning ("couldn't load ui file: %s", path);
		g_clear_error (&error);
		g_object_unref (builder);
		return;
	}

	/* Setup the dialog */
	gtk_window_set_modal (GTK_WINDOW (self), TRUE);
	gtk_window_set_default_size (GTK_WINDOW (self), -1, 410);
	gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (self))),
	                    GTK_WIDGET (gtk_builder_get_object (builder, "generate-select")),
	                    TRUE, TRUE, 0);
	gtk_dialog_add_buttons (GTK_DIALOG (self),
	                        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
	                        _("Continue"), GTK_RESPONSE_OK,
	                        NULL);

	/* Hook it into the view */
	self->view = GTK_TREE_VIEW (gtk_builder_get_object (builder, "keytype-tree"));

	g_object_unref (builder);

	pixcell = gtk_cell_renderer_pixbuf_new ();
	g_object_set (pixcell, "stock-size", GTK_ICON_SIZE_DND, NULL);
	gtk_tree_view_insert_column_with_attributes (self->view, -1, "", pixcell, "gicon", COLUMN_ICON, NULL);
	gtk_tree_view_insert_column_with_attributes (self->view, -1, "", gtk_cell_renderer_text_new (), "markup", COLUMN_TEXT, NULL);
	gtk_tree_view_set_model (self->view, GTK_TREE_MODEL (self->store));

	/* Setup selection, select first item */
	selection = gtk_tree_view_get_selection (self->view);
	gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE);

	gtk_tree_model_get_iter_first (GTK_TREE_MODEL (self->store), &iter);
	gtk_tree_selection_select_iter (selection, &iter);

	g_signal_connect (self->view, "row-activated", G_CALLBACK (on_row_activated), self);
	g_object_set (self->view, "height-request", 410, NULL);

	g_signal_connect (self, "response", G_CALLBACK (on_response), self);
}
Ejemplo n.º 20
0
/**
 * @test 
 */
void test_file_permissions(void)
{
	char filename[MAXPATHLEN] = "/tmp/permsXXXXXX";
	int	 fd;
	int ret;
	GError *gerr = NULL;
	
	g_log_set_always_fatal(G_LOG_FATAL_MASK);

	/* 1st test: non-existent file */
	g_assert_cmpint(chassis_filemode_check_full("/tmp/a_non_existent_file", CHASSIS_FILEMODE_SECURE_MASK, &gerr), ==, -1);
	g_assert_cmpint(gerr->code, ==, G_FILE_ERROR_NOENT);
	g_clear_error(&gerr);

	fd = mkstemp(filename);
	if (fd < 0) {
		g_critical("%s: mkstemp(%s) failed: %s (%d)",
				G_STRLOC,
				filename,
				g_strerror(errno), errno);
	}
	g_assert_cmpint(fd, >=, 0);

	/* 2nd test: too permissive */
	ret = chmod(filename, TOO_OPEN);
	if (ret < 0) {
		g_critical("%s: chmod(%s) failed: %s (%d)",
				G_STRLOC,
				filename,
				g_strerror(errno), errno);
	}
	g_assert_cmpint(ret, ==, 0);
	g_assert_cmpint(chassis_filemode_check_full(filename, CHASSIS_FILEMODE_SECURE_MASK, &gerr), ==, 1);
	g_assert_cmpint(gerr->code, ==, G_FILE_ERROR_PERM);
	g_clear_error(&gerr);

	/* 3rd test: OK */
	ret = chmod(filename, GOOD_PERMS);
	if (ret < 0) {
		g_critical("%s: chmod(%s) failed: %s (%d)",
				G_STRLOC,
				filename,
				g_strerror(errno), errno);
	}
	g_assert_cmpint(ret, ==, 0);
	g_assert_cmpint(chassis_filemode_check_full(filename, CHASSIS_FILEMODE_SECURE_MASK, &gerr), ==, 0);
	g_assert(gerr == NULL);

	/* 4th test: non-regular file */
	close(fd);
	remove(filename);
	ret = mkdir(filename, GOOD_PERMS);
	if (ret < 0) {
		g_critical("%s: mkdir(%s) failed: %s (%d)",
				G_STRLOC,
				filename,
				g_strerror(errno), errno);
	}
	g_assert_cmpint(ret, ==, 0);
	g_assert_cmpint(chassis_filemode_check_full(filename, CHASSIS_FILEMODE_SECURE_MASK, &gerr), ==, -1);
	g_assert_cmpint(gerr->code, ==, G_FILE_ERROR_INVAL);
	g_clear_error(&gerr);

	/* clean up */
	ret = rmdir(filename);
	if (ret < 0) {
		g_critical("%s: rmdir(%s) failed: %s (%d)",
				G_STRLOC,
				filename,
				g_strerror(errno), errno);
	}
	g_assert_cmpint(ret, ==, 0);

}
Ejemplo n.º 21
0
// it will always return FALSE
gboolean socket_fault(int type, GError *error, GIOChannel *channel, gboolean unref)
{
#ifdef DETAIL
	g_debug("! Launch socket_fault() to show the error message !");
#endif
#ifdef UNIT_TEST
#  define G_WARNING g_message
#else
#  define G_WARNING g_warning
#endif
	switch (type)
	{
		case 1:
			G_WARNING("Error when create %s socket(%s): %s",
				  PACKAGE, address.sun_path, g_strerror (errno));
			break;
		case 2:
			g_message("Can NOT connect to a existing %s socket!", PACKAGE);
			break;
		case 3:
			G_WARNING("Can NOT bind on the socket!");
			break;
		case 4:
			G_WARNING("Can NOT listen on the socket!");
			break;
		case 5:
			G_WARNING("Can not watch on the socket!");
			break;
		case 6:
			G_WARNING("Error when accepting client request via socket!");
			break;
		case 7:
			G_WARNING("Error when reading the data client sent via socket!");
			break;
		case 8:
			G_WARNING("Error when running fcntl command on socket!");
			break;
		case 9:
#ifdef SAFEMODE
			if (error)
#endif
				G_WARNING("Error when setting the encoding of channel: %s", error->message);
			break;
		case 10:
#ifdef SAFEMODE
			if (error)
#endif
				G_WARNING("Error when shutdowning a channel: %s", error->message);
			break;
		case 11:
#ifdef SAFEMODE
			if (error)
#endif
				G_WARNING("Error when writing data to the channel: %s", error->message);
			break;
		case 12:
			G_WARNING("Can NOT create a channel for this socket");
			break;
		case 13:
#ifdef SAFEMODE
			if (error)
#endif
				G_WARNING("Error when flushing the write buffer for the channel: %s", error->message);
			break;
		case 14:
			G_WARNING("Got a NULL string from the socket!");
			break;
		default:
#ifdef FATAL
			print_switch_out_of_range_error_dialog("socket_fault", "type", type);
#endif
			break;
	}
	if (error) g_clear_error (&error);
	clear_channel(channel, unref);
#ifdef UNIT_TEST
#  undef G_WARNING
#endif
	return FALSE;
}
Ejemplo n.º 22
0
gboolean
ostree_create_temp_file_from_input (GFile            *dir,
                                    const char       *prefix,
                                    const char       *suffix,
                                    GFileInfo        *finfo,
                                    GVariant         *xattrs,
                                    GInputStream     *input,
                                    GFile           **out_file,
                                    GCancellable     *cancellable,
                                    GError          **error)
{
  gboolean ret = FALSE;
  GError *temp_error = NULL;
  int i = 0;
  ot_lfree char *possible_name = NULL;
  ot_lobj GFile *possible_file = NULL;
  ot_lfree guchar *ret_csum = NULL;
  GString *tmp_name = NULL;

  tmp_name = create_tmp_string (ot_gfile_get_path_cached (dir),
                                prefix, suffix);
  
  /* 128 attempts seems reasonable... */
  for (i = 0; i < 128; i++)
    {
      if (g_cancellable_set_error_if_cancelled (cancellable, error))
        goto out;

      g_free (possible_name);
      possible_name = subst_xxxxxx (tmp_name->str);
      g_clear_object (&possible_file);
      possible_file = g_file_get_child (dir, possible_name);
      
      if (!ostree_create_file_from_input (possible_file, finfo, xattrs, input,
                                          cancellable, &temp_error))
        {
          if (g_error_matches (temp_error, G_IO_ERROR, G_IO_ERROR_EXISTS))
            {
              g_clear_error (&temp_error);
              continue;
            }
          else
            {
              g_propagate_error (error, temp_error);
              goto out;
            }
        }
      else
        {
          break;
        }
    }
  if (i >= 128)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Exhausted 128 attempts to create a temporary file");
      goto out;
    }

  ret = TRUE;
  ot_transfer_out_value(out_file, &possible_file);
 out:
  if (tmp_name)
    g_string_free (tmp_name, TRUE);
  return ret;
}
GeeList* rygel_media_export_dynamic_container_get_uris (RygelMediaExportDynamicContainer* self) {
#line 132 "rygel-media-export-dynamic-container.c"
	GeeList* result = NULL;
	GError * _inner_error_;
	GeeArrayList* _result_;
#line 31 "rygel-media-export-dynamic-container.vala"
	g_return_val_if_fail (self != NULL, NULL);
#line 138 "rygel-media-export-dynamic-container.c"
	_inner_error_ = NULL;
#line 32 "rygel-media-export-dynamic-container.vala"
	_result_ = gee_array_list_new (G_TYPE_STRING, (GBoxedCopyFunc) g_strdup, g_free, NULL);
#line 142 "rygel-media-export-dynamic-container.c"
	{
		GeeArrayList* children;
#line 35 "rygel-media-export-dynamic-container.vala"
		children = rygel_media_export_media_cache_get_children (((RygelMediaExportDBContainer*) self)->media_db, ((RygelMediaObject*) self)->id, (glong) (-1), (glong) (-1), &_inner_error_);
#line 147 "rygel-media-export-dynamic-container.c"
		if (_inner_error_ != NULL) {
			goto __catch15_g_error;
		}
#line 36 "rygel-media-export-dynamic-container.vala"
		if (children != NULL) {
#line 153 "rygel-media-export-dynamic-container.c"
			{
				GeeIterator* _child_it;
				_child_it = gee_abstract_collection_iterator ((GeeAbstractCollection*) children);
#line 37 "rygel-media-export-dynamic-container.vala"
				while (TRUE) {
#line 159 "rygel-media-export-dynamic-container.c"
					RygelMediaObject* child;
#line 37 "rygel-media-export-dynamic-container.vala"
					if (!gee_iterator_next (_child_it)) {
#line 37 "rygel-media-export-dynamic-container.vala"
						break;
#line 165 "rygel-media-export-dynamic-container.c"
					}
#line 37 "rygel-media-export-dynamic-container.vala"
					child = (RygelMediaObject*) gee_iterator_get (_child_it);
#line 38 "rygel-media-export-dynamic-container.vala"
					gee_abstract_collection_add_all ((GeeAbstractCollection*) _result_, (GeeCollection*) child->uris);
#line 171 "rygel-media-export-dynamic-container.c"
					_g_object_unref0 (child);
				}
				_g_object_unref0 (_child_it);
			}
		}
		_g_object_unref0 (children);
	}
	goto __finally15;
	__catch15_g_error:
	{
		GError * err;
		err = _inner_error_;
		_inner_error_ = NULL;
		{
			_g_error_free0 (err);
		}
	}
	__finally15:
	if (_inner_error_ != NULL) {
		_g_object_unref0 (_result_);
		g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
		g_clear_error (&_inner_error_);
		return NULL;
	}
	result = (GeeList*) _result_;
#line 43 "rygel-media-export-dynamic-container.vala"
	return result;
#line 199 "rygel-media-export-dynamic-container.c"
}
Ejemplo n.º 24
0
static gboolean
spawn_x_server (State        *state,
                gboolean      allow_remote_connections,
                GCancellable *cancellable)
{
        GPtrArray           *arguments = NULL;
        GSubprocessLauncher *launcher = NULL;
        GSubprocess         *subprocess = NULL;
        GInputStream        *input_stream = NULL;
        GDataInputStream    *data_stream = NULL;
        GError              *error = NULL;

        char     *auth_file;
        gboolean  is_running = FALSE;
        int       ret;
        int       pipe_fds[2];
        char     *display_fd_string = NULL;
        char     *vt_string = NULL;
        char     *display_number;
        gsize     display_number_size;

        auth_file = prepare_auth_file ();

        g_debug ("Running X server");

        ret = g_unix_open_pipe (pipe_fds, FD_CLOEXEC, &error);

        if (!ret) {
                g_debug ("could not open pipe: %s", error->message);
                goto out;
        }

        arguments = g_ptr_array_new ();
        launcher = g_subprocess_launcher_new (G_SUBPROCESS_FLAGS_STDIN_INHERIT);
        g_subprocess_launcher_setenv (launcher, "XORG_RUN_AS_USER_OK", "1", TRUE);
        g_subprocess_launcher_take_fd (launcher, pipe_fds[1], DISPLAY_FILENO);

        if (g_getenv ("XDG_VTNR") != NULL) {
                int vt;

                vt = atoi (g_getenv ("XDG_VTNR"));

                if (vt > 0 && vt < 64) {
                        vt_string = g_strdup_printf ("vt%d", vt);
                }
        }

        display_fd_string = g_strdup_printf ("%d", DISPLAY_FILENO);

        g_ptr_array_add (arguments, X_SERVER);

        if (vt_string != NULL) {
                g_ptr_array_add (arguments, vt_string);
        }

        g_ptr_array_add (arguments, "-displayfd");
        g_ptr_array_add (arguments, display_fd_string);

        g_ptr_array_add (arguments, "-auth");
        g_ptr_array_add (arguments, auth_file);

        /* If we were compiled with Xserver >= 1.17 we need to specify
         * '-listen tcp' as the X server dosen't listen on tcp sockets
         * by default anymore. In older versions we need to pass
         * -nolisten tcp to disable listening on tcp sockets.
         */
#ifdef HAVE_XSERVER_THAT_DEFAULTS_TO_LOCAL_ONLY
        if (allow_remote_connections) {
                g_ptr_array_add (arguments, "-listen");
                g_ptr_array_add (arguments, "tcp");
        }
#else
        if (!allow_remote_connections) {
                g_ptr_array_add (arguments, "-nolisten");
                g_ptr_array_add (arguments, "tcp");
        }
#endif

        g_ptr_array_add (arguments, "-background");
        g_ptr_array_add (arguments, "none");

        g_ptr_array_add (arguments, "-noreset");
        g_ptr_array_add (arguments, "-keeptty");

        g_ptr_array_add (arguments, "-verbose");
        if (state->debug_enabled) {
                g_ptr_array_add (arguments, "7");
        } else {
                g_ptr_array_add (arguments, "3");
        }

        if (state->debug_enabled) {
                g_ptr_array_add (arguments, "-core");
        }
        g_ptr_array_add (arguments, NULL);

        subprocess = g_subprocess_launcher_spawnv (launcher,
                                                   (const char * const *) arguments->pdata,
                                                   &error);
        g_free (display_fd_string);
        g_clear_object (&launcher);
        g_ptr_array_free (arguments, TRUE);

        if (subprocess == NULL) {
                g_debug ("could not start X server: %s", error->message);
                goto out;
        }

        input_stream = g_unix_input_stream_new (pipe_fds[0], TRUE);
        data_stream = g_data_input_stream_new (input_stream);
        g_clear_object (&input_stream);

        display_number = g_data_input_stream_read_line (data_stream,
                                                        &display_number_size,
                                                        cancellable,
                                                        &error);

        if (error != NULL) {
                g_debug ("could not read display string from X server: %s", error->message);
                goto out;
        }

        if (display_number == NULL) {
                g_debug ("X server did not write display string");
                goto out;
        }

        state->display_name = g_strdup_printf (":%s", display_number);
        g_clear_pointer (&display_number, g_free);

        state->auth_file = g_strdup (auth_file);
        state->x_subprocess = g_object_ref (subprocess);

        g_subprocess_wait_async (state->x_subprocess,
                                 cancellable,
                                 (GAsyncReadyCallback)
                                 on_x_server_finished,
                                 state);

        is_running = TRUE;
out:
        g_clear_pointer (&auth_file, g_free);
        g_clear_object (&data_stream);
        g_clear_object (&subprocess);
        g_clear_object (&launcher);
        g_clear_error (&error);

        return is_running;
}
Ejemplo n.º 25
0
static void
get_current_settings_ready (QmiClientWds *client,
                            GAsyncResult *res,
                            ConnectContext *ctx)
{
    GError *error = NULL;
    QmiMessageWdsGetCurrentSettingsOutput *output;

    g_assert (ctx->running_ipv4 || ctx->running_ipv6);
    g_assert (!(ctx->running_ipv4 && ctx->running_ipv6));

    output = qmi_client_wds_get_current_settings_finish (client, res, &error);
    if (!output ||
        !qmi_message_wds_get_current_settings_output_get_result (output, &error)) {
        /* Never treat this as a hard connection error; not all devices support
         * "WDS Get Current Settings" */
        mm_info ("error: couldn't get current settings: %s", error->message);
        g_error_free (error);
    } else {
        gboolean success;
        guint32 addr, mtu, i;
        GArray *array;
        guint8 prefix;

        if (ctx->running_ipv4) {
            mm_dbg ("QMI IPv4 Settings:");

            /* IPv4 address */
            success = qmi_message_wds_get_current_settings_output_get_ipv4_address (output, &addr, &error);
            print_address4 (success, "Address", addr, error);
            g_clear_error (&error);

            /* IPv4 gateway address */
            success = qmi_message_wds_get_current_settings_output_get_ipv4_gateway_address (output, &addr, &error);
            print_address4 (success, "Gateway", addr, error);
            g_clear_error (&error);

            /* IPv4 subnet mask */
            success = qmi_message_wds_get_current_settings_output_get_ipv4_gateway_subnet_mask (output, &addr, &error);
            print_address4 (success, "Netmask", addr, error);
            g_clear_error (&error);

            /* IPv4 DNS #1 */
            success = qmi_message_wds_get_current_settings_output_get_primary_ipv4_dns_address (output, &addr, &error);
            print_address4 (success, " DNS #1", addr, error);
            g_clear_error (&error);

            /* IPv4 DNS #2 */
            success = qmi_message_wds_get_current_settings_output_get_secondary_ipv4_dns_address (output, &addr, &error);
            print_address4 (success, " DNS #2", addr, error);
            g_clear_error (&error);
        } else {
            mm_dbg ("QMI IPv6 Settings:");

            /* IPv6 address */
            success = qmi_message_wds_get_current_settings_output_get_ipv6_address (output, &array, &prefix, &error);
            print_address6 (success, "Address", array, prefix, error);
            g_clear_error (&error);

            /* IPv6 gateway address */
            success = qmi_message_wds_get_current_settings_output_get_ipv6_gateway_address (output, &array, &prefix, &error);
            print_address6 (success, "Gateway", array, prefix, error);
            g_clear_error (&error);

            /* IPv6 DNS #1 */
            success = qmi_message_wds_get_current_settings_output_get_ipv6_primary_dns_address (output, &array, &error);
            print_address6 (success, " DNS #1", array, 0, error);
            g_clear_error (&error);

            /* IPv6 DNS #2 */
            success = qmi_message_wds_get_current_settings_output_get_ipv6_secondary_dns_address (output, &array, &error);
            print_address6 (success, " DNS #2", array, 0, error);
            g_clear_error (&error);
        }

        /* Domain names */
        if (qmi_message_wds_get_current_settings_output_get_domain_name_list (output, &array, &error)) {
            GString *s = g_string_sized_new (array ? (array->len * 20) : 1);

            for (i = 0; array && (i < array->len); i++) {
                if (s->len)
                    g_string_append (s, ", ");
                g_string_append (s, g_array_index (array, const char *, i));
            }
            mm_dbg ("   Domains: %s", s->str);
            g_string_free (s, TRUE);
        } else {
            mm_dbg ("   Domains: failed (%s)", error ? error->message : "unknown");
            g_clear_error (&error);
        }

        if (qmi_message_wds_get_current_settings_output_get_mtu (output, &mtu, &error))
            mm_dbg ("       MTU: %d", mtu);
        else {
            mm_dbg ("       MTU: failed (%s)", error ? error->message : "unknown");
            g_clear_error (&error);
        }
    }

    if (output)
        qmi_message_wds_get_current_settings_output_unref (output);

    /* Keep on */
    ctx->step++;
    connect_context_step (ctx);
}
Ejemplo n.º 26
0
static gboolean
spawn_bus (State        *state,
           GCancellable *cancellable)
{
        GDBusConnection     *bus_connection = NULL;
        GPtrArray           *arguments = NULL;
        GSubprocessLauncher *launcher = NULL;
        GSubprocess         *subprocess = NULL;
        GInputStream        *input_stream = NULL;
        GDataInputStream    *data_stream = NULL;
        GError              *error = NULL;
        char                *bus_address_fd_string;
        char                *bus_address = NULL;
        gsize                bus_address_size;

        gboolean  is_running = FALSE;
        int       ret;
        int       pipe_fds[2];

        g_debug ("Running session message bus");

        bus_connection = g_bus_get_sync (G_BUS_TYPE_SESSION,
                                         cancellable,
                                         NULL);

        if (bus_connection != NULL) {
                g_debug ("session message bus already running, not starting another one");
                state->bus_connection = bus_connection;
                return TRUE;
        }

        ret = g_unix_open_pipe (pipe_fds, FD_CLOEXEC, &error);

        if (!ret) {
                g_debug ("could not open pipe: %s", error->message);
                goto out;
        }

        arguments = g_ptr_array_new ();
        launcher = g_subprocess_launcher_new (G_SUBPROCESS_FLAGS_NONE);

        g_subprocess_launcher_take_fd (launcher, pipe_fds[1], BUS_ADDRESS_FILENO);

        bus_address_fd_string = g_strdup_printf ("%d", BUS_ADDRESS_FILENO);

        g_ptr_array_add (arguments, "dbus-daemon");

        g_ptr_array_add (arguments, "--print-address");
        g_ptr_array_add (arguments, bus_address_fd_string);
        g_ptr_array_add (arguments, "--session");
        g_ptr_array_add (arguments, NULL);

        subprocess = g_subprocess_launcher_spawnv (launcher,
                                                   (const char * const *) arguments->pdata,
                                                   &error);
        g_free (bus_address_fd_string);
        g_clear_object (&launcher);
        g_ptr_array_free (arguments, TRUE);

        if (subprocess == NULL) {
                g_debug ("could not start dbus-daemon: %s", error->message);
                goto out;
        }

        input_stream = g_unix_input_stream_new (pipe_fds[0], TRUE);
        data_stream = g_data_input_stream_new (input_stream);
        g_clear_object (&input_stream);

        bus_address = g_data_input_stream_read_line (data_stream,
                                                     &bus_address_size,
                                                     cancellable,
                                                     &error);

        if (error != NULL) {
                g_debug ("could not read address from session message bus: %s", error->message);
                goto out;
        }

        if (bus_address == NULL) {
                g_debug ("session message bus did not write address");
                goto out;
        }

        state->bus_address = bus_address;

        state->bus_subprocess = g_object_ref (subprocess);

        g_subprocess_wait_async (state->bus_subprocess,
                                 cancellable,
                                 (GAsyncReadyCallback)
                                 on_bus_finished,
                                 state);


        bus_connection = g_dbus_connection_new_for_address_sync (state->bus_address,
                                                                 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
                                                                 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
                                                                 NULL,
                                                                 cancellable,
                                                                 &error);

        if (bus_connection == NULL) {
                g_debug ("could not open connection to session bus: %s",
                         error->message);
                goto out;
        }

        state->bus_connection = bus_connection;

        is_running = TRUE;
out:
        g_clear_object (&data_stream);
        g_clear_object (&subprocess);
        g_clear_object (&launcher);
        g_clear_error (&error);

        return is_running;
}
Ejemplo n.º 27
0
static gboolean notification_libnotify_create(MsgInfo *msginfo,
					      NotificationFolderType nftype)
{
  GdkPixbuf *pixbuf;
  NotificationPopup *ppopup;
  gchar *summary = NULL;
  gchar *text = NULL;
  gchar *utf8_str = NULL;
  gchar *subj = NULL;
  gchar *from = NULL;
  gchar *foldname = NULL;
  GList *caps = NULL;
  gboolean support_actions = FALSE;

  g_return_val_if_fail(msginfo, FALSE);

  ppopup = &(popup[nftype]);

  /* init libnotify if necessary */
  if(!notify_is_initted()) {
    if(!notify_init("claws-mail")) {
      debug_print("Notification Plugin: Failed to initialize libnotify. "
		  "No popup will be shown.\n");
      return FALSE;
    }
  }

  switch(nftype) {
  case F_TYPE_MAIL:
    summary = _("New Mail message");
    from    = notification_libnotify_sanitize_str(msginfo->from ?
                                                  msginfo->from : _("(No From)"));
    subj    = notification_libnotify_sanitize_str(msginfo->subject ?
                                                  msginfo->subject : _("(No Subject)"));
	if (notify_config.popup_display_folder_name) {
		foldname = notification_libnotify_sanitize_str(msginfo->folder->path);
    	text = g_strconcat(from,"\n\n", subj, "\n\n", foldname, NULL);
	}
	else
		text = g_strconcat(from, "\n\n",subj, NULL);

    /* Make sure text is valid UTF8 */
    utf8_str = notification_validate_utf8_str(text);
    g_free(text);

    if(from) g_free(from);
    if(subj) g_free(subj);
    if(foldname) g_free(foldname);
    break;
  case F_TYPE_NEWS:
    summary = _("New News post");
    utf8_str    = g_strdup(_("A new message arrived"));
    break;
  case F_TYPE_CALENDAR:
    summary = _("New Calendar message");
    utf8_str    = g_strdup(_("A new calendar message arrived"));
    break;
  case F_TYPE_RSS:
    summary = _("New RSS feed article");
    utf8_str = g_strdup(_("A new article in a RSS feed arrived"));
    break;
  default:
    summary = _("New unknown message");
    utf8_str = g_strdup(_("Unknown message type arrived"));
    break;
  }

  ppopup->notification = notify_notification_new(summary, utf8_str, NULL
#if !NOTIFY_CHECK_VERSION(0, 7, 0)
      , NULL
#endif
      );
  g_free(utf8_str);
  if(ppopup->notification == NULL) {
    debug_print("Notification Plugin: Failed to create a new "
		"notification.\n");
    return FALSE;
  }

  caps = notify_get_server_caps();
    if(caps != NULL) {
      GList *c;
      for(c = caps; c != NULL; c = c->next) {
	if(strcmp((char*)c->data, "actions") == 0 ) {
	  support_actions = TRUE;
	  break;
        }
      }

    g_list_foreach(caps, (GFunc)g_free, NULL);
    g_list_free(caps);
  }

  /* Default action */
  if (support_actions)
    notify_notification_add_action(ppopup->notification,
				   "default", _("Present main window"),
				   (NotifyActionCallback)default_action_cb,
				   GINT_TO_POINTER(nftype),
				   notification_libnotify_free_func);

  /* Icon */
  pixbuf = NULL;
#ifndef USE_ALT_ADDRBOOK
  if(msginfo && msginfo->from) {
    gchar *icon_path;
    icon_path = addrindex_get_picture_file(msginfo->from);
    if(is_file_exist(icon_path)) {
      GError *error = NULL;
      gint w, h;

      gdk_pixbuf_get_file_info(icon_path, &w, &h);
      if((w > 64) || (h > 64))
	pixbuf = gdk_pixbuf_new_from_file_at_scale(icon_path,
						   64, 64, TRUE, &error);
      else
	pixbuf = gdk_pixbuf_new_from_file(icon_path, &error);

      if(!pixbuf) {
	debug_print("Could not load picture file: %s\n",
		    error ? error->message : "no details");
	g_error_free(error);
      }
    }
    else
      debug_print("Picture path does not exist: %s\n",icon_path);
    g_free(icon_path);
  }
#endif
  if(!pixbuf)
   pixbuf = g_object_ref(notification_pixbuf_get(NOTIFICATION_CM_LOGO_64x64));

  if(pixbuf) {
    notify_notification_set_icon_from_pixbuf(ppopup->notification, pixbuf);
    g_object_unref(pixbuf);
  }
  else /* This is not fatal */
    debug_print("Notification plugin: Icon could not be loaded.\n");

  /* timeout */
  notify_notification_set_timeout(ppopup->notification, notify_config.popup_timeout);

  /* Category */
  notify_notification_set_category(ppopup->notification, "email.arrived");

  /* get notified on bubble close */
  g_signal_connect(G_OBJECT(popup->notification), "closed", G_CALLBACK(popup_timeout_fun), NULL);

  /* Show the popup */
  notify_notification_set_hint_string(ppopup->notification, "desktop-entry", "claws-mail");
  if(!notify_notification_show(ppopup->notification, &(ppopup->error))) {
    debug_print("Notification Plugin: Failed to send notification: %s\n",
		ppopup->error->message);
    g_clear_error(&(ppopup->error));
    g_object_unref(G_OBJECT(ppopup->notification));
    ppopup->notification = NULL;
    return FALSE;
  }

  debug_print("Notification Plugin: Popup created with libnotify.\n");
  ppopup->count = 1;

  /* Store path to message */
  if(nftype == F_TYPE_MAIL) {
    if(msginfo && msginfo->folder) {
      gchar *ident;
      ident = folder_item_get_identifier(msginfo->folder);
      ppopup->msg_path = g_strdup_printf("%s%s%u", ident,G_DIR_SEPARATOR_S,
					 msginfo->msgnum);
      g_free(ident);
    }
    else
      ppopup->msg_path = NULL;
  }

  return TRUE;
}
Ejemplo n.º 28
0
static void
theme_message_area_update (AppearanceData *data)
{
  const MateThemeMetaInfo *theme;
  gboolean show_apply_background = FALSE;
  gboolean show_apply_font = FALSE;
  gboolean show_revert_font = FALSE;
  gboolean show_error;
  const gchar *message;
  gchar *font;
  GError *error = NULL;

  theme = theme_get_selected (GTK_ICON_VIEW (appearance_capplet_get_widget (data, "theme_list")), data);

  if (!theme) {
    if (data->theme_message_area != NULL)
      gtk_widget_hide (data->theme_message_area);
    return;
  }

  show_error = !mate_theme_meta_info_validate (theme, &error);

  if (!show_error) {
    if (theme->background_image != NULL) {
      gchar *background;

      background = g_settings_get_string (data->wp_settings, WP_FILE_KEY);
      show_apply_background =
          (!background || strcmp (theme->background_image, background) != 0);
      g_free (background);
    }

    if (theme->application_font) {
      font = g_settings_get_string (data->interface_settings, GTK_FONT_KEY);
      show_apply_font =
          (!font || strcmp (theme->application_font, font) != 0);
      g_free (font);
    }

    if (!show_apply_font && theme->documents_font) {
      font = g_settings_get_string (data->interface_settings, DOCUMENT_FONT_KEY);
      show_apply_font =
          (!font || strcmp (theme->application_font, font) != 0);
      g_free (font);
    }

    if (!show_apply_font && theme->desktop_font) {
      font = g_settings_get_string (data->caja_settings, DESKTOP_FONT_KEY);
      show_apply_font =
          (!font || strcmp (theme->application_font, font) != 0);
      g_free (font);
    }

    if (!show_apply_font && theme->windowtitle_font) {
      font = g_settings_get_string (data->marco_settings, WINDOW_TITLE_FONT_KEY);
      show_apply_font =
          (!font || strcmp (theme->application_font, font) != 0);
      g_free (font);
    }

    if (!show_apply_font && theme->monospace_font) {
      font = g_settings_get_string (data->interface_settings, MONOSPACE_FONT_KEY);
      show_apply_font =
          (!font || strcmp (theme->application_font, font) != 0);
      g_free (font);
    }

    show_revert_font = (data->revert_application_font != NULL ||
      data->revert_documents_font != NULL || data->revert_desktop_font != NULL ||
      data->revert_windowtitle_font != NULL || data->revert_monospace_font != NULL);
  }

  if (data->theme_message_area == NULL) {
    GtkWidget *hbox;
    GtkWidget *parent;
    GtkWidget *content;

    if (!show_apply_background && !show_revert_font && !show_apply_font && !show_error)
      return;

    data->theme_message_area = gtk_info_bar_new ();
    gtk_widget_set_no_show_all (data->theme_message_area, TRUE);

    g_signal_connect (data->theme_message_area, "response",
                      (GCallback) theme_message_area_response_cb, data);

    data->apply_background_button = gtk_info_bar_add_button (
        GTK_INFO_BAR (data->theme_message_area),
        _("Apply Background"),
        RESPONSE_APPLY_BG);
    data->apply_font_button = gtk_info_bar_add_button (
        GTK_INFO_BAR (data->theme_message_area),
        _("Apply Font"),
        RESPONSE_APPLY_FONT);
    data->revert_font_button = gtk_info_bar_add_button (
        GTK_INFO_BAR (data->theme_message_area),
        _("Revert Font"),
        RESPONSE_REVERT_FONT);
    data->install_button = gtk_info_bar_add_button (
        GTK_INFO_BAR (data->theme_message_area),
        _("Install"),
        RESPONSE_INSTALL_ENGINE);

    data->theme_message_label = gtk_label_new (NULL);
    gtk_widget_show (data->theme_message_label);
    gtk_label_set_line_wrap (GTK_LABEL (data->theme_message_label), TRUE);
    gtk_misc_set_alignment (GTK_MISC (data->theme_message_label), 0.0, 0.5);

    hbox = gtk_hbox_new (FALSE, 9);
    gtk_widget_show (hbox);
    data->theme_info_icon = gtk_image_new_from_stock (GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
    data->theme_error_icon = gtk_image_new_from_stock (GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
    gtk_misc_set_alignment (GTK_MISC (data->theme_info_icon), 0.5, 0);
    gtk_misc_set_alignment (GTK_MISC (data->theme_error_icon), 0.5, 0);
    gtk_box_pack_start (GTK_BOX (hbox), data->theme_info_icon, FALSE, FALSE, 0);
    gtk_box_pack_start (GTK_BOX (hbox), data->theme_error_icon, FALSE, FALSE, 0);
    gtk_box_pack_start (GTK_BOX (hbox), data->theme_message_label, TRUE, TRUE, 0);
    content = gtk_info_bar_get_content_area (GTK_INFO_BAR (data->theme_message_area));
    gtk_container_add (GTK_CONTAINER (content), hbox);

    parent = appearance_capplet_get_widget (data, "theme_list_vbox");
    gtk_box_pack_start (GTK_BOX (parent), data->theme_message_area, FALSE, FALSE, 0);
  }

  if (show_error)
    message = error->message;
  else if (show_apply_background && show_apply_font && show_revert_font)
    message = _("The current theme suggests a background and a font. Also, the last applied font suggestion can be reverted.");
  else if (show_apply_background && show_revert_font)
    message = _("The current theme suggests a background. Also, the last applied font suggestion can be reverted.");
  else if (show_apply_background && show_apply_font)
    message = _("The current theme suggests a background and a font.");
  else if (show_apply_font && show_revert_font)
    message = _("The current theme suggests a font. Also, the last applied font suggestion can be reverted.");
  else if (show_apply_background)
    message = _("The current theme suggests a background.");
  else if (show_revert_font)
    message = _("The last applied font suggestion can be reverted.");
  else if (show_apply_font)
    message = _("The current theme suggests a font.");
  else
    message = NULL;

  if (show_apply_background)
    gtk_widget_show (data->apply_background_button);
  else
    gtk_widget_hide (data->apply_background_button);

  if (show_apply_font)
    gtk_widget_show (data->apply_font_button);
  else
    gtk_widget_hide (data->apply_font_button);

  if (show_revert_font)
    gtk_widget_show (data->revert_font_button);
  else
    gtk_widget_hide (data->revert_font_button);

  if (show_error
      && g_error_matches (error, MATE_THEME_ERROR, MATE_THEME_ERROR_GTK_ENGINE_NOT_AVAILABLE)
      && packagekit_available ())
    gtk_widget_show (data->install_button);
  else
    gtk_widget_hide (data->install_button);

  if (show_error || show_apply_background || show_apply_font || show_revert_font) {
    gtk_widget_show (data->theme_message_area);
    gtk_widget_queue_draw (data->theme_message_area);

    if (show_error) {
      gtk_widget_show (data->theme_error_icon);
      gtk_widget_hide (data->theme_info_icon);
    } else {
      gtk_widget_show (data->theme_info_icon);
      gtk_widget_hide (data->theme_error_icon);
    }
  } else {
    gtk_widget_hide (data->theme_message_area);
  }

  gtk_label_set_text (GTK_LABEL (data->theme_message_label), message);
  g_clear_error (&error);
}
Ejemplo n.º 29
0
static char* string_replace (const char* self, const char* old, const char* replacement) {
#line 227 "source-spinner-item.c"
	char* result = NULL;
	GError * _inner_error_ = NULL;
#line 1157 "glib-2.0.vapi"
	g_return_val_if_fail (self != NULL, NULL);
#line 1157 "glib-2.0.vapi"
	g_return_val_if_fail (old != NULL, NULL);
#line 1157 "glib-2.0.vapi"
	g_return_val_if_fail (replacement != NULL, NULL);
#line 236 "source-spinner-item.c"
	{
		char* _tmp0_;
		GRegex* _tmp1_;
		GRegex* regex;
		char* _tmp2_;
#line 1159 "glib-2.0.vapi"
		regex = (_tmp1_ = g_regex_new (_tmp0_ = g_regex_escape_string (old, -1), 0, 0, &_inner_error_), _g_free0 (_tmp0_), _tmp1_);
#line 244 "source-spinner-item.c"
		if (_inner_error_ != NULL) {
			if (_inner_error_->domain == G_REGEX_ERROR) {
				goto __catch41_g_regex_error;
			}
			g_critical ("file %s: line %d: unexpected error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
			g_clear_error (&_inner_error_);
			return NULL;
		}
#line 1160 "glib-2.0.vapi"
		_tmp2_ = g_regex_replace_literal (regex, self, (gssize) (-1), 0, replacement, 0, &_inner_error_);
#line 255 "source-spinner-item.c"
		if (_inner_error_ != NULL) {
			_g_regex_unref0 (regex);
			if (_inner_error_->domain == G_REGEX_ERROR) {
				goto __catch41_g_regex_error;
			}
			_g_regex_unref0 (regex);
			g_critical ("file %s: line %d: unexpected error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
			g_clear_error (&_inner_error_);
			return NULL;
		}
		result = _tmp2_;
		_g_regex_unref0 (regex);
#line 1160 "glib-2.0.vapi"
		return result;
#line 270 "source-spinner-item.c"
	}
	goto __finally41;
	__catch41_g_regex_error:
	{
		GError * e;
		e = _inner_error_;
		_inner_error_ = NULL;
		{
#line 1162 "glib-2.0.vapi"
			g_assert_not_reached ();
#line 281 "source-spinner-item.c"
			_g_error_free0 (e);
		}
	}
	__finally41:
	if (_inner_error_ != NULL) {
		g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
		g_clear_error (&_inner_error_);
		return NULL;
	}
}
Ejemplo n.º 30
0
/**
 * proc_plugin_proxy_run:
 * @data: A data container.
 * @run: Run mode.
 * @name: Plug-in name (i.e. data processing function) to run.
 *
 * The plug-in proxy itself, runs plug-in @name on @data.
 *
 * Returns: Whether it succeeded running the plug-in.
 **/
static void
proc_plugin_proxy_run(GwyContainer *data,
                      GwyRunType run,
                      const gchar *name)
{
    ProcPluginInfo *info;
    GwyContainer *newdata;
    gchar *filename, *buffer = NULL;
    GError *err = NULL;
    gint exit_status, id, newid;
    gsize size = 0;
    FILE *fh;
    gchar *args[] = { NULL, "run", NULL, NULL, NULL };
    GQuark dquark, mquark, squark;
    gboolean ok;

    gwy_app_data_browser_get_current(GWY_APP_DATA_FIELD_KEY, &dquark,
                                     GWY_APP_MASK_FIELD_KEY, &mquark,
                                     GWY_APP_DATA_FIELD_ID, &id,
                                     0);

    gwy_debug("called as %s with run mode %d", name, run);
    if (!(info = proc_find_plugin(name, run)))
        return;

    fh = text_dump_export(data, dquark, mquark, &filename, NULL);
    g_return_if_fail(fh);
    args[0] = info->file;
    args[2] = g_strdup(gwy_enum_to_string(run, run_mode_names, -1));
    args[3] = decode_glib_encoded_filename(filename);
    gwy_debug("%s %s %s %s", args[0], args[1], args[2], args[3]);
    ok = g_spawn_sync(NULL, args, NULL, 0, NULL, NULL,
                      NULL, NULL, &exit_status, &err);
    if (!err)
        ok &= g_file_get_contents(filename, &buffer, &size, &err);
    g_unlink(filename);
    fclose(fh);
    gwy_debug("ok = %d, exit_status = %d, err = %p", ok, exit_status, err);
    ok &= !exit_status;
    if (ok && (newdata = text_dump_import(buffer, size, NULL))) {
        GwyDataField *dfield;

        /* Merge data */
        if (gwy_container_gis_object_by_name(newdata, "/0/data", &dfield))
            g_object_ref(dfield);
        else {
            dfield = gwy_container_get_object(data, dquark);
            dfield = gwy_data_field_duplicate(dfield);
        }
        newid = gwy_app_data_browser_add_data_field(dfield, data, TRUE);

        /* Merge mask */
        if (gwy_container_gis_object_by_name(newdata, "/0/mask", &dfield))
            g_object_ref(dfield);
        else if (gwy_container_gis_object(data, mquark, &dfield))
            dfield = gwy_data_field_duplicate(dfield);
        else
            dfield = NULL;

        if (dfield) {
            mquark = gwy_app_get_mask_key_for_id(newid);
            gwy_container_set_object(data, mquark, dfield);
            g_object_unref(dfield);
        }

        /* Merge presentation */
        if (gwy_container_gis_object_by_name(newdata, "/0/show", &dfield)) {
            squark = gwy_app_get_show_key_for_id(newid);
            gwy_container_set_object(data, squark, dfield);
        }

        /* Merge stuff.  XXX: This is brutal and incomplete. */
        gwy_app_sync_data_items(data, data, id, newid, FALSE,
                                GWY_DATA_ITEM_GRADIENT,
                                GWY_DATA_ITEM_RANGE_TYPE,
                                GWY_DATA_ITEM_MASK_COLOR,
                                GWY_DATA_ITEM_REAL_SQUARE,
                                0);
        gwy_app_sync_data_items(newdata, data, 0, newid, FALSE,
                                GWY_DATA_ITEM_GRADIENT,
                                GWY_DATA_ITEM_RANGE_TYPE,
                                0);

        g_object_unref(newdata);
    }
    else {
        g_warning("Cannot run plug-in %s: %s",
                  info->file,
                  err ? err->message : "it returned garbage.");
    }
    g_free(args[3]);
    g_free(args[2]);
    g_clear_error(&err);
    g_free(buffer);
    g_free(filename);
}