Python gi.require_version() Examples

The following are 30 code examples for showing how to use gi.require_version(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module gi , or try the search function .

Example 1
Project: gprime   Author: GenealogyCollective   File: constfunc.py    License: 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
Project: linter-pylama   Author: AtomLinter   File: brain_gi.py    License: MIT License 6 votes vote down vote up
def _looks_like_require_version(node):
    # Return whether this looks like a call to gi.require_version(<name>, <version>)
    # Only accept function calls with two constant arguments
    if len(node.args) != 2:
        return False

    if not all(isinstance(arg, nodes.Const) for arg in node.args):
        return False

    func = node.func
    if isinstance(func, nodes.Attribute):
        if func.attrname != 'require_version':
            return False
        if isinstance(func.expr, nodes.Name) and func.expr.name == 'gi':
            return True

        return False

    if isinstance(func, nodes.Name):
        return func.name == 'require_version'

    return False 
Example 3
Project: pulseaudio-dlna   Author: masmu   File: images.py    License: 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 4
Project: python-netsurv   Author: sofia-netsurv   File: brain_gi.py    License: MIT License 6 votes vote down vote up
def _looks_like_require_version(node):
    # Return whether this looks like a call to gi.require_version(<name>, <version>)
    # Only accept function calls with two constant arguments
    if len(node.args) != 2:
        return False

    if not all(isinstance(arg, nodes.Const) for arg in node.args):
        return False

    func = node.func
    if isinstance(func, nodes.Attribute):
        if func.attrname != "require_version":
            return False
        if isinstance(func.expr, nodes.Name) and func.expr.name == "gi":
            return True

        return False

    if isinstance(func, nodes.Name):
        return func.name == "require_version"

    return False 
Example 5
Project: python-netsurv   Author: sofia-netsurv   File: brain_gi.py    License: MIT License 6 votes vote down vote up
def _looks_like_require_version(node):
    # Return whether this looks like a call to gi.require_version(<name>, <version>)
    # Only accept function calls with two constant arguments
    if len(node.args) != 2:
        return False

    if not all(isinstance(arg, nodes.Const) for arg in node.args):
        return False

    func = node.func
    if isinstance(func, nodes.Attribute):
        if func.attrname != "require_version":
            return False
        if isinstance(func.expr, nodes.Name) and func.expr.name == "gi":
            return True

        return False

    if isinstance(func, nodes.Name):
        return func.name == "require_version"

    return False 
Example 6
Project: pySINDy   Author: luckystarufo   File: brain_gi.py    License: MIT License 6 votes vote down vote up
def _looks_like_require_version(node):
    # Return whether this looks like a call to gi.require_version(<name>, <version>)
    # Only accept function calls with two constant arguments
    if len(node.args) != 2:
        return False

    if not all(isinstance(arg, nodes.Const) for arg in node.args):
        return False

    func = node.func
    if isinstance(func, nodes.Attribute):
        if func.attrname != "require_version":
            return False
        if isinstance(func.expr, nodes.Name) and func.expr.name == "gi":
            return True

        return False

    if isinstance(func, nodes.Name):
        return func.name == "require_version"

    return False 
Example 7
Project: syncthing-gtk   Author: kozec   File: statusicon.py    License: 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
Project: MIA-Dictionary-Addon   Author: mass-immersion-approach   File: Pyperclip.py    License: 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 9
Project: Dragonfire   Author: DragonComputer   File: stray.py    License: 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 10
Project: AutomaThemely   Author: C2N14   File: utils.py    License: 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 11
Project: linter-pylama   Author: AtomLinter   File: brain_gi.py    License: MIT License 5 votes vote down vote up
def _register_require_version(node):
    # Load the gi.require_version locally
    try:
        import gi
        gi.require_version(node.args[0].value, node.args[1].value)
    except Exception:
        pass

    return node 
Example 12
Project: pulseaudio-dlna   Author: masmu   File: images.py    License: 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 13
Project: python-netsurv   Author: sofia-netsurv   File: brain_gi.py    License: MIT License 5 votes vote down vote up
def _register_require_version(node):
    # Load the gi.require_version locally
    try:
        import gi

        gi.require_version(node.args[0].value, node.args[1].value)
    except Exception:
        pass

    return node 
Example 14
Project: python-netsurv   Author: sofia-netsurv   File: brain_gi.py    License: MIT License 5 votes vote down vote up
def _register_require_version(node):
    # Load the gi.require_version locally
    try:
        import gi

        gi.require_version(node.args[0].value, node.args[1].value)
    except Exception:
        pass

    return node 
Example 15
Project: gprime   Author: GenealogyCollective   File: constfunc.py    License: 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 16
Project: brave   Author: bbc   File: test_file_output.py    License: Apache License 2.0 5 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 17
Project: addons-source   Author: gramps-project   File: PrerequisitesCheckerGramplet.py    License: 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 18
Project: addons-source   Author: gramps-project   File: PrerequisitesCheckerGramplet.py    License: 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 19
Project: addons-source   Author: gramps-project   File: PrerequisitesCheckerGramplet.py    License: 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 20
Project: addons-source   Author: gramps-project   File: PrerequisitesCheckerGramplet.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check26_htmlview(self):
        '''HTMLView

        Html Renderer
        Can use the Webkit or Gecko ( Mozilla ) library

        https://github.com/gramps-project/addons-source/blob/maintenance/gramps50/HtmlView/htmlview.py
        '''
        self.append_text("\n")
        self.render_text("""<b>06. <a href="https://gramps-project.org/wiki"""
                         """/index.php?title=Addon:HtmlView">"""
                         """Addon:HTMLView</a> :</b> """)
        # Start check
        NOWEB = 0
        WEBKIT = 1
        # MOZILLA = 2
        KITNAME = ["None", "WebKit", "Mozilla"]
        TOOLKIT = NOWEB

        try:
            gi.require_version('WebKit', '3.0')
            from gi.repository import WebKit as webkit
            webkit_ver = str(webkit._version)
            #print("webkit version " + webkit_ver)
            TOOLKIT = WEBKIT
        except Exception:
            webkit_ver = "Not installed "
            TOOLKIT = NOWEB

        if TOOLKIT is NOWEB:
            #print("0")
            result012 = ")"
        else:
            #print("1/2")
            result012 = " / " + str(KITNAME[TOOLKIT]) + ")"

        result = "(Webkit: " + webkit_ver + result012
        # End check
        self.append_text(result)
        #self.append_text("\n") 
Example 21
Project: volctl   Author: buzz   File: __main__.py    License: 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 22
Project: RAFCON   Author: DLR-RM   File: test_interface.py    License: 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 23
Project: RAFCON   Author: DLR-RM   File: test_interface.py    License: 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 24
Project: pySINDy   Author: luckystarufo   File: brain_gi.py    License: MIT License 5 votes vote down vote up
def _register_require_version(node):
    # Load the gi.require_version locally
    try:
        import gi

        gi.require_version(node.args[0].value, node.args[1].value)
    except Exception:
        pass

    return node 
Example 25
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 26
Project: goreviewpartner   Author: pnprog   File: playsound.py    License: 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 27
Project: mate-i3-applet   Author: city41   File: mate_version.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def import_gtk():
    import gi

    version = get_mate_version()
    if version and version.major < 2 and version.minor < 16:
        gi.require_version("Gtk", "2.0")
        logging.debug("GTK 2.0 loaded")
    elif version:
        gi.require_version("Gtk", "3.0")
        logging.debug("GTK 3.0 loaded")
    else:
        logging.error("MATE is not installed, stopping execution..")
        sys.exit(1)
    gi.require_version('MatePanelApplet', '4.0') 
Example 28
Project: tapas   Author: ldecicco   File: gstfunctions.py    License: 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 29
Project: playsound   Author: TaylorSMarks   File: playsound.py    License: 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 30
Project: zim-desktop-wiki   Author: zim-desktop-wiki   File: actions.py    License: 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