示例#1
0
def later(ms: int, command: str, win_id: int) -> None:
    """Execute a command after some time.

    Args:
        ms: How many milliseconds to wait.
        command: The command to run, with optional args.
    """
    if ms < 0:
        raise cmdutils.CommandError("I can't run something in the past!")
    commandrunner = runners.CommandRunner(win_id)
    app = objreg.get('app')
    timer = usertypes.Timer(name='later', parent=app)
    try:
        timer.setSingleShot(True)
        try:
            timer.setInterval(ms)
        except OverflowError:
            raise cmdutils.CommandError("Numeric argument is too large for "
                                        "internal int representation.")
        timer.timeout.connect(
            functools.partial(commandrunner.run_safely, command))
        timer.timeout.connect(timer.deleteLater)
        timer.start()
    except:
        timer.deleteLater()
        raise
示例#2
0
def zoom(tab: apitypes.Tab,
         level: str = None,
         count: int = None,
         quiet: bool = False) -> None:
    """Set the zoom level for the current tab.

    The zoom can be given as argument or as [count]. If neither is
    given, the zoom is set to the default zoom. If both are given,
    use [count].

    Args:
        level: The zoom percentage to set.
        count: The zoom percentage to set.
        quiet: Don't show a zoom level message.
    """
    if count is not None:
        int_level = count
    elif level is not None:
        try:
            int_level = int(level.rstrip('%'))
        except ValueError:
            raise cmdutils.CommandError("zoom: Invalid int value {}"
                                        .format(level))
    else:
        int_level = int(config.val.zoom.default)

    try:
        tab.zoom.set_factor(int_level / 100)
    except ValueError:
        raise cmdutils.CommandError("Can't zoom {}%!".format(int_level))
    if not quiet:
        message.info("Zoom level: {}%".format(int_level), replace=True)
示例#3
0
def debug_trace(expr: str = "") -> None:
    """Trace executed code via hunter.

    Args:
        expr: What to trace, passed to hunter.
    """
    if hunter is None:
        raise cmdutils.CommandError("You need to install 'hunter' to use this "
                                    "command!")
    try:
        eval('hunter.trace({})'.format(expr))
    except Exception as e:
        raise cmdutils.CommandError("{}: {}".format(e.__class__.__name__, e))
示例#4
0
 def restart_cmd(self):
     """Restart glimpsebrowser while keeping existing tabs open."""
     try:
         ok = self.restart(session='_restart')
     except sessions.SessionError as e:
         log.destroy.exception("Failed to save session!")
         raise cmdutils.CommandError(
             "Failed to save session: {}!".format(e))
     except SyntaxError as e:
         log.destroy.exception("Got SyntaxError")
         raise cmdutils.CommandError("SyntaxError in {}:{}: {}".format(
             e.filename, e.lineno, e))
     if ok:
         self.shutdown(restart=True)
示例#5
0
    def run_macro(self, win_id, register):
        """Run a recorded macro."""
        if register == '@':
            if self._last_register is None:
                raise cmdutils.CommandError("No previous macro")
            register = self._last_register
        self._last_register = register

        if register not in self._macros:
            raise cmdutils.CommandError(
                "No macro recorded in '{}'!".format(register))

        commandrunner = runners.CommandRunner(win_id)
        for _ in range(self._macro_count[win_id]):
            for cmd in self._macros[register]:
                commandrunner.run_safely(*cmd)
示例#6
0
def scroll(tab: apitypes.Tab, direction: str, count: int = 1) -> None:
    """Scroll the current tab in the given direction.

    Note you can use `:run-with-count` to have a keybinding with a bigger
    scroll increment.

    Args:
        direction: In which direction to scroll
                    (up/down/left/right/top/bottom).
        count: multiplier
    """
    funcs = {
        'up': tab.scroller.up,
        'down': tab.scroller.down,
        'left': tab.scroller.left,
        'right': tab.scroller.right,
        'top': tab.scroller.top,
        'bottom': tab.scroller.bottom,
        'page-up': tab.scroller.page_up,
        'page-down': tab.scroller.page_down,
    }
    try:
        func = funcs[direction]
    except KeyError:
        expected_values = ', '.join(sorted(funcs))
        raise cmdutils.CommandError("Invalid value {!r} for direction - "
                                    "expected one of: {}".format(
                                        direction, expected_values))

    if direction in ['top', 'bottom']:
        func()
    else:
        func(count=count)
