Beispiel #1
0
void renameFile(FmFileInfo *file, QWidget *parent) {
  FmPath* path = fm_file_info_get_path(file);
  FilenameDialog dlg(parent);
  dlg.setWindowTitle(QObject::tr("Rename File"));
  dlg.setLabelText(QObject::tr("Please enter a new name:"));
  // FIXME: what's the best way to handle non-UTF8 filename encoding here?
  QString old_name = QString::fromLocal8Bit(fm_path_get_basename(path));
  dlg.setTextValue(old_name);

  if(fm_file_info_is_dir(file)) // select filename extension for directories
    dlg.setSelectExtension(true);

  if(dlg.exec() != QDialog::Accepted)
    return;

  QString new_name = dlg.textValue();

  if(new_name == old_name)
    return;

  GFile* gf = fm_path_to_gfile(path);
  GFile* parent_gf = g_file_get_parent(gf);
  GFile* dest = g_file_get_child(G_FILE(parent_gf), new_name.toLocal8Bit().data());
  g_object_unref(parent_gf);

  GError* err = NULL;
  if(!g_file_move(gf, dest,
                  GFileCopyFlags(G_FILE_COPY_ALL_METADATA |
                                 G_FILE_COPY_NO_FALLBACK_FOR_MOVE |
                                 G_FILE_COPY_NOFOLLOW_SYMLINKS),
                  NULL, /* make this cancellable later. */
                  NULL, NULL, &err)) {
    QMessageBox::critical(parent, QObject::tr("Error"), err->message);
    g_error_free(err);
  }

  g_object_unref(dest);
  g_object_unref(gf);
}
gboolean
panel_is_uri_writable (const char *uri)
{
    GFile     *file;
    GFileInfo *info;
    gboolean   retval;

    g_return_val_if_fail (uri != NULL, FALSE);

    retval = FALSE;

    file = g_file_new_for_uri (uri);

    if (!g_file_query_exists (file, NULL)) {
        GFile *parent;

        parent = g_file_get_parent (file);
        g_object_unref (file);

        if (!g_file_query_exists (parent, NULL)) {
            g_object_unref (parent);
            return FALSE;
        }

        file = parent;
    }

    info = g_file_query_info (file, "access::*",
                              G_FILE_QUERY_INFO_NONE, NULL, NULL);
    g_object_unref (file);

    if (info) {
        retval = g_file_info_get_attribute_boolean (info,
                 G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE);
        g_object_unref (info);
    }

    return retval;
}
Beispiel #3
0
/**
 * rb_file_find_extant_parent:
 * @file: a #GFile to find an extant ancestor of
 *
 * Walks up the filesystem hierarchy to find a #GFile representing
 * the nearest extant ancestor of the specified file, which may be
 * the file itself if it exists.
 *
 * Return value: (transfer full): #GFile for the nearest extant ancestor
 */
GFile *
rb_file_find_extant_parent (GFile *file)
{
    g_object_ref (file);
    while (g_file_query_exists (file, NULL) == FALSE) {
        GFile *parent;

        parent = g_file_get_parent (file);
        if (parent == NULL) {
            char *uri = g_file_get_uri (file);
            g_warning ("filesystem root %s apparently doesn't exist!", uri);
            g_free (uri);
            g_object_unref (file);
            return NULL;
        }

        g_object_unref (file);
        file = parent;
    }

    return file;
}
void macro_edit_button_cb(GtkButton* btn, gpointer user_data)
{
    GtkWidget* parent_dlg = GTK_WIDGET(user_data);

    gtk_widget_set_sensitive(parent_dlg, FALSE);

    GtkWidget* dlg = unikey_macro_dialog_new();

    gchar* macrofile = get_macro_file();

    CMacroTable macro;
    macro.init();
    macro.loadFromFile(macrofile);

    unikey_macro_dialog_load_macro(GTK_DIALOG(dlg), macro);

    int ret = gtk_dialog_run(GTK_DIALOG(dlg));

    if (ret == GTK_RESPONSE_OK)
    {
        unikey_macro_dialog_save_macro(GTK_DIALOG(dlg), &macro);

        GFile* f = g_file_get_parent(g_file_new_for_path(macrofile));
        if (g_file_query_exists(f, NULL) == FALSE)
        {
            g_file_make_directory_with_parents(f, NULL, NULL);
        }
        g_object_unref(f);

        macro.writeToFile(macrofile);
    }

    g_free(macrofile);

    gtk_widget_destroy(dlg);

    gtk_widget_set_sensitive(parent_dlg, TRUE);
}
Beispiel #5
0
static gboolean
setup_extract_tests_directory (const char *executable_path)
{
  g_autoptr (GFile) tests_dir = NULL;
  gboolean found;

  tests_dir = g_file_new_for_commandline_arg (executable_path);

  found = FALSE;
  while (!found && g_file_has_parent (tests_dir, NULL)) {
    GFile *parent;
    g_autofree gchar *parent_basename;

    parent = g_file_get_parent (tests_dir);
    parent_basename = g_file_get_basename (parent);

    if (g_strcmp0 (parent_basename, TESTS_DIR_NAME) == 0) {
      found = TRUE;
    }

    g_object_unref (tests_dir);
    tests_dir = parent;
  }

  if (!found) {
    g_printerr ("Tests directory not in executable path\n");
    return FALSE;
  }

  extract_tests_dir = g_file_get_child (tests_dir, EXTRACT_TESTS_DIR_NAME);

  if (!g_file_query_exists (extract_tests_dir, NULL)) {
    g_printerr ("Extract tests directory does not exist in tests directory\n");
    return FALSE;
  }

  return TRUE;
}
static gboolean
gs_install_appstream_copy_file (GFile *file, GError **error)
{
	g_autofree gchar *basename = g_file_get_basename (file);
	g_autofree gchar *cachefn = gs_external_appstream_utils_get_file_cache_path (basename);
	g_autoptr(GFile) cachefn_file = g_file_new_for_path (cachefn);
	g_autoptr(GFile) cachedir_file = g_file_get_parent (cachefn_file);

	/* make sure the parent directory exists, but if not then create with
	 * the ownership and permissions of the current process */
	if (!g_file_query_exists (cachedir_file, NULL)) {
		if (!g_file_make_directory_with_parents (cachedir_file, NULL, error))
			return FALSE;
	}

	/* do the copy, overwriting existing files and setting the permissions
	 * of the current process (so that should be -rw-r--r--) */
	return g_file_copy (file, cachefn_file,
			    G_FILE_COPY_OVERWRITE |
			    G_FILE_COPY_NOFOLLOW_SYMLINKS |
			    G_FILE_COPY_TARGET_DEFAULT_PERMS,
			    NULL, NULL, NULL, error);
}
Beispiel #7
0
void
gth_browser_activate_action_go_to_container (GtkAction  *action,
					     GthBrowser *browser)
{
	GList *items;
	GList *file_list = NULL;

	items = gth_file_selection_get_selected (GTH_FILE_SELECTION (gth_browser_get_file_list_view (browser)));
	file_list = gth_file_list_get_files (GTH_FILE_LIST (gth_browser_get_file_list (browser)), items);

	if (file_list != NULL) {
		GthFileData *first_file = file_list->data;
		GFile       *parent;

		parent = g_file_get_parent (first_file->file);
		gth_browser_go_to (browser, parent, first_file->file);

		g_object_unref (parent);
	}

	_g_object_list_unref (file_list);
	_gtk_tree_path_list_free (items);
}
static GdkDragAction
xfdesktop_regular_file_icon_get_allowed_drag_actions(XfdesktopIcon *icon)
{
    GFileInfo *info = xfdesktop_file_icon_peek_file_info(XFDESKTOP_FILE_ICON(icon));
    GFile *file = xfdesktop_file_icon_peek_file(XFDESKTOP_FILE_ICON(icon));
    GdkDragAction actions = GDK_ACTION_LINK;  /* we can always link */

    if(!info)
        return 0;

    if(g_file_info_get_attribute_boolean(info,
                                         G_FILE_ATTRIBUTE_ACCESS_CAN_READ))
    {
        GFileInfo *parent_info;
        GFile *parent_file;
        
        actions |= GDK_ACTION_COPY;
        
        /* we can only move if the parent is writable */
        parent_file = g_file_get_parent(file);
        parent_info = g_file_query_info(parent_file, 
                                        XFDESKTOP_FILE_INFO_NAMESPACE,
                                        G_FILE_QUERY_INFO_NONE, 
                                        NULL, NULL);
        if(parent_info) {
            if(g_file_info_get_attribute_boolean(parent_info,
                                                 G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE))
            {
                actions |= GDK_ACTION_MOVE;
            }
            g_object_unref(parent_info);
        }
        g_object_unref(parent_file);
    }
    
    return actions;
}
Beispiel #9
0
static gboolean
amp_group_node_save (AmpNode *group, AmpNode *parent, AmpProject *project, GError **error)
{
	AnjutaTokenFile *tfile;
	AnjutaProjectNode *child;
	gboolean ok = TRUE;
	GFile *directory;

	/* Create directory */
	directory = g_file_get_parent (AMP_GROUP_NODE (group)->makefile);
	g_file_make_directory (directory, NULL, NULL);
	g_object_unref (directory);

	/* Save group */
	tfile = AMP_GROUP_NODE (group)->tfile;
	if (tfile == NULL)
	{
		/* Create an empty makefile */
		g_file_replace_contents (AMP_GROUP_NODE (group)->makefile, "", 0, NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, NULL);

		return TRUE;
	}

	if (anjuta_token_file_is_dirty (tfile))
	{
		if (!anjuta_token_file_save (tfile, error)) return FALSE;
	}

	/* Save all children */
	for (child = anjuta_project_node_first_child (ANJUTA_PROJECT_NODE (group)); child != NULL; child = anjuta_project_node_next_sibling (child))
	{
		/* Try to save all children even if some fail */
		if (!amp_node_save (AMP_NODE (child), group, project, error)) ok = FALSE;
	}

	return ok;
}
static gboolean
do_checkout (OtAdminDeploy     *self,
             const char        *deploy_target,
             const char        *revision,
             GCancellable      *cancellable,
             GError           **error)
{
  gboolean ret = FALSE;
  ot_lobj GFile *deploy_path = NULL;
  ot_lobj GFile *deploy_parent = NULL;
  ot_lfree char *tree_ref = NULL;
  ot_lfree char *repo_path = NULL;
  ot_lfree char *repo_arg = NULL;
  ot_lptrarray GPtrArray *checkout_args = NULL;

  repo_path = g_build_filename (opt_ostree_dir, "repo", NULL);
  repo_arg = g_strconcat ("--repo=", repo_path, NULL);

  deploy_path = ot_gfile_from_build_path (opt_ostree_dir, deploy_target, NULL);
  deploy_parent = g_file_get_parent (deploy_path);
  if (!ot_gfile_ensure_directory (deploy_parent, TRUE, error))
    goto out;

  checkout_args = g_ptr_array_new ();
  ot_ptrarray_add_many (checkout_args, "ostree", repo_arg,
                        "checkout", "--atomic-retarget", revision ? revision : deploy_target,
                        ot_gfile_get_path_cached (deploy_path), NULL);
  g_ptr_array_add (checkout_args, NULL);

  if (!ot_spawn_sync_checked (opt_ostree_dir, (char**)checkout_args->pdata, NULL, G_SPAWN_SEARCH_PATH,
                              NULL, NULL, NULL, NULL, error))
    goto out;

  ret = TRUE;
 out:
  return ret;
}
Beispiel #11
0
/**
 * anjuta_token_stream_push:
 * @parent: a parent #AnjutaTokenStream object or NULL.
 * @root: a token or NULL
 * @content: a token list.
 *
 * Create a new stream from a list of tokens. If a parent stream is passed,
 * the new stream keep a link on it, so we can return it when the new stream
 * will be destroyed.
 *
 * Return value: The newly created stream.
 */
