Example #1
0
def thumbnail_ora(procedure, file, thumb_size, args, data):
    tempdir = tempfile.mkdtemp('gimp-plugin-file-openraster')
    orafile = zipfile.ZipFile(file.peek_path())
    stack, w, h = get_image_attributes(orafile)

    # create temp file
    tmp = os.path.join(tempdir, 'tmp.png')
    with open(tmp, 'wb') as fid:
        fid.write(orafile.read('Thumbnails/thumbnail.png'))

    thumb_file = Gio.file_new_for_path(tmp)
    result = Gimp.get_pdb().run_procedure('file-png-load', [
        GObject.Value(Gimp.RunMode, Gimp.RunMode.NONINTERACTIVE),
        GObject.Value(Gio.File, thumb_file),
    ])
    os.remove(tmp)
    os.rmdir(tempdir)

    if (result.index(0) == Gimp.PDBStatusType.SUCCESS):
        img = result.index(1)
        # TODO: scaling

        return Gimp.ValueArray.new_from_values([
            GObject.Value(Gimp.PDBStatusType, Gimp.PDBStatusType.SUCCESS),
            GObject.Value(Gimp.Image, img),
            GObject.Value(GObject.TYPE_INT, w),
            GObject.Value(GObject.TYPE_INT, h),
            GObject.Value(Gimp.ImageType, Gimp.ImageType.RGB_IMAGE),
            GObject.Value(GObject.TYPE_INT, 1)
        ])
    else:
        return procedure.new_return_values(result.index(0),
                                           GLib.Error(result.index(1)))
Example #2
0
    def on_epub_scheme(self, request):
        """Callback function for epub scheme requests

        Finish a WebKit2.URISchemeRequest by setting the contents of the request
        and its mime type.

        Args:
            request (WebKit2.URISchemeRequest)
        """
        if not self.doc:
            return

        uri = request.get_uri()
        logger.info('Resource request:' + uri)
        try:
            path, fragment = self.get_path_fragment(uri)
            if self.jump_to_path_fragment(path, fragment):
                return
        except BookError as e:
            error_str = str(e)
            logger.error('Could not get resource:' + error_str)
            request.finish_error(GLib.Error(error_str))
        else:
            bytes = self.doc.get_resource(path)
            gbytes = GLib.Bytes(bytes)
            stream = Gio.MemoryInputStream.new_from_bytes(gbytes)
            stream_length = gbytes.get_size()
            mime = self.doc.get_resource_mime(path)

            request.finish(stream, stream_length, mime)
Example #3
0
 def expand_all_cb(self, obj, result, task):
     try:
         self.expand_all_finish(result)
         task.return_boolean(True)
     except Exception as exc:
         print(exc)
         task.return_error(GLib.Error(repr(exc)))
Example #4
0
 def test_matches(self):
     mydomain = GLib.quark_from_string('mydomain')
     notmydomain = GLib.quark_from_string('notmydomain')
     e = GLib.Error('test message', 'mydomain', 42)
     self.assertTrue(e.matches(mydomain, 42))
     self.assertFalse(e.matches(notmydomain, 42))
     self.assertFalse(e.matches(mydomain, 40))
Example #5
0
    def _on_epub_scheme(self, request):
        """Callback function for epub scheme requests

        Finish a WebKit2.URISchemeRequest by setting the contents of
        the request and its mime type.

        Args:
            request (WebKit2.URISchemeRequest)
        """
        if not self.doc:
            return

        uri = request.get_uri()

        try:
            path, fragment = self._get_path_fragment(uri)
        except BookError as e:
            error_str = e.args[1]
            request.finish_error(GLib.Error(error_str))
            return

        if self.doc.is_page(path):
            self.set_chapter_path_fragment(path, fragment)
            return

        resource_content = self.doc.get_resource_content(path)
        resource_gbytes = GLib.Bytes(resource_content)
        stream = Gio.MemoryInputStream.new_from_bytes(resource_gbytes)
        stream_length = resource_gbytes.get_size()
        mime = self.doc.get_resource_mime(path)

        request.finish(stream, stream_length, mime)
