示例#1
0
 def _load_window(self, win):
     """Turn yaml data into windows."""
     window = mainwindow.MainWindow(geometry=win['geometry'],
                                    private=win.get('private', None))
     window.show()
     tabbed_browser = objreg.get('tabbed-browser',
                                 scope='window',
                                 window=window.win_id)
     tab_to_focus = None
     for i, tab in enumerate(win['tabs']):
         new_tab = tabbed_browser.tabopen(background=False)
         self._load_tab(new_tab, tab)
         if tab.get('active', False):
             tab_to_focus = i
         if new_tab.data.pinned:
             new_tab.set_pinned(True)
     if tab_to_focus is not None:
         tabbed_browser.widget.setCurrentIndex(tab_to_focus)
     if win.get('active', False):
         QTimer.singleShot(0, tabbed_browser.widget.activateWindow)
示例#2
0
    def load(self, name, temp=False):
        """Load a named session.

        Args:
            name: The name of the session to load.
            temp: If given, don't set the current session.
        """
        path = self._get_session_path(name, check_exists=True)
        try:
            with open(path, encoding='utf-8') as f:
                data = utils.yaml_load(f)
        except (OSError, UnicodeDecodeError, yaml.YAMLError) as e:
            raise SessionError(e)

        log.sessions.debug("Loading session {} from {}...".format(name, path))
        for win in data['windows']:
            window = mainwindow.MainWindow(geometry=win['geometry'],
                                           private=win.get('private', None))
            window.show()
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=window.win_id)
            tab_to_focus = None
            for i, tab in enumerate(win['tabs']):
                new_tab = tabbed_browser.tabopen()
                self._load_tab(new_tab, tab)
                if tab.get('active', False):
                    tab_to_focus = i
                if new_tab.data.pinned:
                    tabbed_browser.set_tab_pinned(new_tab,
                                                  new_tab.data.pinned,
                                                  loading=True)
            if tab_to_focus is not None:
                tabbed_browser.setCurrentIndex(tab_to_focus)
            if win.get('active', False):
                QTimer.singleShot(0, tabbed_browser.activateWindow)

        if data['windows']:
            self.did_load = True
        if not name.startswith('_') and not temp:
            self._current = name
示例#3
0
    def _click_href(self, click_target):
        """Fake a click on an element with a href by opening the link."""
        baseurl = self._tab.url()
        url = self.resolve_url(baseurl)
        if url is None:
            self._click_fake_event(click_target)
            return

        if click_target in [usertypes.ClickTarget.tab,
                            usertypes.ClickTarget.tab_bg]:
            background = click_target == usertypes.ClickTarget.tab_bg
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=self._tab.win_id)
            tabbed_browser.tabopen(url, background=background)
        elif click_target == usertypes.ClickTarget.window:
            from qutebrowser.mainwindow import mainwindow
            window = mainwindow.MainWindow()
            window.show()
            window.tabbed_browser.tabopen(url)
        else:
            raise ValueError("Unknown ClickTarget {}".format(click_target))
示例#4
0
def _process_args(args):
    """Open startpage etc. and process commandline args."""
    config_obj = objreg.get('config')
    for sect, opt, val in args.temp_settings:
        try:
            config_obj.set('temp', sect, opt, val)
        except (configexc.Error, configparser.Error) as e:
            message.error("set: {} - {}".format(e.__class__.__name__, e))

    if not args.override_restore:
        _load_session(args.session)
    session_manager = objreg.get('session-manager')
    if not session_manager.did_load:
        log.init.debug("Initializing main window...")
        window = mainwindow.MainWindow()
        if not args.nowindow:
            window.show()
        qApp.setActiveWindow(window)

    process_pos_args(args.command)
    _open_startpage()
    _open_quickstart(args)
示例#5
0
def _process_args(args):
    """Open startpage etc. and process commandline args."""
    if not args.override_restore:
        _load_session(args.session)

    if not sessions.session_manager.did_load:
        log.init.debug("Initializing main window...")
        if config.val.content.private_browsing and qtutils.is_single_process():
            err = Exception("Private windows are unavailable with "
                            "the single-process process model.")
            error.handle_fatal_exc(err, args, 'Cannot start in private mode')
            sys.exit(usertypes.Exit.err_init)
        window = mainwindow.MainWindow(private=None)
        if not args.nowindow:
            window.show()
        q_app.setActiveWindow(window)

    process_pos_args(args.command)
    _open_startpage()
    _open_special_pages(args)

    delta = datetime.datetime.now() - earlyinit.START_TIME
    log.init.debug("Init finished after {}s".format(delta.total_seconds()))
