Example #1
0
    def _process_init_args(self):
        """Process initial positional args.

        URLs to open have no prefix, commands to execute begin with a colon.
        """
        tabbed_browser = objreg.get('tabbed-browser')
        for cmd in self._args.command:
            if cmd.startswith(':'):
                log.init.debug("Startup cmd {}".format(cmd))
                self._commandrunner.run_safely_init(cmd.lstrip(':'))
            else:
                log.init.debug("Startup URL {}".format(cmd))
                try:
                    url = urlutils.fuzzy_url(cmd)
                except urlutils.FuzzyUrlError as e:
                    message.error("Error in startup argument '{}': {}".format(
                        cmd, e))
                else:
                    tabbed_browser.tabopen(url)

        if tabbed_browser.count() == 0:
            log.init.debug("Opening startpage")
            for urlstr in config.get('general', 'startpage'):
                try:
                    url = urlutils.fuzzy_url(urlstr)
                except urlutils.FuzzyUrlError as e:
                    message.error("Error when opening startpage: {}".format(e))
                else:
                    tabbed_browser.tabopen(url)
Example #2
0
 def test_invalid_url(self, do_search, exception, is_url_mock, monkeypatch):
     """Test with an invalid URL."""
     is_url_mock.return_value = True
     monkeypatch.setattr('qutebrowser.utils.urlutils.qurl_from_user_input',
                         lambda url: QUrl())
     with pytest.raises(exception):
         urlutils.fuzzy_url('foo', do_search=do_search)
Example #3
0
 def test_invalid_url(self, do_search, exception, is_url_mock, monkeypatch,
                      caplog):
     """Test with an invalid URL."""
     is_url_mock.return_value = True
     monkeypatch.setattr(urlutils, 'qurl_from_user_input',
                         lambda url: QUrl())
     with pytest.raises(exception):
         with caplog.at_level(logging.ERROR):
             urlutils.fuzzy_url('foo', do_search=do_search)
Example #4
0
    def openurl(self, url=None, bg=False, tab=False, window=False, count=None):
        """Open a URL in the current/[count]th tab.

        Args:
            url: The URL to open.
            bg: Open in a new background tab.
            tab: Open in a new tab.
            window: Open in a new window.
            count: The tab index to open the URL in, or None.
        """
        if url is None:
            if tab or bg or window:
                url = config.get('general', 'default-page')
            else:
                raise cmdexc.CommandError("No URL given, but -t/-b/-w is not "
                                          "set!")
        else:
            try:
                url = urlutils.fuzzy_url(url)
            except urlutils.FuzzyUrlError as e:
                raise cmdexc.CommandError(e)
        if tab or bg or window:
            self._open(url, tab, bg, window)
        else:
            curtab = self._cntwidget(count)
            if curtab is None:
                if count is None:
                    # We want to open a URL in the current tab, but none exists
                    # yet.
                    self._tabbed_browser().tabopen(url)
                else:
                    # Explicit count with a tab that doesn't exist.
                    return
            else:
                curtab.openurl(url)
Example #5
0
    def process_args(self, args, via_ipc=False):
        """Process commandline args.

        URLs to open have no prefix, commands to execute begin with a colon.

        Args:
            args: A list of arguments to process.
            via_ipc: Whether the arguments were transmitted over IPC.
        """
        win_id = self._get_window(via_ipc, not args)
        if win_id is None:
            return
        if ipc and not args:
            self._open_startpage(win_id)
        for cmd in args:
            if cmd.startswith(':'):
                log.init.debug("Startup cmd {}".format(cmd))
                commandrunner = runners.CommandRunner(win_id)
                commandrunner.run_safely_init(cmd.lstrip(':'))
            elif not cmd:
                log.init.debug("Empty argument")
                win_id = mainwindow.MainWindow.spawn()
            else:
                tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                            window=win_id)
                log.init.debug("Startup URL {}".format(cmd))
                try:
                    url = urlutils.fuzzy_url(cmd)
                except urlutils.FuzzyUrlError as e:
                    message.error(0, "Error in startup argument '{}': "
                                     "{}".format(cmd, e))
                else:
                    tabbed_browser.tabopen(url)
Example #6
0
    def transform(self, value):
        from qutebrowser.utils import urlutils

        if not value:
            return None
        else:
            return urlutils.fuzzy_url(value, do_search=False)