Example #6
0
 def __on_web_process_crashed(self, view):
     """
         We just crashed :-(
         @param view as WebKit2.WebView
     """
     self._error = GLib.Error()
     f = Gio.File.new_for_uri("resource:///org/gnome/Eolie/error.css")
     (status, css_content, tag) = f.load_contents(None)
     css = css_content.decode("utf-8")
     f = Gio.File.new_for_uri("resource:///org/gnome/Eolie/error.html")
     (status, content, tag) = f.load_contents(None)
     html = content.decode("utf-8")
     html = html % (_("WebKit web engine crashed"), css,
                    "load_uri('https://bugs.webkit.org/"
                    "enter_bug.cgi?product=WebKit')",
                    "internal:/help-faq-symbolic",
                    _("WebKit web engine crashed"), "",
                    _("The webpage was terminated unexpectedly."
                      "To continue, reload or go to another page.<br/><br/>"
                      "If problem persist, you can report a bug :)<br/>"
                      "Use <b>'Webkit Gtk'</b> as component.<br/>"
                      "Set <b>[GTK]</b> as subject prefix."),
                    "suggested-action", _("Report a bug now"))
     self.load_html(html, view.get_uri())
     return True
Example #7
0
    def do_get_targets_async(self, cancellable, callback, data):
        task = Ide.Task.new(self, cancellable, callback)
        task.set_priority(GLib.PRIORITY_LOW)

        context = self.get_context()
        build_system = Ide.BuildSystem.from_context(context)

        if type(build_system) != SwiftBuildSystem:
            task.return_error(
                GLib.Error('Not swift build system',
                           domain=GLib.quark_to_string(Gio.io_error_quark()),
                           code=Gio.IOErrorEnum.NOT_SUPPORTED))
            return

        print(Ide.BuildSystem.from_context(context).project_file.get_path())
        pkg_dump = check_output(
            ["swift", "package", "dump-package"],
            cwd=Ide.BuildSystem.from_context(context).project_file.get_path(),
            universal_newlines=True)
        pkg_set = json.loads(pkg_dump)
        task.targets = []
        for target in pkg_set["targets"]:
            #if target["type"] == "regular":
            newtarget = SwiftBuildTarget(target["name"])
            print("newtarget = ", newtarget.target_name)
            task.targets.append(build_system.ensure_child_typed(newtarget))

        task.return_boolean(True)
Example #8
0
        def build_flags_thread():
            commands_file = path.join(self._get_build_dir().get_path(),
                                      'compile_commands.json')
            try:
                with open(commands_file) as f:
                    commands = json.loads(f.read(), encoding='utf-8')
            except (json.JSONDecodeError, FileNotFoundError,
                    UnicodeDecodeError) as e:
                task.return_error(
                    GLib.Error('Failed to decode meson json: {}'.format(e)))
                return

            infile = ifile.get_path()
            for c in commands:
                filepath = path.normpath(path.join(c['directory'], c['file']))
                if filepath == infile:
                    try:
                        task.build_flags = extract_flags(c['command'])
                    except GLib.Error as e:
                        task.return_error(e)
                        return
                    break
            else:
                print('Meson: Warning: No flags found')

            task.return_boolean(True)
Example #9
0
    def register(self):
        node_xml = "<node name='/'><interface name='%s'>" % self._interface_name
        for method_name, method_info in self._methods.items():
            node_xml += "<method name='%s'>" % method_name
            for argument in method_info[0]:
                node_xml += "<arg type='%s' direction='in'/>" % argument
            if method_info[1]:
                node_xml += "<arg type='%s' direction='out'/>" % method_info[1]
            node_xml += "</method>"
        for signal_name, signal_signature in self._signals.items():
            node_xml += "<signal name='%s'>" % signal_name
            if signal_signature:
                node_xml += "<arg type='%s'/>" % signal_signature
            node_xml += "</signal>"
        node_xml += "</interface></node>"

        node_info = Gio.DBusNodeInfo.new_for_xml(node_xml)

        regid = self._bus.register_object(self._path, node_info.interfaces[0],
                                          self._handle_method_call, None, None)

        if regid:
            self._regid = regid
        else:
            raise GLib.Error('Failed to register object with path: %s',
                             self._path)
