Python gi.repository.GdkPixbuf.Pixbuf() Examples

The following are 30 code examples of gi.repository.GdkPixbuf.Pixbuf(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gi.repository.GdkPixbuf , or try the search function .
Example #1
Source File: uistuff.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def createCombo(combo, data=[], name=None, ellipsize_mode=None):
    if name is not None:
        combo.set_name(name)
    lst_store = Gtk.ListStore(Pixbuf, str)
    for row in data:
        lst_store.append(row)
    combo.clear()

    combo.set_model(lst_store)
    crp = Gtk.CellRendererPixbuf()
    crp.set_property('xalign', 0)
    crp.set_property('xpad', 2)
    combo.pack_start(crp, False)
    combo.add_attribute(crp, 'pixbuf', 0)

    crt = Gtk.CellRendererText()
    crt.set_property('xalign', 0)
    crt.set_property('xpad', 4)
    combo.pack_start(crt, True)
    combo.add_attribute(crt, 'text', 1)
    if ellipsize_mode is not None:
        crt.set_property('ellipsize', ellipsize_mode) 
Example #2
Source File: util.py    From python-eduvpn-client with GNU General Public License v3.0 6 votes vote down vote up
def bytes2pixbuf(data,
                 width=icon_size['width'],
                 height=icon_size['height'],
                 display_name=None):  # type: (bytes, int, int, Optional[str]) -> GdkPixbuf.Pixbuf
    """
    converts raw bytes into a GTK PixBug

    args:
        data (bytes): raw bytes
        width (int): width of image
        height (int): height of images

    returns:
        GtkPixbuf: a GTK Pixbuf

    """
    loader = GdkPixbuf.PixbufLoader()
    loader.set_size(width, height)
    try:
        loader.write(data)
        loader.close()
    except (GLib.Error, TypeError) as e:
        logger.error(u"can't process icon for {}: {}".format(display_name, str(e)))
    else:
        return loader.get_pixbuf() 
Example #3
Source File: imageactions.py    From vimiv with MIT License 6 votes vote down vote up
def save_pixbuf(pixbuf, filename, update_orientation_tag=False):
    """Save the image with all the exif keys that exist if we have exif support.

    NOTE: This is used to override edited images, not to save images to new
        paths. The filename must exist as it is used to retrieve the image
        format and exif data.

    Args:
        pixbuf: GdkPixbuf.Pixbuf image to act on.
        filename: Name of the image to save.
        update_orientation_tag: If True, set orientation tag to NORMAL.
    """
    if not os.path.isfile(filename):
        raise FileNotFoundError("Original file to retrieve data from not found")
    # Get needed information
    info = GdkPixbuf.Pixbuf.get_file_info(filename)[0]
    extension = info.get_extensions()[0]
    if _has_exif:
        exif = GExiv2.Metadata(filename)
    # Save
    pixbuf.savev(filename, extension, [], [])
    if _has_exif and exif.get_supports_exif():
        if update_orientation_tag:
            exif.set_orientation(GExiv2.Orientation.NORMAL)
        exif.save_file() 
Example #4
Source File: image.py    From vimiv with MIT License 6 votes vote down vote up
def _update(self):
        """Show the final image."""
        if not self._app.get_paths() or self._faulty_image:
            return
        # Scale image
        pbo_width = self._pixbuf_original.get_width()
        pbo_height = self._pixbuf_original.get_height()
        pbf_width = int(pbo_width * self.zoom_percent)
        pbf_height = int(pbo_height * self.zoom_percent)
        # Rescaling of svg
        if is_svg(self._app.get_path()) and settings["rescale_svg"].get_value():
            pixbuf_final = GdkPixbuf.Pixbuf.new_from_file_at_scale(
                self._app.get_path(), -1, pbf_height, True)
        else:
            pixbuf_final = self._pixbuf_original.scale_simple(
                pbf_width, pbf_height, GdkPixbuf.InterpType.BILINEAR)
        self.set_from_pixbuf(pixbuf_final)
        # Update the statusbar
        self._app["statusbar"].update_info() 
Example #5
Source File: thumbnails.py    From gprime with GNU General Public License v2.0 6 votes vote down vote up
def find_mime_type_pixbuf(mime_type):
    try:
        icontmp = mime_type.replace('/','-')
        newicon = "gnome-mime-%s" % icontmp
        try:
            return _icon_theme.load_icon(newicon,48,0)
        except:
            icontmp = mime_type.split('/')[0]
            try:
                newicon = "gnome-mime-%s" % icontmp
                return _icon_theme.load_icon(newicon,48,0)
            except:
                return GdkPixbuf.Pixbuf.new_from_file(ICON)
    except:
        return GdkPixbuf.Pixbuf.new_from_file(ICON)
#-------------------------------------------------------------------------
#
# run_thumbnailer
#
#------------------------------------------------------------------------- 
Example #6
Source File: util.py    From python-eduvpn-client with GNU General Public License v3.0 6 votes vote down vote up
def pil2pixbuf(img):  # type: (Any) -> GdkPixbuf.Pixbuf
    """
    Convert a pillow (pil) object to a pixbuf

    args:
        img: (pil.Image): A pillow image

    returns:
        GtkPixbuf: a GTK Pixbuf
    """
    width, height = img.size
    if img.mode != "RGB":  # gtk only supports RGB
        img = img.convert(mode='RGB')
    bytes = GLib.Bytes(img.tobytes())
    pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(bytes, GdkPixbuf.Colorspace.RGB, False, 8, width, height, width * 3)
    return pixbuf 
Example #7
Source File: image.py    From vimiv with MIT License 6 votes vote down vote up
def __init__(self, app):
        """Set default values for attributes."""
        super(Image, self).__init__()
        self._app = app

        # Settings and defaults
        self.fit_image = "overzoom"
        self._pixbuf_iter = GdkPixbuf.PixbufAnimationIter()
        self._pixbuf_original = GdkPixbuf.Pixbuf()
        self.zoom_percent = 1
        self._identifier = 0
        self._size = (1, 1)
        self._timer_id = 0
        self._faulty_image = False

        # Connect signals
        self._app["transform"].connect("changed", self._on_image_changed)
        self._app["commandline"].search.connect("search-completed",
                                                self._on_search_completed)
        settings.connect("changed", self._on_settings_changed) 
Example #8
Source File: applications.py    From zim-desktop-wiki with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
		GObject.GObject.__init__(self)
		self.set_model(
			Gtk.ListStore(str, object, GdkPixbuf.Pixbuf) # NAME_COL, APP_COL, ICON_COL
		)

		cell = Gtk.CellRendererPixbuf()
		self.pack_start(cell, False)
		cell.set_property('xpad', 5)
		self.add_attribute(cell, 'pixbuf', self.ICON_COL)

		cell = Gtk.CellRendererText()
		self.pack_start(cell, True)
		cell.set_property('xalign', 0.0)
		cell.set_property('xpad', 5)
		self.add_attribute(cell, 'text', self.NAME_COL) 
Example #9
Source File: customtools.py    From zim-desktop-wiki with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, manager):
		GObject.GObject.__init__(self)
		self.manager = manager

		model = Gtk.ListStore(GdkPixbuf.Pixbuf, str, str)
				# PIXBUF_COL, TEXT_COL, NAME_COL
		self.set_model(model)
		self.set_headers_visible(False)

		self.get_selection().set_mode(Gtk.SelectionMode.BROWSE)

		cr = Gtk.CellRendererPixbuf()
		column = Gtk.TreeViewColumn('_pixbuf_', cr, pixbuf=self.PIXBUF_COL)
		self.append_column(column)

		cr = Gtk.CellRendererText()
		column = Gtk.TreeViewColumn('_text_', cr, markup=self.TEXT_COL)
		self.append_column(column)

		self.refresh() 
