Python gi.repository() Examples

The following are 30 code examples of gi.repository(). 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 , or try the search function .
Example #1
Source File: constfunc.py    From gprime with GNU General Public License v2.0 8 votes vote down vote up
def is_quartz():
    """
    Tests to see if Python is currently running with gtk and
    windowing system is Mac OS-X's "quartz".
    """
    if mac():
        try:
            import gi
            gi.require_version('Gtk', '3.0')
            gi.require_version('Gdk', '3.0')
            from gi.repository import Gtk
            from gi.repository import Gdk
        except ImportError:
            return False
        return Gdk.Display.get_default().__class__.__name__.endswith("QuartzDisplay")
    return False 
Example #2
Source File: images.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def get_icon_by_name(name, size=256):
    try:
        gi.require_version('Gtk', '3.0')
        from gi.repository import Gtk
    except:
        raise MissingDependencies(
            'Unable to lookup system icons!',
            ['gir1.2-gtk-3.0']
        )

    icon_theme = Gtk.IconTheme.get_default()
    icon = icon_theme.lookup_icon(name, size, 0)
    if icon:
        file_path = icon.get_filename()
        _type = get_type_by_filepath(file_path)
        return _type(file_path)
    else:
        raise IconNotFound(name) 
Example #3
Source File: utils.py    From AutomaThemely with GNU General Public License v3.0 6 votes vote down vote up
def notify(message, title='AutomaThemely'):
    import gi
    gi.require_version('Notify', '0.7')
    from gi.repository import Notify, GLib

    if not Notify.is_initted():
        Notify.init('AutomaThemely')

    n = Notify.Notification.new(title, message, get_resource('automathemely.svg'))
    try:  # I don't even know... https://bugzilla.redhat.com/show_bug.cgi?id=1582833
        n.show()
    except GLib.GError as e:
        if str(e) != 'g-dbus-error-quark: Unexpected reply type (16)' \
                and str(e) != 'g-dbus-error-quark: GDBus.Error:org.freedesktop.DBus.Error.NoReply: Message recipient ' \
                              'disconnected from message bus without replying (4)':
            raise e 
Example #4
Source File: stray.py    From Dragonfire with MIT License 6 votes vote down vote up
def __init__(self):
        """Initialization method of :class:`dragonfire.stray.SystemTrayIcon` class.
        """

        import gi
        gi.require_version('Gtk', '3.0')
        from gi.repository import Gtk
        self.Gtk = Gtk

        self.icon = self.Gtk.StatusIcon()
        self.icon.set_title("Dragonfire")
        if os.path.isfile(TRAY_ICON):
            self.icon.set_from_file(TRAY_ICON)
        else:
            self.icon.set_from_file(DEVELOPMENT_DIR + TRAY_ICON_ALT)
        self.icon.connect('popup-menu', self.popup_menu)
        self.Gtk.main() 
Example #5
Source File: Pyperclip.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 6 votes vote down vote up
def init_gi_clipboard():
    import gi
    gi.require_version('Gtk', '3.0')
    from gi.repository import Gtk, Gdk
    cb = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

    def copy_gi(text):
        cb.set_text(text, -1)
        cb.store()

    def paste_gi():
        clipboardContents = cb.wait_for_text()
        # for python 2, returns None if the clipboard is blank.
        if clipboardContents is None:
            return ''
        else:
            return clipboardContents

    return copy_gi, paste_gi 
Example #6
Source File: notifier.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, autokeyApp):
        Notify.init("AutoKey")
        # Used to rate-limit error notifications to 1 per second. Without this, two notifications per second cause the
        # following exception, which in turn completely locks up the GUI:
        # gi.repository.GLib.GError: g-io-error-quark:
        # GDBus.Error:org.freedesktop.Notifications.Error.ExcessNotificationGeneration:
        # Created too many similar notifications in quick succession (36)
        self.last_notification_timestamp = datetime.datetime.now()
        self.app = autokeyApp
        self.configManager = autokeyApp.service.configManager

        self.indicator = AppIndicator3.Indicator.new("AutoKey", cm.ConfigManager.SETTINGS[cm.NOTIFICATION_ICON],
                                                AppIndicator3.IndicatorCategory.APPLICATION_STATUS)
                                                
        self.indicator.set_attention_icon(common.ICON_FILE_NOTIFICATION_ERROR)
        self.update_visible_status()           
        self.rebuild_menu() 
