예제 #1
0
def _init_variable_replacements() -> Mapping[str, _ReplacementFunction]:
    """Return a dict from variable replacements to fns processing them."""
    replacements: Dict[str, _ReplacementFunction] = {
        'url': lambda tb: _url(tb).toString(
            QUrl.FullyEncoded | QUrl.RemovePassword),
        'url:pretty': lambda tb: _url(tb).toString(
            QUrl.DecodeReserved | QUrl.RemovePassword),
        'url:domain': lambda tb: "{}://{}{}".format(
            _url(tb).scheme(), _url(tb).host(),
            ":" + str(_url(tb).port()) if _url(tb).port() != -1 else ""),
        'url:auth': lambda tb: "{}:{}@".format(
            _url(tb).userName(),
            _url(tb).password()) if _url(tb).userName() else "",
        'url:scheme': lambda tb: _url(tb).scheme(),
        'url:username': lambda tb: _url(tb).userName(),
        'url:password': lambda tb: _url(tb).password(),
        'url:host': lambda tb: _url(tb).host(),
        'url:port': lambda tb: str(
            _url(tb).port()) if _url(tb).port() != -1 else "",
        'url:path': lambda tb: _url(tb).path(),
        'url:query': lambda tb: _url(tb).query(),
        'title': lambda tb: tb.widget.page_title(tb.widget.currentIndex()),
        'clipboard': lambda _: utils.get_clipboard(),
        'primary': lambda _: utils.get_clipboard(selection=True),
    }

    for key in list(replacements):
        modified_key = '{' + key + '}'
        # x = modified_key is to avoid binding x as a closure
        replacements[modified_key] = (
            lambda _, x=modified_key: x)  # type: ignore[misc]
    return replacements
예제 #2
0
def _init_variable_replacements() -> typing.Mapping[str, _ReplacementFunction]:
    """Return a dict from variable replacements to fns processing them."""
    replacements = {
        'url': lambda tb: _url(tb).toString(
            QUrl.FullyEncoded | QUrl.RemovePassword),
        'url:pretty': lambda tb: _url(tb).toString(
            QUrl.DecodeReserved | QUrl.RemovePassword),
        'url:domain': lambda tb: "{}://{}{}".format(
            _url(tb).scheme(), _url(tb).host(),
            ":" + str(_url(tb).port()) if _url(tb).port() != -1 else ""),
        'url:auth': lambda tb: "{}:{}@".format(
            _url(tb).userName(),
            _url(tb).password()) if _url(tb).userName() else "",
        'url:scheme': lambda tb: _url(tb).scheme(),
        'url:username': lambda tb: _url(tb).userName(),
        'url:password': lambda tb: _url(tb).password(),
        'url:host': lambda tb: _url(tb).host(),
        'url:port': lambda tb: str(
            _url(tb).port()) if _url(tb).port() != -1 else "",
        'url:path': lambda tb: _url(tb).path(),
        'url:query': lambda tb: _url(tb).query(),
        'title': lambda tb: tb.widget.page_title(tb.widget.currentIndex()),
        'clipboard': lambda _: utils.get_clipboard(),
        'primary': lambda _: utils.get_clipboard(selection=True),
    }  # type: typing.Dict[str, _ReplacementFunction]

    for key in list(replacements):
        modified_key = '{' + key + '}'
        # x = modified_key is to avoid binding x as a closure
        replacements[modified_key] = (
            lambda _, x=modified_key: x)  # type: ignore
    return replacements