Example #10
Source File: tag_editor.py    From gtg with GNU General Public License v3.0 6 votes vote down vote up
def __load_icon(self):
        """
        Loads emblem icons from the current icon theme

        Sometimes an icon can't be loaded because of a bug in system
        libraries, e.g. bug #1079587. Gracefuly degradate and skip
        the loading of a corrupted icon.
        """
        self.symbol_model = Gtk.ListStore(GdkPixbuf.Pixbuf, str)
        for icon in Gtk.IconTheme.get_default().list_icons(context="Emblems"):
            try:
                img = Gtk.IconTheme.get_default().load_icon(icon, 16, 0)
                self.symbol_model.append([img, icon])
            except GObject.GError:
                log.error(f"Failed to load icon '{icon}'")
        self.symbol_iv.set_model(self.symbol_model)
        self.loaded = True

    # PUBLIC IF ##### 
Example #11
Source File: color_grid.py    From wpgtk with GNU General Public License v2.0 6 votes vote down vote up
def render_theme(self):
        sample_path = files.get_sample_path(self.selected_file)

        try:
            self.color_list = color.get_color_list(self.selected_file)
        except SystemExit:
            self.color_list = themer.set_fallback_theme(self.selected_file)
        self.render_buttons()

        try:
            self.pixbuf_sample = GdkPixbuf.Pixbuf\
                .new_from_file_at_size(sample_path, width=500, height=300)
        except:
            sample.create_sample(self.color_list, sample_path)
            self.pixbuf_sample = GdkPixbuf.Pixbuf\
                .new_from_file_at_size(sample_path, width=500, height=300)

        self.sample.set_from_pixbuf(self.pixbuf_sample)
        self.parent.sample.set_from_pixbuf(self.pixbuf_sample) 