AnjutaTokenStream *
anjuta_token_stream_push (AnjutaTokenStream *parent, AnjutaToken *root, AnjutaToken *content, GFile *file)
{
	AnjutaTokenStream *child;
	AnjutaTokenStream *stream;

	/* Check if content is not already parsed to avoid endless parsing loop */
	for (stream = parent; stream != NULL; stream = stream->parent)
	{
		if (stream->content == content) return NULL;
	}

	/* Create new stream */
	child = g_new (AnjutaTokenStream, 1);
	child->first = content;
	child->pos = 0;
	child->begin = 0;
	child->parent = parent;
	child->content = content;
	child->token = content;
	child->start = child->token;
	child->last = content == NULL ? NULL : anjuta_token_last (content);

	child->root = root == NULL ? anjuta_token_new_static (ANJUTA_TOKEN_FILE, NULL) : root;
	if (file == NULL)
	{
		child->current_directory = parent == NULL ? NULL : (parent->current_directory == NULL ? NULL : g_object_ref (parent->current_directory));
		child->current_file = NULL;
	}
	else
	{
		child->current_directory = g_file_get_parent (file);
		child->current_file = g_object_ref (file);
	}

	return child;
}
Beispiel #12
0
/**
 * mcm_utils_mkdir_for_filename:
 **/
gboolean
mcm_utils_mkdir_for_filename (const gchar *filename, GError **error)
{
	gboolean ret = FALSE;
	GFile *file;
	GFile *parent_dir = NULL;

	/* get a file from the URI / path */
	file = g_file_new_for_path (filename);
	if (file == NULL)
		file = g_file_new_for_path (filename);
	if (file == NULL) {
		g_set_error (error, 1, 0, "could not resolve file for %s", filename);
		goto out;
	}

	/* get parent */
	parent_dir = g_file_get_parent (file);
	if (parent_dir == NULL) {
		g_set_error (error, 1, 0, "could not get parent dir %s", filename);
		goto out;
	}

	/* ensure desination exists */
	ret = g_file_query_exists (parent_dir, NULL);
	if (!ret) {
		ret = g_file_make_directory_with_parents (parent_dir, NULL, error);
		if (!ret)
			goto out;
	}
out:
	if (file != NULL)
		g_object_unref (file);
	if (parent_dir != NULL)
		g_object_unref (parent_dir);
	return ret;
}
Beispiel #13
0
static void
set_current_destination_file (GthPixbufListTask *self)
{
	GthFileData *file_data;
	char        *display_name;
	GFile       *parent;
	GFile       *destination;

	file_data = self->priv->current->data;
	if (self->priv->mime_type != NULL) {
		char           *no_ext;
		GthPixbufSaver *saver;

		no_ext = _g_uri_remove_extension (g_file_info_get_display_name (file_data->info));
		saver = gth_main_get_pixbuf_saver (self->priv->mime_type);
		g_return_if_fail (saver != NULL);
		display_name = g_strconcat (no_ext, ".", gth_pixbuf_saver_get_default_ext (saver), NULL);
		gth_file_data_set_mime_type (file_data, self->priv->mime_type);

		g_object_unref (saver);
		g_free (no_ext);
	}
	else
		display_name = g_strdup (g_file_info_get_display_name (file_data->info));

	if (self->priv->destination_folder != NULL)
		parent = g_object_ref (self->priv->destination_folder);
	else
		parent = g_file_get_parent (file_data->file);
	destination = g_file_get_child_for_display_name (parent, display_name, NULL);
	gth_file_data_set_file (file_data, destination);

	g_object_unref (destination);
	g_object_unref (parent);
	g_free (display_name);
}
Beispiel #14
0
/**
 * anjuta_profile_sync:
 * @profile: a #AnjutaProfile object.
 * @error: error propagation and reporting.
 * 
 * Save the current plugins list in the xml file set with anjuta_profile_set_sync_file().
 *
 * Return value: TRUE on success, FALSE otherwise.
 */
