Python gi.repository.GLib.GError() Examples

The following are 30 code examples of gi.repository.GLib.GError(). 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.GLib , or try the search function .
Example #1
Source File: Notification.py    From battery-monitor with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, type: str) -> None:
        # initiating notification
        Notify.init("Battery Monitor")
        message = MESSAGES[type]
        head = message[0]
        body = message[1]
        icon = ICONS[type]
        self.last_percentage = 0
        self.last_notification = ''
        self.notifier = Notify.Notification.new(head, body, icon)
        self.notifier.set_urgency(Notify.Urgency.CRITICAL)
        try:
            self.notifier.show()
        except GLib.GError as e:
            # fixing GLib.GError: g-dbus-error-quark blindly
            pass
        self.config = configparser.ConfigParser()
        self.load_config() 
Example #2
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 6 votes vote down vote up
def rm_rf(self, url):
        try:
            logger.info("Deleting %s ...", url)
            f = Gio.File.new_for_uri(url)
            deleted = False
            try:
                deleted = f.trash()
            except Exception as exc:
                logger.warning("Failed to trash %s. Will try to delete it"
                               " instead", f.get_uri(), exc_info=exc)
            if not deleted:
                self._rm_rf(f)
            logger.info("%s deleted", url)
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #3
Source File: inputoutputoverlay.py    From brave with Apache License 2.0 6 votes vote down vote up
def create_pipeline_from_string(self, pipeline_string):
        try:
            self.logger.debug('Creating with pipeline: ' + pipeline_string)
            self.pipeline = Gst.parse_launch(pipeline_string)
            setup_messaging(pipe=self.pipeline, parent_object=self)
        except GLib.GError as e:
            self.error_message = str(e)
            self.logger.error('Failed to create pipeline [%s]: %s' % (pipeline_string, self.error_message))
            raise brave.exceptions.PipelineFailure(self.error_message) 
Example #4
Source File: Notification.py    From battery-monitor with GNU General Public License v3.0 6 votes vote down vote up
def show_notification(self, type: str, battery_percentage: int,
                          remaining_time: str = None, _time: int = 5) -> None:

        message = MESSAGES[type]
        head = message[0]
        body = message[1].format(battery_percentage=battery_percentage,
                                 remaining_time=remaining_time)
        icon = ICONS[type]
        self.notifier.update(head, body, icon)
        try:
            self.notifier.show()
        except GLib.GError as e:
            # fixing GLib.GError: g-dbus-error-quark blindly
            # To Do: investigate the main reason and make a fix
            pass
        time.sleep(self.notification_stability)
        self.notifier.close() 
Example #5
Source File: docimport.py    From paperwork-backend with GNU General Public License v3.0 6 votes vote down vote up
def can_import(self, file_uris, current_doc=None):
        """
        Check that the specified file looks like a directory containing many
        pdf files
        """
        if len(file_uris) <= 0:
            return False
        try:
            for file_uri in file_uris:
                file_uri = self.fs.safe(file_uri)
                for child in self.fs.recurse(file_uri):
                    if self.check_file_type(child):
                        return True
        except GLib.GError:
            pass
        return False 
Example #6
Source File: docimport.py    From paperwork-backend with GNU General Public License v3.0 6 votes vote down vote up
def can_import(self, file_uris, current_doc=None):
        """
        Check that the specified file looks like a directory containing many
        pdf files
        """
        if len(file_uris) <= 0:
            return False
        try:
            for file_uri in file_uris:
                file_uri = self.fs.safe(file_uri)
                for child in self.fs.recurse(file_uri):
                    if self.check_file_type(child):
                        return True
        except GLib.GError:
            pass
        return False 