示例#7
0
    def session_save(self, name: typing.Union[str, Sentinel] = default,
                     current: bool = False,
                     quiet: bool = False,
                     force: bool = False,
                     only_active_window: bool = False,
                     with_private: bool = False,
                     win_id: int = None) -> None:
        """Save a session.

        Args:
            name: The name of the session. If not given, the session configured
                  in session.default_name is saved.
            current: Save the current session instead of the default.
            quiet: Don't show confirmation message.
            force: Force saving internal sessions (starting with an underline).
            only_active_window: Saves only tabs of the currently active window.
            with_private: Include private windows.
        """
        if (not isinstance(name, Sentinel) and
                name.startswith('_') and
                not force):
            raise cmdutils.CommandError("{} is an internal session, use "
                                        "--force to save anyways."
                                        .format(name))
        if current:
            if self._current is None:
                raise cmdutils.CommandError("No session loaded currently!")
            name = self._current
            assert not name.startswith('_')
        try:
            if only_active_window:
                name = self.save(name, only_window=win_id,
                                 with_private=True)
            else:
                name = self.save(name, with_private=with_private)
        except SessionError as e:
            raise cmdutils.CommandError("Error while saving session: {}"
                                        .format(e))
        else:
            if quiet:
                log.sessions.debug("Saved session {}.".format(name))
            else:
                message.info("Saved session {}.".format(name))
示例#8
0
    def enter_mode(self, mode):
        """Enter a key mode.

        Args:
            mode: The mode to enter. See `:help bindings.commands` for the
                  available modes, but note that hint/command/yesno/prompt mode
                  can't be entered manually.
        """
        try:
            m = usertypes.KeyMode[mode]
        except KeyError:
            raise cmdutils.CommandError("Mode {} does not exist!".format(mode))

        if m in [usertypes.KeyMode.hint, usertypes.KeyMode.command,
                 usertypes.KeyMode.yesno, usertypes.KeyMode.prompt]:
            raise cmdutils.CommandError(
                "Mode {} can't be entered manually!".format(mode))

        self.enter(m, 'command')
示例#9
0
def log_capacity(capacity: int) -> None:
    """Change the number of log lines to be stored in RAM.

    Args:
       capacity: Number of lines for the log.
    """
    if capacity < 0:
        raise cmdutils.CommandError("Can't set a negative log capacity!")
    assert log.ram_handler is not None
    log.ram_handler.change_log_capacity(capacity)
示例#10
0
def _url(tabbed_browser):
    """Convenience method to get the current url."""
    try:
        return tabbed_browser.current_url()
    except qtutils.QtValueError as e:
        msg = "Current URL is invalid"
        if e.reason:
            msg += " ({})".format(e.reason)
        msg += "!"
        raise cmdutils.CommandError(msg)
示例#11
0
def tab_mute(tab: typing.Optional[apitypes.Tab]) -> None:
    """Mute/Unmute the current/[count]th tab.

    Args:
        count: The tab index to mute or unmute, or None
    """
    if tab is None:
        return
    try:
        tab.audio.set_muted(not tab.audio.is_muted(), override=True)
    except apitypes.WebTabError as e:
        raise cmdutils.CommandError(e)
示例#12
0
def repeat_command(win_id, count=None):
    """Repeat the last executed command.

    Args:
        count: Which count to pass the command.
    """
    mode_manager = objreg.get('mode-manager', scope='window', window=win_id)
    if mode_manager.mode not in runners.last_command:
        raise cmdutils.CommandError("You didn't do anything yet.")
    cmd = runners.last_command[mode_manager.mode]
    commandrunner = runners.CommandRunner(win_id)
    commandrunner.run(cmd[0], count if count is not None else cmd[1])