gboolean
anjuta_profile_sync (AnjutaProfile *profile, GError **error)
{
	gboolean ok;
	gchar *xml_buffer;
	AnjutaProfilePriv *priv;
	GError* file_error = NULL;
	
	g_return_val_if_fail (ANJUTA_IS_PROFILE (profile), FALSE);
	priv = profile->priv;
	
	if (!priv->sync_file)
		return FALSE;
	
	xml_buffer = anjuta_profile_to_xml (profile);
	ok = g_file_replace_contents (priv->sync_file, xml_buffer, strlen(xml_buffer),
								  NULL, FALSE, G_FILE_CREATE_NONE,
								  NULL, NULL, &file_error);
	if (!ok && g_error_matches (file_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
	{
		/* Try to create parent directory */
		GFile* parent = g_file_get_parent (priv->sync_file);
		if (g_file_make_directory (parent, NULL, NULL))
		{
			g_clear_error (&file_error);
			ok = g_file_replace_contents (priv->sync_file, xml_buffer, strlen(xml_buffer),
										  NULL, FALSE, G_FILE_CREATE_NONE,
										  NULL, NULL, &file_error);
		}
		g_object_unref (parent);
	}
	g_free (xml_buffer);
	if (file_error != NULL) g_propagate_error (error, file_error);
	
	return ok;
}
Beispiel #15
0
static void _check_gfile_display_names(FmPath *path, GFile *child)
{
    GFile *gf;
    GFileInfo *inf;

    if (path == NULL || _fm_path_get_display_name(path) != NULL)
        return; /* all done */
    gf = g_file_get_parent(child);
    if (gf == NULL) /* file systems such as search:// don't support this */
        return;
    inf = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME","
                                G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME,
                            G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, NULL);
    if (inf != NULL)
    {
        const char *dname = g_file_info_get_edit_name(inf);
        if (!dname)
            dname = g_file_info_get_display_name(inf);
        _fm_path_set_display_name(path, dname);
        g_object_unref(inf);
    }
    _check_gfile_display_names(fm_path_get_parent(path), gf); /* recursion */
    g_object_unref(gf);
}
GFile *
nautilus_find_existing_uri_in_hierarchy (GFile *location)
{
    GFileInfo *info;
    GFile *tmp;

    g_assert (location != NULL);

    location = g_object_ref (location);
    while (location != NULL) {
        info = g_file_query_info (location,
                                  G_FILE_ATTRIBUTE_STANDARD_NAME,
                                  0, NULL, NULL);
        g_object_unref (info);
        if (info != NULL) {
            return location;
        }
        tmp = location;
        location = g_file_get_parent (location);
        g_object_unref (tmp);
    }

    return location;
}
Beispiel #17
0
static void
migrate_options_directory (void)
{
	char *old_directory_path;
	GFile *old_directory;
	GFile *new_directory;

	old_directory_path = get_home_relative_path (".gnome2/file-roller/options");
	old_directory = g_file_new_for_path (old_directory_path);
	new_directory = _g_file_new_user_config_subdir (ADD_FOLDER_OPTIONS_DIR, FALSE);
	if (g_file_query_exists (old_directory, NULL) && ! g_file_query_exists (new_directory, NULL)) {
		GFile *parent;

		parent = g_file_get_parent (new_directory);
		if (_g_file_make_directory_tree (parent, 0700, NULL))
			g_file_move (old_directory, new_directory, 0, NULL, NULL, NULL, NULL);

		g_object_unref (parent);
	}

	g_object_unref (new_directory);
	g_object_unref (old_directory);
	g_free (old_directory_path);
}
Beispiel #18
0
static gboolean
try_check_file (GIOSchedulerJob *io_job,
                GCancellable *cancellable,
                gpointer data)
{
  AsyncExistenceJob *job = data;
  GFile *file;
  GFileInfo *info;
  GError *error;
  char *uri;

retry:
  error = NULL;
  uri = build_uri (job);
  file = g_file_new_for_uri (uri);

  info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_TYPE,
			    G_FILE_QUERY_INFO_NONE, cancellable, &error);
  if (info != NULL)
    {
      /* file already exists, iterate again */
      g_object_unref (info);
      g_object_unref (file);
      g_free (uri);

      (job->iteration)++;

      goto retry;
    }
  else
    {
      /* see the error to check whether the location is not accessible
       * or the file does not exist.
       */
      if (error->code == G_IO_ERROR_NOT_FOUND)
        {
          GFile *parent;

          /* if the parent directory doesn't exist as well, forget the saved
           * directory and treat this as a generic error.
           */

          parent = g_file_get_parent (file);

          if (!g_file_query_exists (parent, NULL))
            {
              (job->type)++;
              job->iteration = 0;

              g_object_unref (file);
              g_object_unref (parent);
              goto retry;
            }
          else
            {
              job->retval = uri;

              g_object_unref (parent);
              goto out;
            }
        }
      else
        {
          /* another kind of error, assume this location is not
           * accessible.
           */
          g_free (uri);
          if (job->type == TEST_TMP)
            {
              job->retval = NULL;
              goto out;
            }
          else
            {
              (job->type)++;
              job->iteration = 0;

              g_error_free (error);
              g_object_unref (file);
              goto retry;
            }
        }
    }

out:
  g_error_free (error);
  g_object_unref (file);

  g_io_scheduler_job_send_to_mainloop_async (io_job,
                                             check_file_done,
                                             job,
                                             NULL);
  return FALSE;
}
Beispiel #19
0
/**
 * tracker_media_art_get_path:
 * @artist: the artist
 * @title: the title
 * @prefix: For example "album"
 * @uri: NULL or the uri of the file
 * @path: the location to store the local path
 * @local_uri: the location to store the local uri or NULL
 *
 * Get the path to media art for a given resource. Newly allocated data in
 * @path and @local_uri must be freed with g_free.
 *
 * Since: 0.10.14
 */