Example #10
0
    def on_disconnect(self,
                      _item: Gtk.MenuItem,
                      service: Service,
                      port: int = 0) -> None:
        def ok(_obj: AppletService, _result: None, _user_date: None) -> None:
            logging.info("disconnect success")
            self.generate()

        def err(_obj: Optional[AppletService], result: GLib.Error,
                _user_date: None) -> None:
            logging.warning(f"disconnect failed {result}")
            msg, tb = e_(result.message)
            MessageArea.show_message(_("Disconnection Failed: ") + msg, tb)
            self.generate()

        if self._appl is None:
            err(None, GLib.Error('Applet DBus Service not available'), None)
            return

        self._appl.DisconnectService('(osd)',
                                     service.device.get_object_path(),
                                     service.uuid,
                                     port,
                                     result_handler=ok,
                                     error_handler=err)
Example #11
0
    def on_connect(self, _item, service):
        device = service.device

        def success(obj, result, _user_data):
            logging.info("success")
            prog.message(_("Success!"))

            if isinstance(service, SerialPort) and SERIAL_PORT_SVCLASS_ID == service.short_uuid:
                MessageArea.show_message(_("Serial port connected to %s") % result, None, "dialog-information")
            else:
                MessageArea.close()

            self.unset_op(device)

        def fail(obj, result, _user_data):
            prog.message(_("Failed"))

            self.unset_op(device)
            logging.warning("fail %s" % result)
            msg, tb = e_(result.message)
            MessageArea.show_message(_("Connection Failed: ") + msg, tb)

        self.set_op(device, _("Connecting..."))
        prog = ManagerProgressbar(self.Blueman, False)

        if self._appl is None:
            fail(None, GLib.Error('Applet DBus Service not available'), None)
            return

        self._appl.ConnectService('(os)', device.get_object_path(), service.uuid,
                                  result_handler=success, error_handler=fail,
                                  timeout=GLib.MAXINT)

        prog.start()
Example #12
0
    def disconnect_service(self,
                           device: Device,
                           uuid: str = GENERIC_CONNECT,
                           port: int = 0) -> None:
        def ok(_obj: AppletService, _result: None, _user_date: None) -> None:
            logging.info("disconnect success")
            self.generate()

        def err(_obj: Optional[AppletService], result: GLib.Error,
                _user_date: None) -> None:
            logging.warning(f"disconnect failed {result}")
            msg, tb = e_(result.message)
            MessageArea.show_message(_("Disconnection Failed: ") + msg, tb)
            self.generate()

        if self._appl is None:
            err(None, GLib.Error('Applet DBus Service not available'), None)
            return

        self._appl.DisconnectService('(osd)',
                                     device.get_object_path(),
                                     uuid,
                                     port,
                                     result_handler=ok,
                                     error_handler=err,
                                     timeout=GLib.MAXINT)
Example #13
0
 def do_find_nearest_scope_async(self,
                                 location,
                                 cancellable,
                                 callback,
                                 user_data=None):
     task = Gio.Task.new(self, cancellable, callback)
     task.return_error(GLib.Error('Not implemented'))
    def do_update_async(self, cancellable, callback, data):
        task = Gio.Task.new(self, cancellable, callback)
        task.set_priority(GLib.PRIORITY_LOW)

        context = self.get_context()
        build_system = context.get_build_system()

        if type(build_system) != DubBuildSystem:
            task.return_boolean(True)
            return

        build_manager = context.get_build_manager()
        pipeline = build_manager.get_pipeline()

        if not pipeline:
            task.return_error(
                GLib.Error('Cannot update dependencies without build pipeline',
                           domain=GLib.quark_to_string(Gio.io_error_quark()),
                           code=Gio.IOErrorEnum.FAILED))
            return

        launcher = pipeline.create_launcher()
        launcher.push_argv("dub")
        launcher.push_argv("--root=" + get_working_dir(context).get_path())
        launcher.push_argv("upgrade")

        try:
            subprocess = launcher.spawn()
            subprocess.wait_check_async(None, self.wait_check_cb, task)
        except Exception as ex:
            task.return_error(ex)