Example #7
Source File: statusicon.py    From syncthing-gtk with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
		StatusIcon.__init__(self, *args, **kwargs)
		
		try:
			import gi
			gi.require_version('AppIndicator3', '0.1')
			from gi.repository import AppIndicator3 as appindicator
			
			self._status_active  = appindicator.IndicatorStatus.ACTIVE
			self._status_passive = appindicator.IndicatorStatus.PASSIVE
		except (ImportError, ValueError):
			raise NotImplementedError
		
		category = appindicator.IndicatorCategory.APPLICATION_STATUS
		# Whatever icon is set here will be used as a tooltip icon during the entire time to icon is shown
		self._tray = appindicator.Indicator.new("syncthing-gtk", self._get_icon(), category)
		self._tray.set_menu(self._get_popupmenu())
		self._tray.set_title(self.TRAY_TITLE) 
Example #8
Source File: test_file_output.py    From brave with Apache License 2.0 6 votes vote down vote up
def assert_valid_output_file(output_video_location):
    '''
    Given a file, validates it is a video (mp4) file
    '''
    import gi
    gi.require_version('Gst', '1.0')
    from gi.repository import Gst, GLib

    Gst.init(None)
    mainloop = GLib.MainLoop()

    # We create a pipeline so that we can read the file and check it:
    pipeline = Gst.ElementFactory.make("playbin")
    pipeline.set_property('uri','file://'+output_video_location)
    playsink = pipeline.get_by_name('playsink')
    playsink.set_property('video-sink', Gst.ElementFactory.make('fakesink'))
    pipeline.set_state(Gst.State.PAUSED)

    def after_a_second():
        assert pipeline.get_state(0).state == Gst.State.PAUSED
        element = pipeline.get_by_name('inputselector1')
        caps = element.get_static_pad('src').get_current_caps()
        assert caps.to_string() == 'audio/x-raw, format=(string)F32LE, layout=(string)interleaved, rate=(int)48000, channels=(int)2, channel-mask=(bitmask)0x0000000000000003'

        element = pipeline.get_by_name('inputselector0')
        caps = element.get_static_pad('src').get_current_caps()
        assert caps.to_string() == 'video/x-raw, format=(string)NV12, width=(int)640, height=(int)360, interlace-mode=(string)progressive, multiview-mode=(string)mono, multiview-flags=(GstVideoMultiviewFlagsSet)0:ffffffff:/right-view-first/left-flipped/left-flopped/right-flipped/right-flopped/half-aspect/mixed-mono, pixel-aspect-ratio=(fraction)1/1, chroma-site=(string)jpeg, colorimetry=(string)bt601, framerate=(fraction)30/1'

        pipeline.set_state(Gst.State.NULL)
        mainloop.quit()

    GLib.timeout_add(1000, after_a_second)
    mainloop.run() 
Example #9
Source File: gtk.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def create_about_tab(self):
        from gi.repository import Pango
        page = Gtk.VBox()
        page.show()
        tv = Gtk.TextView()
        tv.set_editable(False)
        tv.set_cursor_visible(False)
        tv.modify_font(Pango.FontDescription(MONOSPACE_FONT))
        scroll = Gtk.ScrolledWindow()
        scroll.add(tv)
        page.pack_start(scroll, True, True, 0)
        self.info = tv.get_buffer()
        self.add_tab(page, 'Wall') 
Example #10
Source File: gstfunctions.py    From tapas with GNU General Public License v2.0 5 votes vote down vote up
def gst_init():
    from twisted.internet import gireactor as reactor
    reactor.install()
    import gi
    gi.require_version('Gst', '1.0')
    from gi.repository import GObject, Gst
    GObject.threads_init()
    Gst.init(None) 
Example #11
Source File: shell.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def _get_export_params(args):
    from gi.repository import Gtk

    quality = 50
    page_format = "A4"

    args = list(args)

    if "--quality" in args:
        idx = args.index("--quality")
        quality = args[idx + 1]
        args.pop(idx)
        args.pop(idx)
        quality = int(quality)
    if "--page_format" in args:
        idx = args.index("--page_format")
        page_format = args[idx + 1]
        args.pop(idx)
        args.pop(idx)

    for paper_size in Gtk.PaperSize.get_paper_sizes(True):
        if (paper_size.get_display_name() == page_format or
                paper_size.get_name() == page_format):
            page_format = (
                paper_size.get_width(Gtk.Unit.POINTS),
                paper_size.get_height(Gtk.Unit.POINTS)
            )
            break

    if not isinstance(page_format, tuple):
        raise Exception("Unknown page format: {}".format(page_format))

    return tuple(args) + (quality, page_format) 