Example #7
0
    def openurl(self, url=None, bg=False, tab=False, window=False, count=None):
        """Open a URL in the current/[count]th tab.

        Args:
            url: The URL to open.
            bg: Open in a new background tab.
            tab: Open in a new tab.
            window: Open in a new window.
            count: The tab index to open the URL in, or None.
        """
        if url is None:
            if tab or bg or window:
                url = config.get('general', 'default-page')
            else:
                raise cmdexc.CommandError("No URL given, but -t/-b/-w is not "
                                          "set!")
        else:
            try:
                url = urlutils.fuzzy_url(url)
            except urlutils.FuzzyUrlError as e:
                raise cmdexc.CommandError(e)
        if tab or bg or window:
            self._open(url, tab, bg, window)
        else:
            curtab = self._cntwidget(count)
            if curtab is None:
                if count is None:
                    # We want to open a URL in the current tab, but none exists
                    # yet.
                    self._tabbed_browser().tabopen(url)
                else:
                    # Explicit count with a tab that doesn't exist.
                    return
            else:
                curtab.openurl(url)
Example #8
0
    def _open_startpage(self, win_id=None):
        """Open startpage.

        The startpage is never opened if the given windows are not empty.

        Args:
            win_id: If None, open startpage in all empty windows.
                    If set, open the startpage in the given window.
        """
        if win_id is not None:
            window_ids = [win_id]
        else:
            window_ids = objreg.window_registry
        for cur_win_id in window_ids:
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=cur_win_id)
            if tabbed_browser.count() == 0:
                log.init.debug("Opening startpage")
                for urlstr in config.get('general', 'startpage'):
                    try:
                        url = urlutils.fuzzy_url(urlstr)
                    except urlutils.FuzzyUrlError as e:
                        message.error(0, "Error when opening startpage: "
                                         "{}".format(e))
                        tabbed_browser.tabopen(QUrl('about:blank'))
                    else:
                        tabbed_browser.tabopen(url)
Example #9
0
    def process_args(self, args, via_ipc=False):
        """Process commandline args.

        URLs to open have no prefix, commands to execute begin with a colon.

        Args:
            args: A list of arguments to process.
            via_ipc: Whether the arguments were transmitted over IPC.
        """
        win_id = self._get_window(via_ipc, args)
        if win_id is None:
            return
        if ipc and not args:
            self._open_startpage(win_id)
        for cmd in args:
            if cmd.startswith(':'):
                log.init.debug("Startup cmd {}".format(cmd))
                commandrunner = runners.CommandRunner(win_id)
                commandrunner.run_safely_init(cmd.lstrip(':'))
            elif not cmd:
                log.init.debug("Empty argument")
                win_id = mainwindow.MainWindow.spawn()
            else:
                tabbed_browser = objreg.get('tabbed-browser',
                                            scope='window',
                                            window=win_id)
                log.init.debug("Startup URL {}".format(cmd))
                try:
                    url = urlutils.fuzzy_url(cmd)
                except urlutils.FuzzyUrlError as e:
                    message.error(
                        0, "Error in startup argument '{}': "
                        "{}".format(cmd, e))
                else:
                    tabbed_browser.tabopen(url)
Example #10
0
    def openurl(self, url, bg=False, tab=False, window=False,
                count: {'special': 'count'}=None):
        """Open a URL in the current/[count]th tab.

        Args:
            url: The URL to open.
            bg: Open in a new background tab.
            tab: Open in a new tab.
            window: Open in a new window.
            count: The tab index to open the URL in, or None.
        """
        try:
            url = urlutils.fuzzy_url(url)
        except urlutils.FuzzyUrlError as e:
            raise cmdexc.CommandError(e)
        if tab or bg or window:
            self._open(url, tab, bg, window)
        else:
            curtab = self._cntwidget(count)
            if curtab is None:
                if count is None:
                    # We want to open a URL in the current tab, but none exists
                    # yet.
                    self._tabbed_browser().tabopen(url)
                else:
                    # Explicit count with a tab that doesn't exist.
                    return
            else:
                curtab.openurl(url)
Example #11
0
    def test_file_absolute_expanded(self, os_mock):
        """Make sure ~ gets expanded correctly."""
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = True

        url = urlutils.fuzzy_url('~/foo')
        assert url == QUrl('file://' + os.path.expanduser('~/foo'))
Example #12
0
    def test_file_absolute(self, path, expected, os_mock):
        """Test with an absolute path."""
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = True

        url = urlutils.fuzzy_url(path)
        assert url == expected
Example #13
0
    def test_file_absolute(self, os_mock):
        """Test with an absolute path."""
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = True

        url = urlutils.fuzzy_url('/foo')
        assert url == QUrl('file:///foo')
