Пример #1
0
static void * gio_fopen (const char * filename, const char * mode)
{
    GError * error = 0;

    FileData * data = g_new0 (FileData, 1);

    data->file = g_file_new_for_uri (filename);

    switch (mode[0])
    {
    case 'r':
        if (strchr (mode, '+'))
        {
            data->iostream = (GIOStream *) g_file_open_readwrite (data->file, 0, & error);
            CHECK_ERROR ("open", filename);
            data->istream = g_io_stream_get_input_stream (data->iostream);
            data->ostream = g_io_stream_get_output_stream (data->iostream);
            data->seekable = (GSeekable *) data->iostream;
        }
        else
        {
            data->istream = (GInputStream *) g_file_read (data->file, 0, & error);
            CHECK_ERROR ("open", filename);
            data->seekable = (GSeekable *) data->istream;
        }
        break;
    case 'w':
        if (strchr (mode, '+'))
        {
            data->iostream = (GIOStream *) g_file_replace_readwrite (data->file, 0, 0, 0, 0, & error);
            CHECK_ERROR ("open", filename);
            data->istream = g_io_stream_get_input_stream (data->iostream);
            data->ostream = g_io_stream_get_output_stream (data->iostream);
            data->seekable = (GSeekable *) data->iostream;
        }
        else
        {
            data->ostream = (GOutputStream *) g_file_replace (data->file, 0, 0, 0, 0, & error);
            CHECK_ERROR ("open", filename);
            data->seekable = (GSeekable *) data->ostream;
        }
        break;
    case 'a':
        if (strchr (mode, '+'))
        {
            gio_error ("Cannot open %s: GIO does not support read-and-append mode.", filename);
            goto FAILED;
        }
        else
        {
            data->ostream = (GOutputStream *) g_file_append_to (data->file, 0, 0, & error);
            CHECK_ERROR ("open", filename);
            data->seekable = (GSeekable *) data->ostream;
        }
        break;
    default:
        gio_error ("Cannot open %s: invalid mode.", filename);
        goto FAILED;
    }

    return data;

FAILED:
    g_free (data);
    return 0;
}
Пример #2
0
/**
 * Start file open operation, mount volume when needed and according to file type
 * create file output stream or read directory content.
 * @return NS_OK when file or directory opened successfully, error code otherwise
 */
nsresult
nsGIOInputStream::DoOpen()
{
  nsresult rv;
  GError *error = nullptr;

  NS_ASSERTION(mHandle == nullptr, "already open");

  mHandle = g_file_new_for_uri( mSpec.get() );

  GFileInfo *info = g_file_query_info(mHandle,
                                      "standard::*",
                                      G_FILE_QUERY_INFO_NONE,
                                      nullptr,
                                      &error);

  if (error) {
    if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_NOT_MOUNTED) {
      // location is not yet mounted, try to mount
      g_error_free(error);
      if (NS_IsMainThread()) 
        return NS_ERROR_NOT_CONNECTED;
      error = nullptr;
      rv = MountVolume();
      if (rv != NS_OK) {
        return rv;
      }
      // get info again
      info = g_file_query_info(mHandle,
                               "standard::*",
                               G_FILE_QUERY_INFO_NONE,
                               nullptr,
                               &error);
      // second try to get file info from remote files after media mount
      if (!info) {
        g_warning("Unable to get file info: %s", error->message);
        rv = MapGIOResult(error);
        g_error_free(error);
        return rv;
      }
    } else {
      g_warning("Unable to get file info: %s", error->message);
      rv = MapGIOResult(error);
      g_error_free(error);
      return rv;
    }
  }
  // Get file type to handle directories and file differently
  GFileType f_type = g_file_info_get_file_type(info);
  if (f_type == G_FILE_TYPE_DIRECTORY) {
    // directory
    rv = DoOpenDirectory();
  } else if (f_type != G_FILE_TYPE_UNKNOWN) {
    // file
    rv = DoOpenFile(info);
  } else {
    g_warning("Unable to get file type.");
    rv = NS_ERROR_FILE_NOT_FOUND;
  }
  if (info)
    g_object_unref(info);
  return rv;
}
Пример #3
0
/* This is based on nautilus_compute_title_for_uri() and
 * nautilus_file_get_display_name_nocopy() */
char *
panel_util_get_label_for_uri (const char *text_uri)
{
	GFile *file;
	char  *label;
	GFile *root;
	char  *root_display;

	/* Here's what we do:
	 *  + x-nautilus-search: URI
	 *  + check if the URI is a mount
	 *  + if file: URI:
	 *   - check for known file: URI
	 *   - check for description of the GFile
	 *   - use display name of the GFile
	 *  + else:
	 *   - check for description of the GFile
	 *   - if the URI is a root: "root displayname"
	 *   - else: "root displayname: displayname"
	 */

	label = NULL;

	//FIXME: see nautilus_query_to_readable_string() to have a nice name
	if (g_str_has_prefix (text_uri, "x-nautilus-search:"))
		return g_strdup (_("Search"));

	file = g_file_new_for_uri (text_uri);

	label = panel_util_get_file_display_name_if_mount (file);
	if (label) {
		g_object_unref (file);
		return label;
	}

	if (g_str_has_prefix (text_uri, "file:")) {
		label = panel_util_get_file_display_for_common_files (file);
		if (!label)
			label = panel_util_get_file_description (file);
		if (!label)
			label = panel_util_get_file_display_name (file, TRUE);
		g_object_unref (file);

		return label;
	}

	label = panel_util_get_file_description (file);
	if (label) {
		g_object_unref (file);
		return label;
	}

	root = panel_util_get_gfile_root (file);
	root_display = panel_util_get_file_description (root);
	if (!root_display)
		root_display = panel_util_get_file_display_name (root, FALSE);
	if (!root_display)
		/* can happen with URI schemes non supported by gvfs */
		root_display = g_file_get_uri_scheme (root);

	if (g_file_equal (file, root))
		label = root_display;
	else {
		char *displayname;

		displayname = panel_util_get_file_display_name (file, TRUE);
		/* Translators: the first string is the name of a gvfs
		 * method, and the second string is a path. For
		 * example, "Trash: some-directory". It means that the
		 * directory called "some-directory" is in the trash.
		 */
		label = g_strdup_printf (_("%1$s: %2$s"),
					 root_display, displayname);
		g_free (root_display);
		g_free (displayname);
	}

	g_object_unref (root);
	g_object_unref (file);

	return label;
}
Пример #4
0
static void
panel_place_menu_item_append_gtk_bookmarks (GtkWidget *menu)
{
	typedef struct {
		char *full_uri;
		char *label;
	} PanelBookmark;

	GtkWidget   *add_menu;
	char        *filename;
	GIOChannel  *io_channel;
	GHashTable  *table;
	int          i;
	GSList      *lines = NULL;
	GSList      *add_bookmarks, *l;
	PanelBookmark *bookmark;

	filename = g_build_filename (g_get_home_dir (),
				     BOOKMARKS_FILENAME, NULL);

	io_channel = g_io_channel_new_file (filename, "r", NULL);
	g_free (filename);

	if (!io_channel)
		return;

	/* We use a hard limit to avoid having users shooting their
	 * own feet, and to avoid crashing the system if a misbehaving
	 * application creates a big bookmars file.
	 */
	for (i = 0; i < MAX_BOOKMARK_ITEMS; i++) {
		char      *contents;
		gsize      length;
		gsize      terminator_pos;
		GIOStatus  status;

		status = g_io_channel_read_line (io_channel, &contents, &length, &terminator_pos, NULL);

		if (status != G_IO_STATUS_NORMAL)
			break;

		if (length == 0)
			break;

		/* Clear the line terminator (\n), if any */
		if (terminator_pos > 0)
			contents[terminator_pos] = '\0';

		lines = g_slist_prepend (lines, contents);
	}

	g_io_channel_shutdown (io_channel, FALSE, NULL);
	g_io_channel_unref (io_channel);

	if (!lines)
		return;

	lines = g_slist_reverse (lines);

	table = g_hash_table_new (g_str_hash, g_str_equal);
	add_bookmarks = NULL;

	for (l = lines; l; l = l->next) {
		char *line = (char*) l->data;

		if (line[0] && !g_hash_table_lookup (table, line)) {
			GFile    *file;
			char     *space;
			char     *label;
			gboolean  keep;

			g_hash_table_insert (table, line, line);

			space = strchr (line, ' ');
			if (space) {
				*space = '\0';
				label = g_strdup (space + 1);
			} else {
				label = NULL;
			}

			keep = FALSE;

			if (g_str_has_prefix (line, "x-caja-search:"))
				keep = TRUE;

			if (!keep) {
				file = g_file_new_for_uri (line);
				keep = !g_file_is_native (file) ||
				       g_file_query_exists (file, NULL);
				g_object_unref (file);
			}

			if (!keep) {
				if (label)
					g_free (label);
				continue;
			}

			bookmark = g_malloc (sizeof (PanelBookmark));
			bookmark->full_uri = g_strdup (line);
			bookmark->label = label;
			add_bookmarks = g_slist_prepend (add_bookmarks, bookmark);
		}
	}

	g_hash_table_destroy (table);
	g_slist_foreach (lines, (GFunc) g_free, NULL);
	g_slist_free (lines);

	add_bookmarks = g_slist_reverse (add_bookmarks);

	if (g_slist_length (add_bookmarks) <= MAX_ITEMS_OR_SUBMENU) {
		add_menu = menu;
	} else {
		GtkWidget *item;

		item = gtk_image_menu_item_new ();
		setup_menu_item_with_icon (item, panel_menu_icon_get_size (),
					   PANEL_ICON_BOOKMARKS, NULL, NULL,
					   _("Bookmarks"));

		gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
		gtk_widget_show (item);

		add_menu = create_empty_menu ();
		gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), add_menu);
	}

	for (l = add_bookmarks; l; l = l->next) {
		char *display_name;
		char *tooltip;
		char *label;
		char *icon;
		GFile *file;
		GIcon *gicon;

		bookmark = l->data;

		file = g_file_new_for_uri (bookmark->full_uri);
		display_name = g_file_get_parse_name (file);
		g_object_unref (file);
		/* Translators: %s is a URI */
		tooltip = g_strdup_printf (_("Open '%s'"), display_name);
		g_free (display_name);

		label = NULL;
		if (bookmark->label) {
			label = g_strdup (g_strstrip (bookmark->label));
			if (!label [0]) {
				g_free (label);
				label = NULL;
			}
		}

		if (!label) {
			label = panel_util_get_label_for_uri (bookmark->full_uri);

			if (!label) {
				g_free (tooltip);
				g_free (bookmark->full_uri);
				if (bookmark->label)
					g_free (bookmark->label);
				g_free (bookmark);
				continue;
			}
		}

		icon = panel_util_get_icon_for_uri (bookmark->full_uri);
		/*FIXME: we should probably get a GIcon if possible, so that we
		 * have customized icons for cd-rom, eg */
		if (!icon)
			icon = g_strdup (PANEL_ICON_FOLDER);

		gicon = g_themed_icon_new_with_default_fallbacks (icon);

		//FIXME: drag and drop will be broken for x-caja-search uris
		panel_menu_items_append_place_item (icon, gicon,
						    label,
						    tooltip,
						    add_menu,
						    G_CALLBACK (activate_uri),
						    bookmark->full_uri);

		g_free (icon);
		g_object_unref (gicon);
		g_free (tooltip);
		g_free (label);
		g_free (bookmark->full_uri);
		if (bookmark->label)
			g_free (bookmark->label);
		g_free (bookmark);
	}

	g_slist_free (add_bookmarks);
}
Пример #5
0
static gboolean
xmms_gvfs_init (xmms_xform_t *xform)
{
    xmms_gvfs_data_t *data;
    GFile *file;
    GFileInfo *info;
    GFileInputStream *handle;
    GError *error = NULL;
    const gchar *url;

    url = xmms_xform_indata_get_str (xform, XMMS_STREAM_TYPE_URL);
    g_return_val_if_fail (url, FALSE);

    /* This is an ugly hack to handle files with
       chars needing url encoding */
    if (!g_ascii_strncasecmp (url, "file://", 7)) {
        file = g_file_new_for_path (url+7);
    } else {
        file = g_file_new_for_uri (url);
    }
    handle = g_file_read (file, NULL, &error);
    g_object_unref (file);

    if (!handle) {
        xmms_log_error ("Failed to upen url %s for reading: %s",
                        url, error->message);
        return FALSE;
    }

    data = g_new (xmms_gvfs_data_t, 1);
    data->handle = G_INPUT_STREAM (handle);
    xmms_xform_private_data_set (xform, data);

    info = g_file_input_stream_query_info (handle, (char *)query_attributes,
                                           NULL, &error);

    if (!info) {
        xmms_log_info ("failed to query information for %s", url);
    } else {
        int i;

        for (i = 0; i < G_N_ELEMENTS (attr_map); i++) {
            if (!g_file_info_has_attribute (info, attr_map[i].gvfs)) {
                continue;
            }

            switch (attr_map[i].type) {
            case XMMSV_TYPE_STRING: {
                gchar *attr = g_file_info_get_attribute_as_string (info,
                              attr_map[i].gvfs);
                xmms_xform_metadata_set_str (xform, attr_map[i].mlib, attr);
                g_free (attr);
                break;
            }
            case XMMSV_TYPE_INT32: {
                /* right now the xform metadata api only handles strings
                 * and 32 bit ints. however the gvfs api returns uint64 for
                 * the numeric attributes we're interested in and we just
                 * pass that to the xform and pray that it doesn't overflow
                 * as we know it's unsafe.
                 */

                gint64 attr = g_file_info_get_attribute_uint64 (info,
                              attr_map[i].gvfs);
                xmms_xform_metadata_set_int (xform, attr_map[i].mlib, attr);
                break;
            }
            default:
                g_assert_not_reached ();
            }
        }

        g_object_unref (info);
    }

    xmms_xform_outdata_type_add (xform,
                                 XMMS_STREAM_TYPE_MIMETYPE,
                                 "application/octet-stream",
                                 XMMS_STREAM_TYPE_END);

    return TRUE;
}
Пример #6
0
	extern void desktop_run_in_terminal(char* executable);
    extern char* dentry_get_uri(Entry* e);
	Test({
        GFile* f = g_file_new_for_uri("file:///tmp/test_files/skype.desktop");
		char* s = dentry_get_uri(f);
		// desktop_run_in_terminal(s);//Warning:!!!!! : don't test it , it will open terminal alltimes
		g_free(s);
		g_object_unref(f);
	},"desktop_run_in_terminal");