Example #12
Source File: notifier.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def on_ql_enable_toggled(self, menuitem, data=None):
        from gi.repository import Dbusmenu
        if menuitem.property_get_int(Dbusmenu.Menuitem.MENUITEM_PROP_TOGGLE_STATE) == Dbusmenu.Menuitem.MENUITEM_TOGGLE_STATE_CHECKED:
            self.app.unpause_service()
        else:
            self.app.pause_service() 
Example #13
Source File: playsound.py    From playsound with MIT License 5 votes vote down vote up
def _playsoundNix(sound, block=True):
    """Play a sound using GStreamer.

    Inspired by this:
    https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html
    """
    if not block:
        raise NotImplementedError(
            "block=False cannot be used on this platform yet")

    # pathname2url escapes non-URL-safe characters
    import os
    try:
        from urllib.request import pathname2url
    except ImportError:
        # python 2
        from urllib import pathname2url

    import gi
    gi.require_version('Gst', '1.0')
    from gi.repository import Gst

    Gst.init(None)

    playbin = Gst.ElementFactory.make('playbin', 'playbin')
    if sound.startswith(('http://', 'https://')):
        playbin.props.uri = sound
    else:
        playbin.props.uri = 'file://' + pathname2url(os.path.abspath(sound))

    set_result = playbin.set_state(Gst.State.PLAYING)
    if set_result != Gst.StateChangeReturn.ASYNC:
        raise PlaysoundException(
            "playbin.set_state returned " + repr(set_result))

    # FIXME: use some other bus method than poll() with block=False
    # https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.html
    bus = playbin.get_bus()
    bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)
    playbin.set_state(Gst.State.NULL) 
Example #14
Source File: notifier.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def __getQuickItem(self, label):
        from gi.repository import Dbusmenu
        item = Dbusmenu.Menuitem.new()
        item.property_set(Dbusmenu.MENUITEM_PROP_LABEL, label)
        item.property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE, True)
        return item 
Example #15
Source File: actions.py    From zim-desktop-wiki with GNU General Public License v2.0 5 votes vote down vote up
def _get_modifier_mask():
	import gi
	gi.require_version('Gtk', '3.0')
	from gi.repository import Gtk
	x, mod = Gtk.accelerator_parse('<Primary>')
	return mod 
Example #16
Source File: playsound.py    From goreviewpartner with GNU General Public License v3.0 5 votes vote down vote up
def _playsoundNix(sound, block=True):
    """Play a sound using GStreamer.

    Inspired by this:
    https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html
    """
    if not block:
        raise NotImplementedError(
            "block=False cannot be used on this platform yet")

    # pathname2url escapes non-URL-safe characters
    import os
    try:
        from urllib.request import pathname2url
    except ImportError:
        # python 2
        from urllib import pathname2url

    import gi
    gi.require_version('Gst', '1.0')
    from gi.repository import Gst

    Gst.init(None)

    playbin = Gst.ElementFactory.make('playbin', 'playbin')
    if sound.startswith(('http://', 'https://')):
        playbin.props.uri = sound
    else:
        playbin.props.uri = 'file://' + pathname2url(os.path.abspath(sound))

    set_result = playbin.set_state(Gst.State.PLAYING)
    if set_result != Gst.StateChangeReturn.ASYNC:
        raise PlaysoundException(
            "playbin.set_state returned " + repr(set_result))

    # FIXME: use some other bus method than poll() with block=False
    # https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.html
    bus = playbin.get_bus()
    bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)
    playbin.set_state(Gst.State.NULL) 