示例#13
0
def debug_log_filter(filters: str) -> None:
    """Change the log filter for console logging.

    Args:
        filters: A comma separated list of logger names. Can also be "none" to
                 clear any existing filters.
    """
    if log.console_filter is None:
        raise cmdutils.CommandError("No log.console_filter. Not attached "
                                    "to a console?")

    if filters.strip().lower() == 'none':
        log.console_filter.names = None
        return

    if not set(filters.split(',')).issubset(log.LOGGER_NAMES):
        raise cmdutils.CommandError("filters: Invalid value {} - expected one "
                                    "of: {}".format(
                                        filters, ', '.join(log.LOGGER_NAMES)))

    log.console_filter.names = filters.split(',')
    def completion_item_focus(self, which, history=False):
        """Shift the focus of the completion menu to another item.

        Args:
            which: 'next', 'prev', 'next-category', or 'prev-category'.
            history: Navigate through command history if no text was typed.
        """
        if history:
            status = objreg.get('status-command',
                                scope='window',
                                window=self._win_id)
            if (status.text() == ':' or status.history.is_browsing()
                    or not self._active):
                if which == 'next':
                    status.command_history_next()
                    return
                elif which == 'prev':
                    status.command_history_prev()
                    return
                else:
                    raise cmdutils.CommandError("Can't combine --history with "
                                                "{}!".format(which))

        if not self._active:
            return

        selmodel = self.selectionModel()
        indices = {
            'next': self._next_idx(upwards=False),
            'prev': self._next_idx(upwards=True),
            'next-category': self._next_category_idx(upwards=False),
            'prev-category': self._next_category_idx(upwards=True),
        }
        idx = indices[which]

        if not idx.isValid():
            return

        selmodel.setCurrentIndex(
            idx, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)

        # if the last item is focused, try to fetch more
        if idx.row() == self.model().rowCount(idx.parent()) - 1:
            self.expandAll()

        count = self.model().count()
        if count == 0:
            self.hide()
        elif count == 1 and config.val.completion.quick:
            self.hide()
        elif config.val.completion.show == 'auto':
            self.show()
示例#15
0
    def session_delete(self, name, force=False):
        """Delete a session.

        Args:
            name: The name of the session.
            force: Force deleting internal sessions (starting with an
                   underline).
        """
        if name.startswith('_') and not force:
            raise cmdutils.CommandError("{} is an internal session, use "
                                        "--force to delete anyways."
                                        .format(name))
        try:
            self.delete(name)
        except SessionNotFoundError:
            raise cmdutils.CommandError("Session {} not found!".format(name))
        except SessionError as e:
            log.sessions.exception("Error while deleting session!")
            raise cmdutils.CommandError("Error while deleting session: {}"
                                        .format(e))
        else:
            log.sessions.debug("Deleted session {}.".format(name))
示例#16
0
def zoom_out(tab: apitypes.Tab, count: int = 1, quiet: bool = False) -> None:
    """Decrease the zoom level for the current tab.

    Args:
        count: How many steps to zoom out.
        quiet: Don't show a zoom level message.
    """
    try:
        perc = tab.zoom.apply_offset(-count)
    except ValueError as e:
        raise cmdutils.CommandError(e)
    if not quiet:
        message.info("Zoom level: {}%".format(int(perc)), replace=True)
示例#17
0
    def session_load(self, name, clear=False, temp=False, force=False,
                     delete=False):
        """Load a session.

        Args:
            name: The name of the session.
            clear: Close all existing windows.
            temp: Don't set the current session for :session-save.
            force: Force loading internal sessions (starting with an
                   underline).
            delete: Delete the saved session once it has loaded.
        """
        if name.startswith('_') and not force:
            raise cmdutils.CommandError("{} is an internal session, use "
                                        "--force to load anyways."
                                        .format(name))
        old_windows = list(objreg.window_registry.values())
        try:
            self.load(name, temp=temp)
        except SessionNotFoundError:
            raise cmdutils.CommandError("Session {} not found!".format(name))
        except SessionError as e:
            raise cmdutils.CommandError("Error while loading session: {}"
                                        .format(e))
        else:
            if clear:
                for win in old_windows:
                    win.close()
            if delete:
                try:
                    self.delete(name)
                except SessionError as e:
                    log.sessions.exception("Error while deleting session!")
                    raise cmdutils.CommandError("Error while deleting "
                                                "session: {}".format(e))
                else:
                    log.sessions.debug(
                        "Loaded & deleted session {}.".format(name))