Example #14
0
    def paste(self, sel=False, tab=False, bg=False, window=False):
        """Open a page from the clipboard.

        Args:
            sel: Use the primary selection instead of the clipboard.
            tab: Open in a new tab.
            bg: Open in a background tab.
            window: Open in new window.
        """
        clipboard = QApplication.clipboard()
        if sel and clipboard.supportsSelection():
            mode = QClipboard.Selection
            target = "Primary selection"
        else:
            mode = QClipboard.Clipboard
            target = "Clipboard"
        text = clipboard.text(mode)
        if not text:
            raise cmdexc.CommandError("{} is empty.".format(target))
        log.misc.debug("{} contained: '{}'".format(target, text))
        try:
            url = urlutils.fuzzy_url(text)
        except urlutils.FuzzyUrlError as e:
            raise cmdexc.CommandError(e)
        self._open(url, tab, bg, window)
Example #15
0
    def test_force_search(self, urlstring, get_search_url_mock):
        """Test the force search option."""
        get_search_url_mock.return_value = QUrl('search_url')

        url = urlutils.fuzzy_url(urlstring, force_search=True)

        assert url == QUrl('search_url')
Example #16
0
def _open_startpage(win_id=None):
    """Open startpage.

    The startpage is never opened if the given windows are not empty.

    Args:
        win_id: If None, open startpage in all empty windows.
                If set, open the startpage in the given window.
    """
    if win_id is not None:
        window_ids = [win_id]
    else:
        window_ids = objreg.window_registry
    for cur_win_id in list(window_ids):  # Copying as the dict could change
        tabbed_browser = objreg.get('tabbed-browser',
                                    scope='window',
                                    window=cur_win_id)
        if tabbed_browser.count() == 0:
            log.init.debug("Opening startpage")
            for urlstr in config.get('general', 'startpage'):
                try:
                    url = urlutils.fuzzy_url(urlstr, do_search=False)
                except urlutils.InvalidUrlError as e:
                    message.error("Error when opening startpage: {}".format(e))
                    tabbed_browser.tabopen(QUrl('about:blank'))
                else:
                    tabbed_browser.tabopen(url)
Example #17
0
    def test_file_absolute_expanded(self, os_mock):
        """Make sure ~ gets expanded correctly."""
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = True

        url = urlutils.fuzzy_url('~/foo')
        assert url == QUrl('file://' + os.path.expanduser('~/foo'))
Example #18
0
    def test_address(self, os_mock, is_url_mock):
        """Test passing something with relative=False."""
        os_mock.path.isabs.return_value = False
        is_url_mock.return_value = True

        url = urlutils.fuzzy_url('foo')
        assert url == QUrl('http://foo')
Example #19
0
    def paste(self, sel=False, tab=False, bg=False, window=False):
        """Open a page from the clipboard.

        Args:
            sel: Use the primary selection instead of the clipboard.
            tab: Open in a new tab.
            bg: Open in a background tab.
            window: Open in new window.
        """
        clipboard = QApplication.clipboard()
        if sel and clipboard.supportsSelection():
            mode = QClipboard.Selection
            target = "Primary selection"
        else:
            mode = QClipboard.Clipboard
            target = "Clipboard"
        text = clipboard.text(mode)
        if not text:
            raise cmdexc.CommandError("{} is empty.".format(target))
        log.misc.debug("{} contained: '{}'".format(target, text))
        try:
            url = urlutils.fuzzy_url(text)
        except urlutils.FuzzyUrlError as e:
            raise cmdexc.CommandError(e)
        self._open(url, tab, bg, window)
Example #20
0
    def test_file_absolute(self, path, expected, os_mock):
        """Test with an absolute path."""
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = True

        url = urlutils.fuzzy_url(path)
        assert url == expected
Example #21
0
    def openurl(self,
                url,
                bg=False,
                tab=False,
                window=False,
                count: {'special': 'count'} = None):
        """Open a URL in the current/[count]th tab.

        Args:
            url: The URL to open.
            bg: Open in a new background tab.
            tab: Open in a new tab.
            window: Open in a new window.
            count: The tab index to open the URL in, or None.
        """
        try:
            url = urlutils.fuzzy_url(url)
        except urlutils.FuzzyUrlError as e:
            raise cmdexc.CommandError(e)
        if tab or bg or window:
            self._open(url, tab, bg, window)
        else:
            curtab = self._cntwidget(count)
            if curtab is None:
                if count is None:
                    # We want to open a URL in the current tab, but none exists
                    # yet.
                    self._tabbed_browser().tabopen(url)
                else:
                    # Explicit count with a tab that doesn't exist.
                    return
            else:
                curtab.openurl(url)
Example #22
0
    def test_file_absolute(self, os_mock):
        """Test with an absolute path."""
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = True

        url = urlutils.fuzzy_url('/foo')
        assert url == QUrl('file:///foo')
Example #23
0
    def test_address(self, os_mock, is_url_mock):
        """Test passing something with relative=False."""
        os_mock.path.isabs.return_value = False
        is_url_mock.return_value = True

        url = urlutils.fuzzy_url('foo')
        assert url == QUrl('http://foo')