void
tracker_media_art_get_path (const gchar  *artist,
                            const gchar  *title,
                            const gchar  *prefix,
                            const gchar  *uri,
                            gchar       **path,
                            gchar       **local_uri)
{
    const gchar *space_checksum = "7215ee9c7d9dc229d2921a40e899ec5f";
    const gchar *a, *b;

    gchar *art_filename;
    gchar *dir;
    gchar *artist_down, *title_down;
    gchar *artist_stripped, *title_stripped;
    gchar *artist_norm, *title_norm;
    gchar *artist_checksum = NULL, *title_checksum = NULL;

    /* http://live.gnome.org/MediaArtStorageSpec */

    if (path) {
        *path = NULL;
    }

    if (local_uri) {
        *local_uri = NULL;
    }

    if (!artist && !title) {
        return;
    }

    if (artist) {
        artist_stripped = tracker_media_art_strip_invalid_entities (artist);
        artist_norm = g_utf8_normalize (artist_stripped, -1, G_NORMALIZE_NFKD);
        artist_down = g_utf8_strdown (artist_norm, -1);
        artist_checksum = media_art_checksum_for_data (G_CHECKSUM_MD5,
                          (const guchar *) artist_down,
                          strlen (artist_down));
    }

    if (title) {
        title_stripped = tracker_media_art_strip_invalid_entities (title);
        title_norm = g_utf8_normalize (title_stripped, -1, G_NORMALIZE_NFKD);
        title_down = g_utf8_strdown (title_norm, -1);
        title_checksum = media_art_checksum_for_data (G_CHECKSUM_MD5,
                         (const guchar *) title_down,
                         strlen (title_down));
    }

    dir = g_build_filename (g_get_user_cache_dir (),
                            "media-art",
                            NULL);

    if (!g_file_test (dir, G_FILE_TEST_EXISTS)) {
        g_mkdir_with_parents (dir, 0770);
    }

    if (artist) {
        a = artist_checksum;
        b = title ? title_checksum : space_checksum;
    } else {
        a = title_checksum;
        b = space_checksum;
    }

    art_filename = g_strdup_printf ("%s-%s-%s.jpeg", prefix ? prefix : "album", a, b);

    if (artist) {
        g_free (artist_checksum);
        g_free (artist_stripped);
        g_free (artist_down);
        g_free (artist_norm);
    }

    if (title) {
        g_free (title_checksum);
        g_free (title_stripped);
        g_free (title_down);
        g_free (title_norm);
    }

    if (path) {
        *path = g_build_filename (dir, art_filename, NULL);
    }

    if (local_uri) {
        gchar *local_dir;
        GFile *file, *parent;

        if (strstr (uri, "://")) {
            file = g_file_new_for_uri (uri);
        } else {
            file = g_file_new_for_path (uri);
        }

        parent = g_file_get_parent (file);
        if (parent) {
            local_dir = g_file_get_uri (parent);

            /* This is a URI, don't use g_build_filename here */
            *local_uri = g_strdup_printf ("%s/.mediaartlocal/%s", local_dir, art_filename);

            g_free (local_dir);
            g_object_unref (parent);
        }
        g_object_unref (file);
    }

    g_free (dir);
    g_free (art_filename);
}
Beispiel #20
0
bool PluginPackage::load()
{
    if (m_isLoaded) {
        m_loadCount++;
        return true;
    }

    GOwnPtr<gchar> finalPath(g_strdup(m_path.utf8().data()));
    while (g_file_test(finalPath.get(), G_FILE_TEST_IS_SYMLINK)) {
        GOwnPtr<GFile> file(g_file_new_for_path(finalPath.get()));
        GOwnPtr<GFile> dir(g_file_get_parent(file.get()));
        GOwnPtr<gchar> linkPath(g_file_read_link(finalPath.get(), 0));
        GOwnPtr<GFile> resolvedFile(g_file_resolve_relative_path(dir.get(), linkPath.get()));
        finalPath.set(g_file_get_path(resolvedFile.get()));
    }

    // No joke. If there is a netscape component in the path, go back
    // to the symlink, as flash breaks otherwise.
    // See http://src.chromium.org/viewvc/chrome/trunk/src/webkit/glue/plugins/plugin_list_posix.cc
    GOwnPtr<gchar> baseName(g_path_get_basename(finalPath.get()));
    if (!g_strcmp0(baseName.get(), "libflashplayer.so")
        && g_strstr_len(finalPath.get(), -1, "/netscape/"))
        finalPath.set(g_strdup(m_path.utf8().data()));

    m_module = g_module_open(finalPath.get(), G_MODULE_BIND_LOCAL);

    if (!m_module) {
        LOG(Plugins,"Module Load Failed :%s, Error:%s\n", (m_path.utf8()).data(), g_module_error());
        return false;
    }

    m_isLoaded = true;

    NP_InitializeFuncPtr NP_Initialize = 0;
    m_NPP_Shutdown = 0;

    NPError npErr;

    g_module_symbol(m_module, "NP_Initialize", (void**)&NP_Initialize);
    g_module_symbol(m_module, "NP_Shutdown", (void**)&m_NPP_Shutdown);

    if (!NP_Initialize || !m_NPP_Shutdown)
        goto abort;

    memset(&m_pluginFuncs, 0, sizeof(m_pluginFuncs));
    m_pluginFuncs.size = sizeof(m_pluginFuncs);

    initializeBrowserFuncs();

#if defined(XP_UNIX)
    npErr = NP_Initialize(&m_browserFuncs, &m_pluginFuncs);
#else
    npErr = NP_Initialize(&m_browserFuncs);
#endif
    if (npErr != NPERR_NO_ERROR)
        goto abort;

    m_loadCount++;
    return true;

abort:
    unloadWithoutShutdown();
    return false;
}
Beispiel #21
0
void
nautilus_directory_notify_files_added (GList *files)
{
	GHashTable *added_lists;
	GList *p;
	NautilusDirectory *directory;
	GHashTable *parent_directories;
	NautilusFile *file;
	GFile *location, *parent;

	/* Make a list of added files in each directory. */
	added_lists = g_hash_table_new (NULL, NULL);

	/* Make a list of parent directories that will need their counts updated. */
	parent_directories = g_hash_table_new (NULL, NULL);

	for (p = files; p != NULL; p = p->next) {
		location = p->data;

		/* See if the directory is already known. */
		directory = get_parent_directory_if_exists (location);
		if (directory == NULL) {
			/* In case the directory is not being
			 * monitored, but the corresponding file is,
			 * we must invalidate it's item count.
			 */


			file = NULL;
			parent = g_file_get_parent (location);
			if (parent) {
				file = nautilus_file_get_existing (parent);
				g_object_unref (parent);
			}

			if (file != NULL) {
				nautilus_file_invalidate_count_and_mime_list (file);
				nautilus_file_unref (file);
			}

			continue;
		}

		collect_parent_directories (parent_directories, directory);

		/* If no one is monitoring files in the directory, nothing to do. */
		if (!nautilus_directory_is_file_list_monitored (directory)) {
			nautilus_directory_unref (directory);
			continue;
		}

		file = nautilus_file_get_existing (location);
		/* We check is_added here, because the file could have been added
		 * to the directory by a nautilus_file_get() but not gotten 
		 * files_added emitted
		 */
		if (file && file->details->is_added) {
			/* A file already exists, it was probably renamed.
			 * If it was renamed this could be ignored, but 
			 * queue a change just in case */
			nautilus_file_changed (file);
			nautilus_file_unref (file);
		} else {
			hash_table_list_prepend (added_lists, 
						 directory, 
						 g_object_ref (location));
		}
		nautilus_directory_unref (directory);
	}

	/* Now get file info for the new files. This creates NautilusFile
	 * objects for the new files, and sends out a files_added signal. 
	 */
	g_hash_table_foreach (added_lists, call_get_file_info_free_list, NULL);
	g_hash_table_destroy (added_lists);

	/* Invalidate count for each parent directory. */
	g_hash_table_foreach (parent_directories, invalidate_count_and_unref, NULL);
	g_hash_table_destroy (parent_directories);
}
Beispiel #22
0
void init_mock_requester (GrlNetWc *self)
{
  g_atomic_int_inc (&refcount);

  if (refcount > 1) {
    return;
  }

  char *config_filename = g_strdup (g_getenv (GRL_NET_MOCKED_VAR));
  enable_mocking = FALSE;
  int i;

  if (config_filename == NULL) {
    return;
  }

  /* Read configuration file. */
  GError *error = NULL;
  config = g_key_file_new ();

  GRL_DEBUG ("Loading mock responses from \"%s\"", config_filename);
  g_key_file_load_from_file (config, config_filename, G_KEY_FILE_NONE, &error);

  int version = 0;

  if (error) {
    GRL_WARNING ("Failed to load mock file \"%s\": %s",
                 config_filename, error->message);
    g_clear_error (&error);
  } else {
    /* Check if we managed to load a file */
    version = g_key_file_get_integer (config, "default", "version", &error);

    if (error || version < GRL_NET_MOCK_VERSION) {
      GRL_WARNING ("Unsupported mock version.");
      g_clear_error (&error);
    } else {
      enable_mocking = TRUE;
    }
  }

  if (!enable_mocking) {
    g_free (config_filename);
    g_clear_pointer (&config, g_key_file_unref);
    return;
  }

  char **parameter_names = g_key_file_get_string_list (config, "default",
                                                       "ignored-parameters",
                                                       NULL, NULL);

  /* Build regular expressions for ignored query parameters. */
  if (parameter_names) {
    GString *pattern = g_string_new ("(?:^|\\&)");

    if (parameter_names[0] && strcmp(parameter_names[0], "*") == 0) {
      g_string_append (pattern, "[^=&]+");
    } else {
      g_string_append (pattern, "(?:");

      for (i = 0; parameter_names[i]; ++i) {
        if (i)
          g_string_append (pattern, "|");

        char *escaped = g_regex_escape_string (parameter_names[i], -1);
        g_string_append (pattern, escaped);
        g_free (escaped);
      }

      g_string_append (pattern, ")(?:=[^&]*)?");
    }

    ignored_parameters = g_regex_new (pattern->str, G_REGEX_OPTIMIZE, 0, &error);

    if (error) {
      GRL_WARNING ("Failed to compile regular expression "
                   "for ignored query parameters: %s", error->message);
      g_clear_error (&error);
    }

    g_strfreev (parameter_names);
    g_string_free (pattern, TRUE);
  }

  /* Find base path for mock data. */
  GFile *file = g_file_new_for_commandline_arg (config_filename);
  GFile *parent = g_file_get_parent (file);

  base_path = g_file_get_path (parent);

  g_object_unref (parent);
  g_object_unref (file);
  g_free (config_filename);
}
Beispiel #23
0
static gboolean
trash_empty_update_dialog (gpointer user_data)
{
  gsize deleted, total;
  GFile *file;

  g_assert (trash_empty_update_pending);

  deleted = trash_empty_deleted_files;
  total = trash_empty_total_files;
  file = trash_empty_current_file;

  /* maybe the done() got processed first. */
  if (trash_empty_dialog)
    {
      char *index_str, *total_str;
      char *text_tmp, *text;
      char *tmp;

      /* The i18n tools can't handle a direct embedding of the
       * size format using a macro. This is a work-around. */
      index_str = g_strdup_printf ("%"G_GSIZE_FORMAT, deleted + 1);
      total_str = g_strdup_printf ("%"G_GSIZE_FORMAT, total);
      /* Translators: the %s in this string should be read as %d. */
      text = g_strdup_printf (_("Removing item %s of %s"),
                              index_str, total_str);
      gtk_progress_bar_set_text (trash_empty_progress_bar, text);
      g_free (total_str);
      g_free (index_str);
      g_free (text);

      if (deleted > total)
        gtk_progress_bar_set_fraction (trash_empty_progress_bar, 1.0);
      else
        gtk_progress_bar_set_fraction (trash_empty_progress_bar,
                                       (gdouble) deleted / (gdouble) total);

      /* no g_file_get_basename? */
      {
        GFile *parent;

        parent = g_file_get_parent (file);
        text = g_file_get_uri (parent);
        g_object_unref (parent);
      }
      gtk_label_set_text (trash_empty_location, text);
      g_free (text);

      tmp = g_file_get_basename (file);
      /* Translators: %s is a file name */
      text_tmp = g_strdup_printf (_("Removing: %s"), tmp);
      text = g_markup_printf_escaped ("<i>%s</i>", text_tmp);
      gtk_label_set_markup (trash_empty_file, text);
      g_free (text);
      g_free (text_tmp);
      g_free (tmp);

      /* unhide the labels */
      gtk_widget_show_all (GTK_WIDGET (trash_empty_dialog));
    }

  trash_empty_current_file = NULL;
  g_object_unref (file);

  trash_empty_update_pending = FALSE;

  return FALSE;
}
static void
rygel_media_export_harvester_on_file_added (RygelMediaExportHarvester *self,
                                            GFile                     *file) {
  gchar *uri;
  GError *error;
  RygelMediaExportMediaCache *cache;
  GFileInfo *info;
  RygelMediaExportHarvesterPrivate *priv;

  g_return_if_fail (RYGEL_MEDIA_EXPORT_IS_HARVESTER (self));
  g_return_if_fail (G_IS_FILE (file));

  uri = g_file_get_uri (file);
  g_debug ("Filesystem events settled for %s, scheduling extraction…", uri);
  g_free (uri);
  cache = rygel_media_export_media_cache_get_default ();
  priv = self->priv;
  error = NULL;
  info = g_file_query_info (file,
                            G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
                            G_FILE_QUERY_INFO_NONE,
                            priv->cancellable,
                            &error);
  if (error) {
    g_warning ("Failed to query file: %s", error->message);
    g_error_free (error);
    error = NULL;

    goto out;
  }
  if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY ||
      rygel_media_export_harvester_is_eligible (info)) {
    RygelMediaContainer *parent_container = NULL;
    GFile *current = g_object_ref (file);
    GeeAbstractCollection *abstract_locations = GEE_ABSTRACT_COLLECTION (priv->locations);

    do {
      GFile *parent = g_file_get_parent (current);
      gchar *id = rygel_media_export_media_cache_get_id (parent);
      RygelMediaObject *tmp_object = rygel_media_export_media_cache_get_object (cache, id, &error);

      if (error) {
        g_warning (_("Error fetching object '%s' from database: %s"),
                   id,
                   error->message);
        g_free (id);
        g_object_unref (parent);

        g_error_free (error);
        error = NULL;

        goto inner_out;
      }
      g_free (id);
      if (parent_container) {
        g_object_unref (parent_container);
        parent_container = NULL;
      }
      if (RYGEL_IS_MEDIA_CONTAINER (tmp_object)) {
        parent_container = RYGEL_MEDIA_CONTAINER (tmp_object);
      } else {
        g_object_unref (tmp_object);
      }
      if (!parent_container) {
        g_object_ref (parent);
        g_object_unref (current);
        current = parent;
      }
      g_object_unref (parent);
      if (!parent_container &&
          gee_abstract_collection_contains (abstract_locations, current)) {
        RygelMediaObject* another_object = rygel_media_export_media_cache_get_object (cache,
                                                                                      RYGEL_MEDIA_EXPORT_ROOT_CONTAINER_FILESYSTEM_FOLDER_ID,
                                                                                      &error);

        if (error) {
          goto inner_out;
        }
        if (parent_container) {
          g_object_unref (parent_container);
          parent_container = NULL;
        }
        if (RYGEL_IS_MEDIA_CONTAINER (another_object)) {
          parent_container = RYGEL_MEDIA_CONTAINER (another_object);
        }

        break;
      }
    } while (!parent_container);
    rygel_media_export_harvester_schedule (self, current, parent_container, NULL);
  inner_out:

    g_object_unref (current);
    if (parent_container) {
      g_object_unref (parent_container);
    }
  } else {
    gchar* file_uri = g_file_get_uri (file);

    g_debug ("%s is not eligible for extraction", file_uri);
    g_free (file_uri);
  }
 out:
  g_object_unref (cache);
}
Beispiel #25
0
gboolean
shmdata_base_reader_start (shmdata_base_reader_t * reader, const char *socketPath)
{
    if (NULL == reader)
        return FALSE;
    g_mutex_lock (&reader->mutex_);
    destroy_polling_g_source (reader);
    if (reader->install_sync_handler_)
    {
        g_debug ("installing a sync handler");
        //looking for the bus, searching the top level
        GstElement *pipe = reader->bin_;

        while (pipe != NULL && !GST_IS_PIPELINE (pipe))
            pipe = GST_ELEMENT_PARENT (pipe);

        if( GST_IS_PIPELINE (pipe))
        {
            GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipe));

            gst_bus_set_sync_handler (bus, shmdata_base_reader_message_handler, NULL);
            gst_object_unref (bus);
        }
        else
        {
            g_warning ("no top level pipeline found when starting, cannot install sync_handler");
            g_mutex_unlock (&reader->mutex_);
            return FALSE;
        }
    }
    reader->socket_name_ = g_strdup (socketPath);
    //monitoring the shared memory file
    reader->shmfile_ = g_file_new_for_commandline_arg (reader->socket_name_);
    if (g_file_query_exists (reader->shmfile_, NULL))
    {
        g_debug ("existing shmdata, attaching (%s)",
                 reader->socket_name_);
        reader->initialized_ = TRUE;
        g_mutex_unlock (&reader->mutex_);//give hand to user
        reader->on_first_data_ (reader, reader->on_first_data_userData_);
        shmdata_base_reader_attach (reader); //attach is acquiring mutex
        g_mutex_lock (&reader->mutex_);//get hand back
    }
    else
        g_debug ("monitoring %s",
                 reader->socket_name_);
    //#ifdef HAVE_OSX