Example #12
Source File: thumbnails.py    From gprime with GNU General Public License v2.0 6 votes vote down vote up
def get_thumbnail_path(src_file, mtype=None, rectangle=None, size=SIZE_NORMAL):
    """
    Return the path to the thumbnail image associated with the
    source file passed to the function. If the thumbnail does not exist,
    or if it is older than the source file, we create a new thumbnail image.

    :param src_file: Source media file
    :type src_file: unicode
    :param mime_type: mime type of the source file
    :type mime_type: unicode
    :param rectangle: subsection rectangle
    :type rectangle: tuple
    :returns: thumbnail representing the source file
    :rtype: GdkPixbuf.Pixbuf
    """
    filename = __build_thumb_path(src_file, rectangle, size)
    if not os.path.isfile(src_file):
        return os.path.join(IMAGE_DIR, "image-missing.png")
    else:
        if (not os.path.isfile(filename)) or (
                os.path.getmtime(src_file) > os.path.getmtime(filename)):
            if not __create_thumbnail_image(src_file, mtype, rectangle, size):
                return os.path.join(IMAGE_DIR, "document.png")
        return os.path.abspath(filename) 
Example #13
Source File: notebookdialog.py    From zim-desktop-wiki with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, notebooklist=None):
		'''Constructor. If "notebooklist" is None, the default list as
		provided by zim.notebook.get_notebook_list() is used.

		@param notebooklist: a list of L{NotebookInfo} objects
		'''
		Gtk.ListStore.__init__(self, bool, str, str, GdkPixbuf.Pixbuf, object)
						# OPEN_COL, NAME_COL, TEXT_COL PIXBUF_COL INFO_COL

		if notebooklist is None:
			self.notebooklist = get_notebook_list()
		else:
			self.notebooklist = notebooklist

		self._loading = True
		for info in self.notebooklist:
			self._append(info)
		self._loading = False 
Example #14
Source File: widgets.py    From zim-desktop-wiki with GNU General Public License v2.0 6 votes vote down vote up
def on_update_preview(self, *a):
		try:
			filename = self.filechooser.get_preview_filename()

			info, w, h = GdkPixbuf.Pixbuf.get_file_info(filename)
			if w <= 128 and h <= 128:
				# Show icons etc. on real size
				pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
			else:
				# Scale other images to fit the window
				pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(filename, 128, 128)
			self.preview_widget.set_from_pixbuf(pixbuf)
			self.filechooser.set_preview_widget_active(True)
		except:
			self.filechooser.set_preview_widget_active(False)
		return 
