コード例 #1
0
    def download_cancel(self, all_=False, count=0):
        """Cancel the last/[count]th download.

        Args:
            all_: Cancel all running downloads
            count: The index of the download to cancel.
        """
        downloads = self._all_downloads()
        if all_:
            for download in downloads:
                if not download.done:
                    download.cancel()
        else:
            try:
                download = downloads[count - 1]
            except IndexError:
                self._raise_no_download(count)
            if download.done:
                if not count:
                    count = len(self)
                raise cmdutils.CommandError(
                    "Download {} is already done!".format(count))
            download.cancel()
コード例 #2
0
    def download_open(self, cmdline: str = None, count: int = 0) -> None:
        """Open the last/[count]th download.

        If no specific command is given, this will use the system's default
        application to open the file.

        Args:
            cmdline: The command which should be used to open the file. A `{}`
                     is expanded to the temporary file name. If no `{}` is
                     present, the filename is automatically appended to the
                     cmdline.
            count: The index of the download to open.
        """
        try:
            download = self[count - 1]
        except IndexError:
            self._raise_no_download(count)
        if not download.successful:
            if not count:
                count = len(self)
            raise cmdutils.CommandError(
                "Download {} is not done!".format(count))
        download.open_file(cmdline)
コード例 #3
0
    def prompt_accept(self, value=None, *, save=False):
        """Accept the current prompt.

        //

        This executes the next action depending on the question mode, e.g. asks
        for the password or leaves the mode.

        Args:
            value: If given, uses this value instead of the entered one.
                   For boolean prompts, "yes"/"no" are accepted as value.
            save: Save the value to the config.
        """
        question = self._prompt.question

        try:
            done = self._prompt.accept(value, save=save)
        except Error as e:
            raise cmdutils.CommandError(str(e))

        if done:
            message.global_bridge.prompt_done.emit(self._prompt.KEY_MODE)
            question.done()
コード例 #4
0
def printpage(tab: Optional[apitypes.Tab],
              preview: bool = False,
              *,
              pdf: str = None) -> None:
    """Print the current/[count]th tab.

    Args:
        preview: Show preview instead of printing.
        count: The tab index to print, or None.
        pdf: The file path to write the PDF to.
    """
    if tab is None:
        return

    try:
        if preview:
            _print_preview(tab)
        elif pdf:
            _print_pdf(tab, pdf)
        else:
            tab.printing.show_dialog()
    except apitypes.WebTabError as e:
        raise cmdutils.CommandError(e)
コード例 #5
0
ファイル: runners.py プロジェクト: zfenj/qutebrowser
def replace_variables(win_id, arglist):
    """Utility function to replace variables like {url} in a list of args."""
    tabbed_browser = objreg.get('tabbed-browser',
                                scope='window',
                                window=win_id)
    values = {}
    args = []

    def repl_cb(matchobj):
        """Return replacement for given match."""
        var = matchobj.group("var")
        if var not in values:
            values[var] = VARIABLE_REPLACEMENTS[var](tabbed_browser)
        return values[var]

    try:
        for arg in arglist:
            # using re.sub with callback function replaces all variables in a
            # single pass and avoids expansion of nested variables (e.g.
            # "{url}" from clipboard is not expanded)
            args.append(VARIABLE_REPLACEMENT_PATTERN.sub(repl_cb, arg))
    except utils.ClipboardError as e:
        raise cmdutils.CommandError(e)
    return args
コード例 #6
0
ファイル: utilcmds.py プロジェクト: ykgmfq/qutebrowser
def debug_pyeval(s, file=False, quiet=False):
    """Evaluate a python string and display the results as a web page.

    Args:
        s: The string to evaluate.
        file: Interpret s as a path to file, also implies --quiet.
        quiet: Don't show the output in a new tab.
    """
    if file:
        quiet = True
        path = os.path.expanduser(s)
        try:
            with open(path, 'r', encoding='utf-8') as f:
                s = f.read()
        except OSError as e:
            raise cmdutils.CommandError(str(e))
        try:
            exec(s)
            out = "No error"
        except Exception:
            out = traceback.format_exc()
    else:
        try:
            r = eval(s)
            out = repr(r)
        except Exception:
            out = traceback.format_exc()

    qutescheme.pyeval_output = out
    if quiet:
        log.misc.debug("pyeval output: {}".format(out))
    else:
        tabbed_browser = objreg.get('tabbed-browser',
                                    scope='window',
                                    window='last-focused')
        tabbed_browser.load_url(QUrl('qute://pyeval'), newtab=True)