Example #17
Source File: actions.py    From zim-desktop-wiki with GNU General Public License v2.0 5 votes vote down vote up
def get_gtk_actiongroup(obj):
	'''Return a C{Gtk.ActionGroup} for an object using L{Action}
	objects as attributes.

	Defines the attribute C{obj.actiongroup} if it does not yet exist.

	This method can only be used when gtk is available
	'''
	from gi.repository import Gtk

	if hasattr(obj, 'actiongroup') \
	and obj.actiongroup is not None:
		return obj.actiongroup

	obj.actiongroup = Gtk.ActionGroup(obj.__class__.__name__)

	for name, action in get_actions(obj):
		if isinstance(action, RadioAction):
			obj.actiongroup.add_radio_actions(action._entries)
			gaction = obj.actiongroup.get_action(action._entries[0][0])
			gaction.connect('changed', action.do_changed, obj)
			if not obj in action._proxies:
				action._proxies[obj] = []
			action._proxies[obj].append(gaction)
			if obj in action._state:
				key = action._state[obj]
				gtk_radioaction_set_current(gaction, key)
		else:
			_gtk_add_action_with_accel(obj, obj.actiongroup, action, action._attr, action._accel)
			if action._alt_accel:
				_gtk_add_action_with_accel(obj, obj.actiongroup, action, action._alt_attr, action._alt_accel)

	return obj.actiongroup 
Example #18
Source File: gstreamer_pipeline.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gobject_mainloop():
        gi.require_version('Gst', '1.0')
        from gi.repository import GLib
        GStreamerPipeline._mainloop = GLib.MainLoop()
        try:
            GStreamerPipeline._mainloop.run()
        except KeyboardInterrupt:
            pass 
Example #19
Source File: actions.py    From zim-desktop-wiki with GNU General Public License v2.0 5 votes vote down vote up
def _gtk_add_action_with_accel(obj, actiongroup, action, attr, accel):
	from gi.repository import Gtk

	if isinstance(action, ToggleAction):
		gaction = Gtk.ToggleAction(*attr)
	else:
		gaction = Gtk.Action(*attr)

	gaction.zim_readonly = not bool(
		'edit' in action.menuhints or 'insert' in action.menuhints
	)
	action.connect_actionable(obj, gaction)
	actiongroup.add_action_with_accel(gaction, accel) 
Example #20
Source File: test_interface.py    From RAFCON with Eclipse Public License 1.0 5 votes vote down vote up
def test_gui_create_folder(monkeypatch):
    """Tests `create_folder` function from `rafcon.core.interface`"""
    testing_utils.dummy_gui(None)
    print("execute test_gui_create_folder")
    import rafcon.gui.interface as gui_interface
    import gi
    gi.require_version('Gtk', '3.0')
    from gi.repository import Gtk

    class PatchedFileChooserDialog(Gtk.FileChooserDialog):
        """Subclass for FileChooserDialog

        FileChooserDialog cannot be monkey-patched directly. It must first be replaced by a subclass, which is this one.
        """
        pass

    # prepare FileChooserDialog for monkey-patching
    monkeypatch.setattr(Gtk, "FileChooserDialog", PatchedFileChooserDialog)
    # replaces run by an expression that returns Gtk.ResponseType.OK
    monkeypatch.setattr(Gtk.FileChooserDialog, 'run', lambda _: Gtk.ResponseType.OK)
    # replaces get_filename by an expression that returns "/tmp"
    monkeypatch.setattr(Gtk.FileChooserDialog, 'get_filename', lambda _: RAFCON_TEMP_PATH_TEST_BASE)

    # Return user input
    assert gui_interface.create_folder("query") == RAFCON_TEMP_PATH_TEST_BASE
    # Return user input despite default path given
    assert gui_interface.create_folder("query", "/home") == RAFCON_TEMP_PATH_TEST_BASE
    assert gui_interface.create_folder("query", "new", "/home") == RAFCON_TEMP_PATH_TEST_BASE

    # replaces run by an expression that returns Gtk.ResponseType.CANCEL
    monkeypatch.setattr(Gtk.FileChooserDialog, 'run', lambda _: Gtk.ResponseType.CANCEL)

    # Return None if no user input and no default path
    assert gui_interface.create_folder("query") is None
    # Return default path if no user input is given
    assert gui_interface.create_folder("query", "new_folder", RAFCON_TEMP_PATH_TEST_BASE) == os.path.join(
                                                          RAFCON_TEMP_PATH_TEST_BASE, "new_folder")
    # Return None if no user input and default path cannot be created (without root permissions)
    assert gui_interface.create_folder("query", "new_folder", "/root/not/writable") is None
    # Return None if no user input and insufficient path information given
    assert gui_interface.create_folder("query", "new_folder") is None 