Example #15
Source File: widgets.py    From zim-desktop-wiki with GNU General Public License v2.0 6 votes vote down vote up
def rotate_pixbuf(pixbuf):
	'''Rotate the pixbuf to match orientation from EXIF info.
	This is intended for e.g. photos that have EXIF information that
	shows how the camera was held.
	@returns: a new version of the pixbuf or the pixbuf itself.
	'''
	# For newer gtk we could use GdkPixbuf.Pixbuf.apply_embedded_orientation

	# Values for orientation seen in some random snippet in gtkpod
	o = pixbuf.get_option('orientation')
	if o:
		o = int(o)
	if o == 3: # 180 degrees
		return pixbuf.rotate_simple(Gdk.PIXBUF_ROTATE_UPSIDEDOWN)
	elif o == 6: # 270 degrees
		return pixbuf.rotate_simple(Gdk.PIXBUF_ROTATE_CLOCKWISE)
	elif o == 9: # 90 degrees
		return pixbuf.rotate_simple(Gdk.PIXBUF_ROTATE_COUNTERCLOCKWISE)
	else:
		# No rotation info, older gtk version, or advanced transpose
		return pixbuf 
Example #16
Source File: image_enhance.py    From vimiv with MIT License 6 votes vote down vote up
def enhance_bc(pixbuf, brightness, contrast):
    """Enhance brightness and contrast of a GdkPixbuf.Pixbuf.

    Args:
        pixbuf: Original GdkPixbuf.Pixbuf to work with.
        brightness: Float between -1.0 and 1.0 to change brightness.
        contrast: Float between -1.0 and 1.0 to change contrast.
    Return:
        The enhanced GdkPixbuf.Pixbuf
    """
    data = pixbuf.get_pixels()
    has_alpha = pixbuf.get_has_alpha()
    c_has_alpha = 1 if has_alpha else 0  # Numbers are easier for C
    # Update plain bytes using C extension
    # Pylint does not read this properly
    # pylint: disable=no-member
    data = _image_enhance.enhance_bc(data, c_has_alpha, brightness, contrast)
    gdata = GLib.Bytes.new(data)
    return GdkPixbuf.Pixbuf.new_from_bytes(gdata,
                                           pixbuf.get_colorspace(),
                                           has_alpha,
                                           pixbuf.get_bits_per_sample(),
                                           pixbuf.get_width(),
                                           pixbuf.get_height(),
                                           pixbuf.get_rowstride()) 
Example #17
Source File: widgets.py    From badKarma with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, database, host, *args, **kwargs):
		super(PortsTree, self).__init__(*args, **kwargs)
		""" Single host ports treeview class """

		self.set_model(Gtk.ListStore(GdkPixbuf.Pixbuf, int, str, str, str, str, str, int))
		self.port_liststore = self.get_model()
		
		for i, column_title in enumerate(["#","Port", "State", "Type", "Service", "Banner", "Fingerprint"]):
			if i == 0:

				renderer = Gtk.CellRendererPixbuf()
				column = Gtk.TreeViewColumn(column_title, renderer, pixbuf=0)
			else:
				renderer = Gtk.CellRendererText()
				column = Gtk.TreeViewColumn(column_title, renderer, text=i)

			self.append_column(column)

		self.show_all()

		self.database = database
		self.host     = host

		self.refresh(self.database, self.host) 
Example #18
Source File: alttoolbar_type.py    From alternative-toolbar with GNU General Public License v3.0 6 votes vote down vote up
def display_song_album_art_callback(self, *args):
        # key, filename, data, entry):
        """
          RBExtDB signal callback to display the album-art
        """
        # rhythmbox 3.2 breaks the API - need to find the parameter with the
        # pixbuf
        data = None
        for data in args:
            if isinstance(data, GdkPixbuf.Pixbuf):
                break

        if ((data is not None) and (isinstance(data, GdkPixbuf.Pixbuf))):
            self.cover_pixbuf = data
            scale_cover = \
                self.cover_pixbuf.scale_simple(34, 34,
                                               GdkPixbuf.InterpType.HYPER)

            self.album_cover.set_from_pixbuf(scale_cover)
        else:
            self.cover_pixbuf = None
            self.album_cover.clear()

        self.album_cover.trigger_tooltip_query() 