#if 1
    //directory monitoring is not working on osx, use polling :(
    /* g_timeout_add (500, */
    /*                shmdata_base_reader_poll_shmdata_path, */
    /* 		 reader); */
    //GSource *source;
    reader->polling_g_source_ = g_timeout_source_new (500);
    g_source_set_callback (reader->polling_g_source_,
                           shmdata_base_reader_poll_shmdata_path,
                           reader,
                           NULL);
    g_source_attach (reader->polling_g_source_,
                     reader->g_main_context_);
    g_source_unref (reader->polling_g_source_);
#else
    //FIXME fix monitoring with custom gmaincontext... find how to use "g_main_context_push_thread_default"...
    if (reader->g_main_context_ != NULL)
    {
        g_debug ("shmdata_base_reader_start: set a custom maincontext");
        g_main_context_push_thread_default (reader->g_main_context_);
    }
    GFile *dir = g_file_get_parent (reader->shmfile_);
    if (!g_file_supports_thread_contexts(dir))
        g_debug ("does not support thread_context");
    GError *error = NULL;
    reader->dirMonitor_ = g_file_monitor_directory (dir,
                          G_FILE_MONITOR_NONE,
                          NULL, &error);
    g_object_unref (dir);
    if (reader->dirMonitor_ == NULL)
    {
        g_warning ("monitor directory failled: %s",
                   error->message);
        g_error_free (error);
        g_mutex_unlock (&reader->mutex_);
        return FALSE;
    }
    g_signal_connect (reader->dirMonitor_,
                      "changed",
                      G_CALLBACK (shmdata_base_reader_file_system_monitor_change),
                      reader);
    if (reader->g_main_context_ != NULL)
        g_main_context_pop_thread_default (reader->g_main_context_);