Example #21
Source File: test_interface.py    From RAFCON with Eclipse Public License 1.0 5 votes vote down vote up
def test_gui_open_folder(monkeypatch):
    """Tests `open_folder` function from `rafcon.core.interface`"""
    testing_utils.dummy_gui(None)
    print("execute test_gui_open_folder")
    import rafcon.gui.interface as gui_interface
    import gi
    gi.require_version('Gtk', '3.0')
    from gi.repository import Gtk

    class PatchedFileChooserDialog(Gtk.FileChooserDialog):
        """Subclass for FileChooserDialog

        FileChooserDialog cannot be monkey-patched directly. It must first be replaced by a subclass, which is this one.
        """
        pass

    # prepare FileChooserDialog for monkey-patching
    monkeypatch.setattr(Gtk, "FileChooserDialog", PatchedFileChooserDialog)
    # replaces run by an expression that returns Gtk.ResponseType.OK
    monkeypatch.setattr(Gtk.FileChooserDialog, 'run', lambda _: Gtk.ResponseType.OK)
    # replaces get_filename by an expression that returns "/tmp"
    monkeypatch.setattr(Gtk.FileChooserDialog, 'get_filename', lambda _: "/tmp")

    # Return user input
    assert gui_interface.open_folder("query") == "/tmp"
    # Return user input despite default path given
    assert gui_interface.open_folder("query", "/home") == "/tmp"

    # replaces run by an expression that returns Gtk.ResponseType.CANCEL
    monkeypatch.setattr(Gtk.FileChooserDialog, 'run', lambda _: Gtk.ResponseType.CANCEL)

    # Return None if no user input and no default path
    assert gui_interface.open_folder("query") is None
    # Return default path if no user input is given
    assert gui_interface.open_folder("query", "/tmp") == "/tmp"
    # Return None if no user input and default path does not exist
    assert gui_interface.open_folder("query", "/non/existing/path") is None 
Example #22
Source File: widgets.py    From zim-desktop-wiki with GNU General Public License v2.0 5 votes vote down vote up
def get_debug_text(self, exc_info=None):
		'''Get the text to show in the log of a "You found a bug" dialog.
		Includes zim version info and traceback info.

		@param exc_info: this is an optional argument that takes the
		result of C{sys.exc_info()}
		@returns: debug log as string
		'''
		from gi.repository import GObject
		import zim
		import traceback

		if not exc_info:
			exc_info = sys.exc_info()

		if exc_info[2]:
			tb = exc_info[2]
		else:
			tb = None

		text = 'This is zim %s\n' % zim.__version__ + \
			'Platform: %s\n' % os.name + \
			'Locale: %s %s\n' % locale.getdefaultlocale() + \
			'FS encoding: %s\n' % sys.getfilesystemencoding() + \
			'Python: %s\n' % str(tuple(sys.version_info)) + \
			'PyGObject: %s\n' % str(GObject.pygobject_version)

		text += '\n======= Traceback =======\n'
		if tb:
			lines = traceback.format_tb(tb)
			text += ''.join(lines)
		else:
			text += '<Could not extract stack trace>\n'

		text += self.error.__class__.__name__ + ': ' + str(self.error)

		del exc_info # recommended by manual

		return text 
Example #23
Source File: __main__.py    From volctl with GNU General Public License v2.0 5 votes vote down vote up
def main():
    """Start volctl."""
    import gi

    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk
    from volctl.app import VolctlApp

    VolctlApp()
    Gtk.main() 
Example #24
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def check22_graphview(self):
        '''
        Graph View - Requires: PyGoocanvas and Goocanvas and
        graphviz (python-pygoocanvas, gir1.2-goocanvas-2.0)
        '''
        self.append_text("\n")
        self.render_text("""<b>02. <a href="https://gramps-project.org/wiki"""
                         """/index.php?title=Graph_View">"""
                         """Addon:Graph View</a> :</b> """)
        # Start check

        # check for GooCanvas
        try:
            try:
                gi.require_version('GooCanvas', '2.0')
            except Exception:
                print("Why, when same code works in Graphview")
            from gi.repository import GooCanvas
            goocanvas_ver = str(GooCanvas._version)
            #print("GooCanvas version:" + goocanvas_ver)
        except ImportError:
            goocanvas_ver = "Not installed"

        result = "(GooCanvas:" + goocanvas_ver + ")(PyGoocanvas: TBD?)"
        # End check
        self.append_text(result)
        self.append_text("(")
        self.check12_graphviz()
        self.append_text(")") 