Example #19
Source File: treeviews.py    From bokken with GNU General Public License v2.0 6 votes vote down vote up
def create_exports_columns(self):

        self.exp_pix = GdkPixbuf.Pixbuf.new_from_file(datafile_path('export.png'))
        rendererPix = Gtk.CellRendererPixbuf()
        rendererText = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("Offset")
        column.set_spacing(5)
        column.pack_start(rendererPix, False)
        column.pack_start(rendererText, True)
        column.set_attributes(rendererText, text=1)
        column.set_attributes(rendererPix, pixbuf=0)
        self.store.set_sort_column_id(1,Gtk.SortType.ASCENDING)
        column.set_sort_column_id(1)
        self.append_column(column)

        rendererText = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("Name", rendererText, text=2)
        column.set_sort_column_id(2)
        self.append_column(column)

        rendererText = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("Ordinal", rendererText, text=3)
        column.set_sort_column_id(3)
        self.append_column(column)
        self.set_model(self.store) 
Example #20
Source File: treeviews.py    From bokken with GNU General Public License v2.0 6 votes vote down vote up
def create_functions_columns(self):

        rendererText = Gtk.CellRendererText()
        rendererText.tooltip_handle = self.connect('motion-notify-event', self.fcn_tooltip)
        rendererPix = Gtk.CellRendererPixbuf()
        self.fcn_pix = GdkPixbuf.Pixbuf.new_from_file(datafile_path('function.png'))
        self.bb_pix = GdkPixbuf.Pixbuf.new_from_file(datafile_path('block.png'))
        column = Gtk.TreeViewColumn("Function")
        column.set_spacing(5)
        column.pack_start(rendererPix, False)
        column.pack_start(rendererText, True)
        column.set_attributes(rendererText, text=1)
        column.set_attributes(rendererPix, pixbuf=0)
        column.set_sort_column_id(1)
        self.store.set_sort_column_id(1,Gtk.SortType.ASCENDING)
        self.append_column(column)
        self.set_model(self.store) 
Example #21
Source File: cheatsheet_dialog.py    From bokken with GNU General Public License v2.0 6 votes vote down vote up
def populate_tree(self, groups):
        """ Accepts an array of n rows made of 2 elements each, and returns a TreeView."""

        store = Gtk.TreeStore(GdkPixbuf.Pixbuf, str, str)

        for group in groups:
            #header = '<span background=\"#5a58ff\" foreground=\"white\"><b> ' + group.replace('_', ' ').capitalize() + '\t</b></span>'
            header = group.replace('_', ' ').capitalize()
            it = store.append(None, [self.pix, header, ''])
            for row in eval('self.' + group):
                store.append(it, [None, row[0], row[1]])

        tv = Gtk.TreeView(store)
        #tv.set_rules_hint(True)
        #tv.set_enable_tree_lines(True)
        tv.set_show_expanders(False)
        tv.set_level_indentation(10)
        tv.expand_all()

        return tv 
Example #22
Source File: test_icon.py    From ubuntu-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def test_get_from_name_load_icon_exception(self):
        """On exception `load_icon()` should be called again."""
        m_pixbuf = mock.Mock(spec=GdkPixbuf.Pixbuf, get_height=lambda: DEFAULT_SIZE)
        with patch_load_icon(side_effect=[Exception, m_pixbuf]) as m_load_icon, patch_log() as m_log:
            m_load_icon.return_value.scale_simple.return_value = m_pixbuf
            pixbuf = get_from_name()
        self.assertEqual(
            m_load_icon.call_args_list,
            [mock.call("gtk-execute", 24, 0), mock.call("gtk-execute", 24, 0)]
        )
        self.assertEqual(m_log.warning.call_count, 1)
        self.assertEqual(m_log.error.call_count, 0)
        self.assertEqual(pixbuf, m_pixbuf)
        # more than one exception would fallback to random alter icon loading
        with patch_load_icon(side_effect=[Exception, Exception, m_pixbuf]) as m_load_icon, patch_log() as m_log:
            m_load_icon.return_value.scale_simple.return_value = m_pixbuf
            pixbuf = get_from_name()
        self.assertEqual(
            m_load_icon.call_args_list,
            [mock.call("gtk-execute", 24, 0), mock.call("gtk-execute", 24, 0), mock.call(mock.ANY, 24, 0)]
        )
        self.assertEqual(m_log.warning.call_count, 1)
        self.assertEqual(m_log.error.call_count, 1)
        self.assertEqual(pixbuf, m_pixbuf) 