#endif
    g_debug ("shmdata reader started (%s)", reader->socket_name_);
    g_mutex_unlock (&reader->mutex_);
    return TRUE;
}
/* Prepare a root filesystem, taking mainly the contents of /usr from yumroot */
static gboolean
create_rootfs_from_yumroot_content (GFile         *targetroot,
                                    GFile         *yumroot,
                                    JsonObject    *treefile,
                                    GCancellable  *cancellable,
                                    GError       **error)
{
    gboolean ret = FALSE;
    glnx_fd_close int src_rootfs_fd = -1;
    glnx_fd_close int target_root_dfd = -1;
    gs_unref_object GFile *kernel_path = NULL;
    gs_unref_object GFile *initramfs_path = NULL;
    gs_unref_hashtable GHashTable *preserve_groups_set = NULL;
    gboolean container = FALSE;

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

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

    g_print ("Preparing kernel\n");
    if (!container && !do_kernel_prep (yumroot, treefile, cancellable, error))
        goto out;

    g_print ("Initializing rootfs\n");
    if (!init_rootfs (targetroot, cancellable, error))
        goto out;

    if (!glnx_opendirat (AT_FDCWD, gs_file_get_path_cached (targetroot), TRUE, &target_root_dfd, error))
        goto out;

    g_print ("Migrating /etc/passwd to /usr/lib/\n");
    if (!rpmostree_passwd_migrate_except_root (yumroot, RPM_OSTREE_PASSWD_MIGRATE_PASSWD, NULL,
            cancellable, error))
        goto out;

    if (json_object_has_member (treefile, "etc-group-members"))
    {
        JsonArray *etc_group_members = json_object_get_array_member (treefile, "etc-group-members");
        preserve_groups_set = _rpmostree_jsonutil_jsarray_strings_to_set (etc_group_members);
    }

    g_print ("Migrating /etc/group to /usr/lib/\n");
    if (!rpmostree_passwd_migrate_except_root (yumroot, RPM_OSTREE_PASSWD_MIGRATE_GROUP,
            preserve_groups_set,
            cancellable, error))
        goto out;

    /* NSS configuration to look at the new files */
    {
        gs_unref_object GFile *yumroot_etc =
            g_file_resolve_relative_path (yumroot, "etc");

        if (!replace_nsswitch (yumroot_etc, cancellable, error))
            goto out;
    }

    /* We take /usr from the yum content */
    g_print ("Moving /usr to target\n");
    {
        gs_unref_object GFile *usr = g_file_get_child (yumroot, "usr");
        if (!move_to_dir (usr, targetroot, cancellable, error))
            goto out;
    }

    /* Except /usr/local -> ../var/usrlocal */
    g_print ("Linking /usr/local -> ../var/usrlocal\n");
    {
        gs_unref_object GFile *target_usrlocal =
            g_file_resolve_relative_path (targetroot, "usr/local");

        if (!gs_shutil_rm_rf (target_usrlocal, cancellable, error))
            goto out;

        if (!g_file_make_symbolic_link (target_usrlocal, "../var/usrlocal",
                                        cancellable, error))
            goto out;
    }

    /* And now we take the contents of /etc and put them in /usr/etc */
    g_print ("Moving /etc to /usr/etc\n");
    {
        gs_unref_object GFile *yumroot_etc =
            g_file_get_child (yumroot, "etc");
        gs_unref_object GFile *target_usretc =
            g_file_resolve_relative_path (targetroot, "usr/etc");

        if (!gs_file_rename (yumroot_etc, target_usretc,
                             cancellable, error))
            goto out;
    }

    if (!migrate_rpm_and_yumdb (targetroot, yumroot, cancellable, error))
        goto out;

    if (!convert_var_to_tmpfiles_d (src_rootfs_fd, target_root_dfd, cancellable, error))
        goto out;

    /* Move boot, but rename the kernel/initramfs to have a checksum */
    if (!container)
    {
        gs_unref_object GFile *yumroot_boot =
            g_file_get_child (yumroot, "boot");
        gs_unref_object GFile *target_boot =
            g_file_get_child (targetroot, "boot");
        gs_unref_object GFile *target_usrlib =
            g_file_resolve_relative_path (targetroot, "usr/lib");
        gs_unref_object GFile *target_usrlib_ostree_boot =
            g_file_resolve_relative_path (target_usrlib, "ostree-boot");
        RpmOstreePostprocessBootLocation boot_location =
            RPMOSTREE_POSTPROCESS_BOOT_LOCATION_BOTH;
        const char *boot_location_str = NULL;

        g_print ("Moving /boot\n");

        if (!_rpmostree_jsonutil_object_get_optional_string_member (treefile,
                "boot_location",
                &boot_location_str, error))
            goto out;

        if (boot_location_str != NULL)
        {
            if (strcmp (boot_location_str, "legacy") == 0)
                boot_location = RPMOSTREE_POSTPROCESS_BOOT_LOCATION_LEGACY;
            else if (strcmp (boot_location_str, "both") == 0)
                boot_location = RPMOSTREE_POSTPROCESS_BOOT_LOCATION_BOTH;
            else if (strcmp (boot_location_str, "new") == 0)
                boot_location = RPMOSTREE_POSTPROCESS_BOOT_LOCATION_NEW;
            else
            {
                g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                             "Invalid boot location '%s'", boot_location_str);
                goto out;
            }
        }

        if (!gs_file_ensure_directory (target_usrlib, TRUE, cancellable, error))
            goto out;

        switch (boot_location)
        {
        case RPMOSTREE_POSTPROCESS_BOOT_LOCATION_LEGACY:
        {
            g_print ("Using boot location: legacy\n");
            if (!gs_file_rename (yumroot_boot, target_boot, cancellable, error))
                goto out;
        }
        break;
        case RPMOSTREE_POSTPROCESS_BOOT_LOCATION_BOTH:
        {
            g_print ("Using boot location: both\n");
            if (!gs_file_rename (yumroot_boot, target_boot, cancellable, error))
                goto out;
            /* Hardlink the existing content, only a little ugly as
             * we'll end up sha256'ing it twice, but oh well. */
            if (!gs_shutil_cp_al_or_fallback (target_boot, target_usrlib_ostree_boot, cancellable, error))
                goto out;
        }
        break;
        case RPMOSTREE_POSTPROCESS_BOOT_LOCATION_NEW:
        {
            g_print ("Using boot location: new\n");
            if (!gs_file_rename (yumroot_boot, target_usrlib_ostree_boot, cancellable, error))
                goto out;
        }
        break;
        }
    }

    /* Also carry along toplevel compat links */
    g_print ("Copying toplevel compat symlinks\n");
    {
        guint i;
        const char *toplevel_links[] = { "lib", "lib64", "lib32",
                                         "bin", "sbin"
                                       };
        for (i = 0; i < G_N_ELEMENTS (toplevel_links); i++)
        {
            gs_unref_object GFile *srcpath =
                g_file_get_child (yumroot, toplevel_links[i]);

            if (g_file_query_file_type (srcpath, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL) == G_FILE_TYPE_SYMBOLIC_LINK)
            {
                if (!move_to_dir (srcpath, targetroot, cancellable, error))
                    goto out;
            }
        }
    }

    g_print ("Adding tmpfiles-ostree-integration.conf\n");
    {
        gs_unref_object GFile *src_pkglibdir = g_file_new_for_path (PKGLIBDIR);
        gs_unref_object GFile *src_tmpfilesd =
            g_file_get_child (src_pkglibdir, "tmpfiles-ostree-integration.conf");
        gs_unref_object GFile *target_tmpfilesd =
            g_file_resolve_relative_path (targetroot, "usr/lib/tmpfiles.d/tmpfiles-ostree-integration.conf");
        gs_unref_object GFile *target_tmpfilesd_parent = g_file_get_parent (target_tmpfilesd);

        if (!gs_file_ensure_directory (target_tmpfilesd_parent, TRUE, cancellable, error))
            goto out;

        if (!g_file_copy (src_tmpfilesd, target_tmpfilesd, 0,
                          cancellable, NULL, NULL, error))
            goto out;
    }

    ret = TRUE;