Example #25
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def check19_geocodeglib(self):
        '''geocodeglib
        # added to gramps master v5.1.0
        #TODO: add to gramps-v check

        https://github.com/gramps-project/gramps/blob/maintenance/gramps50/gramps/plugins/lib/maps/placeselection.py
        '''
        self.append_text("\n")
        # Start check
        geocodeglib_min_ver = "1.0"

        try:
            gi.require_version('GeocodeGlib', '1.0')
            from gi.repository import GeocodeGlib
            geocodeglib_ver = str(GeocodeGlib._version)
            GEOCODEGLIB = True
        except Exception:
            geocodeglib_ver = "Not found"
            GEOCODEGLIB = False

        if GEOCODEGLIB:
            result = ("* geocodeglib " + geocodeglib_ver +
                      " (Success version " + geocodeglib_min_ver +
                      " or greater installed.)")
        else:
            result = ("* geocodeglib " + geocodeglib_ver +
                      " (Requires version " + geocodeglib_min_ver +
                      " or greater installed.)")

        # End check
        self.append_text(result) 
Example #26
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def check11_osmgpsmap(self):
        '''osmgpsmap'''
        # Start check
        OSMGPSMAP_MIN_VERSION = (1, 0)
        OSMGPSMAP_FOUND = False

        try:
            from gi import Repository
            repository = Repository.get_default()
            if repository.enumerate_versions("OsmGpsMap"):
                gi.require_version('OsmGpsMap', '1.0')
                from gi.repository import OsmGpsMap as osmgpsmap
                try:
                    osmgpsmap_str = osmgpsmap._version
                    OSMGPSMAP_FOUND = True
                except Exception:  # any failure to 'get' the version
                    osmgpsmap_str = 'unknown version'
            else:
                osmgpsmap_str = 'not found'

        except ImportError:
            osmgpsmap_str = 'not found'

        if OSMGPSMAP_FOUND:
            result = ("* osmgpsmap " + osmgpsmap_str + " (Success version " +
                      verstr(OSMGPSMAP_MIN_VERSION) +
                      " or greater installed.)")
        else:
            result = ("* osmgpsmap " + osmgpsmap_str + " (Requires version " +
                      verstr(OSMGPSMAP_MIN_VERSION) + " or greater)")

        # End check
        self.append_text(result) 
Example #27
Source File: images.py    From pulseaudio-dlna with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, cached=True, size=256):
        try:
            gi.require_version('Rsvg', '2.0')
            from gi.repository import Rsvg
        except:
            raise MissingDependencies(
                'Unable to convert SVG image to PNG!', ['gir1.2-rsvg-2.0']
            )
        try:
            import cairo
        except:
            raise MissingDependencies(
                'Unable to convert SVG image to PNG!', ['cairo']
            )

        tmp_file = tempfile.NamedTemporaryFile()
        image_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size)
        rsvg_handle = Rsvg.Handle.new_from_file(path)

        context = cairo.Context(image_surface)
        context.scale(
            float(size) / rsvg_handle.props.height,
            float(size) / rsvg_handle.props.width
        )
        rsvg_handle.render_cairo(context)
        image_surface.write_to_png(tmp_file.name)

        BaseImage.__init__(self, tmp_file.name, cached=True) 
Example #28
Source File: constfunc.py    From gprime with GNU General Public License v2.0 5 votes vote down vote up
def has_display():
    """
    Tests to see if Python is currently running with gtk
    """
    # FIXME: currently, Gtk.init_check() requires all strings
    # in argv, and we might have unicode.
    temp, sys.argv = sys.argv, sys.argv[:1]
    try:
        import gi
        gi.require_version('Gtk', '3.0')
        gi.require_version('Gdk', '3.0')
        from gi.repository import Gtk
        from gi.repository import Gdk
    except ImportError:
        return False

    try:
        test = Gtk.init_check(temp) and \
            Gdk.Display.get_default()
        sys.argv = temp
        return bool(test)
    except:
        sys.argv = temp
        return False