Example #24
0
def _open_startpage(win_id=None):
    """Open startpage.

    The startpage is never opened if the given windows are not empty.

    Args:
        win_id: If None, open startpage in all empty windows.
                If set, open the startpage in the given window.
    """
    if win_id is not None:
        window_ids = [win_id]
    else:
        window_ids = objreg.window_registry
    for cur_win_id in window_ids:
        tabbed_browser = objreg.get("tabbed-browser", scope="window", window=cur_win_id)
        if tabbed_browser.count() == 0:
            log.init.debug("Opening startpage")
            for urlstr in config.get("general", "startpage"):
                try:
                    url = urlutils.fuzzy_url(urlstr, do_search=False)
                except urlutils.InvalidUrlError as e:
                    message.error("current", "Error when opening startpage: " "{}".format(e))
                    tabbed_browser.tabopen(QUrl("about:blank"))
                else:
                    tabbed_browser.tabopen(url)
Example #25
0
    def test_force_search(self, urlstring, get_search_url_mock):
        """Test the force search option."""
        get_search_url_mock.return_value = QUrl('search_url')

        url = urlutils.fuzzy_url(urlstring, force_search=True)

        assert url == QUrl('search_url')
Example #26
0
    def test_search_term(self, os_mock, is_url_mock, get_search_url_mock):
        """Test passing something with do_search=True."""
        os_mock.path.isabs.return_value = False
        is_url_mock.return_value = False
        get_search_url_mock.return_value = QUrl('search_url')

        url = urlutils.fuzzy_url('foo', do_search=True)
        assert url == QUrl('search_url')
Example #27
0
    def test_search_term(self, os_mock, is_url_mock, get_search_url_mock):
        """Test passing something with do_search=True."""
        os_mock.path.isabs.return_value = False
        is_url_mock.return_value = False
        get_search_url_mock.return_value = QUrl('search_url')

        url = urlutils.fuzzy_url('foo', do_search=True)
        assert url == QUrl('search_url')
Example #28
0
    def test_search_term_value_error(self, os_mock, is_url_mock, get_search_url_mock):
        """Test with do_search=True and ValueError in _get_search_url."""
        os_mock.path.isabs.return_value = False
        is_url_mock.return_value = False
        get_search_url_mock.side_effect = ValueError

        url = urlutils.fuzzy_url("foo", do_search=True)
        assert url == QUrl("http://foo")
Example #29
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        try:
            return urlutils.fuzzy_url(value, do_search=False)
        except urlutils.InvalidUrlError as e:
            raise configexc.ValidationError(value, str(e))
Example #30
0
    def test_file_relative_cwd(self, os_mock):
        """Test with relative=True, cwd set, and an existing file."""
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = False

        url = urlutils.fuzzy_url('foo', cwd='cwd', relative=True)

        os_mock.path.exists.assert_called_once_with('cwd/foo')
        assert url == QUrl('file:cwd/foo')
Example #31
0
    def test_file_relative_cwd(self, os_mock):
        """Test with relative=True, cwd set, and an existing file."""
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = False

        url = urlutils.fuzzy_url('foo', cwd='cwd', relative=True)

        os_mock.path.exists.assert_called_once_with('cwd/foo')
        assert url == QUrl('file:cwd/foo')
Example #32
0
    def to_py(self, value):
        self._basic_py_validation(value, str)
        if not value:
            return None

        try:
            return urlutils.fuzzy_url(value, do_search=False)
        except urlutils.InvalidUrlError as e:
            raise configexc.ValidationError(value, str(e))
Example #33
0
    def test_search_term_value_error(self, os_mock, is_url_mock,
                                     get_search_url_mock):
        """Test with do_search=True and ValueError in _get_search_url."""
        os_mock.path.isabs.return_value = False
        is_url_mock.return_value = False
        get_search_url_mock.side_effect = ValueError

        url = urlutils.fuzzy_url('foo', do_search=True)
        assert url == QUrl('http://foo')
Example #34
0
    def test_file_relative(self, os_mock):
        """Test with relative=True and cwd unset."""
        os_mock.path.exists.return_value = True
        os_mock.path.abspath.return_value = 'abs_path'
        os_mock.path.isabs.return_value = False

        url = urlutils.fuzzy_url('foo', relative=True)

        os_mock.path.exists.assert_called_once_with('abs_path')
        assert url == QUrl('file:abs_path')
Example #35
0
 def get_by_qurl(self, url):
     if url.toString() not in self.marks:
         raise urlmarks.DoesNotExistError(
             "Quickmark for '{}' does not exist!".format(name))
     try:
         url = urlutils.fuzzy_url(url, do_search=False)
     except urlutils.InvalidUrlError as e:
         raise urlmarks.InvalidUrlError(
             "Invalid URL for quickmark {}: {}".format(url, str(e)))
     return url