out:
    return ret;
}
Beispiel #27
0
static char *
get_prefix_for_entry (GMenuTreeEntry *entry)
{
  char *prefix = NULL, *file_prefix = NULL;
  const char *id;
  GFile *file;
  char *name;
  int i = 0;

  id = gmenu_tree_entry_get_desktop_file_id (entry);
  file = g_file_new_for_path (gmenu_tree_entry_get_desktop_file_path (entry));
  name = g_file_get_basename (file);

  if (!name)
    {
      g_object_unref (file);
      return NULL;
    }
  for (i = 0; vendor_prefixes[i]; i++)
    {
      if (g_str_has_prefix (name, vendor_prefixes[i]))
        {
          file_prefix = g_strdup (vendor_prefixes[i]);
          break;
        }
    }

  while (strcmp (name, id) != 0)
    {
      char *t;
      char *pname;
      GFile *parent = g_file_get_parent (file);

      if (!parent)
        {
          g_warn_if_reached ();
          break;
        }

      pname = g_file_get_basename (parent);
      if (!pname)
        {
          g_object_unref (parent);
          break;
        }
      if (!g_strstr_len (id, -1, pname))
        {
          /* handle <LegacyDir prefix="..."> */
          char *t;
          size_t name_len = strlen (name);
          size_t id_len = strlen (id);
          char *t_id = g_strdup (id);

          t_id[id_len - name_len] = '\0';
          t = g_strdup(t_id);
          g_free (prefix);
          g_free (t_id);
          g_free (name);
          name = g_strdup (id);
          prefix = t;

          g_object_unref (file);
          file = parent;
          g_free (pname);
          g_free (file_prefix);
          file_prefix = NULL;
          break;
        }

      t = g_strconcat (pname, "-", name, NULL);
      g_free (name);
      name = t;

      t = g_strconcat (pname, "-", prefix, NULL);
      g_free (prefix);
      prefix = t;

      g_object_unref (file);
      file = parent;
      g_free (pname);
    }

  if (file)
    g_object_unref (file);

  if (strcmp (name, id) == 0)
    {
      g_free (name);
      if (file_prefix && !prefix)
        return file_prefix;
      if (file_prefix)
        {
          char *t = g_strconcat (prefix, "-", file_prefix, NULL);
          g_free (prefix);
          g_free (file_prefix);
          prefix = t;
        }
      return prefix;
    }

  g_free (name);
  g_free (prefix);
  g_free (file_prefix);
  g_return_val_if_reached (NULL);
}
static void
gth_metadata_provider_comment_write (GthMetadataProvider   *self,
				     GthMetadataWriteFlags  flags,
				     GthFileData           *file_data,
				     const char            *attributes,
				     GCancellable          *cancellable)
{
	GthComment    *comment;
	GthMetadata   *metadata;
	const char    *text;
	char          *data;
	gsize          length;
	GthStringList *categories;
	GFile         *comment_file;
	GFile         *comment_folder;

	comment = gth_comment_new ();

	/* caption */

	text = NULL;
	metadata = (GthMetadata *) g_file_info_get_attribute_object (file_data->info, "general::title");
	if (metadata != NULL)
		text = gth_metadata_get_raw (metadata);
	gth_comment_set_caption (comment, text);

	/* comment */

	text = NULL;
	metadata = (GthMetadata *) g_file_info_get_attribute_object (file_data->info, "general::description");
	if (metadata != NULL)
		text = gth_metadata_get_raw (metadata);
	gth_comment_set_note (comment, text);

	/* location */

	text = NULL;
	metadata = (GthMetadata *) g_file_info_get_attribute_object (file_data->info, "general::location");
	if (metadata != NULL)
		text = gth_metadata_get_raw (metadata);
	gth_comment_set_place (comment, text);

	/* time */

	text = NULL;
	metadata = (GthMetadata *) g_file_info_get_attribute_object (file_data->info, "general::datetime");
	if (metadata != NULL)
		text = gth_metadata_get_raw (metadata);
	gth_comment_set_time_from_exif_format (comment, text);

	/* keywords */

	metadata = (GthMetadata *) g_file_info_get_attribute_object (file_data->info, "general::tags");
	categories = gth_metadata_get_string_list (metadata);
	if (categories != NULL) {
		GList *list;
		GList *scan;

		list = gth_string_list_get_list (categories);
		for (scan = list; scan; scan = scan->next)
			gth_comment_add_category (comment, (char *) scan->data);
	}

	/* rating */

	metadata = (GthMetadata *) g_file_info_get_attribute_object (file_data->info, "general::rating");
	if (metadata != NULL) {
		int rating;

		sscanf (gth_metadata_get_raw (metadata), "%d", &rating);
		gth_comment_set_rating (comment, rating);
	}

	data = gth_comment_to_data (comment, &length);
	comment_file = gth_comment_get_comment_file (file_data->file);
	comment_folder = g_file_get_parent (comment_file);

	g_file_make_directory (comment_folder, NULL, NULL);
	_g_file_write (comment_file, FALSE, 0, data, length, cancellable, NULL);

	g_object_unref (comment_folder);
	g_object_unref (comment_file);
	g_free (data);
	g_object_unref (comment);
}
Beispiel #29
0
static void
gb_vim_complete_edit_files (GtkWidget *active_widget,
                            const gchar   *command,
                            GPtrArray     *ar,
                            const gchar   *prefix)
{
  IdeWorkbench *workbench;
  IdeContext *context;
  IdeVcs *vcs;
  GFile *workdir;
  g_autoptr(GFile) child = NULL;
  g_autoptr(GFile) parent = NULL;

  IDE_ENTRY;

  g_assert (command);
  g_assert (ar);
  g_assert (prefix);

  if (!(workbench = ide_widget_get_workbench (GTK_WIDGET (active_widget))) ||
      !(context = ide_workbench_get_context (workbench)) ||
      !(vcs = ide_context_get_vcs (context)) ||
      !(workdir = ide_vcs_get_working_directory (vcs)))
    IDE_EXIT;

  child = g_file_get_child (workdir, prefix);

  if (g_file_query_exists (child, NULL))
    {
      if (g_file_query_file_type (child, 0, NULL) == G_FILE_TYPE_DIRECTORY)
        {
          g_autoptr(GFileEnumerator) fe = NULL;
          GFileInfo *descendent;

          if (!g_str_has_suffix (prefix, "/"))
            {
              g_ptr_array_add (ar, g_strdup_printf ("%s %s/", command, prefix));
              IDE_EXIT;
            }

          fe = g_file_enumerate_children (child,
                                          G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
                                          G_FILE_QUERY_INFO_NONE,
                                          NULL, NULL);

          if (fe == NULL)
            IDE_EXIT;

          while ((descendent = g_file_enumerator_next_file (fe, NULL, NULL)))
            {
              const gchar *name;

              name = g_file_info_get_display_name (descendent);
              g_ptr_array_add (ar, g_strdup_printf ("%s %s%s", command, prefix, name));
              g_object_unref (descendent);
            }

          IDE_EXIT;
        }
    }

  parent = g_file_get_parent (child);

  if (parent != NULL)
    {
      g_autoptr(GFileEnumerator) fe = NULL;
      GFileInfo *descendent;
      const gchar *slash;
      const gchar *partial_name;
      g_autofree gchar *prefix_dir = NULL;

#ifdef IDE_ENABLE_TRACE
      {
        g_autofree gchar *parent_path = g_file_get_path (parent);
        IDE_TRACE_MSG ("parent_path: %s", parent_path);
      }
#endif

      if ((slash = strrchr (prefix, G_DIR_SEPARATOR)))
        {
          partial_name = slash + 1;
          prefix_dir = g_strndup (prefix, slash - prefix + 1);
        }
      else
        {
          partial_name = prefix;
        }

      fe = g_file_enumerate_children (parent,
                                      G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
                                      G_FILE_QUERY_INFO_NONE,
                                      NULL, NULL);

      if (fe == NULL)
        IDE_EXIT;

      while ((descendent = g_file_enumerator_next_file (fe, NULL, NULL)))
        {
          const gchar *name;
          name = g_file_info_get_display_name (descendent);

          IDE_TRACE_MSG ("name=%s prefix=%s", name, prefix);

          if (name && g_str_has_prefix (name, partial_name))
            {
              gchar *completed_command;
              const gchar *descendent_name;
              g_autofree gchar *full_path = NULL;
              g_autofree gchar *parent_path = NULL;

              parent_path = g_file_get_path (parent);
              descendent_name = g_file_info_get_name (descendent);
              full_path = g_build_filename (parent_path, descendent_name, NULL);

              if (prefix[0] == G_DIR_SEPARATOR)
                completed_command = g_strdup_printf ("%s %s", command, full_path);
              else if (strchr (prefix, G_DIR_SEPARATOR) == NULL)
                completed_command = g_strdup_printf ("%s %s", command, descendent_name);
              else
                completed_command = g_strdup_printf ("%s %s%s", command, prefix_dir, descendent_name);

              IDE_TRACE_MSG ("edit completion: %s", completed_command);

              g_ptr_array_add (ar, completed_command);
            }
          g_object_unref (descendent);
        }

      IDE_EXIT;
    }

  IDE_EXIT;
}
static gboolean
trash_empty_update_dialog (gpointer user_data)
{
        gsize deleted, total;
        GFile *file;
        gboolean actually_deleting;

        g_assert (trash_empty_update_pending);

        deleted = trash_empty_deleted_files;
        total = trash_empty_total_files;
        file = trash_empty_current_file;
        actually_deleting = trash_empty_actually_deleting;

        /* maybe the done() got processed first. */
        if (!trash_empty_dialog)
                goto out;

        if (!actually_deleting) {
                /* If we havent finished counting yet, then pulse the progressbar every 100ms.
                 * This stops the user from thinking the dialog has frozen if there are
                 * a lot of files to delete. We don't pulse it every time we are called from the
                 * worker thread, otherwise it moves to fast and looks hideous
                 */
                if (timer) {
                        if (g_timer_elapsed (timer, NULL) > 0.1) {
                                gtk_progress_bar_pulse (GTK_PROGRESS_BAR (progressbar));
                                g_timer_start (timer);
                        }
                } else {
                        timer = g_timer_new ();
                        g_timer_start (timer);
                        gtk_progress_bar_pulse (GTK_PROGRESS_BAR (progressbar));
                }
        } else {
                gchar *text;
                gchar *tmp;
                gchar *markup;
                GFile *parent;

                text = g_strdup_printf (_("Removing item %lu of %lu"),
                                        deleted, total);
                gtk_progress_bar_set_text (GTK_PROGRESS_BAR (progressbar), text);

                g_free (text);

                if (deleted > total)
                        gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progressbar), 1.0);
                else
                        gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progressbar),
                                                       (gdouble) deleted / (gdouble) total);

                parent = g_file_get_parent (file);
                text = g_file_get_uri (parent);
                g_object_unref (parent);

                gtk_label_set_text (GTK_LABEL (location_label), text);
                g_free (text);

                tmp = g_file_get_basename (file);
                text = g_markup_printf_escaped (_("Removing: %s"), tmp);
                markup = g_strdup_printf ("<i>%s</i>", text);
                gtk_label_set_markup (GTK_LABEL (file_label), markup);
                g_free (markup);
                g_free (text);
                g_free (tmp);

                /* unhide the labels */
                gtk_widget_show_all (GTK_WIDGET (trash_empty_dialog));
        }

out:
        trash_empty_current_file = NULL;
        g_object_unref (file);

        trash_empty_update_pending = FALSE;

        return FALSE;
}