Example #7
Source File: daemonprocess.py    From syncthing-gtk with GNU General Public License v2.0 6 votes vote down vote up
def _cb_finished(self, proc, results):
		"""
		Callback for wait_check_async.
		With Gio < 3.12, timer and _cb_check_alive is used.
		"""
		try:
			proc.wait_check_finish(results)
			log.info("Subprocess finished with code %s", proc.get_exit_status())
		except GLib.GError:
			# Exited with exit code
			log.info("Subprocess exited with code %s", proc.get_exit_status())
		if proc.get_exit_status() == 127:
			# Command not found
			self.emit("failed", Exception("Command not found"))
		else:
			self.emit('exit', proc.get_exit_status())
		if IS_WINDOWS: self._stdout.close()
		self._cancel.cancel() 
Example #8
Source File: publish_properties.py    From pydbus with GNU Lesser General Public License v2.1 6 votes vote down vote up
def t1_func():
		for obj in [remote, remote_iface]:
			assert(obj.Foo == "foo")
			assert(obj.Foobar == "foobar")
			obj.Foobar = "barfoo"
			assert(obj.Foobar == "barfoo")
			obj.Foobar = "foobar"
			assert(obj.Foobar == "foobar")
			obj.Bar = "rab"

		remote.Foobar = "barfoo"

		try:
			remote.Get("net.lew21.pydbus.tests.publish_properties", "Bar")
			assert(False)
		except GLib.GError:
			pass
		try:
			remote.Set("net.lew21.pydbus.tests.publish_properties", "Foo", Variant("s", "haxor"))
			assert(False)
		except GLib.GError:
			pass
		assert(remote.GetAll("net.lew21.pydbus.tests.publish_properties") == {'Foobar': 'barfoo', 'Foo': 'foo'})
		remote.Quit() 
Example #9
Source File: SubProcess.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def write_stdin(self, writer, line):
        if self.terminated:
            return
        try:
            log.debug(line, extra={"task": self.defname})
            writer.write(line.encode())
            await writer.drain()
        except BrokenPipeError:
            log.debug('SubProcess.write_stdin(): BrokenPipeError', extra={"task": self.defname})
            self.emit("died")
            self.terminate()
        except ConnectionResetError:
            log.debug('SubProcess.write_stdin(): ConnectionResetError', extra={"task": self.defname})
            self.emit("died")
            self.terminate()
        except GLib.GError:
            log.debug("SubProcess.write_stdin(): GLib.GError", extra={"task": self.defname})
            self.emit("died")
            self.terminate() 
Example #10
Source File: image.py    From vimiv with MIT License 6 votes vote down vote up
def _load_thread(self, loader, path):
        # The try ... except wrapper and the _faulty_image attribute are used to
        # catch weird images that break GdkPixbufLoader but work otherwise
        # See https://github.com/karlch/vimiv/issues/49 for more information
        try:
            self._faulty_image = True
            with open(path, "rb") as f:
                image_bytes = f.read()
                loader.write(image_bytes)
            self._faulty_image = False
            loader.close()
        except GLib.GError:
            self._pixbuf_original = GdkPixbuf.Pixbuf.new_from_file(path)
            self._faulty_image = False
            self._set_image_pixbuf()
            GLib.idle_add(self._update) 
Example #11
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 #12
Source File: doc.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def import_pdf(self, file_uri):
        logger.info("PDF: Importing '%s'" % (file_uri))
        gfile = Gio.File.new_for_uri(file_uri)
        try:
            # try opening it to make sure it's valid
            pdf = Poppler.Document.new_from_gfile(gfile)
            pdf.get_n_pages()
        except GLib.GError as exc:
            logger.error(
                "Warning: Unable to open the PDF to import: {}/{}".format(
                    file_uri, exc
                )
            )
            return str(exc)

        try:
            dest = Gio.File.new_for_uri(self.path)
            dest.make_directory(None)
        except GLib.GError as exc:
            logger.error("Warning: Error while trying to create '%s': %s"
                         % (self.path, exc))
            return str(exc)
        f = Gio.File.parse_name(file_uri)
        dest = dest.get_child(PDF_FILENAME)
        f.copy(dest,
               0,  # TODO(Jflesch): Missing flags: don't keep attributes
               None, None, None)
        self.pdfpath = dest.get_uri()
        return None 