# A couple of places add menu accelerators using <alt>, which doesn't
# work with Gtk-quartz. <Meta> is the usually correct replacement, but
# in one case the key is a number, and <meta>number is used by Spaces
# (a mac feature), so we'll use control instead. 
Example #29
Source File: gstreamer.py    From project-posenet with Apache License 2.0 4 votes vote down vote up
def setup_window(self):
        # Only set up our own window if we have Coral overlay sink in the pipeline.
        if not self.overlaysink:
            return

        gi.require_version('GstGL', '1.0')
        from gi.repository import GstGL

        # Needed to commit the wayland sub-surface.
        def on_gl_draw(sink, widget):
            widget.queue_draw()

        # Needed to account for window chrome etc.
        def on_widget_configure(widget, event, overlaysink):
            allocation = widget.get_allocation()
            overlaysink.set_render_rectangle(allocation.x, allocation.y,
                    allocation.width, allocation.height)
            return False

        window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
        window.fullscreen()

        drawing_area = Gtk.DrawingArea()
        window.add(drawing_area)
        drawing_area.realize()

        self.overlaysink.connect('drawn', on_gl_draw, drawing_area)

        # Wayland window handle.
        wl_handle = self.overlaysink.get_wayland_window_handle(drawing_area)
        self.overlaysink.set_window_handle(wl_handle)

        # Wayland display context wrapped as a GStreamer context.
        wl_display = self.overlaysink.get_default_wayland_display_context()
        self.overlaysink.set_context(wl_display)

        drawing_area.connect('configure-event', on_widget_configure, self.overlaysink)
        window.connect('delete-event', Gtk.main_quit)
        window.show_all()

        # The appsink pipeline branch must use the same GL display as the screen
        # rendering so they get the same GL context. This isn't automatically handled
        # by GStreamer as we're the ones setting an external display handle.
        def on_bus_message_sync(bus, message, overlaysink):
            if message.type == Gst.MessageType.NEED_CONTEXT:
                _, context_type = message.parse_context_type()
                if context_type == GstGL.GL_DISPLAY_CONTEXT_TYPE:
                    sinkelement = overlaysink.get_by_interface(GstVideo.VideoOverlay)
                    gl_context = sinkelement.get_property('context')
                    if gl_context:
                        display_context = Gst.Context.new(GstGL.GL_DISPLAY_CONTEXT_TYPE, True)
                        GstGL.context_set_gl_display(display_context, gl_context.get_display())
                        message.src.set_context(display_context)
            return Gst.BusSyncReply.PASS

        bus = self.pipeline.get_bus()
        bus.set_sync_handler(on_bus_message_sync, self.overlaysink) 
Example #30
Source File: brain_gi.py    From linter-pylama with MIT License 4 votes vote down vote up
def _import_gi_module(modname):
    # we only consider gi.repository submodules
    if not modname.startswith('gi.repository.'):
        raise AstroidBuildingError(modname=modname)
    # build astroid representation unless we already tried so
    if modname not in _inspected_modules:
        modnames = [modname]
        optional_modnames = []

        # GLib and GObject may have some special case handling
        # in pygobject that we need to cope with. However at
        # least as of pygobject3-3.13.91 the _glib module doesn't
        # exist anymore, so if treat these modules as optional.
        if modname == 'gi.repository.GLib':
            optional_modnames.append('gi._glib')
        elif modname == 'gi.repository.GObject':
            optional_modnames.append('gi._gobject')

        try:
            modcode = ''
            for m in itertools.chain(modnames, optional_modnames):
                try:
                    with warnings.catch_warnings():
                        # Just inspecting the code can raise gi deprecation
                        # warnings, so ignore them.
                        try:
                            from gi import PyGIDeprecationWarning, PyGIWarning
                            warnings.simplefilter("ignore", PyGIDeprecationWarning)
                            warnings.simplefilter("ignore", PyGIWarning)
                        except Exception:
                            pass

                        __import__(m)
                        modcode += _gi_build_stub(sys.modules[m])
                except ImportError:
                    if m not in optional_modnames:
                        raise
        except ImportError:
            astng = _inspected_modules[modname] = None
        else:
            astng = AstroidBuilder(MANAGER).string_build(modcode, modname)
            _inspected_modules[modname] = astng
    else:
        astng = _inspected_modules[modname]
    if astng is None:
        raise AstroidBuildingError(modname=modname)
    return astng