Example #23
Source File: test_icon.py    From ubuntu-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def test_get_from_list(self):
        """Only the last working pixbuf loaded should be returned."""
        m_pixbuf = mock.Mock(spec=GdkPixbuf.Pixbuf, get_height=lambda: DEFAULT_SIZE)
        names = ("icon-name1", "icon-name2")
        size = 1234
        with patch_load_icon() as m_load_icon, patch_log() as m_log, patch_get_from_name() as m_get_from_name:
            m_load_icon.side_effect = [None, m_pixbuf]
            pixbuf = get_from_list(names, size)
        self.assertEqual(
            m_load_icon.call_args_list, [
                mock.call("icon-name1", size, Gtk.IconLookupFlags.USE_BUILTIN),
                mock.call("icon-name2", size, Gtk.IconLookupFlags.USE_BUILTIN)
            ]
        )
        self.assertEqual(m_log.method_calls, [])
        self.assertEqual(m_get_from_name.call_args_list, [])
        self.assertEqual(pixbuf, m_pixbuf) 
Example #24
Source File: test_icon.py    From ubuntu-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def test_get_from_list_exception(self):
        """On exception the next pixbuf is returned."""
        m_pixbuf = mock.Mock(spec=GdkPixbuf.Pixbuf, get_height=lambda: DEFAULT_SIZE)
        names = ("icon-name1", "icon-name2")
        size = 1234
        with patch_load_icon() as m_load_icon, patch_log() as m_log, patch_get_from_name() as m_get_from_name:
            m_load_icon.side_effect = [Exception, m_pixbuf]
            pixbuf = get_from_list(names, size)
        self.assertEqual(
            m_load_icon.call_args_list, [
                mock.call("icon-name1", size, Gtk.IconLookupFlags.USE_BUILTIN),
                mock.call("icon-name2", size, Gtk.IconLookupFlags.USE_BUILTIN)
            ]
        )
        self.assertEqual(
            m_log.method_calls,
            [mock.call.warning('get_from_list for icon-name1 failed, try next')]
        )
        self.assertEqual(m_get_from_name.call_args_list, [])
        self.assertEqual(pixbuf, m_pixbuf) 
Example #25
Source File: test_icon.py    From ubuntu-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def test_get_from_mime_type(self):
        """By defaults returns the pixbuf using `get_from_list()`."""
        m_pixbuf = mock.Mock(spec=GdkPixbuf.Pixbuf)
        mime = "application/vnd.debian.binary-package"
        size = 1234
        with patch_log() as m_log, patch_get_from_list() as m_get_from_list, patch_get_from_name() as m_get_from_name:
            m_get_from_list.return_value = m_pixbuf
            pixbuf = get_from_mime_type(mime, size)
        self.assertEqual(
            m_get_from_list.call_args_list, [
                mock.call(["application-vnd.debian.binary-package", "package-x-generic"], size=size),
            ]
        )
        self.assertEqual(m_log.method_calls, [])
        self.assertEqual(m_get_from_name.call_args_list, [])
        self.assertEqual(pixbuf, m_pixbuf) 
