Python gi.require_version() Examples
The following are 30
code examples of gi.require_version().
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 |
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: utils.py From AutomaThemely with GNU General Public License v3.0 | 6 votes |
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 #3
Source File: brain_gi.py From linter-pylama with MIT License | 6 votes |
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 #4
Source File: brain_gi.py From pySINDy with MIT License | 6 votes |
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
Source File: statusicon.py From syncthing-gtk with GNU General Public License v2.0 | 6 votes |
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 #6
Source File: test_file_output.py From brave with Apache License 2.0 | 6 votes |
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 #7
Source File: Pyperclip.py From MIA-Dictionary-Addon with GNU General Public License v3.0 | 6 votes |
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 #8
Source File: brain_gi.py From python-netsurv with MIT License | 6 votes |
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 #9
Source File: brain_gi.py From python-netsurv with MIT License | 6 votes |
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 #10
Source File: stray.py From Dragonfire with MIT License | 6 votes |
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 #11
Source File: images.py From pulseaudio-dlna with GNU General Public License v3.0 | 6 votes |
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 #12
Source File: playsound.py From playsound with MIT License | 5 votes |
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 #13
Source File: gstfunctions.py From tapas with GNU General Public License v2.0 | 5 votes |
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 #14
Source File: actions.py From zim-desktop-wiki with GNU General Public License v2.0 | 5 votes |
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 #15
Source File: mate_version.py From mate-i3-applet with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #16
Source File: playsound.py From goreviewpartner with GNU General Public License v3.0 | 5 votes |
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: gstreamer_pipeline.py From video-analytics-serving with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #18
Source File: brain_gi.py From pySINDy with MIT License | 5 votes |
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 #19
Source File: __main__.py From volctl with GNU General Public License v2.0 | 5 votes |
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 #20
Source File: test_interface.py From RAFCON with Eclipse Public License 1.0 | 5 votes |
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 |
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: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 5 votes |
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 #23
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 5 votes |
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 #24
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 5 votes |
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 #25
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 5 votes |
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 #26
Source File: constfunc.py From gprime with GNU General Public License v2.0 | 5 votes |
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 #27
Source File: brain_gi.py From python-netsurv with MIT License | 5 votes |
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 #28
Source File: brain_gi.py From python-netsurv with MIT License | 5 votes |
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 #29
Source File: images.py From pulseaudio-dlna with GNU General Public License v3.0 | 5 votes |
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 #30
Source File: brain_gi.py From linter-pylama with MIT License | 5 votes |
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