Example #15
0
    def _get_build_flags_build_communicate_cb(self, subprocess, result, task):
        """
        Completes the asynchronous request to get the build flags from the make
        helper subprocess.
        """
        try:
            _, stdout, stderr = subprocess.communicate_utf8_finish(result)

            info = {}
            for line in stdout.split('\n'):
                if '=' in line:
                    k, v = line.split('=', 1)
                    info[k.strip()] = v.strip()

            if task.type == _TYPE_C:
                flags = info.get('CFLAGS', '') + " " + info.get('INCLUDES', '')
            elif task.type == _TYPE_CPLUSPLUS:
                flags = info.get('CXXFLAGS', '') + " " + info.get(
                    'INCLUDES', '')
            else:
                raise RuntimeError

            _, build_flags = GLib.shell_parse_argv(flags)

            task.build_flags = build_flags
            task.return_boolean(True)

        except Exception as ex:
            print(repr(ex))
            task.return_error(GLib.Error(message=repr(ex)))
Example #16
0
 def do_lookup_symbol_async(self,
                            location,
                            cancellable,
                            callback,
                            user_data=None):
     task = Gio.Task.new(self, cancellable, callback)
     task.return_error(GLib.Error('Not implemented'))
Example #17
0
    def get_sphinx_rst_worker(self, task, text, path, basedir, builddir):
        add_override_file(path, text)

        if GLib.find_program_in_path('sphinx-build-3'):
            program = 'sphinx-build-3'
        else:
            program = 'sphinx-build'

        rel_path = os.path.relpath(path, start=basedir)
        command = [program, '-Q', '-b', 'html', basedir, builddir, path]

        rel_path_html = os.path.splitext(rel_path)[0] + '.html'
        builddir_path = os.path.join(builddir, rel_path_html)

        try:
            launcher = Ide.SubprocessLauncher.new(
                0)  # Gio.SubprocessFlags.STDOUT_SILENCE |
            # Gio.SubprocessFlags.STDERR_SILENCE)
            launcher.push_args(command)
            subprocess = launcher.spawn()
            subprocess.wait_check()

            task.builddir_path = builddir_path
            task.return_boolean(True)
        except Exception as ex:
            task.return_error(GLib.Error(ex))
        finally:
            remove_override_file(path)
Example #18
0
    def register(self) -> None:
        node_xml = f"<node name='/'><interface name='{self._interface_name}'>"
        for property_name, signature in self._properties.items():
            node_xml += f"<property name='{property_name}' type='{signature}' access='read'/>"
        for method_name, method_info in self._methods.items():
            node_xml += f"<method name='{method_name}'>"
            for argument in method_info[0]:
                node_xml += f"<arg type='{argument}' direction='in'/>"
            for result in method_info[1]:
                node_xml += f"<arg type='{result}' direction='out'/>"
            node_xml += "</method>"
        for signal_name, signal_signature in self._signals.items():
            node_xml += f"<signal name='{signal_name}'>"
            for signature in signal_signature:
                node_xml += f"<arg type='{signature}'/>"
            node_xml += "</signal>"
        node_xml += "</interface></node>"

        node_info = Gio.DBusNodeInfo.new_for_xml(node_xml)

        regid = self._bus.register_object(self._path, node_info.interfaces[0],
                                          self._handle_method_call,
                                          self._get_property, None)

        if regid:
            self._regid = regid
        else:
            raise GLib.Error(
                f"Failed to register object with path: {self._path}")
Example #19
0
    def on_drag_data_received(self, widget: Gtk.Widget,
                              drag_context: Gdk.DragContext, x: int, y: int,
                              data: Gtk.SelectionData, info: int,
                              time: int) -> None:
        drop_source: Tuple[str, Any] = GLib.filename_from_uri(data.get_text())
        folder_path: str = drop_source[0].rstrip()
        saved_folders: List[str] = self.settings.get_value(
            'saved-folders').unpack()

        try:
            if GLib.file_test(folder_path, GLib.FileTest.IS_DIR):
                self._main_label_box.props.visible = False
                label: str = folder_path
                folder: FolderBox = FolderBox(label)
                self._main_list_box.props.visible = True
                folder.set_title(label)
                self._main_list_box.add(folder)
                saved_folders.append(label)
                self.settings.set_value('saved-folders',
                                        GLib.Variant('as', saved_folders))
            else:
                raise GLib.Error(
                    message=f'Error: {folder_path} is not a folder.')
        except GLib.Error as err:
            print('%s' % err.message)