Example #26
Source File: test_icon.py    From ubuntu-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def test_get_from_mime_type_fallback(self):
        """Should fallback to `get_from_name()` on exception."""
        m_pixbuf = mock.Mock(spec=GdkPixbuf.Pixbuf)
        mime = "application/vnd.debian.binary-package"
        size = 1234
        with patch_log() as m_log, patch_get_from_list() as m_get_from_list, patch_get_from_name() as m_get_from_name:
            m_get_from_list.side_effect = [Exception]
            m_get_from_name.return_value = m_pixbuf
            pixbuf = get_from_mime_type(mime, size)
        self.assertEqual(
            m_get_from_list.call_args_list, [
                mock.call(["application-vnd.debian.binary-package", "package-x-generic"], size=size),
            ]
        )
        self.assertEqual(
            m_log.method_calls, [mock.call.error('get_from_mime_type failed: ')])
        self.assertEqual(m_get_from_name.call_args_list, [mock.call(size=size)])
        self.assertEqual(pixbuf, m_pixbuf) 
Example #27
Source File: sections_treeview.py    From bokken with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, uicore, textviews):
        super(SectionsView ,self).__init__()

        self.uicore = uicore

        self.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        self.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)

        self.sections_tree = SectionsTreeView(self.uicore, textviews)

        self.fcn_pix = GdkPixbuf.Pixbuf.new_from_file(datafile_path('function.png'))
        self.data_sec_pix = GdkPixbuf.Pixbuf.new_from_file(datafile_path('data-sec.png'))

        # Add Textview to Scrolled Window
        self.add(self.sections_tree)
        self.show_all() 
Example #28
Source File: test_icon.py    From ubuntu-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def test_get_from_file_fallback(self):
        """Should fallback to `get_from_name()` on exception."""
        m_pixbuf = mock.Mock(spec=GdkPixbuf.Pixbuf)
        file_path = "/path/to/file"
        size = 1234
        with patch_log() as m_log, patch_get_from_name() as m_get_from_name, \
                patch_new_from_file_at_size() as m_new_from_file_at_size:
            m_new_from_file_at_size.side_effect = [Exception]
            m_get_from_name.return_value = m_pixbuf
            pixbuf = get_from_file(file_path, size)
        self.assertEqual(m_get_from_name.call_args_list, [mock.call(only_path=False, size=1234)])
        self.assertEqual(m_log.method_calls, [mock.call.error('get_from_file failed: ')])
        self.assertEqual(
            m_new_from_file_at_size.call_args_list, [mock.call(file_path, size, size)])
        self.assertEqual(m_get_from_name.call_args_list, [mock.call(only_path=False, size=1234)])
        self.assertEqual(
            m_log.method_calls, [mock.call.error('get_from_file failed: ')])
        self.assertEqual(pixbuf, m_pixbuf) 
Example #29
Source File: widget_chooser.py    From hazzy with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
        Gtk.IconView.__init__(self)

        # Add style class
        style_context = self.get_style_context()
        style_context.add_class("WidgetChooser")

        self.set_text_column(0)
        self.set_pixbuf_column(1)
        self.set_item_width(130)
        self.set_columns(1)

        self.model = Gtk.ListStore(str, GdkPixbuf.Pixbuf, str)
        self.set_model(self.model)

        # Enable DnD
        self.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.COPY)
        self.connect("drag-data-get", self.on_drag_data_get)
        self.connect("drag-begin", self.on_drag_begin)
        self.connect("drag-end", self.on_drag_end)
        self.drag_source_set_target_list(None)
        self.drag_source_add_text_targets()
        self.drag = False

        self.connect('focus-out-event', self.on_focus_out) 
Example #30
Source File: widget_chooser.py    From hazzy with GNU General Public License v2.0 6 votes vote down vote up
def populate(self, categories):

        for category, packages in sorted(categories.items()):
            expander = Expander(category)
            icon_vew = WidgetView()
            expander.add(icon_vew)
            self.box.pack_start(expander, False, False, 0)

            count = 0
            for package, info in sorted(packages.items()):
                name = info.get('name', package)
                import_str = info['import_str']
                image_path = info.get('image')

                if os.path.exists(image_path):
                    image = GdkPixbuf.Pixbuf.new_from_file(image_path)
                    w, h = image.get_width(), image.get_height()
                    scale = 200 / float(w)
                    image = image.scale_simple(w * scale, h * scale, GdkPixbuf.InterpType.BILINEAR)
                else:
                    image = self.image_missing

                icon_vew.add_item(name, image, import_str)
                count += 1
            expander.set_item_count(count)