コード例 #7
0
 def completion_item_del(self):
     """Delete the current completion item."""
     index = self.currentIndex()
     if not index.isValid():
         raise cmdutils.CommandError("No item selected!")
     self.model().delete_cur_item(index)
コード例 #8
0
    def start(
            self,  # pylint: disable=keyword-arg-before-vararg
            group: str = 'all',
            target: Target = Target.normal,
            *args: str,
            mode: str = None,
            add_history: bool = False,
            rapid: bool = False,
            first: bool = False) -> None:
        """Start hinting.

        Args:
            rapid: Whether to do rapid hinting. With rapid hinting, the hint
                   mode isn't left after a hint is followed, so you can easily
                   open multiple links. This is only possible with targets
                   `tab` (with `tabs.background=true`), `tab-bg`,
                   `window`, `run`, `hover`, `userscript` and `spawn`.
            add_history: Whether to add the spawned or yanked link to the
                         browsing history.
            first: Click the first hinted element without prompting.
            group: The element types to hint.

                - `all`: All clickable elements.
                - `links`: Only links.
                - `images`: Only images.
                - `inputs`: Only input fields.

                Custom groups can be added via the `hints.selectors` setting
                and also used here.

            target: What to do with the selected element.

                - `normal`: Open the link.
                - `current`: Open the link in the current tab.
                - `tab`: Open the link in a new tab (honoring the
                         `tabs.background` setting).
                - `tab-fg`: Open the link in a new foreground tab.
                - `tab-bg`: Open the link in a new background tab.
                - `window`: Open the link in a new window.
                - `hover` : Hover over the link.
                - `right-click`: Right-click the element.
                - `yank`: Yank the link to the clipboard.
                - `yank-primary`: Yank the link to the primary selection.
                - `run`: Run the argument as command.
                - `fill`: Fill the commandline with the command given as
                          argument.
                - `download`: Download the link.
                - `userscript`: Call a userscript with `$QUTE_URL` set to the
                                link.
                - `spawn`: Spawn a command.
                - `delete`: Delete the selected element.

            mode: The hinting mode to use.

                - `number`: Use numeric hints.
                - `letter`: Use the chars in the hints.chars setting.
                - `word`: Use hint words based on the html elements and the
                          extra words.

            *args: Arguments for spawn/userscript/run/fill.

                - With `spawn`: The executable and arguments to spawn.
                                `{hint-url}` will get replaced by the selected
                                URL.
                - With `userscript`: The userscript to execute. Either store
                                     the userscript in
                                     `~/.local/share/qutebrowser/userscripts`
                                     (or `$XDG_DATA_HOME`), or use an absolute
                                     path.
                - With `fill`: The command to fill the statusbar with.
                                `{hint-url}` will get replaced by the selected
                                URL.
                - With `run`: Same as `fill`.
        """
        tabbed_browser = objreg.get('tabbed-browser',
                                    scope='window',
                                    window=self._win_id)
        tab = tabbed_browser.widget.currentWidget()
        if tab is None:
            raise cmdutils.CommandError("No WebView available yet!")

        mode_manager = modeman.instance(self._win_id)
        if mode_manager.mode == usertypes.KeyMode.hint:
            modeman.leave(self._win_id, usertypes.KeyMode.hint, 're-hinting')

        if rapid:
            if target in [
                    Target.tab_bg, Target.window, Target.run, Target.hover,
                    Target.userscript, Target.spawn, Target.download,
                    Target.normal, Target.current, Target.yank,
                    Target.yank_primary
            ]:
                pass
            elif target == Target.tab and config.val.tabs.background:
                pass
            else:
                name = target.name.replace('_', '-')
                raise cmdutils.CommandError("Rapid hinting makes no sense "
                                            "with target {}!".format(name))

        self._check_args(target, *args)

        try:
            baseurl = tabbed_browser.current_url()
        except qtutils.QtValueError:
            raise cmdutils.CommandError("No URL set for this page yet!")

        self._context = HintContext(
            tab=tab,
            target=target,
            rapid=rapid,
            hint_mode=self._get_hint_mode(mode),
            add_history=add_history,
            first=first,
            baseurl=baseurl,
            args=list(args),
            group=group,
        )

        try:
            selector = webelem.css_selector(self._context.group,
                                            self._context.baseurl)
        except webelem.Error as e:
            raise cmdutils.CommandError(str(e))

        self._context.tab.elements.find_css(
            selector,
            callback=self._start_cb,
            error_cb=lambda err: message.error(str(err)),
            only_visible=True)