Example #20
0
    def _get_build_flags_build_cb(self, build_manager, result, task):
        """
        Completes the asynchronous call to advance the pipeline to CONFIGURE phase
        and then runs a make subprocess to extract build flags from Makefile.
        """
        try:
            build_manager.build_finish(result)

            pipeline = build_manager.get_pipeline()

            # Launcher defaults to $builddir
            launcher = pipeline.create_launcher()
            launcher.set_flags(Gio.SubprocessFlags.STDIN_PIPE
                               | Gio.SubprocessFlags.STDOUT_PIPE
                               | Gio.SubprocessFlags.STDERR_PIPE)
            launcher.push_argv('make')
            launcher.push_argv('-f')
            launcher.push_argv('-')
            launcher.push_argv('print-CFLAGS')
            launcher.push_argv('print-CXXFLAGS')
            launcher.push_argv('print-INCLUDES')
            subprocess = launcher.spawn()
            subprocess.communicate_utf8_async(
                _BUILD_FLAGS_STDIN_BUF, task.get_cancellable(),
                self._get_build_flags_build_communicate_cb, task)
        except Exception as ex:
            print(repr(ex))
            task.return_error(GLib.Error(message=repr(ex)))
Example #21
0
 def __on_web_process_crashed(self, view):
     """
         We just crashed :-(
         @param view as WebKit2.WebView
     """
     self._error = GLib.Error()
     print("WebViewErrors::__on_web_process_crashed():", view)
Example #22
0
 def signal_wait_timeout(self):
     if not self.device or not self.connection:
         self.err_cb(
             GLib.Error("Network Manager did not support the connection"))
         if self.connection:
             self.remove_connection()
         self.cleanup()
Example #23
0
 def do_find_references_async(self,
                              location,
                              language_id,
                              cancellable,
                              callback,
                              user_data=None):
     task = Gio.Task.new(self, cancellable, callback)
     task.return_error(GLib.Error('Not implemented'))
Example #24
0
 def expand_all_cb(self, obj, result, task):
     try:
         self.expand_all_finish(result)
         task.return_boolean(True)
     except Exception as exc:
         if isinstance(exc, GLib.Error):
             task.return_error(exc)
         else:
             task.return_error(GLib.Error(repr(exc)))
Example #25
0
 def do_generate_key_async(self,
                           location,
                           flags,
                           cancellable,
                           callback,
                           user_data=None):
     # print('generate key')
     task = Gio.Task.new(self, cancellable, callback)
     task.return_error(GLib.Error('Not implemented'))
Example #26
0
    def _get_tree_thread(self, task, launcher, file_):
        try:
            proc = launcher.spawn()
            success, stdout, stderr = proc.communicate_utf8(None, None)

            if not success:
                task.return_error(GLib.Error('Failed to run gjs'))
                return

            task.symbol_tree = JsSymbolTree(json.loads(stdout), file_)
        except GLib.Error as err:
            task.return_error(err)
        except (json.JSONDecodeError, UnicodeDecodeError) as e:
            task.return_error(GLib.Error('Failed to decode gjs json: {}'.format(e)))
        except (IndexError, KeyError) as e:
            task.return_error(GLib.Error('Failed to extract information from ast: {}'.format(e)))
        else:
            task.return_boolean(True)