Example #36
0
    def test_file_relative_os_error(self, os_mock, is_url_mock):
        """Test with relative=True, cwd unset and abspath raising OSError."""
        os_mock.path.abspath.side_effect = OSError
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = False
        is_url_mock.return_value = True

        url = urlutils.fuzzy_url('foo', relative=True)
        assert not os_mock.path.exists.called
        assert url == QUrl('http://foo')
Example #37
0
    def test_file_relative(self, os_mock):
        """Test with relative=True and cwd unset."""
        os_mock.path.exists.return_value = True
        os_mock.path.abspath.return_value = 'abs_path'
        os_mock.path.isabs.return_value = False

        url = urlutils.fuzzy_url('foo', relative=True)

        os_mock.path.exists.assert_called_once_with('abs_path')
        assert url == QUrl('file:abs_path')
Example #38
0
    def test_file_relative_os_error(self, os_mock, is_url_mock):
        """Test with relative=True, cwd unset and abspath raising OSError."""
        os_mock.path.abspath.side_effect = OSError
        os_mock.path.exists.return_value = True
        os_mock.path.isabs.return_value = False
        is_url_mock.return_value = True

        url = urlutils.fuzzy_url('foo', relative=True)
        assert not os_mock.path.exists.called
        assert url == QUrl('http://foo')
Example #39
0
 def get(self, name):
     """Get the URL of the quickmark named name as a QUrl."""
     if name not in self.marks:
         raise DoesNotExistError(
             "Quickmark '{}' does not exist!".format(name))
     urlstr = self.marks[name]
     try:
         url = urlutils.fuzzy_url(urlstr, do_search=False)
     except urlutils.InvalidUrlError as e:
         raise InvalidUrlError(
             "Invalid URL for quickmark {}: {}".format(name, str(e)))
     return url
Example #40
0
 def get(self, name):
     """Get the URL of the quickmark named name as a QUrl."""
     if name not in self.marks:
         raise DoesNotExistError(
             "Quickmark '{}' does not exist!".format(name))
     urlstr = self.marks[name]
     try:
         url = urlutils.fuzzy_url(urlstr, do_search=False)
     except urlutils.InvalidUrlError as e:
         raise InvalidUrlError("Invalid URL for quickmark {}: {}".format(
             name, str(e)))
     return url
Example #41
0
def process_pos_args(args, via_ipc=False, cwd=None, target_arg=None):
    """Process positional commandline args.

    URLs to open have no prefix, commands to execute begin with a colon.

    Args:
        args: A list of arguments to process.
        via_ipc: Whether the arguments were transmitted over IPC.
        cwd: The cwd to use for fuzzy_url.
        target_arg: Command line argument received by a running instance via
                    ipc. If the --target argument was not specified, target_arg
                    will be an empty string.
    """
    new_window_target = ('private-window' if target_arg == 'private-window'
                         else 'window')
    command_target = config.val.new_instance_open_target
    if command_target in {'window', 'private-window'}:
        command_target = 'tab-silent'

    win_id: Optional[int] = None

    if via_ipc and (not args or args == ['']):
        win_id = mainwindow.get_window(via_ipc=via_ipc,
                                       target=new_window_target)
        _open_startpage(win_id)
        return

    for cmd in args:
        if cmd.startswith(':'):
            if win_id is None:
                win_id = mainwindow.get_window(via_ipc=via_ipc,
                                               target=command_target)
            log.init.debug("Startup cmd {!r}".format(cmd))
            commandrunner = runners.CommandRunner(win_id)
            commandrunner.run_safely(cmd[1:])
        elif not cmd:
            log.init.debug("Empty argument")
            win_id = mainwindow.get_window(via_ipc=via_ipc,
                                           target=new_window_target)
        else:
            if via_ipc and target_arg and target_arg != 'auto':
                open_target = target_arg
            else:
                open_target = None
            if not cwd:  # could also be an empty string due to the PyQt signal
                cwd = None
            try:
                url = urlutils.fuzzy_url(cmd, cwd, relative=True)
            except urlutils.InvalidUrlError as e:
                message.error("Error in startup argument '{}': {}".format(
                    cmd, e))
            else:
                win_id = open_url(url, target=open_target, via_ipc=via_ipc)