コード例 #9
0
 def _parse_key(self, key: str) -> keyutils.KeySequence:
     """Parse a key argument."""
     try:
         return keyutils.KeySequence.parse(key)
     except keyutils.KeyParseError as e:
         raise cmdutils.CommandError(str(e))
コード例 #10
0
 def _handle_config_error(self) -> typing.Iterator[None]:
     """Catch errors in set_command and raise CommandError."""
     try:
         yield
     except configexc.Error as e:
         raise cmdutils.CommandError(str(e))
コード例 #11
0
ファイル: urlutils.py プロジェクト: yarish/qutebrowser
def raise_cmdexc_if_invalid(url: QUrl) -> None:
    """Check if the given QUrl is invalid, and if so, raise a CommandError."""
    try:
        ensure_valid(url)
    except InvalidUrlError as e:
        raise cmdutils.CommandError(str(e))
コード例 #12
0
def knights_who_say_ni() -> None:
    """We are the Knights Who Say... 'Ni'!"""  # noqa: D400
    raise cmdutils.CommandError("Do you demand a shrubbery?")
コード例 #13
0
def raise_cmdexc_if_invalid(url):
    """Check if the given QUrl is invalid, and if so, raise a CommandError."""
    if not url.isValid():
        raise cmdutils.CommandError(get_errstring(url))
コード例 #14
0
def devtools_focus(tab: apitypes.Tab) -> None:
    """Toggle focus between the devtools/tab."""
    try:
        tab.data.splitter.cycle_focus()
    except apitypes.InspectorError as e:
        raise cmdutils.CommandError(e)
コード例 #15
0
ファイル: misccommands.py プロジェクト: mkonig/qutebrowser
def click_element(
        tab: apitypes.Tab,
        filter_: str,
        value: str = None,
        *,  # noqa: C901
        target: apitypes.ClickTarget = apitypes.ClickTarget.normal,
        force_event: bool = False,
        select_first: bool = False) -> None:
    """Click the element matching the given filter.

    The given filter needs to result in exactly one element, otherwise, an
    error is shown.

    Args:
        filter_: How to filter the elements.

            - id: Get an element based on its ID.
            - css: Filter by a CSS selector.
            - position: Click the element at specified position.
               Specify `value` as 'x,y'.
            - focused: Click the currently focused element.
        value: The value to filter for. Optional for 'focused' filter.
        target: How to open the clicked element (normal/tab/tab-bg/window).
        force_event: Force generating a fake click event.
        select_first: Select first matching element if there are multiple.
    """
    def do_click(elem: apitypes.WebElement) -> None:
        try:
            elem.click(target, force_event=force_event)
        except apitypes.WebElemError as e:
            message.error(str(e))

    def single_cb(elem: Optional[apitypes.WebElement]) -> None:
        """Click a single element."""
        if elem is None:
            message.error(
                f"No element found {_FILTER_ERRORS[filter_](value)}!")
            return

        do_click(elem)

    def multiple_cb(elems: Sequence[apitypes.WebElement]) -> None:
        if not elems:
            message.error(
                f"No element found {_FILTER_ERRORS[filter_](value)}!")
            return

        if not select_first and len(elems) > 1:
            message.error(
                f"Multiple elements found {_FILTER_ERRORS[filter_](value)}!")
            return

        do_click(elems[0])

    if value is None and filter_ != 'focused':
        raise cmdutils.CommandError("Argument 'value' is only "
                                    "optional with filter 'focused'!")

    if filter_ == "id":
        assert value is not None
        tab.elements.find_id(elem_id=value, callback=single_cb)
    elif filter_ == "css":
        assert value is not None
        tab.elements.find_css(
            value,
            callback=multiple_cb,
            error_cb=lambda exc: message.error(str(exc)),
        )
    elif filter_ == "position":
        assert value is not None
        _wrap_find_at_pos(value, tab=tab, callback=single_cb)
    elif filter_ == "focused":
        tab.elements.find_focused(callback=single_cb)
    else:
        raise utils.Unreachable(filter_)