示例#6
0
def get_tab(win_id, target):
    """Get a tab widget for the given usertypes.ClickTarget.

    Args:
        win_id: The window ID to open new tabs in
        target: A usertypes.ClickTarget
    """
    if target == usertypes.ClickTarget.tab:
        bg_tab = False
    elif target == usertypes.ClickTarget.tab_bg:
        bg_tab = True
    elif target == usertypes.ClickTarget.window:
        tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                    window=win_id)
        window = mainwindow.MainWindow(private=tabbed_browser.is_private)
        window.show()
        win_id = window.win_id
        bg_tab = False
    else:
        raise ValueError("Invalid ClickTarget {}".format(target))

    tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                window=win_id)
    return tabbed_browser.tabopen(url=None, background=bg_tab)
示例#7
0
    def follow_prevnext(self, frame, baseurl, prev=False, tab=False,
                        background=False, window=False):
        """Click a "previous"/"next" element on the page.

        Args:
            frame: The frame where the element is in.
            baseurl: The base URL of the current tab.
            prev: True to open a "previous" link, False to open a "next" link.
            tab: True to open in a new tab, False for the current tab.
            background: True to open in a background tab.
            window: True to open in a new window, False for the current one.
        """
        from qutebrowser.mainwindow import mainwindow
        elem = self._find_prevnext(frame, prev)
        if elem is None:
            raise cmdexc.CommandError("No {} links found!".format(
                "prev" if prev else "forward"))
        url = self._resolve_url(elem, baseurl)
        if url is None:
            raise cmdexc.CommandError("No {} links found!".format(
                "prev" if prev else "forward"))
        qtutils.ensure_valid(url)
        if window:
            new_window = mainwindow.MainWindow()
            new_window.show()
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=new_window.win_id)
            tabbed_browser.tabopen(url, background=False)
        elif tab:
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=self._win_id)
            tabbed_browser.tabopen(url, background=background)
        else:
            webview = objreg.get('webview', scope='tab', window=self._win_id,
                                 tab=self._tab_id)
            webview.openurl(url)
示例#8
0
    def _prevnext_cb(elems):
        if elems is None:
            message.error("Unknown error while getting hint elements")
            return
        elif isinstance(elems, webelem.Error):
            message.error(str(elems))
            return

        elem = _find_prevnext(prev, elems)
        word = 'prev' if prev else 'forward'

        if elem is None:
            message.error("No {} links found!".format(word))
            return
        url = elem.resolve_url(baseurl)
        if url is None:
            message.error("No {} links found!".format(word))
            return
        qtutils.ensure_valid(url)

        cur_tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=win_id)

        if window:
            new_window = mainwindow.MainWindow(
                private=cur_tabbed_browser.is_private)
            new_window.show()
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=new_window.win_id)
            tabbed_browser.tabopen(url, background=False)
        elif tab:
            cur_tabbed_browser.tabopen(url, background=background)
        else:
            browsertab.openurl(url)
示例#9
0
def _process_args(args):
    """Open startpage etc. and process commandline args."""
    for opt, val in args.temp_settings:
        try:
            config.instance.set_str(opt, val)
        except configexc.Error as e:
            message.error("set: {} - {}".format(e.__class__.__name__, e))

    if not args.override_restore:
        _load_session(args.session)
    session_manager = objreg.get('session-manager')
    if not session_manager.did_load:
        log.init.debug("Initializing main window...")
        window = mainwindow.MainWindow(private=None)
        if not args.nowindow:
            window.show()
        qApp.setActiveWindow(window)

    process_pos_args(args.command)
    _open_startpage()
    _open_special_pages(args)

    delta = datetime.datetime.now() - earlyinit.START_TIME
    log.init.debug("Init finished after {}s".format(delta.total_seconds()))