Example #42
0
def process_pos_args(args, via_ipc=False, cwd=None, target_arg=None):
    """Process positional commandline args.

    URLs to open have no prefix, commands to execute begin with a colon.

    Args:
        args: A list of arguments to process.
        via_ipc: Whether the arguments were transmitted over IPC.
        cwd: The cwd to use for fuzzy_url.
        target_arg: Command line argument received by a running instance via
                    ipc. If the --target argument was not specified, target_arg
                    will be an empty string instead of None. This behavior is
                    caused by the PyQt signal
                    ``got_args = pyqtSignal(list, str, str)``
                    used in the misc.ipc.IPCServer class. PyQt converts the
                    None value into a null QString and then back to an empty
                    python string
    """
    if via_ipc and not args:
        win_id = mainwindow.get_window(via_ipc, force_window=True)
        _open_startpage(win_id)
        return
    win_id = None
    for cmd in args:
        if cmd.startswith(':'):
            if win_id is None:
                win_id = mainwindow.get_window(via_ipc, force_tab=True)
            log.init.debug("Startup cmd {}".format(cmd))
            commandrunner = runners.CommandRunner(win_id)
            commandrunner.run_safely_init(cmd[1:])
        elif not cmd:
            log.init.debug("Empty argument")
            win_id = mainwindow.get_window(via_ipc, force_window=True)
        else:
            if via_ipc and target_arg and target_arg != 'auto':
                open_target = target_arg
            else:
                open_target = config.get('general', 'new-instance-open-target')
            win_id = mainwindow.get_window(via_ipc, force_target=open_target)
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=win_id)
            log.init.debug("Startup URL {}".format(cmd))
            try:
                url = urlutils.fuzzy_url(cmd, cwd, relative=True)
            except urlutils.InvalidUrlError as e:
                message.error(
                    'current', "Error in startup argument '{}': "
                    "{}".format(cmd, e))
            else:
                background = open_target in ('tab-bg', 'tab-bg-silent')
                tabbed_browser.tabopen(url, background=background)
Example #43
0
 def get(self, name):
     """Get the URL of the quickmark named name as a QUrl."""
     if name not in self.marks:
         raise cmdexc.CommandError(
             "Quickmark '{}' does not exist!".format(name))
     urlstr = self.marks[name]
     try:
         url = urlutils.fuzzy_url(urlstr)
     except urlutils.FuzzyUrlError:
         raise cmdexc.CommandError(
             "Invalid URL for quickmark {}: {} ({})".format(
                 name, urlstr, url.errorString()))
     return url
Example #44
0
 def get(self, name):
     """Get the URL of the quickmark named name as a QUrl."""
     if name not in self.marks:
         raise cmdexc.CommandError(
             "Quickmark '{}' does not exist!".format(name))
     urlstr = self.marks[name]
     try:
         url = urlutils.fuzzy_url(urlstr)
     except urlutils.FuzzyUrlError:
         raise cmdexc.CommandError(
             "Invalid URL for quickmark {}: {} ({})".format(
                 name, urlstr, url.errorString()))
     return url
Example #45
0
def process_pos_args(args, via_ipc=False, cwd=None, target_arg=None):
    """Process positional commandline args.

    URLs to open have no prefix, commands to execute begin with a colon.

    Args:
        args: A list of arguments to process.
        via_ipc: Whether the arguments were transmitted over IPC.
        cwd: The cwd to use for fuzzy_url.
        target_arg: Command line argument received by a running instance via
                    ipc. If the --target argument was not specified, target_arg
                    will be an empty string.
    """
    if via_ipc and not args:
        win_id = mainwindow.get_window(via_ipc, force_window=True)
        _open_startpage(win_id)
        return
    win_id = None
    for cmd in args:
        if cmd.startswith(':'):
            if win_id is None:
                win_id = mainwindow.get_window(via_ipc, force_tab=True)
            log.init.debug("Startup cmd {!r}".format(cmd))
            commandrunner = runners.CommandRunner(win_id)
            commandrunner.run_safely_init(cmd[1:])
        elif not cmd:
            log.init.debug("Empty argument")
            win_id = mainwindow.get_window(via_ipc, force_window=True)
        else:
            if via_ipc and target_arg and target_arg != 'auto':
                open_target = target_arg
            else:
                open_target = config.get('general', 'new-instance-open-target')
            win_id = mainwindow.get_window(via_ipc, force_target=open_target)
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=win_id)
            log.init.debug("Startup URL {}".format(cmd))
            if not cwd:  # could also be an empty string due to the PyQt signal
                cwd = None
            try:
                url = urlutils.fuzzy_url(cmd, cwd, relative=True)
            except urlutils.InvalidUrlError as e:
                message.error("Error in startup argument '{}': {}".format(
                    cmd, e))
            else:
                background = open_target in ['tab-bg', 'tab-bg-silent']
                tabbed_browser.tabopen(url,
                                       background=background,
                                       explicit=True)