예제 #3
0
    def yank(self, url: QUrl, context: HintContext) -> None:
        """Yank an element to the clipboard or primary selection."""
        sel = (context.target == Target.yank_primary
               and utils.supports_selection())

        flags = QUrl.FullyEncoded | QUrl.RemovePassword
        if url.scheme() == 'mailto':
            flags |= QUrl.RemoveScheme
        urlstr = url.toString(flags)  # type: ignore[arg-type]

        new_content = urlstr

        # only second and consecutive yanks are to append to the clipboard
        if context.rapid and not context.first_run:
            try:
                old_content = utils.get_clipboard(selection=sel)
            except utils.ClipboardEmptyError:
                pass
            else:
                new_content = os.linesep.join([old_content, new_content])
        utils.set_clipboard(new_content, selection=sel)

        msg = "Yanked URL to {}: {}".format(
            "primary selection" if sel else "clipboard", urlstr)
        message.info(msg)
예제 #4
0
def replace_variables(win_id, arglist):
    """Utility function to replace variables like {url} in a list of args."""
    variables = {
        'url': lambda: _current_url(tabbed_browser).toString(
            QUrl.FullyEncoded | QUrl.RemovePassword),
        'url:pretty': lambda: _current_url(tabbed_browser).toString(
            QUrl.DecodeReserved | QUrl.RemovePassword),
        'clipboard': utils.get_clipboard,
        'primary': lambda: utils.get_clipboard(selection=True),
    }
    values = {}
    args = []
    tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                window=win_id)

    def repl_cb(matchobj):
        """Return replacement for given match."""
        var = matchobj.group("var")
        if var not in values:
            values[var] = variables[var]()
        return values[var]
    repl_pattern = re.compile("{(?P<var>" + "|".join(variables.keys()) + ")}")

    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(repl_pattern.sub(repl_cb, arg))
    except utils.ClipboardError as e:
        raise cmdexc.CommandError(e)
    return args
예제 #5
0
def replace_variables(win_id, arglist):
    """Utility function to replace variables like {url} in a list of args."""
    variables = {
        'url': lambda: _current_url(tabbed_browser).toString(
            QUrl.FullyEncoded | QUrl.RemovePassword),
        'url:pretty': lambda: _current_url(tabbed_browser).toString(
            QUrl.DecodeReserved | QUrl.RemovePassword),
        'clipboard': utils.get_clipboard,
        'primary': lambda: utils.get_clipboard(selection=True),
    }
    values = {}
    args = []
    tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                window=win_id)

    def repl_cb(matchobj):
        """Return replacement for given match."""
        var = matchobj.group("var")
        if var not in values:
            values[var] = variables[var]()
        return values[var]
    repl_pattern = re.compile("{(?P<var>" + "|".join(variables.keys()) + ")}")

    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(repl_pattern.sub(repl_cb, arg))
    except utils.ClipboardError as e:
        raise cmdexc.CommandError(e)
    return args
예제 #6
0
def replace_variables(win_id, arglist):
    """Utility function to replace variables like {url} in a list of args."""
    variables = {
        '{url}': lambda: _current_url(tabbed_browser).toString(
            QUrl.FullyEncoded | QUrl.RemovePassword),
        '{url:pretty}': lambda: _current_url(tabbed_browser).toString(
            QUrl.RemovePassword),
        '{clipboard}': utils.get_clipboard,
        '{primary}': lambda: utils.get_clipboard(selection=True),
    }
    values = {}
    args = []
    tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                window=win_id)

    try:
        for arg in arglist:
            for var, func in variables.items():
                if var in arg:
                    if var not in values:
                        values[var] = func()
                    arg = arg.replace(var, values[var])
            args.append(arg)
    except utils.ClipboardError as e:
        raise cmdexc.CommandError(e)
    return args
예제 #7
0
    def yank(self, url, context):
        """Yank an element to the clipboard or primary selection.

        Args:
            url: The URL to open as a QUrl.
            context: The HintContext to use.
        """
        sel = (context.target == Target.yank_primary and
               utils.supports_selection())

        flags = QUrl.FullyEncoded | QUrl.RemovePassword
        if url.scheme() == 'mailto':
            flags |= QUrl.RemoveScheme
        urlstr = url.toString(flags)

        new_content = urlstr

        # only second and consecutive yanks are to append to the clipboard
        if context.rapid and not context.first_run:
            try:
                old_content = utils.get_clipboard(selection=sel)
            except utils.ClipboardEmptyError:
                pass
            else:
                new_content = os.linesep.join([old_content, new_content])
        utils.set_clipboard(new_content, selection=sel)

        msg = "Yanked URL to {}: {}".format(
            "primary selection" if sel else "clipboard",
            urlstr)
        message.info(msg)