示例#10
0
    def _on_link_clicked(self, url):
        log.webview.debug("link clicked: url {}, override target {}, "
                          "open_target {}".format(
                              url.toDisplayString(),
                              self.data.override_target,
                              self.data.open_target))

        if not url.isValid():
            msg = urlutils.get_errstring(url, "Invalid link clicked")
            message.error(msg)
            self.data.open_target = usertypes.ClickTarget.normal
            return False

        target = self.data.combined_target()

        if target == usertypes.ClickTarget.normal:
            return
        elif target == usertypes.ClickTarget.tab:
            win_id = self.win_id
            bg_tab = False
        elif target == usertypes.ClickTarget.tab_bg:
            win_id = self.win_id
            bg_tab = True
        elif target == usertypes.ClickTarget.window:
            from qutebrowser.mainwindow import mainwindow
            window = mainwindow.MainWindow()
            window.show()
            win_id = window.win_id
            bg_tab = False
        else:
            raise ValueError("Invalid ClickTarget {}".format(target))

        tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                    window=win_id)
        tabbed_browser.tabopen(url, background=bg_tab)
        self.data.open_target = usertypes.ClickTarget.normal
示例#11
0
    def _click_href(self, click_target: usertypes.ClickTarget) -> None:
        """Fake a click on an element with a href by opening the link."""
        baseurl = self._tab.url()
        url = self.resolve_url(baseurl)
        if url is None:
            self._click_fake_event(click_target)
            return

        tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                    window=self._tab.win_id)

        if click_target in [usertypes.ClickTarget.tab,
                            usertypes.ClickTarget.tab_bg]:
            background = click_target == usertypes.ClickTarget.tab_bg
            tabbed_browser.tabopen(url, background=background)
        elif click_target == usertypes.ClickTarget.window:
            from qutebrowser.mainwindow import mainwindow
            window = mainwindow.MainWindow(private=tabbed_browser.is_private)
            window.show()
            # FIXME:typing Why can't mypy determine the type of
            # window.tabbed_browser?
            window.tabbed_browser.tabopen(url)  # type: ignore
        else:
            raise ValueError("Unknown ClickTarget {}".format(click_target))
示例#12
0
    def tabopen(self,
                url=None,
                background=None,
                explicit=False,
                idx=None,
                *,
                ignore_tabs_are_windows=False):
        """Open a new tab with a given URL.

        Inner logic for open-tab and open-tab-bg.
        Also connect all the signals we need to _filter_signals.

        Args:
            url: The URL to open as QUrl or None for an empty tab.
            background: Whether to open the tab in the background.
                        if None, the background-tabs setting decides.
            explicit: Whether the tab was opened explicitly.
                      If this is set, the new position might be different. With
                      the default settings we handle it like Chromium does:
                          - Tabs from clicked links etc. are to the right of
                            the current.
                          - Explicitly opened tabs are at the very right.
            idx: The index where the new tab should be opened.
            ignore_tabs_are_windows: If given, never open a new window, even
                                     with tabs-are-windows set.

        Return:
            The opened WebView instance.
        """
        if url is not None:
            qtutils.ensure_valid(url)
        log.webview.debug("Creating new tab with URL {}, background {}, "
                          "explicit {}, idx {}".format(url, background,
                                                       explicit, idx))

        if (config.get('tabs', 'tabs-are-windows') and self.count() > 0
                and not ignore_tabs_are_windows):
            from qutebrowser.mainwindow import mainwindow
            window = mainwindow.MainWindow(private=self.private)
            window.show()
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=window.win_id)
            return tabbed_browser.tabopen(url, background, explicit)

        tab = browsertab.create(win_id=self._win_id,
                                private=self.private,
                                parent=self)
        self._connect_tab_signals(tab)

        if idx is None:
            idx = self._get_new_tab_idx(explicit)
        self.insertTab(idx, tab, "")

        if url is not None:
            tab.openurl(url)

        if background is None:
            background = config.get('tabs', 'background-tabs')
        if background:
            # Make sure the background tab has the correct initial size.
            # With a foreground tab, it's going to be resized correctly by the
            # layout anyways.
            if self.tabBar().vertical:
                tab_size = QSize(self.width() - self.tabBar().width(),
                                 self.height())
            else:
                tab_size = QSize(self.width(),
                                 self.height() - self.tabBar().height())
            tab.resize(tab_size)
            self.tab_index_changed.emit(self.currentIndex(), self.count())
        else:
            self.setCurrentWidget(tab)

        tab.show()
        self.new_tab.emit(tab, idx)
        return tab