Example #27
0
    def execute(self, task, launcher, srcdir, file, file_content):
        try:
            launcher.push_args(
                (self._get_eslint(srcdir), '-f', 'json', '--ignore-pattern',
                 '!node_modules/*', '--ignore-pattern', '!bower_components/*'))

            if file_content:
                launcher.push_argv('--stdin')
                launcher.push_argv('--stdin-filename=' + file.get_path())
            else:
                launcher.push_argv(file.get_path())

            sub_process = launcher.spawn()
            success, stdout, stderr = sub_process.communicate_utf8(
                file_content, None)

            if not success:
                task.return_boolean(False)
                return

            results = json.loads(stdout)
            for result in results:
                for message in result.get('messages', []):
                    if 'line' not in message or 'column' not in message:
                        continue
                    start_line = max(message['line'] - 1, 0)
                    start_col = max(message['column'] - 1, 0)
                    start = Ide.SourceLocation.new(file, start_line, start_col,
                                                   0)
                    end = None
                    if 'endLine' in message:
                        end_line = max(message['endLine'] - 1, 0)
                        end_col = max(message['endColumn'] - 1, 0)
                        end = Ide.SourceLocation.new(file, end_line, end_col,
                                                     0)

                    severity = SEVERITY_MAP[message['severity']]
                    diagnostic = Ide.Diagnostic.new(severity,
                                                    message['message'], start)
                    if end is not None:
                        range_ = Ide.SourceRange.new(start, end)
                        diagnostic.add_range(range_)
                        # if 'fix' in message:
                        # Fixes often come without end* information so we
                        # will rarely get here, instead it has a file offset
                        # which is not actually implemented in IdeSourceLocation
                        # fixit = Ide.Fixit.new(range_, message['fix']['text'])
                        # diagnostic.take_fixit(fixit)

                    task.diagnostics_list.append(diagnostic)
        except GLib.Error as err:
            task.return_error(err)
        except (json.JSONDecodeError, UnicodeDecodeError, IndexError) as e:
            task.return_error(
                GLib.Error('Failed to decode eslint json: {}'.format(e)))
        else:
            task.return_boolean(True)
Example #28
0
    def test_gerror_boxing(self):
        error = GLib.Error('test message', domain='mydomain', code=42)
        value = GObject.Value(GLib.Error, error)
        self.assertEqual(value.g_type, GObject.type_from_name('GError'))

        unboxed = value.get_value()
        self.assertEqual(unboxed.message, error.message)
        self.assertEqual(unboxed.domain, error.domain)
        self.assertEqual(unboxed.code, error.code)
Example #29
0
    def _index_file_cb(self, subprocess, result, task):
        try:
            _, stdout, stderr = subprocess.communicate_utf8_finish(result)

            ide_file = Ide.File(file=task.file, context=self.get_context())
            try:
                root_node = JsSymbolTree._node_from_dict(json.loads(stdout), ide_file)
            except (json.JSONDecodeError, UnicodeDecodeError) as e:
                raise GLib.Error('Failed to decode gjs json: {}'.format(e))
            except (IndexError, KeyError) as e:
                raise GLib.Error('Failed to extract information from ast: {}'.format(e))

            builder = Ide.CodeIndexEntryBuilder()

            entries = []
            # TODO: Avoid recreating the same data
            for node in self._flatten_node_list(root_node):
                builder.set_key(node.props.file.get_path() + '|' + node.props.name) # Some unique value..
                builder.set_name(self._get_node_name(node))
                builder.set_kind(node.props.kind)
                builder.set_flags(node.props.flags)
                # Not sure why offset here doesn't match tree
                builder.set_range(node.props.line + 1, node.props.col + 1, 0, 0)
                entries.append(builder.build())

            task.entries = JsCodeIndexEntries(task.file, entries)
            task.return_boolean(True)

        except Exception as ex:
            print(repr(ex))
            task.return_error(GLib.Error(message=repr(ex)))

        finally:
            try:
                if self.queue:
                    task = self.queue.pop(0)
                    launcher = GjsSymbolProvider._get_launcher(self.get_context(), task.file)
                    proc = launcher.spawn()
                    proc.communicate_utf8_async(None, task.get_cancellable(), self._index_file_cb, task)
                    return
            except Exception as ex:
                print(repr(ex))

            self.active = False
Example #30
0
                def update_title_task_func(task, source_object, task_data, cancellable):
                    try:
                        html = urllib.request.urlopen(self._data).read().decode("UTF-8")
                        soup = BeautifulSoup(html, "html.parser")
                        value = GObject.Value(str, soup.title.string)

                        task.return_value(value)
                    except (urllib.error.HTTPError, urllib.error.URLError) as ex:
                        error = GLib.Error("Fetching title for problem report failed: %s" % (ex))
                        task.return_error(error)