Example #46
0
def process_pos_args(args, via_ipc=False, cwd=None, target_arg=None):
    """Process positional commandline args.

    URLs to open have no prefix, commands to execute begin with a colon.

    Args:
        args: A list of arguments to process.
        via_ipc: Whether the arguments were transmitted over IPC.
        cwd: The cwd to use for fuzzy_url.
        target_arg: Command line argument received by a running instance via
                    ipc. If the --target argument was not specified, target_arg
                    will be an empty string instead of None. This behavior is
                    caused by the PyQt signal
                    ``got_args = pyqtSignal(list, str, str)``
                    used in the misc.ipc.IPCServer class. PyQt converts the
                    None value into a null QString and then back to an empty
                    python string
    """
    if via_ipc and not args:
        win_id = mainwindow.get_window(via_ipc, force_window=True)
        _open_startpage(win_id)
        return
    win_id = None
    for cmd in args:
        if cmd.startswith(':'):
            if win_id is None:
                win_id = mainwindow.get_window(via_ipc, force_tab=True)
            log.init.debug("Startup cmd {}".format(cmd))
            commandrunner = runners.CommandRunner(win_id)
            commandrunner.run_safely_init(cmd[1:])
        elif not cmd:
            log.init.debug("Empty argument")
            win_id = mainwindow.get_window(via_ipc, force_window=True)
        else:
            if via_ipc and target_arg and target_arg != 'auto':
                open_target = target_arg
            else:
                open_target = config.get('general', 'new-instance-open-target')
            win_id = mainwindow.get_window(via_ipc, force_target=open_target)
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=win_id)
            log.init.debug("Startup URL {}".format(cmd))
            try:
                url = urlutils.fuzzy_url(cmd, cwd, relative=True)
            except urlutils.InvalidUrlError as e:
                message.error('current', "Error in startup argument '{}': "
                              "{}".format(cmd, e))
            else:
                background = open_target in ('tab-bg', 'tab-bg-silent')
                tabbed_browser.tabopen(url, background=background)
Example #47
0
 def get(self, name):
     """Get the URL of the quickmark named name as a QUrl."""
     if name not in self.marks:
         raise cmdexc.CommandError("Quickmark '{}' does not exist!".format(name))
     urlstr = self.marks[name]
     try:
         url = urlutils.fuzzy_url(urlstr, do_search=False)
     except urlutils.FuzzyUrlError as e:
         if e.url is None or not e.url.errorString():
             errstr = ""
         else:
             errstr = " ({})".format(e.url.errorString())
         raise cmdexc.CommandError("Invalid URL for quickmark {}: " "{}{}".format(name, urlstr, errstr))
     return url
Example #48
0
def process_pos_args(args, via_ipc=False, cwd=None, target_arg=None):
    """Process positional commandline args.

    URLs to open have no prefix, commands to execute begin with a colon.

    Args:
        args: A list of arguments to process.
        via_ipc: Whether the arguments were transmitted over IPC.
        cwd: The cwd to use for fuzzy_url.
        target_arg: Command line argument received by a running instance via
                    ipc. If the --target argument was not specified, target_arg
                    will be an empty string.
    """
    if via_ipc and not args:
        win_id = mainwindow.get_window(via_ipc, force_window=True)
        _open_startpage(win_id)
        return
    win_id = None
    for cmd in args:
        if cmd.startswith(':'):
            if win_id is None:
                win_id = mainwindow.get_window(via_ipc, force_tab=True)
            log.init.debug("Startup cmd {!r}".format(cmd))
            commandrunner = runners.CommandRunner(win_id)
            commandrunner.run_safely_init(cmd[1:])
        elif not cmd:
            log.init.debug("Empty argument")
            win_id = mainwindow.get_window(via_ipc, force_window=True)
        else:
            if via_ipc and target_arg and target_arg != 'auto':
                open_target = target_arg
            else:
                open_target = config.get('general', 'new-instance-open-target')
            win_id = mainwindow.get_window(via_ipc, force_target=open_target)
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=win_id)
            log.init.debug("Startup URL {}".format(cmd))
            if not cwd:  # could also be an empty string due to the PyQt signal
                cwd = None
            try:
                url = urlutils.fuzzy_url(cmd, cwd, relative=True)
            except urlutils.InvalidUrlError as e:
                message.error("Error in startup argument '{}': {}".format(
                    cmd, e))
            else:
                background = open_target in ['tab-bg', 'tab-bg-silent']
                tabbed_browser.tabopen(url, background=background,
                                       explicit=True)