Example #13
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def exists(self, url):
        try:
            f = Gio.File.new_for_uri(url)
            return f.query_exists()
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #14
Source File: gi_composites.py    From Apostrophe with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, cls):
        
        if not issubclass(cls, Gtk.Widget):
            raise TypeError("Can only use @GtkTemplate on Widgets")

        # Nested templates don't work
        if hasattr(cls, '__gtemplate_methods__'):
            raise TypeError("Cannot nest template classes")
        
        # Load the template either from a resource path or a file
        # - Prefer the resource path first

        try:
            template_bytes = Gio.resources_lookup_data(self.ui, Gio.ResourceLookupFlags.NONE)
        except GLib.GError:
            ui = self.ui
            if isinstance(ui, (list, tuple)):
                ui = join(ui)

            if _GtkTemplate.__ui_path__ is not None:
                ui = join(_GtkTemplate.__ui_path__, ui)

            with open(ui, 'rb') as fp:
                template_bytes = GLib.Bytes.new(fp.read())

        _register_template(cls, template_bytes)
        return cls


   
# Future shim support if this makes it into PyGI?
#if hasattr(Gtk, 'GtkTemplate'):
#    GtkTemplate = lambda c: c
#else: 
Example #15
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def _recurse(self, parent, dir_included=False):
        """
        Yield all the children (depth first), but not the parent.
        """
        try:
            children = parent.enumerate_children(
                Gio.FILE_ATTRIBUTE_STANDARD_NAME,
                Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
                None
            )
        except GLib.GError:
            # assumes it's a file and not a directory
            yield parent
            return

        for child in children:
            name = child.get_name()
            child = parent.get_child(name)
            try:
                for sub in self._recurse(child):
                    yield sub
            except GLib.GError:
                yield child

        if dir_included:
            yield parent 
Example #16
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def mkdir_p(self, url):
        try:
            f = Gio.File.new_for_uri(url)
            if not f.query_exists():
                f.make_directory_with_parents()
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #17
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def isdir(self, url):
        try:
            f = Gio.File.new_for_uri(url)
            fi = f.query_info(
                Gio.FILE_ATTRIBUTE_STANDARD_TYPE, Gio.FileQueryInfoFlags.NONE
            )
            return fi.get_file_type() == Gio.FileType.DIRECTORY
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #18
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def getsize(self, url):
        try:
            f = Gio.File.new_for_uri(url)
            fi = f.query_info(
                Gio.FILE_ATTRIBUTE_STANDARD_SIZE, Gio.FileQueryInfoFlags.NONE
            )
            return fi.get_attribute_uint64(Gio.FILE_ATTRIBUTE_STANDARD_SIZE)
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #19
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def getmtime(self, url):
        try:
            f = Gio.File.new_for_uri(url)
            if not f.query_exists():
                raise IOError("File {} does not exist".format(str(url)))
            fi = f.query_info(
                Gio.FILE_ATTRIBUTE_TIME_CHANGED, Gio.FileQueryInfoFlags.NONE
            )
            return fi.get_attribute_uint64(Gio.FILE_ATTRIBUTE_TIME_CHANGED)
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #20
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def _rm_rf(self, gfile):
        try:
            to_delete = [f for f in self._recurse(gfile, dir_included=True)]
            for f in to_delete:
                if not f.delete():
                    raise IOError("Failed to delete %s" % f.get_uri())
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #21
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def rename(self, old_url, new_url):
        try:
            old = Gio.File.new_for_uri(old_url)
            new = Gio.File.new_for_uri(new_url)
            assert(not old.equal(new))
            old.move(new, Gio.FileCopyFlags.NONE)
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #22
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def listdir(self, url):
        try:
            f = Gio.File.new_for_uri(url)
            children = f.enumerate_children(
                Gio.FILE_ATTRIBUTE_STANDARD_NAME, Gio.FileQueryInfoFlags.NONE,
                None
            )
            for child in children:
                child = f.get_child(child.get_name())
                yield child.get_uri()
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #23
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def open(self, uri, mode='rb'):
        f = Gio.File.new_for_uri(uri)
        if ('w' not in mode and 'a' not in mode) and not f.query_exists():
            raise IOError("File does not exist")
        try:
            raw = GioFileAdapter(f, mode)
            if 'b' in mode:
                return raw
            return GioUTF8FileAdapter(raw)
        except GLib.GError as exc:
            logger.warning("Gio.Gerror", exc_info=exc)
            raise IOError(str(exc)) 