#if 0
    extern gboolean activate_file (GFile* file, const char* content_type, gboolean is_executable, GFile* _file_arg);
    Test({
    	g_message("activate_file start");
        GFile* f = g_file_new_for_uri("file:///tmp/test_files/skype.desktop");
        ArrayContainer fs;
        fs.data=&f;
        fs.num = 1;
	    	// g_message("file is GFile");
			#if 1

	        gboolean launch_res = TRUE;
	        GFileInfo* info = g_file_query_info(f, "standard::content-type,access::can-execute", G_FILE_QUERY_INFO_NONE, NULL, NULL);
	        if (info != NULL) {
	            const char* content_type = g_file_info_get_attribute_string(info, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE);
	            gboolean is_executable = g_file_info_get_attribute_boolean(info, "access::can-execute");
	            //ugly hack here. we just read the first GFile*.
	            GFile* _file_arg = NULL;
	            ArrayContainer _fs;
	            GFile** files = NULL;
Пример #7
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);
}
Пример #8
0
/* serverside */
static void
on_message_received (const char *message,
		     gpointer    data)
{
	const PlumaEncoding *encoding = NULL;
	gchar **commands;
	gchar **params;
	gint workspace;
	gint viewport_x;
	gint viewport_y;
	gchar *display_name;
	gint screen_number;
	gint i;
	PlumaApp *app;
	PlumaWindow *window;
	GdkDisplay *display;
	GdkScreen *screen;

	g_return_if_fail (message != NULL);

	pluma_debug_message (DEBUG_APP, "Received message:\n%s\n", message);

	commands = g_strsplit (message, "\v", -1);

	/* header */
	params = g_strsplit (commands[0], "\t", 6);
	startup_timestamp = atoi (params[0]);
	display_name = params[1];
	screen_number = atoi (params[2]);
	workspace = atoi (params[3]);
	viewport_x = atoi (params[4]);
	viewport_y = atoi (params[5]);

	display = display_open_if_needed (display_name);
	if (display == NULL)
	{
		g_warning ("Could not open display %s\n", display_name);
		g_strfreev (params);
		goto out;
	}

	screen = gdk_display_get_screen (display, screen_number);

	g_strfreev (params);

	/* body */
	for (i = 1; commands[i] != NULL; i++)
	{
		params = g_strsplit (commands[i], "\t", -1);

		if (strcmp (params[0], "NEW-WINDOW") == 0)
		{
			new_window_option = TRUE;
		}
		else if (strcmp (params[0], "NEW-DOCUMENT") == 0)
		{
			new_document_option = TRUE;
		}
		else if (strcmp (params[0], "OPEN-URIS") == 0)
		{
			gint n_uris, j;
			gchar **uris;

			line_position = atoi (params[1]);

			if (params[2] != '\0')
				encoding = pluma_encoding_get_from_charset (params[2]);

			n_uris = atoi (params[3]);
			uris = g_strsplit (params[4], " ", n_uris);

			for (j = 0; j < n_uris; j++)
			{
				GFile *file;

				file = g_file_new_for_uri (uris[j]);
				file_list = g_slist_prepend (file_list, file);
			}

			file_list = g_slist_reverse (file_list);

			/* the list takes ownerhip of the strings,
			 * only free the array */
			g_free (uris);
		}
		else
		{
			g_warning ("Unexpected bacon command");
		}

		g_strfreev (params);
	}

	/* execute the commands */

	app = pluma_app_get_default ();

	if (new_window_option)
	{
		window = pluma_app_create_window (app, screen);
	}
	else
	{
		/* get a window in the current workspace (if exists) and raise it */
		window = _pluma_app_get_window_in_viewport (app,
							    screen,
							    workspace,
							    viewport_x,
							    viewport_y);
	}

	if (file_list != NULL)
	{
		_pluma_cmd_load_files_from_prompt (window,
						   file_list,
						   encoding,
						   line_position);

		if (new_document_option)
			pluma_window_create_tab (window, TRUE);
	}
	else
	{
		PlumaDocument *doc;
		doc = pluma_window_get_active_document (window);

		if (doc == NULL ||
		    !pluma_document_is_untouched (doc) ||
		    new_document_option)
			pluma_window_create_tab (window, TRUE);
	}

	/* set the proper interaction time on the window.
	 * Fall back to roundtripping to the X server when we
	 * don't have the timestamp, e.g. when launched from
	 * terminal. We also need to make sure that the window
	 * has been realized otherwise it will not work. lame.
	 */
	if (!gtk_widget_get_realized (GTK_WIDGET (window)))
		gtk_widget_realize (GTK_WIDGET (window));

	if (startup_timestamp <= 0)
		startup_timestamp = gdk_x11_get_server_time (gtk_widget_get_window (GTK_WIDGET (window)));

	gdk_x11_window_set_user_time (gtk_widget_get_window (GTK_WIDGET (window)),
				      startup_timestamp);

	gtk_window_present (GTK_WINDOW (window));

 out:
	g_strfreev (commands);

	free_command_line_data ();
}
Пример #9
0
static int
gth_application_command_line (GApplication            *application,
                              GApplicationCommandLine *command_line)
{
	char           **argv;
	int              argc;
	GOptionContext  *context;
	GError          *error = NULL;
	const char      *arg;
	int              i;
	GList           *files;
	GList           *dirs;
	GFile           *location;
	gboolean         singleton;
	GList           *scan;

	argv = g_application_command_line_get_arguments (command_line, &argc);

	/* parse command line options */

	context = gth_application_create_option_context ();
	if (! g_option_context_parse (context, &argc, &argv, &error)) {
		g_critical ("Failed to parse arguments: %s", error->message);
		g_error_free (error);
		g_option_context_free (context);
		return EXIT_FAILURE;
	}
	g_option_context_free (context);
	g_strfreev (argv);

	gdk_notify_startup_complete ();

	/* exec the command line */

	if (ImportPhotos) {
		GFile *location = NULL;

		if (remaining_args != NULL)
			location = g_file_new_for_commandline_arg (remaining_args[0]);
		import_photos_from_location (location);

		return 0;
	}

	if (remaining_args == NULL) { /* No location specified. */
		GFile     *location;
		GSettings *settings;
		char      *file_to_select_uri;
		GFile     *file_to_select;

		location = g_file_new_for_uri (gth_pref_get_startup_location ());
		settings = g_settings_new (GTHUMB_BROWSER_SCHEMA);
		file_to_select_uri = _g_settings_get_uri (settings, PREF_BROWSER_STARTUP_CURRENT_FILE);
		if (file_to_select_uri != NULL)
			file_to_select = g_file_new_for_uri (file_to_select_uri);
		else
			file_to_select = NULL;

		open_browser_window (location, file_to_select, TRUE);

		_g_object_unref (file_to_select);
		g_free (file_to_select_uri);
		g_object_unref (settings);
		g_object_unref (location);

		return 0;
	}

	/* At least a location was specified */

	files = NULL;
	dirs = NULL;
	for (i = 0; (arg = remaining_args[i]) != NULL; i++) {
		GFile     *location;
		GFileType  file_type;

		location = g_file_new_for_commandline_arg (arg);
		file_type = _g_file_get_standard_type (location);
		if (file_type == G_FILE_TYPE_REGULAR)
			files = g_list_prepend (files, location);
		else
			dirs = g_list_prepend (dirs, location);
	}
	files = g_list_reverse (files);
	dirs = g_list_reverse (dirs);

	location = gth_hook_invoke_get ("command-line-files", files);
	if (location != NULL) {
		open_browser_window (location, NULL, FALSE);
		g_object_unref (location);
	}
	else {
		/* Open each file in a new window */

		singleton = (files != NULL) && (files->next == NULL);
		for (scan = files; scan; scan = scan->next)
			open_browser_window ((GFile *) scan->data, NULL, ! singleton);
	}

	/* Open each dir in a new window */

	for (scan = dirs; scan; scan = scan->next)
		open_browser_window ((GFile *) scan->data, NULL, TRUE);

	_g_object_list_unref (dirs);
	_g_object_list_unref (files);

	return 0;
}
static void
panel_place_menu_item_append_gtk_bookmarks (GtkWidget *menu)
{
	typedef struct {
		char *full_uri;
		char *label;
	} PanelBookmark;

	GtkWidget   *add_menu;
	char        *filename;
	char        *contents;
	gchar      **lines;
	GHashTable  *table;
	int          i;
	GSList      *add_bookmarks, *l;
	PanelBookmark *bookmark;

	filename = g_build_filename (g_get_home_dir (),
				     BOOKMARKS_FILENAME, NULL);

	if (!g_file_get_contents (filename, &contents, NULL, NULL)) {
		g_free (filename);
		return;
	}

	g_free (filename);

	lines = g_strsplit (contents, "\n", -1);
	g_free (contents);

	table = g_hash_table_new (g_str_hash, g_str_equal);
	add_bookmarks = NULL;

	for (i = 0; lines[i]; i++) {
		if (lines[i][0] && !g_hash_table_lookup (table, lines[i])) {
			GFile    *file;
			char     *space;
			char     *label;
			gboolean  keep;

			g_hash_table_insert (table, lines[i], lines[i]);

			space = strchr (lines[i], ' ');
			if (space) {
				*space = '\0';
				label = g_strdup (space + 1);
			} else {
				label = NULL;
			}

			keep = FALSE;

			if (g_str_has_prefix (lines[i], "x-nautilus-search:"))
				keep = TRUE;

			if (!keep) {
				file = g_file_new_for_uri (lines[i]);
				keep = !g_file_is_native (file) ||
				       g_file_query_exists (file, NULL);
				g_object_unref (file);
			}

			if (!keep) {
				if (label)
					g_free (label);
				continue;
			}

			bookmark = g_malloc (sizeof (PanelBookmark));
			bookmark->full_uri = g_strdup (lines[i]);
			bookmark->label = label;
			add_bookmarks = g_slist_prepend (add_bookmarks, bookmark);
		}
	}

	g_hash_table_destroy (table);
	g_strfreev (lines);

	add_bookmarks = g_slist_reverse (add_bookmarks);

	if (g_slist_length (add_bookmarks) <= MAX_ITEMS_OR_SUBMENU) {
		add_menu = menu;
	} else {
		GtkWidget *item;

		item = gtk_image_menu_item_new ();
		setup_menu_item_with_icon (item, panel_menu_icon_get_size (),
					   PANEL_ICON_BOOKMARKS, NULL, NULL,
					   _("Bookmarks"));

		gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
		gtk_widget_show (item);

		add_menu = create_empty_menu ();
		gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), add_menu);
	}

	for (l = add_bookmarks; l; l = l->next) {
		char *display_name;
		char *tooltip;
		char *label;
		char *icon;
		GFile *file;

		bookmark = l->data;
		
		file = g_file_new_for_uri (bookmark->full_uri);
		display_name = g_file_get_parse_name (file);
		g_object_unref (file);
		/* Translators: %s is a URI */
		tooltip = g_strdup_printf (_("Open '%s'"), display_name);
		g_free (display_name);

		label = NULL;
		if (bookmark->label) {
			label = g_strdup (g_strstrip (bookmark->label));
			if (!label [0]) {
				g_free (label);
				label = NULL;
			}
		}

		if (!label) {
			label = panel_util_get_label_for_uri (bookmark->full_uri);

			if (!label) {
				g_free (tooltip);
				g_free (bookmark->full_uri);
				if (bookmark->label)
					g_free (bookmark->label);
				g_free (bookmark);
				continue;
			}
		}

		icon = panel_util_get_icon_for_uri (bookmark->full_uri);
		/*FIXME: we should probably get a GIcon if possible, so that we
		 * have customized icons for cd-rom, eg */
		if (!icon)
			icon = g_strdup (PANEL_ICON_FOLDER);

		//FIXME: drag and drop will be broken for x-nautilus-search uris
		panel_menu_items_append_place_item (icon, NULL,
						    label,
						    tooltip,
						    add_menu,
						    G_CALLBACK (activate_uri),
						    bookmark->full_uri);

		g_free (icon);
		g_free (tooltip);
		g_free (label);
		g_free (bookmark->full_uri);
		if (bookmark->label)
			g_free (bookmark->label);
		g_free (bookmark);
	}

	g_slist_free (add_bookmarks);
}
Пример #11
0
void
Tetris::dragDrop(GtkWidget *widget, GdkDragContext *context,
		 gint x, gint y, GtkSelectionData *data, guint info,
		 guint time, Tetris * t)
{
	const char *fileuri;

	GError *error = NULL;
	GFile *file;
	GFile *outfile;
	GFileInfo *fileinfo;
	GFileInputStream *istream;
	GFileOutputStream *outstream;
	goffset filesize;
	gssize bytesread, byteswrote;

	GdkPixbufLoader *loader;
	GdkPixbuf *pixbuf;
	guchar *buffer;


	/* Accept a dropped filename and try and load it as the
	   background image. In the event of any kind of failure we
	   silently ignore it. */

	/* FIXME: We don't handle colour gradients (e.g. from the gimp) */

	/* FIXME: Dropped URLs from mozilla don't work (see below). */

	if (data->length < 0) {
		gtk_drag_finish (context, FALSE, FALSE, time);
		return;
	}

	gtk_drag_finish (context, TRUE, FALSE, time);

	if (info == COLOUR) {
		if (data->length == 8)
			decodeColour ((guint16 *)data->data, t);
		return;
	}

	if (info == RESET) {
		resetColour (t);
		return;
	}

	fileuri = decodeDropData ((char *)data->data, info);
	/* Silently ignore bad data. */
	if (fileuri == NULL)
		goto error_exit;

	/* Now that we have a URI we load it and test it to see if it is
	 * an image file. */

	file = g_file_new_for_uri (fileuri);
	istream = g_file_read (file, NULL, &error);

	if (error)
		goto error_exit;

	fileinfo =  g_file_input_stream_query_info (istream, (char *)G_FILE_ATTRIBUTE_STANDARD_SIZE, NULL, &error);

	if (error)
		goto error_exit_handle;

	filesize = g_file_info_get_size (fileinfo);

	buffer = (guchar *)g_malloc (filesize);
	if (buffer == NULL)
		goto error_exit_handle;

	bytesread = g_input_stream_read (G_INPUT_STREAM (istream), buffer, filesize, NULL, &error);

	/* FIXME: We should reread if not enough was read. */
	if (error || (bytesread != filesize))
		goto error_exit_buffer;

	loader = gdk_pixbuf_loader_new ();

	if (!gdk_pixbuf_loader_write (loader, buffer, filesize, NULL))
		goto error_exit_loader;

	gdk_pixbuf_loader_close (loader, NULL);

	pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
	if (pixbuf == NULL)
		goto error_exit_loader;

	g_object_ref (pixbuf);

	/* We now have an image file, in memory, that we know gdk-pixbuf
	 * can handle. Now we save it to disk. This is necessary so that
	 * "slow" URIs (e.g. http) behave well in the long run. */

	outfile = g_file_new_for_path (t->bgPixmap);
	outstream = g_file_replace (outfile, NULL, FALSE, G_FILE_CREATE_PRIVATE,
					NULL, &error);

	if (error)
		goto error_exit_loader;

	byteswrote = g_output_stream_write (G_OUTPUT_STREAM (outstream), buffer,
						bytesread, NULL, &error);

	if (byteswrote != filesize)
	    goto error_exit_saver;

	t->usebg = TRUE;
	t->saveBgOptions ();

 error_exit_saver:
	g_object_unref(outstream);
 error_exit_loader:
	g_object_unref (loader);
 error_exit_buffer:
	g_free (buffer);
 error_exit_handle:
	g_object_unref(istream);
 error_exit:
	if(error)
		g_error_free(error);
	return;
}
Пример #12
0
static void
drag_data_received_callback (GtkWidget *widget,
		       	     GdkDragContext *context,
		       	     int x,
		       	     int y,
		       	     GtkSelectionData *data,
		             guint info,
		             guint32 time,
			     gpointer callback_data)
{
	char **names;
	NemoApplication *application;
	int name_count;
	NemoWindow *new_window, *window;
	GdkScreen      *screen;
	gboolean new_windows_for_extras;
	char *prompt;
	char *detail;
	GFile *location;
	NemoLocationBar *self = NEMO_LOCATION_BAR (widget);

	g_assert (data != NULL);
	g_assert (callback_data == NULL);

	names = g_uri_list_extract_uris ((const gchar *) gtk_selection_data_get_data (data));

	if (names == NULL || *names == NULL) {
		g_warning ("No D&D URI's");
		g_strfreev (names);
		gtk_drag_finish (context, FALSE, FALSE, time);
		return;
	}

	window = nemo_location_bar_get_window (widget);
	new_windows_for_extras = FALSE;
	/* Ask user if they really want to open multiple windows
	 * for multiple dropped URIs. This is likely to have been
	 * a mistake.
	 */
	name_count = g_strv_length (names);
	if (name_count > 1) {
		prompt = g_strdup_printf (ngettext("Do you want to view %d location?",
						   "Do you want to view %d locations?",
						   name_count),
					  name_count);
		detail = g_strdup_printf (ngettext("This will open %d separate window.",
						   "This will open %d separate windows.",
						   name_count),
					  name_count);
		/* eel_run_simple_dialog should really take in pairs
		 * like gtk_dialog_new_with_buttons() does. */
		new_windows_for_extras = eel_run_simple_dialog
			(GTK_WIDGET (window),
			 TRUE,
			 GTK_MESSAGE_QUESTION,
			 prompt,
			 detail,
			 GTK_STOCK_CANCEL, GTK_STOCK_OK,
			 NULL) != 0 /* GNOME_OK */;

		g_free (prompt);
		g_free (detail);

		if (!new_windows_for_extras) {
			g_strfreev (names);
			gtk_drag_finish (context, FALSE, FALSE, time);
			return;
		}
	}

	nemo_location_bar_set_location (self, names[0]);
	emit_location_changed (self);

	if (new_windows_for_extras) {
		int i;

		application = nemo_application_get_singleton ();
		screen = gtk_window_get_screen (GTK_WINDOW (window));

		for (i = 1; names[i] != NULL; ++i) {
			new_window = nemo_application_create_window (application, screen);
			location = g_file_new_for_uri (names[i]);
			nemo_window_go_to (new_window, location);
			g_object_unref (location);
		}
	}

	g_strfreev (names);

	gtk_drag_finish (context, TRUE, FALSE, time);
}
Пример #13
0
static void
catalog_new_dialog_response_cb (GtkWidget *dialog,
				int        response_id,
				gpointer   user_data)
{
	GthBrowser    *browser = user_data;
	char          *name;
	GthFileData   *selected_parent;
	GFile         *parent;
	GthFileSource *file_source;
	GFile         *gio_parent;
	char          *display_name;
	GError        *error = NULL;
	GFile         *gio_file;

	if (response_id != GTK_RESPONSE_OK) {
		gtk_widget_destroy (dialog);
		return;
	}

	name = gth_request_dialog_get_normalized_text (GTH_REQUEST_DIALOG (dialog));
	if (_g_utf8_all_spaces (name)) {
		g_free (name);
		gth_request_dialog_set_info_text (GTH_REQUEST_DIALOG (dialog), GTK_MESSAGE_ERROR, _("No name specified"));
		return;
	}

	if (g_regex_match_simple ("/", name, 0, 0)) {
		char *message;

		message = g_strdup_printf (_("Invalid name. The following characters are not allowed: %s"), "/");
		gth_request_dialog_set_info_text (GTH_REQUEST_DIALOG (dialog), GTK_MESSAGE_ERROR, message);

		g_free (message);
		g_free (name);

		return;
	}

	selected_parent = gth_browser_get_folder_popup_file_data (browser);
	if (selected_parent != NULL) {
		GthFileSource *file_source;
		GFileInfo     *info;

		file_source = gth_main_get_file_source (selected_parent->file);
		info = gth_file_source_get_file_info (file_source, selected_parent->file, GFILE_BASIC_ATTRIBUTES);
		if (g_file_info_get_attribute_boolean (info, "gthumb::no-child"))
			parent = g_file_get_parent (selected_parent->file);
		else
			parent = g_file_dup (selected_parent->file);

		g_object_unref (info);
		g_object_unref (file_source);
	}
	else
		parent = g_file_new_for_uri ("catalog:///");

	file_source = gth_main_get_file_source (parent);
	gio_parent = gth_file_source_to_gio_file (file_source, parent);
	display_name = g_strconcat (name, ".catalog", NULL);
	gio_file = g_file_get_child_for_display_name (gio_parent, display_name, &error);
	if (gio_file != NULL) {
		GFileOutputStream *stream;

		stream = g_file_create (gio_file, G_FILE_CREATE_NONE, NULL, &error);
		if (stream != NULL) {
			GFile *file;
			GList *list;

			file = gth_catalog_file_from_gio_file (gio_file, NULL);
			list = g_list_prepend (NULL, file);
			gth_monitor_folder_changed (gth_main_get_default_monitor (),
						    parent,
						    list,
						    GTH_MONITOR_EVENT_CREATED);

			g_list_free (list);
			g_object_unref (file);
			g_object_unref (stream);
		}

		g_object_unref (gio_file);
	}

	if (error != NULL) {
		if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_EXISTS))
			gth_request_dialog_set_info_text (GTH_REQUEST_DIALOG (dialog), GTK_MESSAGE_ERROR, _("Name already used"));
		else
			gth_request_dialog_set_info_text (GTH_REQUEST_DIALOG (dialog), GTK_MESSAGE_ERROR, error->message);
		g_clear_error (&error);
	}
	else
		gtk_widget_destroy (dialog);

	g_free (display_name);
	g_object_unref (gio_parent);
	g_object_unref (file_source);
	g_free (name);
}
Пример #14
0
static void
jpeg_thumbnailer_create (TumblerAbstractThumbnailer *thumbnailer,
                         GCancellable               *cancellable,
                         TumblerFileInfo            *info)
{
  TumblerThumbnailFlavor *flavor;
  TumblerImageData        data;
  TumblerThumbnail       *thumbnail;
  struct stat             statb;
  const gchar            *uri;
  GdkPixbuf              *pixbuf = NULL;
  gboolean                streaming_needed = TRUE;
  JOCTET                 *content;
  GError                 *error = NULL;
  GFile                  *file;
  gchar                  *path;
  gsize                   length;
  gint                    fd;
  gint                    height;
  gint                    width;
  gint                    size;

  g_return_if_fail (IS_JPEG_THUMBNAILER (thumbnailer));
  g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
  g_return_if_fail (TUMBLER_IS_FILE_INFO (info));

  /* do nothing if cancelled */
  if (g_cancellable_is_cancelled (cancellable)) 
    return;

  uri = tumbler_file_info_get_uri (info);

  /* try to open the source file for reading */
  file = g_file_new_for_uri (uri);

  thumbnail = tumbler_file_info_get_thumbnail (info);
  g_assert (thumbnail != NULL);

  flavor = tumbler_thumbnail_get_flavor (thumbnail);
  g_assert (flavor != NULL);

  tumbler_thumbnail_flavor_get_size (flavor, &width, &height);
  size = MIN (width, height);

#ifdef HAVE_MMAP
  if (g_file_is_native (file))
    {
      path = g_file_get_path (file);

      /* try to open the file at the given path */
      fd = open (path, O_RDONLY);
      if (G_LIKELY (fd >= 0))
        {
          /* determine the status of the file */
          if (G_LIKELY (fstat (fd, &statb) == 0 && statb.st_size > 0))
            {
              /* try to mmap the file */
              content = (JOCTET *) mmap (NULL, statb.st_size, PROT_READ, 
                                         MAP_SHARED, fd, 0);

              /* verify whether the mmap was successful */
              if (G_LIKELY (content != (JOCTET *) MAP_FAILED))
                {
                  /* try to load the embedded thumbnail first */
                  pixbuf = tvtj_jpeg_load_thumbnail (content, statb.st_size, size);
                  if (pixbuf == NULL)
                    {
                      /* fall back to loading and scaling the image itself */
                      pixbuf = tvtj_jpeg_load (content, statb.st_size, size);

                      if (pixbuf == NULL)
                        {
                          g_set_error (&error, TUMBLER_ERROR, 
                                       TUMBLER_ERROR_INVALID_FORMAT,
                                       _("Thumbnail could not be inferred from file contents"));
                        }
                    }

                  /* we have successfully mmapped the file. we may not have
                   * a thumbnail but trying to read the image from a stream
                   * won't help us here, so we don't need to attempt streaming
                   * as a fallback */
                  streaming_needed = FALSE;
                }

              /* unmap the file content */
              munmap ((void *) content, statb.st_size);
            }

          /* close the file */
          close (fd);
        }

      g_free (path);
    }
#endif

  if (streaming_needed)
    {
      g_file_load_contents (file, cancellable, (gchar **)&content, &length, 
                            NULL, &error);

      if (error == NULL)
        {
          pixbuf = tvtj_jpeg_load_thumbnail (content, length, size);

          if (pixbuf == NULL)
            {
              pixbuf = tvtj_jpeg_load (content, length, size);
              if (pixbuf == NULL)
                {
                  g_set_error (&error, TUMBLER_ERROR, TUMBLER_ERROR_INVALID_FORMAT,
                               _("Thumbnail could not be inferred from file contents"));
                }
            }
        }
    }

  /* either we have an error now or we have a valid thumbnail pixbuf */
  g_assert (error != NULL || pixbuf != NULL);

  if (pixbuf != NULL)
    {
      data.data = gdk_pixbuf_get_pixels (pixbuf);
      data.has_alpha = gdk_pixbuf_get_has_alpha (pixbuf);
      data.bits_per_sample = gdk_pixbuf_get_bits_per_sample (pixbuf);
      data.width = gdk_pixbuf_get_width (pixbuf);
      data.height = gdk_pixbuf_get_height (pixbuf);
      data.rowstride = gdk_pixbuf_get_rowstride (pixbuf);
      data.colorspace = (TumblerColorspace) gdk_pixbuf_get_colorspace (pixbuf);

      tumbler_thumbnail_save_image_data (thumbnail, &data, 
                                         tumbler_file_info_get_mtime (info), 
                                         NULL, &error);

      g_object_unref (pixbuf);
    }

  if (error != NULL)
    {
      g_signal_emit_by_name (thumbnailer, "error", uri, error->code, error->message);
      g_error_free (error);
    }
  else
    {
      g_signal_emit_by_name (thumbnailer, "ready", uri);
    }

  g_object_unref (flavor);
  g_object_unref (thumbnail);
  g_object_unref (file);
}
Пример #15
0
GList *
_filter_out_unshowable_recent_items (PengeEverythingPane *pane,
                                     ZeitgeistResultSet  *set)
{
  PengeEverythingPanePrivate *priv = GET_PRIVATE (pane);
  GList *ret = NULL;
  guint i; /* loop index */

  /* probably an error (or an actual empty set, obv), we need to return empty
   * list anyway */
  if (set == NULL)
    return NULL;

  while (zeitgeist_result_set_has_next (set))
  {
    ZeitgeistEvent *event = NULL;
    gchar *thumbnail_path = NULL;

    /* We have to do this because we edit the list */
    event = zeitgeist_result_set_next (set);

    /* FIXME, so far this is the assumption, then we can use a better data
     * structure for managing events with multiple subjects */
    g_assert (zeitgeist_event_num_subjects (event) == 1);

    for (i = 0; i < zeitgeist_event_num_subjects (event); ++i)
      {
        ZeitgeistSubject *s;
        GFile *file;
        const gchar *uri = NULL;

        s = zeitgeist_event_get_subject (event, i);
        g_assert (s != NULL);
        uri = zeitgeist_subject_get_uri (s);
        g_assert (uri != NULL);

        /* Just a small debug help :)
        g_warning ("%s: subj(%d): i=%s m=%s",
            zeitgeist_subject_get_uri (s),
            i,
            zeitgeist_subject_get_interpretation (s),
            zeitgeist_subject_get_manifestation (s));
        */


        /* Current detault template look for local files only, if it's not local,
         * it's probably a template error, log it and move on */
        if (!g_str_has_prefix (uri, "file:"))
          {
            g_warning ("uri %s for recent event is not local", uri);
            continue;
          }

        file = g_file_new_for_uri (uri);

        /* if the file does not exist anymore we ignore it and move on */
        if (!g_file_query_exists (file, NULL))
          break; /* consider the next event */

        thumbnail_path = mpl_utils_get_thumbnail_path (uri);

        /* add to the return list only if it has a valid thumbnail */
        if (thumbnail_path && g_file_test (thumbnail_path, G_FILE_TEST_EXISTS))
          ret = g_list_prepend (ret, g_object_ref (event));

        g_free (thumbnail_path);
        g_object_unref (file);
      }
  }

  return ret;
}
Пример #16
0
gboolean
nemo_link_local_create (const char     *directory_uri,
			    const char     *base_name,
			    const char     *display_name,
			    const char     *image,
			    const char     *target_uri,
			    const GdkPoint *point,
			    int             screen,
			    gboolean        unique_filename)
{
	char *real_directory_uri;
	char *uri, *contents;
	GFile *file;
	GList dummy_list;
	NemoFileChangesQueuePosition item;

	g_return_val_if_fail (directory_uri != NULL, FALSE);
	g_return_val_if_fail (base_name != NULL, FALSE);
	g_return_val_if_fail (display_name != NULL, FALSE);
	g_return_val_if_fail (target_uri != NULL, FALSE);

	if (eel_uri_is_trash (directory_uri) ||
	    eel_uri_is_search (directory_uri)) {
		return FALSE;
	}

	if (eel_uri_is_desktop (directory_uri)) {
		real_directory_uri = nemo_get_desktop_directory_uri ();
	} else {
		real_directory_uri = g_strdup (directory_uri);
	}

	if (unique_filename) {
		uri = nemo_ensure_unique_file_name (real_directory_uri,
							base_name, ".desktop");
		if (uri == NULL) {
			g_free (real_directory_uri);
			return FALSE;
		}
		file = g_file_new_for_uri (uri);
		g_free (uri);
	} else {
		char *link_name;
		GFile *dir;

		link_name = g_strdup_printf ("%s.desktop", base_name);

		/* replace '/' with '-', just in case */
		g_strdelimit (link_name, "/", '-');

		dir = g_file_new_for_uri (directory_uri);
		file = g_file_get_child (dir, link_name);

		g_free (link_name);
		g_object_unref (dir);
	}

	g_free (real_directory_uri);

	contents = g_strdup_printf ("[Desktop Entry]\n"
				    "Encoding=UTF-8\n"
				    "Name=%s\n"
				    "Type=Link\n"
				    "URL=%s\n"
				    "%s%s\n",
				    display_name,
				    target_uri,
				    image != NULL ? "Icon=" : "",
				    image != NULL ? image : "");


	if (!g_file_replace_contents (file,
				      contents, strlen (contents),
				      NULL, FALSE,
				      G_FILE_CREATE_NONE,
				      NULL, NULL, NULL)) {
		g_free (contents);
		g_object_unref (file);
		return FALSE;
	}
	g_free (contents);

	dummy_list.data = file;
	dummy_list.next = NULL;
	dummy_list.prev = NULL;
	nemo_directory_notify_files_added (&dummy_list);

	if (point != NULL) {
		item.location = file;
		item.set = TRUE;
		item.point.x = point->x;
		item.point.y = point->y;
		item.screen = screen;
		dummy_list.data = &item;
		dummy_list.next = NULL;
		dummy_list.prev = NULL;
	
		nemo_directory_schedule_position_set (&dummy_list);
	}

	g_object_unref (file);
	return TRUE;
}
Пример #17
0
static void
terminal_nautilus_menu_item_activate (NautilusMenuItem *item)
{
  TerminalNautilusMenuItem *menu_item = TERMINAL_NAUTILUS_MENU_ITEM (item);
  TerminalNautilus *nautilus = menu_item->nautilus;
  char *uri, *path;
  TerminalFileInfo info;
  ExecData *data;

  uri = nautilus_file_info_get_activation_uri (menu_item->file_info);
  if (uri == NULL)
    return;

  path = NULL;
  info = get_terminal_file_info_from_uri (uri);

  switch (info) {
    case FILE_INFO_LOCAL:
      path = g_filename_from_uri (uri, NULL, NULL);
      break;

    case FILE_INFO_DESKTOP:
      if (desktop_is_home_dir (nautilus) || desktop_opens_home_dir (nautilus)) {
        path = g_strdup (g_get_home_dir ());
      } else {
        path = g_strdup (g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP));
      }
      break;

    case FILE_INFO_SFTP:
      if (menu_item->remote_terminal)
        break;

      /* fall through */

    case FILE_INFO_OTHER: {
      GFile *file;

      /* map back remote URI to local path */
      file = g_file_new_for_uri (uri);
      path = g_file_get_path (file);
      g_object_unref (file);
      break;
    }

    default:
      g_assert_not_reached ();
  }

  if (path == NULL && (info != FILE_INFO_SFTP || !menu_item->remote_terminal)) {
    g_free (uri);
    return;
  }

  data = g_new (ExecData, 1);
  data->nautilus = g_object_ref (nautilus);
  data->timestamp = gtk_get_current_event_time ();
  data->path = path;
  data->uri = uri;
  data->display = gdk_screen_make_display_name (menu_item->screen);
  data->info = info;
  data->remote = menu_item->remote_terminal;
  data->run_in_mc = menu_item->run_in_mc;

  create_terminal (data);
}
Пример #18
0
static void
on_monitors_changed (MetaScreen *screen,
                     MetaPlugin *plugin)
{
  MetaDefaultPlugin *self = META_DEFAULT_PLUGIN (plugin);
  __attribute__ ((unused)) ClutterAnimation *animation;
  int i, n;
  gchar *wallpaper = NULL;
  GFile *wallpaper_file = NULL;
  gchar *filename = NULL;
  GDesktopBackgroundStyle style;
  GDesktopBackgroundShading  shading_direction;
  ClutterColor primary_color;
  ClutterColor secondary_color;
  gboolean random_colour = FALSE;

  clutter_actor_destroy_all_children (self->priv->background_group);

  wallpaper = g_settings_get_string (self->priv->settings, PICTURE_URI_KEY);
  /* We don't currently support slideshows */
  if (!wallpaper || g_str_has_suffix(wallpaper, ".xml"))
    random_colour = TRUE;
  else {
    gchar *color_str;

    /* Shading direction*/
    shading_direction = g_settings_get_enum (self->priv->settings, COLOR_SHADING_TYPE_KEY);

    /* Primary color */
    color_str = g_settings_get_string (self->priv->settings, PRIMARY_COLOR_KEY);
    if (color_str)
    {
      clutter_color_from_string (&primary_color, color_str);
      g_free (color_str);
      color_str = NULL;
    }
      
    /* Secondary color */
    color_str = g_settings_get_string (self->priv->settings, SECONDARY_COLOR_KEY);
    if (color_str)
    {
      clutter_color_from_string (&secondary_color, color_str);
      g_free (color_str);
      color_str = NULL;
    }

    /* Picture options: "none", "wallpaper", "centered", "scaled", "stretched", "zoom", "spanned" */
    style = g_settings_get_enum (self->priv->settings, BACKGROUND_STYLE_KEY);

    wallpaper_file = g_file_new_for_uri(wallpaper);
    filename = g_file_get_path(wallpaper_file);
  }

  n = meta_screen_get_n_monitors (screen);

  for (i = 0; i < n; i++)
    {
      MetaBackground *content;
      MetaRectangle rect;
      ClutterActor *background;

      background = meta_background_actor_new ();

      content = meta_background_new (screen, 
                                     i, 
                                     META_BACKGROUND_EFFECTS_NONE);
      // Don't use rand() here, mesa calls srand() internally when
      // parsing the driconf XML, but it's nice if the colors are
      // reproducible.
      if (random_colour)
      {
        clutter_color_init (&primary_color,
          g_random_int () % 255,
          g_random_int () % 255,
          g_random_int () % 255,
          255);

        meta_background_load_color (content, &primary_color);
      } else {
        if (style == G_DESKTOP_BACKGROUND_STYLE_NONE ||
            g_str_has_suffix (filename, GNOME_COLOR_HACK))
        {
          if (shading_direction == G_DESKTOP_BACKGROUND_SHADING_SOLID)
            meta_background_load_color (content, &primary_color);
          else
            meta_background_load_gradient (content,
                                           shading_direction,
                                           &primary_color,
                                           &secondary_color);
        } else {
          /* Set the background */
          meta_background_load_file_async (content,
                                           filename,
                                           style,
                                           NULL, /*TODO use cancellable*/
                                           background_load_file_cb,
                                           self);
        }
      }

      clutter_actor_set_content (background, CLUTTER_CONTENT (content));
      g_object_unref (content);

      meta_screen_get_monitor_geometry (screen, i, &rect);

      clutter_actor_set_position (background, rect.x, rect.y);
      clutter_actor_set_size (background, rect.width, rect.height);
      clutter_actor_add_child (self->priv->background_group, background);
      clutter_actor_set_scale (background, 0.0, 0.0);
      clutter_actor_show (background);
      clutter_actor_set_pivot_point (background, 0.5, 0.5);

      /* Ease in the background using a scale effect */
      animation = clutter_actor_animate (background, CLUTTER_EASE_IN_SINE,
                                         BACKGROUND_TIMEOUT,
                                         "scale-x", 1.0,
                                         "scale-y", 1.0,
                                         NULL);
    }
    if (wallpaper_file)
      g_object_unref(wallpaper_file);
    g_free(wallpaper);
    g_free(filename);
}
Пример #19
0
int
main (int argc, char *argv[])
{
	GtkApplication	*app;
	GError		*error = NULL;
	GOptionContext	*context;
	GOptionGroup	*debug;
	gulong		debug_flags = 0;
	LifereaDBus	*dbus = NULL;
	gchar		*feedUri = NULL;
	gint 		status;

	GOptionEntry entries[] = {
		{ "mainwindow-state", 'w', 0, G_OPTION_ARG_STRING, &initialStateOption, N_("Start Liferea with its main window in STATE. STATE may be `shown', `iconified', or `hidden'"), N_("STATE") },
		{ "version", 'v', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, show_version, N_("Show version information and exit"), NULL },
		{ "add-feed", 'a', 0, G_OPTION_ARG_STRING, &feedUri, N_("Add a new subscription"), N_("uri") },
		{ NULL, 0, 0, 0, NULL, NULL, NULL }
	};

	GOptionEntry debug_entries[] = {
		{ "debug-all", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of all types"), NULL },
		{ "debug-cache", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages for the cache handling"), NULL },
		{ "debug-conf", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages for the configuration handling"), NULL },
		{ "debug-db", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of the database handling"), NULL },
		{ "debug-gui", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of all GUI functions"), NULL },
		{ "debug-html", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Enables HTML rendering debugging. Each time Liferea renders HTML output it will also dump the generated HTML into ~/.cache/liferea/output.xhtml"), NULL },
		{ "debug-net", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of all network activity"), NULL },
		{ "debug-parsing", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of all parsing functions"), NULL },
		{ "debug-performance", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages when a function takes too long to process"), NULL },
		{ "debug-trace", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages when entering/leaving functions"), NULL },
		{ "debug-update", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of the feed update processing"), NULL },
		{ "debug-vfolder", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print debugging messages of the search folder matching"), NULL },
		{ "debug-verbose", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, debug_entries_parse_callback, N_("Print verbose debugging messages"), NULL },
		{ NULL, 0, 0, 0, NULL, NULL, NULL }
	};

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

	debug = g_option_group_new ("debug",
				    _("Print debugging messages for the given topic"),
				    _("Print debugging messages for the given topic"),
				    &debug_flags,
				    NULL);
	g_option_group_set_translation_domain(debug, GETTEXT_PACKAGE);
	g_option_group_add_entries (debug, debug_entries);

	context = g_option_context_new (NULL);
	g_option_context_set_summary (context, N_("Liferea, the Linux Feed Reader"));
	g_option_context_set_description (context, N_("For more information, please visit http://lzone.de/liferea/"));
	g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
	g_option_context_set_translation_domain(context, GETTEXT_PACKAGE);
	g_option_context_add_group (context, debug);
	g_option_context_add_group (context, gtk_get_option_group (FALSE));
	g_option_context_add_group (context, g_irepository_get_option_group ());

	g_option_context_parse (context, &argc, &argv, &error);
	g_option_context_free (context);
	if (error) {
		g_print ("Error parsing options: %s\n", error->message);
	}

	set_debug_level (debug_flags);

	/* Configuration necessary for network options, so it
	   has to be initialized before update_init() */
	conf_init ();

	/* We need to do the network initialization here to allow
	   network-manager to be setup before gtk_init() */
	update_init ();

	gtk_init (&argc, &argv);

	/* Single instance checks, also note that we pass or only RPC (add-feed)
	   as activate signal payload as it is simply an URI string. */
	app = gtk_application_new ("net.sourceforge.liferea", G_APPLICATION_HANDLES_OPEN);
	g_signal_connect (app, "activate", G_CALLBACK (on_app_activate), feedUri);
	g_signal_connect (app, "open", G_CALLBACK (on_feed_add), NULL);

	g_set_prgname ("liferea");
	g_set_application_name (_("Liferea"));
	gtk_window_set_default_icon_name ("liferea");	/* GTK theme support */

	debug_start_measurement (DEBUG_DB);

	/* order is important! */
	db_init ();			/* initialize sqlite */
	xml_init ();			/* initialize libxml2 */
#ifdef HAVE_LIBNOTIFY
	notification_plugin_register (&libnotify_plugin);
#endif
	social_init ();			/* initialize social bookmarking */

	dbus = liferea_dbus_new ();

	signal (SIGTERM, signal_handler);
	signal (SIGINT, signal_handler);
	signal (SIGHUP, signal_handler);

	/* Note: we explicitely do not use the gdk_thread_*
	   locking in Liferea because it freezes the program
	   when running Flash applets */

	runState = STATE_STARTING;
	
	debug_end_measurement (DEBUG_DB, "startup");

	status = g_application_run (G_APPLICATION (app), 0, NULL);

	/* Trigger RPCs if we are not primary instance (currently only feed-add) */
	if (feedUri && g_application_get_is_remote (G_APPLICATION (app))) {
		GFile *uris[2];

		uris[0] = g_file_new_for_uri (feedUri);
		uris[1] = NULL;
		g_application_open (G_APPLICATION (app), uris, 1, "feed-add");
		g_object_unref (uris[0]);
	}
	
	g_object_unref (G_OBJECT (dbus));
	g_object_unref (app);

	return status;
}
Пример #20
0
/**
 * shell_util_get_icon_for_uri:
 * @text_uri: A URI
 *
 * Look up the icon that should be associated with a given URI.  Handles
 * various special GNOME-internal cases like x-nautilus-search, etc.
 *
 * Return Value: (transfer full): A new #GIcon
 */
GIcon *
shell_util_get_icon_for_uri (const char *text_uri)
{
  const char *name;
  GFile *file;
  GFileInfo *info;
  GIcon *retval;

  /* Here's what we do:
   *  + check for known file: URI
   *  + x-nautilus-search: URI
   *  + override burn: URI icon
   *  + check if the URI is a mount
   *  + override trash: URI icon for subfolders
   *  + check for application/x-gnome-saved-search mime type and override
   *    icon of the GFile
   *  + use icon of the GFile
   */

  /* this only checks file: URI */
  name = shell_util_get_icon_for_uri_known_folders (text_uri);
  if (name)
    return g_themed_icon_new (name);

  if (g_str_has_prefix (text_uri, "x-nautilus-search:"))
    return g_themed_icon_new ("folder-saved-search");

  /* gvfs doesn't give us a nice icon, so overriding */
  if (g_str_has_prefix (text_uri, "burn:"))
    return g_themed_icon_new ("nautilus-cd-burner");

  file = g_file_new_for_uri (text_uri);

  retval = shell_util_get_file_icon_if_mount (file);
  if (retval)
    return retval;

  /* gvfs doesn't give us a nice icon for subfolders of the trash, so
   * overriding */
  if (g_str_has_prefix (text_uri, "trash:"))
    {
      GFile *root;

      root = shell_util_get_gfile_root (file);
      g_object_unref (file);
      file = root;
    }

  info = g_file_query_info (file, "standard::icon", G_FILE_QUERY_INFO_NONE,
                            NULL, NULL);
  g_object_unref (file);

  if (!info)
    return g_themed_icon_new ("gtk-file");

  retval = g_file_info_get_icon (info);
  if (retval)
    g_object_ref (retval);
  g_object_unref (info);

  if (retval)
    return retval;

  return g_themed_icon_new ("gtk-file");
}
Пример #21
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;
}
Пример #22
0
static void
drag_data_received_callback (GtkWidget *widget,
			     GdkDragContext *context,
			     int x,
			     int y,
			     GtkSelectionData *data,
			     guint info,
			     guint32 time,
			     gpointer user_data)
{
    	NemoDragInfo *drag_info;
	char *tmp;
	const char *tmp_raw;
	int length;
	gboolean success;

	drag_info = &(NEMO_ICON_CONTAINER (widget)->details->dnd_info->drag_info);

	drag_info->got_drop_data_type = TRUE;
	drag_info->data_type = info;

	switch (info) {
	case NEMO_ICON_DND_GNOME_ICON_LIST:
		nemo_icon_container_dropped_icon_feedback (widget, data, x, y);
		break;
	case NEMO_ICON_DND_URI_LIST:
	case NEMO_ICON_DND_TEXT:
	case NEMO_ICON_DND_XDNDDIRECTSAVE:
	case NEMO_ICON_DND_RAW:
		/* Save the data so we can do the actual work on drop. */
		if (drag_info->selection_data != NULL) {
			gtk_selection_data_free (drag_info->selection_data);
		}
		drag_info->selection_data = gtk_selection_data_copy (data);
		break;

	/* Netscape keeps sending us the data, even though we accept the first drag */
	case NEMO_ICON_DND_NETSCAPE_URL:
		if (drag_info->selection_data != NULL) {
			gtk_selection_data_free (drag_info->selection_data);
			drag_info->selection_data = gtk_selection_data_copy (data);
		}
		break;
	case NEMO_ICON_DND_ROOTWINDOW_DROP:
		/* Do nothing, this won't even happen, since we don't want to call get_data twice */
		break;
	}

	/* this is the second use case of this callback.
	 * we have to do the actual work for the drop.
	 */
	if (drag_info->drop_occured) {

		success = FALSE;
		switch (info) {
		case NEMO_ICON_DND_GNOME_ICON_LIST:
			nemo_icon_container_receive_dropped_icons
				(NEMO_ICON_CONTAINER (widget),
				 context, x, y);
			break;
		case NEMO_ICON_DND_NETSCAPE_URL:
			receive_dropped_netscape_url
				(NEMO_ICON_CONTAINER (widget),
				 (char *) gtk_selection_data_get_data (data), context, x, y);
			success = TRUE;
			break;
		case NEMO_ICON_DND_URI_LIST:
			receive_dropped_uri_list
				(NEMO_ICON_CONTAINER (widget),
				 (char *) gtk_selection_data_get_data (data), context, x, y);
			success = TRUE;
			break;
		case NEMO_ICON_DND_TEXT:
			tmp = gtk_selection_data_get_text (data);
			receive_dropped_text
				(NEMO_ICON_CONTAINER (widget),
				 (char *) tmp, context, x, y);
			success = TRUE;
			g_free (tmp);
			break;
		case NEMO_ICON_DND_RAW:
			length = gtk_selection_data_get_length (data);
			tmp_raw = gtk_selection_data_get_data (data);
			receive_dropped_raw
				(NEMO_ICON_CONTAINER (widget),
				 tmp_raw, length, drag_info->direct_save_uri,
				 context, x, y);
			success = TRUE;
			break;
		case NEMO_ICON_DND_ROOTWINDOW_DROP:
			/* Do nothing, everything is done by the sender */
			break;
		case NEMO_ICON_DND_XDNDDIRECTSAVE:
		{
			const guchar *selection_data;
			gint selection_length;
			gint selection_format;

			selection_data = gtk_selection_data_get_data (drag_info->selection_data);
			selection_length = gtk_selection_data_get_length (drag_info->selection_data);
			selection_format = gtk_selection_data_get_format (drag_info->selection_data);

			if (selection_format == 8 &&
			    selection_length == 1 &&
			    selection_data[0] == 'F') {
				gtk_drag_get_data (widget, context,
				                  gdk_atom_intern (NEMO_ICON_DND_RAW_TYPE,
				                                   FALSE),
				                  time);
				return;
			} else if (selection_format == 8 &&
				   selection_length == 1 &&
				   selection_data[0] == 'F' &&
			           drag_info->direct_save_uri != NULL) {
				GdkPoint p;
				GFile *location;

				location = g_file_new_for_uri (drag_info->direct_save_uri);

				nemo_file_changes_queue_file_added (location);
				p.x = x; p.y = y;
				nemo_file_changes_queue_schedule_position_set (
				                 location,
				                 p,
				                 gdk_screen_get_number (
				                             gtk_widget_get_screen (widget)));
				g_object_unref (location);
				nemo_file_changes_consume_changes (TRUE);
				success = TRUE;
			}
			break;
		} /* NEMO_ICON_DND_XDNDDIRECTSAVE */
		}
		gtk_drag_finish (context, success, FALSE, time);
		
		nemo_icon_container_free_drag_data (NEMO_ICON_CONTAINER (widget));
		
		set_drop_target (NEMO_ICON_CONTAINER (widget), NULL);

		/* reinitialise it for the next dnd */
		drag_info->drop_occured = FALSE;
	}

}
nsresult
nsIconChannel::InitWithGIO(nsIMozIconURI *aIconURI)
{
    GIcon *icon = NULL;
    nsCOMPtr<nsIURL> fileURI;

    // Read icon content
    aIconURI->GetIconURL(getter_AddRefs(fileURI));

    // Get icon for file specified by URI
    if (fileURI) {
        bool isFile;
        nsAutoCString spec;
        fileURI->GetAsciiSpec(spec);
        if (NS_SUCCEEDED(fileURI->SchemeIs("file", &isFile)) && isFile) {
            GFile *file = g_file_new_for_uri(spec.get());
            GFileInfo *fileInfo = g_file_query_info(file,
                                                    G_FILE_ATTRIBUTE_STANDARD_ICON,
                                                    G_FILE_QUERY_INFO_NONE, NULL, NULL);
            g_object_unref(file);
            if (fileInfo) {
                // icon from g_content_type_get_icon doesn't need unref
                icon = g_file_info_get_icon(fileInfo);
                if (icon)
                    g_object_ref(icon);
                g_object_unref(fileInfo);
            }
        }
    }

    // Try to get icon by using MIME type
    if (!icon) {
        nsAutoCString type;
        aIconURI->GetContentType(type);
        // Try to get MIME type from file extension by using nsIMIMEService
        if (type.IsEmpty()) {
            nsCOMPtr<nsIMIMEService> ms(do_GetService("@mozilla.org/mime;1"));
            if (ms) {
                nsAutoCString fileExt;
                aIconURI->GetFileExtension(fileExt);
                ms->GetTypeFromExtension(fileExt, type);
            }
        }
        char *ctype = NULL; // character representation of content type
        if (!type.IsEmpty()) {
            ctype = g_content_type_from_mime_type(type.get());
        }
        if (ctype) {
            icon = g_content_type_get_icon(ctype);
            g_free(ctype);
        }
    }

    // Get default icon theme
    GtkIconTheme *iconTheme = gtk_icon_theme_get_default();
    GtkIconInfo *iconInfo = NULL;
    // Get icon size
    int32_t iconSize = GetIconSize(aIconURI);

    if (icon) {
        // Use icon and theme to get GtkIconInfo
        iconInfo = gtk_icon_theme_lookup_by_gicon(iconTheme,
                   icon, iconSize,
                   (GtkIconLookupFlags)0);
        g_object_unref(icon);
    }

    if (!iconInfo) {
        // Mozilla's mimetype lookup failed. Try the "unknown" icon.
        iconInfo = gtk_icon_theme_lookup_icon(iconTheme,
                                              "unknown", iconSize,
                                              (GtkIconLookupFlags)0);
        if (!iconInfo) {
            return NS_ERROR_NOT_AVAILABLE;
        }
    }

    // Create a GdkPixbuf buffer containing icon and scale it
    GdkPixbuf* buf = gtk_icon_info_load_icon(iconInfo, NULL);
    gtk_icon_info_free(iconInfo);
    if (!buf) {
        return NS_ERROR_UNEXPECTED;
    }

    nsresult rv = ScaleIconBuf(&buf, iconSize);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = moz_gdk_pixbuf_to_channel(buf, aIconURI,
                                   getter_AddRefs(mRealChannel));
    g_object_unref(buf);
    return rv;
}
Пример #24
0
void
ori_open (gchar * fn, gboolean replace)
{

  GString *gstr;
  GFile *fp;
  GFileInputStream *file_in;
  char *nullstr = "NULLSTRING";
  gssize bytes = 1;

  if (!fn)
	fn = nullstr;

  fp = g_file_new_for_uri (fn);

  if (fp == NULL)
	{
	  gchar errmsg[MAX_ERR_MSG_SIZE + 1];
	  g_snprintf (errmsg, MAX_ERR_MSG_SIZE, _("Failed to open <%s>"),
				  fn);
	  gui_app_show_msg (GTK_MESSAGE_ERROR, errmsg);
	  return;
	}

  gstr = g_string_new ("");
  file_in = g_file_read (fp, NULL, NULL);
  
  while (bytes != 0)
	{
	  gchar buf[100] = { 0 };
	  bytes = g_input_stream_read (G_INPUT_STREAM (file_in), buf, 100, NULL, NULL);
	  g_string_append_len (gstr, buf, bytes);
	}
  g_input_stream_close (G_INPUT_STREAM (file_in), NULL, NULL);

  gui_editor_set_text (app->editor, gstr->str);
  gtk_text_buffer_set_modified ((GtkTextBuffer *)app->editor->buffer, FALSE);

  /* Set breakpoints as instructed in the source */
  {
	gchar *str = gstr->str;
	gint ln = 0;

	gchar **lines = NULL;

	g_assert (str);

	lines = g_strsplit (str, "\n", -1);
	g_assert (lines);

	/* for each line */
	while (lines[ln])
	  {
		/* check for ;@ */
		if (strlen (lines[ln]) > 1)
		  {
			if (lines[ln][0] == ';'
				&& lines[ln][1] == '@')
			  {
				/* add breakpoint */
				gui_editor_set_mark (app->editor,
									 ln + 1, TRUE);
				//exit(99);
			  }
		  }
		ln++;
	  }

	g_strfreev (lines);
  }

  g_string_free (gstr, TRUE);
  if (replace)
	_set_file_name (fn);
}
Пример #25
0
static GdkPixbuf *
_gdk_pixbuf_new_from_uri_at_scale (const char  *uri,
				   gint         size,
				   GError     **error)
{
    gboolean result;
    guchar buffer[LOAD_BUFFER_SIZE];
    gssize bytes_read;
    GdkPixbufLoader *loader = NULL;
    GdkPixbuf *pixbuf;	
    GdkPixbufAnimation *animation;
    GdkPixbufAnimationIter *iter;
    gboolean has_frame;
    SizePrepareContext info;
    GFile *file;
    GInputStream *input_stream;

    g_return_val_if_fail (uri != NULL, NULL);

    file = g_file_new_for_uri (uri);

    input_stream = G_INPUT_STREAM (g_file_read (file, NULL, error));
    if (input_stream == NULL) {
        g_object_unref (file);
        return NULL;
    }

    has_frame = FALSE;

    result = FALSE;
    while (!has_frame) {

	bytes_read = g_input_stream_read (input_stream,
					  buffer,
					  sizeof (buffer),
					  NULL,
					  error);
        if (bytes_read == -1) {
            break;
        }
	result = TRUE;
	if (bytes_read == 0) {
	    break;
	}

        if (loader == NULL) {
            loader = create_loader (file, buffer, bytes_read);
            if (1 <= size) {
              info.size = size;
              info.input_width = info.input_height = 0;
              g_signal_connect (loader, "size-prepared", G_CALLBACK (size_prepared_cb), &info);
            }
            g_assert (loader != NULL);
        }

	if (!gdk_pixbuf_loader_write (loader,
				      (unsigned char *)buffer,
				      bytes_read,
				      error)) {
	    result = FALSE;
	    break;
	}

	animation = gdk_pixbuf_loader_get_animation (loader);
	if (animation) {
		iter = gdk_pixbuf_animation_get_iter (animation, NULL);
		if (!gdk_pixbuf_animation_iter_on_currently_loading_frame (iter)) {
			has_frame = TRUE;
		}
		g_object_unref (iter);
	}
    }

    if (loader == NULL) {
        /* This can happen if the above loop was exited due to the
         * g_input_stream_read() call failing. */
        result = FALSE;
    } else if (*error != NULL) {
        gdk_pixbuf_loader_close (loader, NULL);
        result = FALSE;
    } else if (gdk_pixbuf_loader_close (loader, error) == FALSE) {
        if (!g_error_matches (*error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INCOMPLETE_ANIMATION))
          result = FALSE;
        else
          g_clear_error (error);
    }

    if (!result) {
        g_clear_object (&loader);
	g_input_stream_close (input_stream, NULL, NULL);
	g_object_unref (input_stream);
	g_object_unref (file);
	return NULL;
    }

    g_input_stream_close (input_stream, NULL, NULL);
    g_object_unref (input_stream);
    g_object_unref (file);

    pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
    if (pixbuf != NULL) {
	g_object_ref (G_OBJECT (pixbuf));
	g_object_set_data (G_OBJECT (pixbuf), "gnome-original-width",
			   GINT_TO_POINTER (info.input_width));
	g_object_set_data (G_OBJECT (pixbuf), "gnome-original-height",
			   GINT_TO_POINTER (info.input_height));
    }
    g_object_unref (G_OBJECT (loader));

    return pixbuf;
}
Пример #26
0
Файл: xcf.c Проект: STRNG/gimp
static GimpValueArray *
xcf_load_invoker (GimpProcedure         *procedure,
                  Gimp                  *gimp,
                  GimpContext           *context,
                  GimpProgress          *progress,
                  const GimpValueArray  *args,
                  GError               **error)
{
  XcfInfo         info = { 0, };
  GimpValueArray *return_vals;
  GimpImage      *image   = NULL;
  const gchar    *uri;
  gchar          *filename;
  GFile          *file;
  gboolean        success = FALSE;
  gchar           id[14];
  GError         *my_error = NULL;

  gimp_set_busy (gimp);

  uri      = g_value_get_string (gimp_value_array_index (args, 1));
#ifdef GIO_IS_FIXED
  file     = g_file_new_for_uri (uri);
#else
  file     = g_file_new_for_path (uri);
#endif
  filename = g_file_get_parse_name (file);

  info.input = G_INPUT_STREAM (g_file_read (file, NULL, &my_error));

  if (info.input)
    {
      info.gimp        = gimp;
      info.seekable    = G_SEEKABLE (info.input);
      info.progress    = progress;
      info.filename    = filename;
      info.compression = COMPRESS_NONE;

      if (progress)
        {
          gchar *name = g_filename_display_name (filename);
          gchar *msg  = g_strdup_printf (_("Opening '%s'"), name);

          gimp_progress_start (progress, msg, FALSE);

          g_free (msg);
          g_free (name);
        }

      success = TRUE;

      info.cp += xcf_read_int8 (info.input, (guint8 *) id, 14);

      if (! g_str_has_prefix (id, "gimp xcf "))
        {
          success = FALSE;
        }
      else if (strcmp (id + 9, "file") == 0)
        {
          info.file_version = 0;
        }
      else if (id[9] == 'v')
        {
          info.file_version = atoi (id + 10);
        }
      else
        {
          success = FALSE;
        }

      if (success)
        {
          if (info.file_version >= 0 &&
              info.file_version < G_N_ELEMENTS (xcf_loaders))
            {
              image = (*(xcf_loaders[info.file_version])) (gimp, &info, error);

              if (! image)
                success = FALSE;
            }
          else
            {
              g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                           _("XCF error: unsupported XCF file version %d "
                             "encountered"), info.file_version);
              success = FALSE;
            }
        }

      g_object_unref (info.input);

      if (progress)
        gimp_progress_end (progress);
    }
  else
    {
      g_propagate_prefixed_error (error, my_error,
                                  _("Could not open '%s' for reading: "),
                                  filename);
    }

  g_free (filename);
  g_object_unref (file);

  return_vals = gimp_procedure_get_return_values (procedure, success,
                                                  error ? *error : NULL);

  if (success)
    gimp_value_set_image (gimp_value_array_index (return_vals, 1), image);

  gimp_unset_busy (gimp);

  return return_vals;
}
Пример #27
0
static gboolean
drop_urilist (PanelWidget *panel,
	      int          pos,
	      char        *urilist)
{
	char     **uris;
	gboolean   success;
	int        i;

	uris = g_uri_list_extract_uris (urilist);

	success = TRUE;
	for (i = 0; uris[i]; i++) {
		GFile      *file;
		GFileInfo  *info;
		const char *uri;

		uri = uris[i];

		if (g_ascii_strncasecmp (uri, "http:", strlen ("http:")) == 0 ||
		    g_ascii_strncasecmp (uri, "https:", strlen ("https:")) == 0 ||
		    g_ascii_strncasecmp (uri, "ftp:", strlen ("ftp:")) == 0 ||
		    g_ascii_strncasecmp (uri, "gopher:", strlen ("gopher:")) == 0 ||
		    g_ascii_strncasecmp (uri, "ghelp:", strlen ("ghelp:")) == 0 ||
		    g_ascii_strncasecmp (uri, "man:", strlen ("man:")) == 0 ||
		    g_ascii_strncasecmp (uri, "info:", strlen ("info:")) == 0) {
			/* FIXME: probably do this only on link,
			 * in fact, on link always set up a link,
			 * on copy do all the other stuff.  Or something. */
			if ( ! drop_url (panel, pos, uri))
				success = FALSE;
			continue;
		}

		if (g_ascii_strncasecmp (uri, "x-caja-desktop:",
					 strlen ("x-caja-desktop:")) == 0) {
			success = drop_caja_desktop_uri (panel, pos, uri);
			continue;
		}

		file = g_file_new_for_uri (uri);
		info = g_file_query_info (file,
					  "standard::type,"
					  "standard::content-type,"
					  "access::can-execute",
					  G_FILE_QUERY_INFO_NONE,
					  NULL, NULL);

		if (info) {
			const char *mime;
			GFileType   type;
			gboolean    can_exec;

			mime = g_file_info_get_content_type (info);
			type = g_file_info_get_file_type (info);
			can_exec = g_file_info_get_attribute_boolean (info,
								      G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE);

			if (mime &&
			    g_str_has_prefix (mime, "image")) {
				if (!set_background_image_from_uri (panel->toplevel, uri))
					success = FALSE;
			} else if (mime &&
				   (!strcmp (mime, "application/x-mate-app-info") ||
				    !strcmp (mime, "application/x-desktop") ||
				    !strcmp (mime, "application/x-kde-app-info"))) {
				if (panel_profile_id_lists_are_writable ())
					panel_launcher_create (panel->toplevel, pos, uri);
				else
					success = FALSE;
			} else if (type != G_FILE_TYPE_DIRECTORY && can_exec) {
				char *filename;

				filename = g_file_get_path (file);

				if (panel_profile_id_lists_are_writable ())
					/* executable and local, so add a
					 * launcher with it */
					ask_about_launcher (filename, panel,
							    pos, TRUE);
				else
					success = FALSE;
				g_free (filename);
			} else {
				if (!drop_uri (panel, pos, uri,
					       PANEL_ICON_UNKNOWN))
					success = FALSE;
			}
		} else {
			if (!drop_uri (panel, pos, uri, PANEL_ICON_UNKNOWN))
				success = FALSE;
		}

		g_object_unref (info);
		g_object_unref (file);
	}

	g_strfreev (uris);

	return success;
}
Пример #28
0
Файл: xcf.c Проект: STRNG/gimp
static GimpValueArray *
xcf_save_invoker (GimpProcedure         *procedure,
                  Gimp                  *gimp,
                  GimpContext           *context,
                  GimpProgress          *progress,
                  const GimpValueArray  *args,
                  GError               **error)
{
  XcfInfo         info = { 0, };
  GimpValueArray *return_vals;
  GimpImage      *image;
  const gchar    *uri;
  gchar          *filename;
  GFile          *file;
  gboolean        success  = FALSE;
  GError         *my_error = NULL;

  gimp_set_busy (gimp);

  image    = gimp_value_get_image (gimp_value_array_index (args, 1), gimp);
  uri      = g_value_get_string (gimp_value_array_index (args, 3));
#ifdef GIO_IS_FIXED
  file     = g_file_new_for_uri (uri);
#else
  file     = g_file_new_for_path (uri);
#endif
  filename = g_file_get_parse_name (file);

  info.output = G_OUTPUT_STREAM (g_file_replace (file, NULL, FALSE, 0, NULL,
                                                 &my_error));

  if (info.output)
    {
      info.gimp        = gimp;
      info.seekable    = G_SEEKABLE (info.output);
      info.progress    = progress;
      info.filename    = filename;
      info.compression = COMPRESS_RLE;

      if (progress)
        {
          gchar *name = g_filename_display_name (filename);
          gchar *msg  = g_strdup_printf (_("Saving '%s'"), name);

          gimp_progress_start (progress, msg, FALSE);

          g_free (msg);
          g_free (name);
        }

      xcf_save_choose_format (&info, image);

      success = xcf_save_image (&info, image, error);

      g_object_unref (info.output);

      if (progress)
        gimp_progress_end (progress);
    }
  else
    {
      g_propagate_prefixed_error (error, my_error,
                                  _("Could not open '%s' for writing: "),
                                  filename);
    }

  g_free (filename);
  g_object_unref (file);

  return_vals = gimp_procedure_get_return_values (procedure, success,
                                                  error ? *error : NULL);

  gimp_unset_busy (gimp);

  return return_vals;
}
Пример #29
0
int
ddb_gvfs_scandir (const char *dir, struct dirent ***namelist, int (*selector) (const struct dirent *), int (*cmp) (const struct dirent **, const struct dirent **))
{
  GQueue *file_list = g_queue_new ();
  GQueue *dir_list = g_queue_new ();
  g_queue_push_head (dir_list, g_file_new_for_uri (dir));

  GFile *gdir;
  while ((gdir = g_queue_pop_head (dir_list)) != NULL)
    {
      GFileEnumerator *file_enumerator = g_file_enumerate_children (gdir, G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, NULL);
      if (file_enumerator == NULL)
        {
          g_object_unref (gdir);
          continue;
        }

      GFileInfo *file_info;
      GFile *child_file;

     while ((file_info = g_file_enumerator_next_file (file_enumerator, NULL, NULL)) != NULL)
        {
          child_file = g_file_get_child (gdir, g_file_info_get_name (file_info));
          g_object_unref (file_info);

          if (g_file_query_file_type (child_file, G_FILE_QUERY_INFO_NONE, NULL) == G_FILE_TYPE_DIRECTORY)
            g_queue_push_head (dir_list, child_file);
          else
            {
              g_queue_push_tail (file_list, g_file_get_uri (child_file));
              g_object_unref (child_file);
            }
        }

      g_file_enumerator_close (file_enumerator, NULL, NULL);
      g_object_unref (file_enumerator);

      g_object_unref (gdir);
    }

  g_queue_free (dir_list);

  int num_files = 0;
  *namelist = malloc (sizeof(void *) * g_queue_get_length (file_list));

  char *fname;
  while ((fname = g_queue_pop_head (file_list)) != NULL)
    {
      struct dirent entry;
      strncpy (entry.d_name, fname, sizeof(entry.d_name) - 1);
      entry.d_name[sizeof(entry.d_name) - 1] = '\0';

      if (selector == NULL || (selector && selector(&entry)))
        {
          (*namelist)[num_files] = calloc (1, sizeof (struct dirent));
          strcpy ((*namelist)[num_files]->d_name, entry.d_name);
          num_files++;
        }

      g_free (fname);
    }

  g_queue_free (file_list);
  return num_files;
}
Пример #30
0
bool TextFileSaver::step()
{
    GOutputStream *stream = NULL;

    // Open the file.
    GFile *file = g_file_new_for_uri(uri());
    GFileOutputStream *fileStream = g_file_replace(file,
                                                   NULL,
                                                   TRUE,
                                                   G_FILE_CREATE_NONE,
                                                   NULL,
                                                   &m_error);
    if (!fileStream)
    {
        g_object_unref(file);
        return true;
    }

    // Open the encoding converter and setup the input stream.
    if (m_encoding == "UTF-8")
        stream = G_OUTPUT_STREAM(fileStream);
    else
    {
        GCharsetConverter *encodingConverter =
            g_charset_converter_new(m_encoding.c_str(), "UTF-8", &m_error);
        if (!encodingConverter)
        {
            g_object_unref(file);
            g_object_unref(fileStream);
            return true;
        }
        stream =
            g_converter_output_stream_new(G_OUTPUT_STREAM(fileStream),
                                          G_CONVERTER(encodingConverter));
        g_object_unref(fileStream);
        g_object_unref(encodingConverter);
    }

    // Convert and write.
    int size =
        g_output_stream_write(stream,
                              m_text.get(),
                              m_length == -1 ? strlen(m_text.get()) : m_length,
                              NULL,
                              &m_error);
    if (size == -1)
    {
        g_object_unref(file);
        g_object_unref(stream);
        return true;
    }

    if (!g_output_stream_close(stream, NULL, &m_error))
    {
        g_object_unref(file);
        g_object_unref(stream);
        return true;
    }
    g_object_unref(stream);

    // Get the time when the file was last modified.
    GFileInfo *fileInfo;
    fileInfo =
        g_file_query_info(file,
                          G_FILE_ATTRIBUTE_TIME_MODIFIED,
                          G_FILE_QUERY_INFO_NONE,
                          NULL,
                          &m_error);
    if (!fileInfo)
    {
        g_object_unref(file);
        return true;
    }
    m_modifiedTime.seconds = g_file_info_get_attribute_uint64(
        fileInfo,
        G_FILE_ATTRIBUTE_TIME_MODIFIED);
    g_object_unref(fileInfo);
    fileInfo =
        g_file_query_info(file,
                          G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
                          G_FILE_QUERY_INFO_NONE,
                          NULL,
                          &m_error);
    if (!fileInfo)
    {
        g_object_unref(file);
        return true;
    }
    m_modifiedTime.microSeconds = g_file_info_get_attribute_uint32(
        fileInfo,
        G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC);
    g_object_unref(fileInfo);
    g_object_unref(file);
    return true;
}