示例#13
0
    def tabopen(
        self,
        url: QUrl = None,
        background: bool = None,
        related: bool = True,
        idx: int = None,
    ) -> browsertab.AbstractTab:
        """Open a new tab with a given URL.

        Inner logic for open-tab and open-tab-bg.
        Also connect all the signals we need to _filter_signals.

        Args:
            url: The URL to open as QUrl or None for an empty tab.
            background: Whether to open the tab in the background.
                        if None, the `tabs.background` setting decides.
            related: Whether the tab was opened from another existing tab.
                     If this is set, the new position might be different. With
                     the default settings we handle it like Chromium does:
                         - Tabs from clicked links etc. are to the right of
                           the current (related=True).
                         - Explicitly opened tabs are at the very right
                           (related=False)
            idx: The index where the new tab should be opened.

        Return:
            The opened WebView instance.
        """
        if url is not None:
            qtutils.ensure_valid(url)
        log.webview.debug("Creating new tab with URL {}, background {}, "
                          "related {}, idx {}".format(url, background, related,
                                                      idx))

        prev_focus = QApplication.focusWidget()

        if config.val.tabs.tabs_are_windows and self.widget.count() > 0:
            window = mainwindow.MainWindow(private=self.is_private)
            window.show()
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=window.win_id)
            return tabbed_browser.tabopen(url=url,
                                          background=background,
                                          related=related)

        tab = browsertab.create(win_id=self._win_id,
                                private=self.is_private,
                                parent=self.widget)
        self._connect_tab_signals(tab)

        if idx is None:
            idx = self._get_new_tab_idx(related)
        self.widget.insertTab(idx, tab, "")

        if url is not None:
            tab.load_url(url)

        if background is None:
            background = config.val.tabs.background
        if background:
            # Make sure the background tab has the correct initial size.
            # With a foreground tab, it's going to be resized correctly by the
            # layout anyways.
            tab.resize(self.widget.currentWidget().size())
            self.widget.tab_index_changed.emit(self.widget.currentIndex(),
                                               self.widget.count())
            # Refocus webview in case we lost it by spawning a bg tab
            self.widget.currentWidget().setFocus()
        else:
            self.widget.setCurrentWidget(tab)

        mode = modeman.instance(self._win_id).mode
        if mode in [
                usertypes.KeyMode.command, usertypes.KeyMode.prompt,
                usertypes.KeyMode.yesno
        ]:
            # If we were in a command prompt, restore old focus
            # The above commands need to be run to switch tabs
            if prev_focus is not None:
                prev_focus.setFocus()

        tab.show()
        self.new_tab.emit(tab, idx)
        return tab
示例#14
0
    def tabopen(self,
                url=None,
                background=None,
                related=True,
                idx=None,
                *,
                ignore_tabs_are_windows=False):
        """Open a new tab with a given URL.

        Inner logic for open-tab and open-tab-bg.
        Also connect all the signals we need to _filter_signals.

        Args:
            url: The URL to open as QUrl or None for an empty tab.
            background: Whether to open the tab in the background.
                        if None, the `tabs.background_tabs`` setting decides.
            related: Whether the tab was opened from another existing tab.
                     If this is set, the new position might be different. With
                     the default settings we handle it like Chromium does:
                         - Tabs from clicked links etc. are to the right of
                           the current (related=True).
                         - Explicitly opened tabs are at the very right
                           (related=False)
            idx: The index where the new tab should be opened.
            ignore_tabs_are_windows: If given, never open a new window, even
                                     with tabs.tabs_are_windows set.

        Return:
            The opened WebView instance.
        """
        if url is not None:
            qtutils.ensure_valid(url)
        log.webview.debug("Creating new tab with URL {}, background {}, "
                          "related {}, idx {}".format(url, background, related,
                                                      idx))

        if (config.val.tabs.tabs_are_windows and self.count() > 0
                and not ignore_tabs_are_windows):
            window = mainwindow.MainWindow(private=self.private)
            window.show()
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=window.win_id)
            return tabbed_browser.tabopen(url=url,
                                          background=background,
                                          related=related)

        tab = browsertab.create(win_id=self._win_id,
                                private=self.private,
                                parent=self)
        self._connect_tab_signals(tab)

        # this was necessary to remove otherwise it was making a hell of a mess in tree structure
        # if idx is None:
        #     idx = self._get_new_tab_idx(related)
        idx = self._get_new_tab_idx(related)

        self.insertTab(idx, tab, "")

        if url is not None:
            tab.openurl(url)

        if background is None:
            background = config.val.tabs.background
        if background:
            # Make sure the background tab has the correct initial size.
            # With a foreground tab, it's going to be resized correctly by the
            # layout anyways.
            tab.resize(self.currentWidget().size())
            self.tab_index_changed.emit(self.currentIndex(), self.count())
        else:
            self.setCurrentWidget(tab)

        tab.show()
        self.new_tab.emit(tab, idx)
        return tab