Example #24
Source File: fs.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, gfile, mode='r'):
        super().__init__()
        self.gfile = gfile
        self.mode = mode

        if 'w' in mode and 'r' not in mode:
            self.size = 0
        elif ('w' in mode or 'a' in mode) and not gfile.query_exists():
            self.size = 0
        else:
            try:
                fi = gfile.query_info(
                    Gio.FILE_ATTRIBUTE_STANDARD_SIZE,
                    Gio.FileQueryInfoFlags.NONE
                )
                self.size = fi.get_attribute_uint64(
                    Gio.FILE_ATTRIBUTE_STANDARD_SIZE
                )
            except GLib.GError as exc:
                logger.warning("Gio.Gerror", exc_info=exc)
                raise IOError(str(exc))

        self.gfd = None
        self.gin = None
        self.gout = None

        if 'r' in mode:
            self.gin = self.gfd = gfile.read()
        elif 'w' in mode or 'a' in mode:
            if gfile.query_exists():
                self.gfd = gfile.open_readwrite()
            else:
                self.gfd = gfile.create_readwrite(Gio.FileCreateFlags.NONE)
            if 'w' in mode:
                self.gfd.seek(0, GLib.SeekType.SET)
                self.gfd.truncate(0)
            self.gin = self.gfd.get_input_stream()
            self.gout = self.gfd.get_output_stream()

        if 'a' in mode:
            self.seek(0, whence=os.SEEK_END) 
Example #25
Source File: silatycal.py    From Silaty with GNU General Public License v3.0 5 votes vote down vote up
def set_image_from_file(self, iconpath):
		try:
			pixbuf = GdkPixbuf.Pixbuf.new_from_file(iconpath)
			icon = Gtk.Image.new_from_pixbuf(pixbuf)
		except GLib.GError:
			icon = Gtk.Image.new_from_stock(Gtk.STOCK_MISSING_IMAGE, 22)
		return icon 
Example #26
Source File: sidebar.py    From Silaty with GNU General Public License v3.0 5 votes vote down vote up
def set_image_from_file(self, iconpath):
		try:
			pixbuf = GdkPixbuf.Pixbuf.new_from_file(iconpath)
			icon = Gtk.Image.new_from_pixbuf(pixbuf)
		except GLib.GError:
			icon = Gtk.Image.new_from_stock(Gtk.STOCK_MISSING_IMAGE, 22)
		return icon 
Example #27
Source File: daemon.py    From syncthing-gtk with GNU General Public License v2.0 5 votes vote down vote up
def _error(self, exception):
		if self._connection:
			self._connection.close(None)
		if self._epoch == self._parent._epoch:
			if isinstance(exception, GLib.GError):
				if exception.code in (0, 39, 34):	# Connection terminated unexpectedly, Connection Refused
					self._parent._disconnected(message=str(exception))
					return
			self._parent.timer(None, 1, self.start) 