Example #49
0
 def get(self, name):
     """Get the URL of the quickmark named name as a QUrl."""
     if name not in self.marks:
         raise cmdexc.CommandError(
             "Quickmark '{}' does not exist!".format(name))
     urlstr = self.marks[name]
     try:
         url = urlutils.fuzzy_url(urlstr, do_search=False)
     except urlutils.FuzzyUrlError as e:
         if e.url is None or not e.url.errorString():
             errstr = ''
         else:
             errstr = ' ({})'.format(e.url.errorString())
         raise cmdexc.CommandError("Invalid URL for quickmark {}: "
                                   "{}{}".format(name, urlstr, errstr))
     return url
Example #50
0
def process_pos_args(args, via_ipc=False, cwd=None):
    """Process positional commandline args.

    URLs to open have no prefix, commands to execute begin with a colon.

    Args:
        args: A list of arguments to process.
        via_ipc: Whether the arguments were transmitted over IPC.
        cwd: The cwd to use for fuzzy_url.
    """
    if via_ipc and not args:
        win_id = mainwindow.get_window(via_ipc, force_window=True)
        _open_startpage(win_id)
        return
    win_id = None
    for cmd in args:
        if cmd.startswith(':'):
            if win_id is None:
                win_id = mainwindow.get_window(via_ipc, force_tab=True)
            log.init.debug("Startup cmd {}".format(cmd))
            commandrunner = runners.CommandRunner(win_id)
            commandrunner.run_safely_init(cmd[1:])
        elif not cmd:
            log.init.debug("Empty argument")
            win_id = mainwindow.get_window(via_ipc, force_window=True)
        else:
            win_id = mainwindow.get_window(via_ipc)
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=win_id)
            log.init.debug("Startup URL {}".format(cmd))
            try:
                url = urlutils.fuzzy_url(cmd, cwd, relative=True)
            except urlutils.InvalidUrlError as e:
                message.error(
                    'current', "Error in startup argument '{}': "
                    "{}".format(cmd, e))
            else:
                open_target = config.get('general', 'new-instance-open-target')
                background = open_target in ('tab-bg', 'tab-bg-silent')
                tabbed_browser.tabopen(url, background=background)
Example #51
0
    def process_pos_args(self, args, via_ipc=False, cwd=None):
        """Process positional commandline args.

        URLs to open have no prefix, commands to execute begin with a colon.

        Args:
            args: A list of arguments to process.
            via_ipc: Whether the arguments were transmitted over IPC.
            cwd: The cwd to use for fuzzy_url.
        """
        if via_ipc and not args:
            win_id = self._get_window(via_ipc, force_window=True)
            self._open_startpage(win_id)
            return
        win_id = None
        for cmd in args:
            if cmd.startswith(':'):
                if win_id is None:
                    win_id = self._get_window(via_ipc, force_tab=True)
                log.init.debug("Startup cmd {}".format(cmd))
                commandrunner = runners.CommandRunner(win_id)
                commandrunner.run_safely_init(cmd[1:])
            elif not cmd:
                log.init.debug("Empty argument")
                win_id = self._get_window(via_ipc, force_window=True)
            else:
                win_id = self._get_window(via_ipc)
                tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                            window=win_id)
                log.init.debug("Startup URL {}".format(cmd))
                try:
                    url = urlutils.fuzzy_url(cmd, cwd, relative=True)
                except urlutils.FuzzyUrlError as e:
                    message.error(0, "Error in startup argument '{}': "
                                     "{}".format(cmd, e))
                else:
                    open_target = config.get('general',
                                             'new-instance-open-target')
                    background = open_target in ('tab-bg', 'tab-bg-silent')
                    tabbed_browser.tabopen(url, background=background)
Example #52
0
 def test_empty(self, url):
     with pytest.raises(urlutils.InvalidUrlError):
         urlutils.fuzzy_url(url, do_search=True)
Example #53
0
 def transform(self, value):
     from qutebrowser.utils import urlutils
     if not value:
         return None
     else:
         return urlutils.fuzzy_url(value, do_search=False)
Example #54
0
    def test_no_do_search(self, is_url_mock):
        """Test with do_search = False."""
        is_url_mock.return_value = False

        url = urlutils.fuzzy_url('foo', do_search=False)
        assert url == QUrl('http://foo')
Example #55
0
    def test_no_do_search(self, is_url_mock):
        """Test with do_search = False."""
        is_url_mock.return_value = False

        url = urlutils.fuzzy_url('foo', do_search=False)
        assert url == QUrl('http://foo')
Example #56
0
 def test_invalid_url(self, do_search, caplog):
     """Test with an invalid URL."""
     with pytest.raises(urlutils.InvalidUrlError):
         with caplog.at_level(logging.ERROR):
             urlutils.fuzzy_url('', do_search=do_search)
Example #57
0
 def test_empty(self, url):
     with pytest.raises(urlutils.InvalidUrlError):
         urlutils.fuzzy_url(url, do_search=True)