예제 #8
0
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)
    url = lambda: _current_url(tabbed_browser)

    variables = {
        'url': lambda: url().toString(
            QUrl.FullyEncoded | QUrl.RemovePassword),
        'url:pretty': lambda: url().toString(
            QUrl.DecodeReserved | QUrl.RemovePassword),
        'url:domain': lambda: "{}://{}{}".format(
            url().scheme(),
            url().host(),
            ":" + str(url().port()) if url().port() != -1 else ""),
        'url:auth': lambda: "{}:{}@".format(
            url().userName(),
            url().password()) if url().userName() else "",
        'url:scheme': lambda: url().scheme(),
        'url:username': lambda: url().userName(),
        'url:password': lambda: url().password(),
        'url:host': lambda: url().host(),
        'url:port': lambda: str(url().port()) if url().port() != -1 else "",
        'url:path': lambda: url().path(),
        'url:query': lambda: url().query(),
        'title': lambda: tabbed_browser.widget.page_title(
            tabbed_browser.widget.currentIndex()),
        'clipboard': utils.get_clipboard,
        'primary': lambda: utils.get_clipboard(selection=True),
    }

    for key in list(variables):
        modified_key = '{' + key + '}'
        variables[modified_key] = lambda x=modified_key: x

    values = {}
    args = []

    def repl_cb(matchobj):
        """Return replacement for given match."""
        var = matchobj.group("var")
        if var not in values:
            values[var] = variables[var]()
        return values[var]
    repl_pattern = re.compile("{(?P<var>" + "|".join(variables.keys()) + ")}")

    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(repl_pattern.sub(repl_cb, arg))
    except utils.ClipboardError as e:
        raise cmdutils.CommandError(e)
    return args
예제 #9
0
 def keyPressEvent(self, e):
     """Override keyPressEvent to paste primary selection on Shift + Ins."""
     if e.key() == Qt.Key_Insert and e.modifiers() == Qt.ShiftModifier:
         try:
             text = utils.get_clipboard(selection=True, fallback=True)
         except utils.ClipboardError:  # pragma: no cover
             e.ignore()
         else:
             e.accept()
             self.insert(text)
         return
     super().keyPressEvent(e)
예제 #10
0
 def keyPressEvent(self, e):
     """Override keyPressEvent to paste primary selection on Shift + Ins."""
     if e.key() == Qt.Key_Insert and e.modifiers() == Qt.ShiftModifier:
         try:
             text = utils.get_clipboard(selection=True)
         except utils.SelectionUnsupportedError:
             pass
         else:
             e.accept()
             self.insert(text)
             return
     super().keyPressEvent(e)
예제 #11
0
 def keyPressEvent(self, e):
     """Override keyPressEvent to paste primary selection on Shift + Ins."""
     if e.key() == Qt.Key_Insert and e.modifiers() == Qt.ShiftModifier:
         try:
             text = utils.get_clipboard(selection=True, fallback=True)
         except utils.ClipboardError:  # pragma: no cover
             e.ignore()
         else:
             e.accept()
             self.insert(text)
         return
     super().keyPressEvent(e)
예제 #12
0
 def keyPressEvent(self, e):
     """Override keyPressEvent to paste primary selection on Shift + Ins."""
     if e.key() == Qt.Key_Insert and e.modifiers() == Qt.ShiftModifier:
         try:
             text = utils.get_clipboard(selection=True)
         except utils.SelectionUnsupportedError:
             pass
         else:
             e.accept()
             self.insert(text)
             return
     super().keyPressEvent(e)