Example #28
Source File: daemon.py    From syncthing-gtk with GNU General Public License v2.0 5 votes vote down vote up
def _syncthing_cb_config_error(self, exception, command):
		self.cancel_all()
		if isinstance(exception, GLib.GError):
			if exception.code in (0, 39, 34, 45):	# Connection Refused / Cannot connect to destination
				# It usually means that daemon is not yet fully started or not running at all.
				epoch = self._epoch
				self.emit("connection-error", Daemon.REFUSED, exception.message, exception)
				if epoch == self._epoch:
					r = RESTRequest(self, "system/config", self._syncthing_cb_config, self._syncthing_cb_config_error)
					self.timer("config", self._refresh_interval, r.start)
				return
		elif isinstance(exception, HTTPAuthException):
			self.emit("connection-error", Daemon.NOT_AUTHORIZED, exception.message, exception)
			return
		elif isinstance(exception, HTTPCode):
			# HTTP 404 may acually mean old daemon version
			version = get_header(exception.headers, "X-Syncthing-Version")
			if version != None and not compare_version(version, MIN_VERSION):
				self._epoch += 1
				msg = "daemon is too old"
				self.emit("connection-error", Daemon.OLD_VERSION, msg, Exception(msg))
			else:
				self.emit("connection-error", Daemon.UNKNOWN, exception.message, exception)
			return
		elif isinstance(exception, TLSUnsupportedException):
			self.emit("connection-error", Daemon.TLS_UNSUPPORTED, exception.message, exception)
			return
		elif isinstance(exception, ConnectionRestarted):
			# Happens on Windows. Just try again.
			GLib.idle_add(self._request_config)
			return
		elif isinstance(exception, TLSUnsupportedException):
			self.emit("connection-error", Daemon.TLS_UNSUPPORTED, exception.message, exception)
			return
		self.emit("connection-error", Daemon.UNKNOWN, exception.message, exception) 
Example #29
Source File: SubProcess.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        log.debug("SubProcess.start(): create_subprocess_exec...", extra={"task": self.defname})
        if sys.platform == "win32":
            # To prevent engines opening console window
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        else:
            startupinfo = None

        create = asyncio.create_subprocess_exec(* self.argv,
                                                stdin=asyncio.subprocess.PIPE,
                                                stdout=asyncio.subprocess.PIPE,
                                                startupinfo=startupinfo,
                                                env=self.env,
                                                cwd=self.cwd)
        try:
            self.proc = await asyncio.wait_for(create, TIME_OUT_SECOND)
            self.pid = self.proc.pid
            # print(self.pid, self.path)
            if self.lowPriority:
                proc = psutil.Process(self.pid)
                if sys.platform == "win32":
                    niceness = psutil.BELOW_NORMAL_PRIORITY_CLASS
                else:
                    niceness = 15  # The higher, the lower the priority
                if psutil.__version__ >= "2.0.0":
                    proc.nice(niceness)
                else:
                    proc.set_nice(niceness)
            self.read_stdout_task = create_task(self.read_stdout(self.proc.stdout))
            self.write_task = None
        except asyncio.TimeoutError:
            log.warning("TimeoutError", extra={"task": self.defname})
            raise
        except GLib.GError:
            log.warning("GLib.GError", extra={"task": self.defname})
            raise
        except Exception:
            e = sys.exc_info()[0]
            log.warning("%s" % e, extra={"task": self.defname})
            raise 
Example #30
Source File: interface.py    From RAFCON with Eclipse Public License 1.0 5 votes vote down vote up
def add_library_root_path_to_shortcut_folders_of_dialog(dialog):
    from gi.repository import GLib
    from rafcon.gui.singleton import library_manager
    library_paths = library_manager.library_root_paths
    library_keys = sorted(library_paths)
    for library_key in library_keys:
        try:
            dialog.add_shortcut_folder(library_paths[library_key])
        except GLib.GError:
            # this occurs if the shortcut file already exists
            # unfortunately dialog.list_shortcut_folders() does not work
            # that's why the error is caught
            pass