Beispiel #1
0
def init(args, crash_handler):
    """Initialize everything.

    Args:
        args: The argparse namespace.
        crash_handler: The CrashHandler instance.
    """
    log.init.debug("Starting init...")
    qApp.setQuitOnLastWindowClosed(False)
    _init_icon()

    try:
        _init_modules(args, crash_handler)
    except (OSError, UnicodeDecodeError, browsertab.WebTabError) as e:
        error.handle_fatal_exc(e, args, "Error while initializing!",
                               pre_text="Error while initializing")
        sys.exit(usertypes.Exit.err_init)

    log.init.debug("Initializing eventfilter...")
    event_filter = EventFilter(qApp)
    qApp.installEventFilter(event_filter)
    objreg.register('event-filter', event_filter)

    log.init.debug("Connecting signals...")
    qApp.focusChanged.connect(on_focus_changed)

    _process_args(args)

    QDesktopServices.setUrlHandler('http', open_desktopservices_url)
    QDesktopServices.setUrlHandler('https', open_desktopservices_url)
    QDesktopServices.setUrlHandler('qute', open_desktopservices_url)

    log.init.debug("Init done!")
    crash_handler.raise_crashdlg()
Beispiel #2
0
def _init_key_config(parent):
    """Initialize the key config.

    Args:
        parent: The parent to use for the KeyConfigParser.
    """
    args = objreg.get('args')
    try:
        key_config = keyconf.KeyConfigParser(standarddir.config(), 'keys.conf',
                                             args.relaxed_config,
                                             parent=parent)
    except (keyconf.KeyConfigError, UnicodeDecodeError) as e:
        log.init.exception(e)
        errstr = "Error while reading key config:\n"
        if e.lineno is not None:
            errstr += "In line {}: ".format(e.lineno)
        error.handle_fatal_exc(e, args, "Error while reading key config!",
                               pre_text=errstr)
        # We didn't really initialize much so far, so we just quit hard.
        sys.exit(usertypes.Exit.err_key_config)
    else:
        objreg.register('key-config', key_config)
        if standarddir.config() is not None:
            save_manager = objreg.get('save-manager')
            filename = os.path.join(standarddir.config(), 'keys.conf')
            save_manager.add_saveable(
                'key-config', key_config.save, key_config.config_dirty,
                config_opt=('general', 'auto-save-config'), filename=filename,
                dirty=key_config.is_dirty)
Beispiel #3
0
def init(win_id, parent):
    """Initialize the mode manager and the keyparsers for the given win_id."""
    KM = usertypes.KeyMode  # pylint: disable=invalid-name
    modeman = ModeManager(win_id, parent)
    objreg.register('mode-manager', modeman, scope='window', window=win_id)
    keyparsers = {
        KM.normal: modeparsers.NormalKeyParser(win_id, modeman),
        KM.hint: modeparsers.HintKeyParser(win_id, modeman),
        KM.insert: keyparser.PassthroughKeyParser(win_id, 'insert', modeman),
        KM.passthrough: keyparser.PassthroughKeyParser(win_id, 'passthrough',
                                                       modeman),
        KM.command: keyparser.PassthroughKeyParser(win_id, 'command', modeman),
        KM.prompt: keyparser.PassthroughKeyParser(win_id, 'prompt', modeman,
                                                  warn=False),
        KM.yesno: modeparsers.PromptKeyParser(win_id, modeman),
        KM.caret: modeparsers.CaretKeyParser(win_id, modeman),
        KM.set_mark: modeparsers.RegisterKeyParser(win_id, KM.set_mark,
                                                   modeman),
        KM.jump_mark: modeparsers.RegisterKeyParser(win_id, KM.jump_mark,
                                                    modeman),
        KM.record_macro: modeparsers.RegisterKeyParser(win_id, KM.record_macro,
                                                       modeman),
        KM.run_macro: modeparsers.RegisterKeyParser(win_id, KM.run_macro,
                                                    modeman),
    }
    objreg.register('keyparsers', keyparsers, scope='window', window=win_id)
    modeman.destroyed.connect(
        functools.partial(objreg.delete, 'keyparsers', scope='window',
                          window=win_id))
    for mode, parser in keyparsers.items():
        modeman.register(mode, parser)
    return modeman
Beispiel #4
0
 def _init_completion(self):
     self._completion = completionwidget.CompletionView(self.win_id, self)
     cmd = objreg.get("status-command", scope="window", window=self.win_id)
     completer_obj = completer.Completer(cmd, self.win_id, self._completion)
     self._completion.selection_changed.connect(completer_obj.on_selection_changed)
     objreg.register("completion", self._completion, scope="window", window=self.win_id)
     self._overlays.append((self._completion, self._completion.update_geometry))
Beispiel #5
0
def status_command_stub(stubs, qtbot, win_registry):
    """Fixture which provides a fake status-command object."""
    cmd = stubs.StatusBarCommandStub()
    objreg.register('status-command', cmd, scope='window', window=0)
    qtbot.addWidget(cmd)
    yield cmd
    objreg.delete('status-command', scope='window', window=0)
Beispiel #6
0
def init(win_id, parent):
    """Initialize the mode manager and the keyparsers for the given win_id."""
    KM = usertypes.KeyMode  # pylint: disable=invalid-name
    modeman = ModeManager(win_id, parent)
    objreg.register('mode-manager', modeman, scope='window', window=win_id)
    keyparsers = {
        KM.normal: modeparsers.NormalKeyParser(win_id, modeman),
        KM.hint: modeparsers.HintKeyParser(win_id, modeman),
        KM.insert: keyparser.PassthroughKeyParser(win_id, 'insert', modeman),
        KM.passthrough: keyparser.PassthroughKeyParser(win_id, 'passthrough',
                                                       modeman),
        KM.command: keyparser.PassthroughKeyParser(win_id, 'command', modeman),
        KM.prompt: keyparser.PassthroughKeyParser(win_id, 'prompt', modeman,
                                                  warn=False),
        KM.yesno: modeparsers.PromptKeyParser(win_id, modeman),
    }
    objreg.register('keyparsers', keyparsers, scope='window', window=win_id)
    modeman.destroyed.connect(
        functools.partial(objreg.delete, 'keyparsers', scope='window',
                          window=win_id))
    modeman.register(KM.normal, keyparsers[KM.normal].handle)
    modeman.register(KM.hint, keyparsers[KM.hint].handle)
    modeman.register(KM.insert, keyparsers[KM.insert].handle, passthrough=True)
    modeman.register(KM.passthrough, keyparsers[KM.passthrough].handle,
                     passthrough=True)
    modeman.register(KM.command, keyparsers[KM.command].handle,
                     passthrough=True)
    modeman.register(KM.prompt, keyparsers[KM.prompt].handle, passthrough=True)
    modeman.register(KM.yesno, keyparsers[KM.yesno].handle)
    return modeman
Beispiel #7
0
def download_stub(win_registry):
    """Register a FakeDownloadManager."""
    stub = FakeDownloadManager()
    objreg.register('download-manager', stub,
                    scope='window', window='last-focused')
    yield
    objreg.delete('download-manager', scope='window', window='last-focused')
Beispiel #8
0
    def __init__(self, win_id, parent=None):
        super().__init__(parent)
        self._win_id = win_id
        objreg.register('completion', self, scope='window', window=win_id)
        cmd = objreg.get('status-command', scope='window', window=win_id)
        completer_obj = completer.Completer(cmd, win_id, self)
        completer_obj.next_prev_item.connect(self.on_next_prev_item)
        objreg.register('completer', completer_obj, scope='window',
                        window=win_id)
        self.enabled = config.get('completion', 'show')
        objreg.get('config').changed.connect(self.set_enabled)
        # FIXME handle new aliases.
        # objreg.get('config').changed.connect(self.init_command_completion)

        self._column_widths = base.BaseCompletionModel.COLUMN_WIDTHS

        self._delegate = completiondelegate.CompletionItemDelegate(self)
        self.setItemDelegate(self._delegate)
        style.set_register_stylesheet(self)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)
        self.setHeaderHidden(True)
        self.setAlternatingRowColors(True)
        self.setIndentation(0)
        self.setItemsExpandable(False)
        self.setExpandsOnDoubleClick(False)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # WORKAROUND
        # This is a workaround for weird race conditions with invalid
        # item indexes leading to segfaults in Qt.
        #
        # Some background: http://bugs.quassel-irc.org/issues/663
        # The proposed fix there was later reverted because it didn't help.
        self.setUniformRowHeights(True)
        self.hide()
Beispiel #9
0
    def __init__(self, *, win_id: int, private: bool,
                 parent: QWidget = None) -> None:
        self.is_private = private
        self.win_id = win_id
        self.tab_id = next(tab_id_gen)
        super().__init__(parent)

        self.registry = objreg.ObjectRegistry()
        tab_registry = objreg.get('tab-registry', scope='window',
                                  window=win_id)
        tab_registry[self.tab_id] = self
        objreg.register('tab', self, registry=self.registry)

        self.data = TabData()
        self._layout = miscwidgets.WrapperLayout(self)
        self._widget = None  # type: typing.Optional[QWidget]
        self._progress = 0
        self._has_ssl_errors = False
        self._load_status = usertypes.LoadStatus.none
        self._mouse_event_filter = mouse.MouseEventFilter(
            self, parent=self)
        self.backend = None

        # FIXME:qtwebengine  Should this be public api via self.hints?
        #                    Also, should we get it out of objreg?
        hintmanager = hints.HintManager(win_id, self.tab_id, parent=self)
        objreg.register('hintmanager', hintmanager, scope='tab',
                        window=self.win_id, tab=self.tab_id)

        self.before_load_started.connect(self._on_before_load_started)
Beispiel #10
0
def init():
    """Initialize global prompt objects."""
    global prompt_queue
    prompt_queue = PromptQueue()
    objreg.register('prompt-queue', prompt_queue)  # for commands
    message.global_bridge.ask_question.connect(
        prompt_queue.ask_question, Qt.DirectConnection)
Beispiel #11
0
def default_config():
    """Fixture that provides and registers an empty default config object."""
    config_obj = config.ConfigManager()
    config_obj.read(configdir=None, fname=None, relaxed=True)
    objreg.register('config', config_obj)
    yield config_obj
    objreg.delete('config')
Beispiel #12
0
def send_or_listen(args):
    """Send the args to a running instance or start a new IPCServer.

    Args:
        args: The argparse namespace.

    Return:
        The IPCServer instance if no running instance was detected.
        None if an instance was running and received our request.
    """
    socketname = _get_socketname(args.basedir)
    legacy_socketname = _get_socketname(args.basedir, legacy=True)
    try:
        try:
            sent = send_to_running_instance(socketname, args.command, args.target, legacy_name=legacy_socketname)
            if sent:
                return None
            log.init.debug("Starting IPC server...")
            server = IPCServer(socketname)
            server.listen()
            objreg.register("ipc-server", server)
            return server
        except AddressInUseError as e:
            # This could be a race condition...
            log.init.debug("Got AddressInUseError, trying again.")
            time.sleep(0.5)
            sent = send_to_running_instance(socketname, args.command, args.target, legacy_name=legacy_socketname)
            if sent:
                return None
            else:
                raise
    except Error as e:
        display_error(e, args)
        raise
 def setUp(self):
     objreg.register('key-config', fake_keyconfig)
     basekeyparser.usertypes.Timer = mock.Mock()
     self.kp = basekeyparser.BaseKeyParser(0, supports_chains=True,
                                           supports_count=True)
     self.kp.execute = mock.Mock()
     self.kp.read_config('test')
def fake_keyconfig():
    """Create a mock of a KeyConfiguration and register it into objreg."""
    fake_keyconfig = mock.Mock(spec=['get_bindings_for'])
    fake_keyconfig.get_bindings_for.side_effect = lambda s: BINDINGS[s]
    objreg.register('key-config', fake_keyconfig)
    yield
    objreg.delete('key-config')
Beispiel #15
0
 def setUp(self):
     """Set up mocks and read the test config."""
     objreg.register('key-config', fake_keyconfig)
     self.kp = basekeyparser.BaseKeyParser(0, supports_chains=True,
                                           supports_count=False)
     self.kp.execute = mock.Mock()
     self.kp.read_config('test')
Beispiel #16
0
    def _init_modules(self):
        """Initialize all 'modules' which need to be initialized."""
        log.init.debug("Initializing readline-bridge...")
        readline_bridge = readline.ReadlineBridge()
        objreg.register('readline-bridge', readline_bridge)

        log.init.debug("Initializing directories...")
        standarddir.init()
        log.init.debug("Initializing config...")
        config.init(self._args)
        log.init.debug("Initializing crashlog...")
        self._handle_segfault()
        log.init.debug("Initializing websettings...")
        websettings.init()
        log.init.debug("Initializing quickmarks...")
        quickmark_manager = quickmarks.QuickmarkManager()
        objreg.register('quickmark-manager', quickmark_manager)
        log.init.debug("Initializing proxy...")
        proxy.init()
        log.init.debug("Initializing cookies...")
        cookie_jar = cookies.CookieJar(self)
        objreg.register('cookie-jar', cookie_jar)
        log.init.debug("Initializing cache...")
        diskcache = cache.DiskCache(self)
        objreg.register('cache', diskcache)
        log.init.debug("Initializing downloads...")
        download_manager = downloads.DownloadManager(self)
        objreg.register('download-manager', download_manager)
        log.init.debug("Initializing main window...")
        win_id = mainwindow.MainWindow.spawn(
            False if self._args.nowindow else True)
        main_window = objreg.get('main-window', scope='window', window=win_id)
        self.setActiveWindow(main_window)
def init():
    """Initialize QtWebEngine-specific modules."""
    # For some reason we need to keep a reference, otherwise the scheme handler
    # won't work...
    # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html
    global _qute_scheme_handler
    app = QApplication.instance()

    software_rendering = (os.environ.get('LIBGL_ALWAYS_SOFTWARE') == '1' or
                          'QT_XCB_FORCE_SOFTWARE_OPENGL' in os.environ)
    if version.opengl_vendor() == 'nouveau' and not software_rendering:
        # FIXME:qtwebengine display something more sophisticated here
        raise browsertab.WebTabError(
            "QtWebEngine is not supported with Nouveau graphics (unless "
            "QT_XCB_FORCE_SOFTWARE_OPENGL is set as environment variable).")

    log.init.debug("Initializing qute://* handler...")
    _qute_scheme_handler = webenginequtescheme.QuteSchemeHandler(parent=app)
    _qute_scheme_handler.install(webenginesettings.default_profile)
    _qute_scheme_handler.install(webenginesettings.private_profile)

    log.init.debug("Initializing request interceptor...")
    host_blocker = objreg.get('host-blocker')
    req_interceptor = interceptor.RequestInterceptor(
        host_blocker, parent=app)
    req_interceptor.install(webenginesettings.default_profile)
    req_interceptor.install(webenginesettings.private_profile)

    log.init.debug("Initializing QtWebEngine downloads...")
    download_manager = webenginedownloads.DownloadManager(parent=app)
    download_manager.install(webenginesettings.default_profile)
    download_manager.install(webenginesettings.private_profile)
    objreg.register('webengine-download-manager', download_manager)
Beispiel #18
0
def init():
    """Inizialize the mode manager and the keyparsers."""
    KM = usertypes.KeyMode  # pylint: disable=invalid-name
    modeman = ModeManager(objreg.get('app'))
    objreg.register('mode-manager', modeman)
    keyparsers = {
        KM.normal: modeparsers.NormalKeyParser(modeman),
        KM.hint: modeparsers.HintKeyParser(modeman),
        KM.insert: keyparser.PassthroughKeyParser('insert', modeman),
        KM.passthrough: keyparser.PassthroughKeyParser('passthrough', modeman),
        KM.command: keyparser.PassthroughKeyParser('command', modeman),
        KM.prompt: keyparser.PassthroughKeyParser('prompt', modeman,
                                                  warn=False),
        KM.yesno: modeparsers.PromptKeyParser(modeman),
    }
    objreg.register('keyparsers', keyparsers)
    modeman.register(KM.normal, keyparsers[KM.normal].handle)
    modeman.register(KM.hint, keyparsers[KM.hint].handle)
    modeman.register(KM.insert, keyparsers[KM.insert].handle, passthrough=True)
    modeman.register(KM.passthrough, keyparsers[KM.passthrough].handle,
                     passthrough=True)
    modeman.register(KM.command, keyparsers[KM.command].handle,
                     passthrough=True)
    modeman.register(KM.prompt, keyparsers[KM.prompt].handle, passthrough=True)
    modeman.register(KM.yesno, keyparsers[KM.yesno].handle)
Beispiel #19
0
    def __init__(self, win_id, tab_id, tab, parent=None):
        super().__init__(parent)
        if sys.platform == 'darwin' and qtutils.version_check('5.4'):
            # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-42948
            # See https://github.com/The-Compiler/qutebrowser/issues/462
            self.setStyle(QStyleFactory.create('Fusion'))
        self.tab = tab
        self.win_id = win_id
        self._check_insertmode = False
        self.scroll_pos = (-1, -1)
        self._old_scroll_pos = (-1, -1)
        self._ignore_wheel_event = False
        self._set_bg_color()
        self._tab_id = tab_id

        page = self._init_page()
        hintmanager = hints.HintManager(win_id, self._tab_id, self)
        hintmanager.mouse_event.connect(self.on_mouse_event)
        hintmanager.start_hinting.connect(page.on_start_hinting)
        hintmanager.stop_hinting.connect(page.on_stop_hinting)
        objreg.register('hintmanager', hintmanager, scope='tab', window=win_id,
                        tab=tab_id)
        mode_manager = objreg.get('mode-manager', scope='window',
                                  window=win_id)
        mode_manager.entered.connect(self.on_mode_entered)
        mode_manager.left.connect(self.on_mode_left)
        if config.get('input', 'rocker-gestures'):
            self.setContextMenuPolicy(Qt.PreventContextMenu)
        objreg.get('config').changed.connect(self.on_config_changed)
Beispiel #20
0
    def __init__(self, win_id, parent=None):
        super().__init__(parent)
        objreg.register('statusbar', self, scope='window', window=win_id)
        self.setObjectName(self.__class__.__name__)
        self.setAttribute(Qt.WA_StyledBackground)
        style.set_register_stylesheet(self)

        self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)

        self._win_id = win_id
        self._option = None

        self._hbox = QHBoxLayout(self)
        self.set_hbox_padding()
        objreg.get('config').changed.connect(self.set_hbox_padding)
        self._hbox.setSpacing(5)

        self._stack = QStackedLayout()
        self._hbox.addLayout(self._stack)
        self._stack.setContentsMargins(0, 0, 0, 0)

        self.cmd = command.Command(win_id)
        self._stack.addWidget(self.cmd)
        objreg.register('status-command', self.cmd, scope='window',
                        window=win_id)

        self.txt = textwidget.Text()
        self._stack.addWidget(self.txt)

        self.prompt = prompt.Prompt(win_id)
        self._stack.addWidget(self.prompt)

        self.cmd.show_cmd.connect(self._show_cmd_widget)
        self.cmd.hide_cmd.connect(self._hide_cmd_widget)
        self._hide_cmd_widget()
        prompter = objreg.get('prompter', scope='window', window=self._win_id)
        prompter.show_prompt.connect(self._show_prompt_widget)
        prompter.hide_prompt.connect(self._hide_prompt_widget)
        self._hide_prompt_widget()

        self.keystring = keystring.KeyString()
        self._hbox.addWidget(self.keystring)

        self.url = url.UrlText()
        self._hbox.addWidget(self.url)

        self.percentage = percentage.Percentage()
        self._hbox.addWidget(self.percentage)

        self.tabindex = tabindex.TabIndex()
        self._hbox.addWidget(self.tabindex)

        # We add a parent to Progress here because it calls self.show() based
        # on some signals, and if that happens before it's added to the layout,
        # it will quickly blink up as independent window.
        self.prog = progress.Progress(self)
        self._hbox.addWidget(self.prog)

        objreg.get('config').changed.connect(self.maybe_hide)
        QTimer.singleShot(0, self.maybe_hide)
Beispiel #21
0
    def __init__(self, win_id, parent=None):
        self.win_id = win_id
        self.tab_id = next(tab_id_gen)
        super().__init__(parent)

        self.registry = objreg.ObjectRegistry()
        tab_registry = objreg.get('tab-registry', scope='window',
                                  window=win_id)
        tab_registry[self.tab_id] = self
        objreg.register('tab', self, registry=self.registry)

        # self.history = AbstractHistory(self)
        # self.scroller = AbstractScroller(self, parent=self)
        # self.caret = AbstractCaret(win_id=win_id, tab=self, mode_manager=...,
        #                            parent=self)
        # self.zoom = AbstractZoom(win_id=win_id)
        # self.search = AbstractSearch(parent=self)
        # self.printing = AbstractPrinting()
        # self.elements = AbstractElements(self)

        self.data = TabData()
        self._layout = miscwidgets.WrapperLayout(self)
        self._widget = None
        self._progress = 0
        self._has_ssl_errors = False
        self._load_status = usertypes.LoadStatus.none
        self._mouse_event_filter = mouse.MouseEventFilter(
            self, widget_class=self.WIDGET_CLASS, parent=self)
        self.backend = None

        # FIXME:qtwebengine  Should this be public api via self.hints?
        #                    Also, should we get it out of objreg?
        hintmanager = hints.HintManager(win_id, self.tab_id, parent=self)
        objreg.register('hintmanager', hintmanager, scope='tab',
                        window=self.win_id, tab=self.tab_id)
Beispiel #22
0
    def __init__(self, *, win_id, mode_manager, private, parent=None):
        self.private = private
        self.win_id = win_id
        self.tab_id = next(tab_id_gen)
        super().__init__(parent)

        self.registry = objreg.ObjectRegistry()
        tab_registry = objreg.get('tab-registry', scope='window',
                                  window=win_id)
        tab_registry[self.tab_id] = self
        objreg.register('tab', self, registry=self.registry)

        self.data = TabData()
        self._layout = miscwidgets.WrapperLayout(self)
        self._widget = None
        self._progress = 0
        self._has_ssl_errors = False
        self._mode_manager = mode_manager
        self._load_status = usertypes.LoadStatus.none
        self._mouse_event_filter = mouse.MouseEventFilter(
            self, parent=self)
        self.backend = None

        # FIXME:qtwebengine  Should this be public api via self.hints?
        #                    Also, should we get it out of objreg?
        hintmanager = hints.HintManager(win_id, self.tab_id, parent=self)
        objreg.register('hintmanager', hintmanager, scope='tab',
                        window=self.win_id, tab=self.tab_id)

        self.predicted_navigation.connect(
            lambda url: self.title_changed.emit(url.toDisplayString()))
Beispiel #23
0
def fake_args(request):
    ns = types.SimpleNamespace()
    ns.backend = 'webengine' if request.config.webengine else 'webkit'
    ns.debug_flags = []
    objreg.register('args', ns)
    yield ns
    objreg.delete('args')
Beispiel #24
0
def init():
    """Initialize QtWebEngine-specific modules."""
    # For some reason we need to keep a reference, otherwise the scheme handler
    # won't work...
    # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html
    global _qute_scheme_handler

    app = QApplication.instance()
    log.init.debug("Initializing qute://* handler...")
    _qute_scheme_handler = webenginequtescheme.QuteSchemeHandler(parent=app)
    _qute_scheme_handler.install(webenginesettings.default_profile)
    _qute_scheme_handler.install(webenginesettings.private_profile)

    log.init.debug("Initializing request interceptor...")
    host_blocker = objreg.get('host-blocker')
    req_interceptor = interceptor.RequestInterceptor(
        host_blocker, parent=app)
    req_interceptor.install(webenginesettings.default_profile)
    req_interceptor.install(webenginesettings.private_profile)

    log.init.debug("Initializing QtWebEngine downloads...")
    download_manager = webenginedownloads.DownloadManager(parent=app)
    download_manager.install(webenginesettings.default_profile)
    download_manager.install(webenginesettings.private_profile)
    objreg.register('webengine-download-manager', download_manager)

    greasemonkey = objreg.get('greasemonkey')
    greasemonkey.scripts_reloaded.connect(webenginesettings.inject_userscripts)
    webenginesettings.inject_userscripts()
Beispiel #25
0
 def __init__(self, win_id, parent=None):
     super().__init__(win_id, parent)
     self._win_id = win_id
     self._tab_insert_idx_left = 0
     self._tab_insert_idx_right = -1
     self._shutting_down = False
     self.tabCloseRequested.connect(self.on_tab_close_requested)
     self.currentChanged.connect(self.on_current_changed)
     self.cur_load_started.connect(self.on_cur_load_started)
     self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     self._undo_stack = []
     self._filter = signalfilter.SignalFilter(win_id, self)
     dispatcher = commands.CommandDispatcher(win_id)
     objreg.register('command-dispatcher', dispatcher, scope='window',
                     window=win_id)
     self.destroyed.connect(
         functools.partial(objreg.delete, 'command-dispatcher',
                           scope='window', window=win_id))
     self._now_focused = None
     # FIXME adjust this to font size
     # https://github.com/The-Compiler/qutebrowser/issues/119
     self.setIconSize(QSize(12, 12))
     objreg.get('config').changed.connect(self.update_favicons)
     objreg.get('config').changed.connect(self.update_window_title)
     objreg.get('config').changed.connect(self.update_tab_titles)
    def __init__(self, win_id, parent=None):
        self.win_id = win_id
        self.tab_id = next(tab_id_gen)
        super().__init__(parent)

        self.registry = objreg.ObjectRegistry()
        tab_registry = objreg.get('tab-registry', scope='window',
                                  window=win_id)
        tab_registry[self.tab_id] = self
        objreg.register('tab', self, registry=self.registry)

        # self.history = AbstractHistory(self)
        # self.scroller = AbstractScroller(self, parent=self)
        # self.caret = AbstractCaret(win_id=win_id, tab=self, mode_manager=...,
        #                            parent=self)
        # self.zoom = AbstractZoom(win_id=win_id)
        # self.search = AbstractSearch(parent=self)
        # self.printing = AbstractPrinting()
        self.data = TabData()
        self._layout = miscwidgets.WrapperLayout(self)
        self._widget = None
        self._progress = 0
        self._has_ssl_errors = False
        self._load_status = usertypes.LoadStatus.none
        self.backend = None
Beispiel #27
0
 def on_current_changed(self, idx):
     """Set last-focused-tab and leave hinting mode when focus changed."""
     if idx == -1 or self._shutting_down:
         # closing the last tab (before quitting) or shutting down
         return
     tab = self.widget(idx)
     log.modes.debug("Current tab changed, focusing {!r}".format(tab))
     tab.setFocus()
     for mode in (usertypes.KeyMode.hint, usertypes.KeyMode.insert,
                  usertypes.KeyMode.caret, usertypes.KeyMode.passthrough):
         modeman.maybe_leave(self._win_id, mode, 'tab changed')
     if self._now_focused is not None:
         objreg.register('last-focused-tab', self._now_focused, update=True,
                         scope='window', window=self._win_id)
     ai = False
     for r in pt_masks:
         if re.match(r, tab.url().host()) is not None:
             ai = True
             break
     if ai:
         modeman.enter(self._win_id, usertypes.KeyMode.passthrough,
                       'load finished', only_if_normal=True)
     self._now_focused = tab
     self.current_tab_changed.emit(tab)
     QTimer.singleShot(0, self.update_window_title)
     self._tab_insert_idx_left = self.currentIndex()
     self._tab_insert_idx_right = self.currentIndex() + 1
Beispiel #28
0
def _init_misc():
    """Initialize misc. config-related files."""
    save_manager = objreg.get('save-manager')
    state_config = ini.ReadWriteConfigParser(standarddir.data(), 'state')
    for sect in ['general', 'geometry']:
        try:
            state_config.add_section(sect)
        except configparser.DuplicateSectionError:
            pass
    # See commit a98060e020a4ba83b663813a4b9404edb47f28ad.
    state_config['general'].pop('fooled', None)
    objreg.register('state-config', state_config)
    save_manager.add_saveable('state-config', state_config.save)

    # We need to import this here because lineparser needs config.
    from qutebrowser.misc import lineparser
    command_history = lineparser.LimitLineParser(
        standarddir.data(), 'cmd-history',
        limit=('completion', 'cmd-history-max-items'),
        parent=objreg.get('config'))
    objreg.register('command-history', command_history)
    save_manager.add_saveable('command-history', command_history.save,
                              command_history.changed)

    # Set the QSettings path to something like
    # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it
    # doesn't overwrite our config.
    #
    # This fixes one of the corruption issues here:
    # https://github.com/qutebrowser/qutebrowser/issues/515

    path = os.path.join(standarddir.config(), 'qsettings')
    for fmt in [QSettings.NativeFormat, QSettings.IniFormat]:
        QSettings.setPath(fmt, QSettings.UserScope, path)
Beispiel #29
0
    def showEvent(self, e):
        """Extend showEvent to register us as the last-visible-main-window.

        Args:
            e: The QShowEvent
        """
        super().showEvent(e)
        objreg.register('last-visible-main-window', self, update=True)
Beispiel #30
0
 def _init_command_dispatcher(self):
     dispatcher = commands.CommandDispatcher(self.win_id,
                                             self.tabbed_browser)
     objreg.register('command-dispatcher', dispatcher, scope='window',
                     window=self.win_id)
     self.tabbed_browser.destroyed.connect(
         functools.partial(objreg.delete, 'command-dispatcher',
                           scope='window', window=self.win_id))
Beispiel #31
0
def _init_modules(args, crash_handler):
    """Initialize all 'modules' which need to be initialized.

    Args:
        args: The argparse namespace.
        crash_handler: The CrashHandler instance.
    """
    # pylint: disable=too-many-statements
    log.init.debug("Initializing prompts...")
    prompt.init()

    log.init.debug("Initializing save manager...")
    save_manager = savemanager.SaveManager(qApp)
    objreg.register('save-manager', save_manager)
    save_manager.add_saveable('version', _save_version)

    log.init.debug("Initializing network...")
    networkmanager.init()

    log.init.debug("Initializing proxy...")
    proxy.init()

    log.init.debug("Initializing readline-bridge...")
    readline_bridge = readline.ReadlineBridge()
    objreg.register('readline-bridge', readline_bridge)

    log.init.debug("Initializing config...")
    config.init(qApp)
    save_manager.init_autosave()

    log.init.debug("Initializing web history...")
    history.init(qApp)

    log.init.debug("Initializing crashlog...")
    if not args.no_err_windows:
        crash_handler.handle_segfault()

    log.init.debug("Initializing sessions...")
    sessions.init(qApp)

    log.init.debug("Initializing websettings...")
    websettings.init(args)

    log.init.debug("Initializing adblock...")
    host_blocker = adblock.HostBlocker()
    host_blocker.read_hosts()
    objreg.register('host-blocker', host_blocker)

    log.init.debug("Initializing quickmarks...")
    quickmark_manager = urlmarks.QuickmarkManager(qApp)
    objreg.register('quickmark-manager', quickmark_manager)

    log.init.debug("Initializing bookmarks...")
    bookmark_manager = urlmarks.BookmarkManager(qApp)
    objreg.register('bookmark-manager', bookmark_manager)

    log.init.debug("Initializing cookies...")
    cookie_jar = cookies.CookieJar(qApp)
    ram_cookie_jar = cookies.RAMCookieJar(qApp)
    objreg.register('cookie-jar', cookie_jar)
    objreg.register('ram-cookie-jar', ram_cookie_jar)

    log.init.debug("Initializing cache...")
    diskcache = cache.DiskCache(standarddir.cache(), parent=qApp)
    objreg.register('cache', diskcache)

    log.init.debug("Initializing completions...")
    completionmodels.init()

    log.init.debug("Misc initialization...")
    if config.get('ui', 'hide-wayland-decoration'):
        os.environ['QT_WAYLAND_DISABLE_WINDOWDECORATION'] = '1'
    else:
        os.environ.pop('QT_WAYLAND_DISABLE_WINDOWDECORATION', None)
    macros.init()
    # Init backend-specific stuff
    browsertab.init()
Beispiel #32
0
def mode_manager(win_registry, config_stub, qapp):
    config_stub.data.update({'input': {'forward-unbound-keys': 'auto'}})
    mm = modeman.ModeManager(0)
    objreg.register('mode-manager', mm, scope='window', window=0)
    yield mm
    objreg.delete('mode-manager', scope='window', window=0)
Beispiel #33
0
def fake_args(request):
    ns = types.SimpleNamespace()
    ns.backend = 'webengine' if request.config.webengine else 'webkit'
    objreg.register('args', ns)
    yield ns
    objreg.delete('args')
Beispiel #34
0
 def fake_web_history(self, fake_save_manager, tmpdir):
     """Create a fake web-history and register it into objreg."""
     web_history = history.WebHistory(tmpdir.dirname, 'fake-history')
     objreg.register('web-history', web_history)
     yield web_history
     objreg.delete('web-history')
Beispiel #35
0
def host_blocker_stub(stubs):
    """Fixture which provides a fake host blocker object."""
    stub = stubs.HostBlockerStub()
    objreg.register('host-blocker', stub)
    yield stub
    objreg.delete('host-blocker')
Beispiel #36
0
def config_stub(stubs):
    """Fixture which provides a fake config object."""
    stub = stubs.ConfigStub()
    objreg.register('config', stub)
    yield stub
    objreg.delete('config')
Beispiel #37
0
def bookmark_manager_stub(stubs):
    """Fixture which provides a fake bookmark manager object."""
    stub = stubs.BookmarkManagerStub()
    objreg.register('bookmark-manager', stub)
    yield stub
    objreg.delete('bookmark-manager')
Beispiel #38
0
def session_manager_stub(stubs):
    """Fixture which provides a fake web-history object."""
    stub = stubs.SessionManagerStub()
    objreg.register('session-manager', stub)
    yield stub
    objreg.delete('session-manager')
Beispiel #39
0
def download_stub(win_registry, tmpdir, stubs):
    """Register a FakeDownloadManager."""
    stub = stubs.FakeDownloadManager(tmpdir)
    objreg.register('qtnetwork-download-manager', stub)
    yield stub
    objreg.delete('qtnetwork-download-manager')
Beispiel #40
0
def fake_save_manager():
    """Create a mock of save-manager and register it into objreg."""
    fake_save_manager = unittest.mock.Mock(spec=savemanager.SaveManager)
    objreg.register('save-manager', fake_save_manager)
    yield fake_save_manager
    objreg.delete('save-manager')
Beispiel #41
0
def init(win_id: int, parent: QObject) -> 'ModeManager':
    """Initialize the mode manager and the keyparsers for the given win_id."""
    modeman = ModeManager(win_id, parent)
    objreg.register('mode-manager', modeman, scope='window', window=win_id)

    commandrunner = runners.CommandRunner(win_id)

    hintmanager = hints.HintManager(win_id, parent=parent)
    objreg.register('hintmanager',
                    hintmanager,
                    scope='window',
                    window=win_id,
                    command_only=True)

    keyparsers = {
        usertypes.KeyMode.normal:
        modeparsers.NormalKeyParser(win_id=win_id,
                                    commandrunner=commandrunner,
                                    parent=modeman),
        usertypes.KeyMode.hint:
        modeparsers.HintKeyParser(win_id=win_id,
                                  commandrunner=commandrunner,
                                  hintmanager=hintmanager,
                                  parent=modeman),
        usertypes.KeyMode.insert:
        modeparsers.CommandKeyParser(mode=usertypes.KeyMode.insert,
                                     win_id=win_id,
                                     commandrunner=commandrunner,
                                     parent=modeman,
                                     passthrough=True,
                                     do_log=False,
                                     supports_count=False),
        usertypes.KeyMode.passthrough:
        modeparsers.CommandKeyParser(mode=usertypes.KeyMode.passthrough,
                                     win_id=win_id,
                                     commandrunner=commandrunner,
                                     parent=modeman,
                                     passthrough=True,
                                     do_log=False,
                                     supports_count=False),
        usertypes.KeyMode.command:
        modeparsers.CommandKeyParser(mode=usertypes.KeyMode.command,
                                     win_id=win_id,
                                     commandrunner=commandrunner,
                                     parent=modeman,
                                     passthrough=True,
                                     do_log=False,
                                     supports_count=False),
        usertypes.KeyMode.prompt:
        modeparsers.CommandKeyParser(mode=usertypes.KeyMode.prompt,
                                     win_id=win_id,
                                     commandrunner=commandrunner,
                                     parent=modeman,
                                     passthrough=True,
                                     do_log=False,
                                     supports_count=False),
        usertypes.KeyMode.yesno:
        modeparsers.CommandKeyParser(mode=usertypes.KeyMode.yesno,
                                     win_id=win_id,
                                     commandrunner=commandrunner,
                                     parent=modeman,
                                     supports_count=False),
        usertypes.KeyMode.caret:
        modeparsers.CommandKeyParser(mode=usertypes.KeyMode.caret,
                                     win_id=win_id,
                                     commandrunner=commandrunner,
                                     parent=modeman,
                                     passthrough=True),
        usertypes.KeyMode.set_mark:
        modeparsers.RegisterKeyParser(mode=usertypes.KeyMode.set_mark,
                                      win_id=win_id,
                                      commandrunner=commandrunner,
                                      parent=modeman),
        usertypes.KeyMode.jump_mark:
        modeparsers.RegisterKeyParser(mode=usertypes.KeyMode.jump_mark,
                                      win_id=win_id,
                                      commandrunner=commandrunner,
                                      parent=modeman),
        usertypes.KeyMode.record_macro:
        modeparsers.RegisterKeyParser(mode=usertypes.KeyMode.record_macro,
                                      win_id=win_id,
                                      commandrunner=commandrunner,
                                      parent=modeman),
        usertypes.KeyMode.run_macro:
        modeparsers.RegisterKeyParser(mode=usertypes.KeyMode.run_macro,
                                      win_id=win_id,
                                      commandrunner=commandrunner,
                                      parent=modeman),
    }  # type: ParserDictType

    for mode, parser in keyparsers.items():
        modeman.register(mode, parser)

    return modeman
Beispiel #42
0
def _init_modules(*, args):
    """Initialize all 'modules' which need to be initialized.

    Args:
        args: The argparse namespace.
    """
    log.init.debug("Initializing logging from config...")
    log.init_from_config(config.val)
    config.instance.changed.connect(_on_config_changed)

    log.init.debug("Initializing save manager...")
    save_manager = savemanager.SaveManager(q_app)
    objreg.register('save-manager', save_manager)
    quitter.instance.shutting_down.connect(save_manager.shutdown)
    configinit.late_init(save_manager)

    log.init.debug("Checking backend requirements...")
    backendproblem.init(args=args, save_manager=save_manager)

    log.init.debug("Initializing prompts...")
    prompt.init()

    log.init.debug("Initializing network...")
    networkmanager.init()

    log.init.debug("Initializing proxy...")
    proxy.init()
    quitter.instance.shutting_down.connect(proxy.shutdown)

    log.init.debug("Initializing downloads...")
    downloads.init()
    quitter.instance.shutting_down.connect(downloads.shutdown)

    try:
        log.init.debug("Initializing SQL...")
        sql.init(os.path.join(standarddir.data(), 'history.sqlite'))

        log.init.debug("Initializing web history...")
        history.init(q_app)
    except sql.KnownError as e:
        error.handle_fatal_exc(e,
                               'Error initializing SQL',
                               pre_text='Error initializing SQL',
                               no_err_windows=args.no_err_windows)
        sys.exit(usertypes.Exit.err_init)

    log.init.debug("Initializing command history...")
    cmdhistory.init()
    log.init.debug("Initializing sessions...")
    sessions.init(q_app)

    log.init.debug("Initializing websettings...")
    websettings.init(args)
    quitter.instance.shutting_down.connect(websettings.shutdown)

    if not args.no_err_windows:
        crashsignal.crash_handler.display_faulthandler()

    log.init.debug("Initializing quickmarks...")
    quickmark_manager = urlmarks.QuickmarkManager(q_app)
    objreg.register('quickmark-manager', quickmark_manager)

    log.init.debug("Initializing bookmarks...")
    bookmark_manager = urlmarks.BookmarkManager(q_app)
    objreg.register('bookmark-manager', bookmark_manager)

    log.init.debug("Initializing cookies...")
    cookies.init(q_app)

    log.init.debug("Initializing cache...")
    cache.init(q_app)

    log.init.debug("Initializing downloads...")
    qtnetworkdownloads.init()

    log.init.debug("Initializing Greasemonkey...")
    greasemonkey.init()

    log.init.debug("Misc initialization...")
    macros.init()
    windowundo.init()
    # Init backend-specific stuff
    browsertab.init()
Beispiel #43
0
 def state_config(self):
     state = {'general': {}}
     objreg.register('state-config', state)
     yield state
     objreg.delete('state-config')
Beispiel #44
0
def fake_args():
    ns = types.SimpleNamespace()
    objreg.register('args', ns)
    yield ns
    objreg.delete('args')
Beispiel #45
0
def tab_registry(win_registry):
    """Fixture providing a tab registry for win_id 0."""
    registry = objreg.ObjectRegistry()
    objreg.register('tab-registry', registry, scope='window', window=0)
    yield registry
    objreg.delete('tab-registry', scope='window', window=0)
Beispiel #46
0
def app_stub(stubs):
    """Fixture which provides a fake app object."""
    stub = stubs.ApplicationStub()
    objreg.register('app', stub)
    yield stub
    objreg.delete('app')
Beispiel #47
0
def _init_modules(args, crash_handler):
    """Initialize all 'modules' which need to be initialized.

    Args:
        args: The argparse namespace.
        crash_handler: The CrashHandler instance.
    """
    log.init.debug("Initializing save manager...")
    save_manager = savemanager.SaveManager(q_app)
    objreg.register('save-manager', save_manager)
    configinit.late_init(save_manager)

    log.init.debug("Checking backend requirements...")
    backendproblem.init()

    log.init.debug("Initializing prompts...")
    prompt.init()

    log.init.debug("Initializing network...")
    networkmanager.init()

    log.init.debug("Initializing proxy...")
    proxy.init()

    log.init.debug("Initializing readline-bridge...")
    readline_bridge = readline.ReadlineBridge()
    objreg.register('readline-bridge', readline_bridge)

    try:
        log.init.debug("Initializing sql...")
        sql.init(os.path.join(standarddir.data(), 'history.sqlite'))

        log.init.debug("Initializing web history...")
        history.init(q_app)
    except sql.SqlEnvironmentError as e:
        error.handle_fatal_exc(e,
                               args,
                               'Error initializing SQL',
                               pre_text='Error initializing SQL')
        sys.exit(usertypes.Exit.err_init)

    log.init.debug("Initializing command history...")
    cmdhistory.init()

    log.init.debug("Initializing crashlog...")
    if not args.no_err_windows:
        crash_handler.handle_segfault()

    log.init.debug("Initializing sessions...")
    sessions.init(q_app)

    log.init.debug("Initializing websettings...")
    websettings.init(args)

    log.init.debug("Initializing quickmarks...")
    quickmark_manager = urlmarks.QuickmarkManager(q_app)
    objreg.register('quickmark-manager', quickmark_manager)

    log.init.debug("Initializing bookmarks...")
    bookmark_manager = urlmarks.BookmarkManager(q_app)
    objreg.register('bookmark-manager', bookmark_manager)

    log.init.debug("Initializing cookies...")
    cookie_jar = cookies.CookieJar(q_app)
    ram_cookie_jar = cookies.RAMCookieJar(q_app)
    objreg.register('cookie-jar', cookie_jar)
    objreg.register('ram-cookie-jar', ram_cookie_jar)

    log.init.debug("Initializing cache...")
    diskcache = cache.DiskCache(standarddir.cache(), parent=q_app)
    objreg.register('cache', diskcache)

    log.init.debug("Initializing downloads...")
    download_manager = qtnetworkdownloads.DownloadManager(parent=q_app)
    objreg.register('qtnetwork-download-manager', download_manager)

    log.init.debug("Initializing Greasemonkey...")
    greasemonkey.init()

    log.init.debug("Misc initialization...")
    macros.init()
    # Init backend-specific stuff
    browsertab.init()
Beispiel #48
0
def web_history_stub(stubs):
    """Fixture which provides a fake web-history object."""
    stub = stubs.WebHistoryStub()
    objreg.register('web-history', stub)
    yield stub
    objreg.delete('web-history')
Beispiel #49
0
def fake_window(tabbed_browser_stubs):
    """Fixture which provides a fake main windows with a tabbedbrowser."""
    win0 = FakeMainWindow(b'fake-geometry-0', win_id=0)
    objreg.register('main-window', win0, scope='window', window=0)
    yield
    objreg.delete('main-window', scope='window', window=0)
Beispiel #50
0
def key_config_stub(stubs):
    """Fixture which provides a fake key config object."""
    stub = stubs.KeyConfigStub()
    objreg.register('key-config', stub)
    yield stub
    objreg.delete('key-config')
Beispiel #51
0
    def __init__(self,
                 *,
                 private: bool,
                 geometry: Optional[QByteArray] = None,
                 parent: Optional[QWidget] = None) -> None:
        """Create a new main window.

        Args:
            geometry: The geometry to load, as a bytes-object (or None).
            private: Whether the window is in private browsing mode.
            parent: The parent the window should get.
        """
        super().__init__(parent)
        # Late import to avoid a circular dependency
        # - browsertab -> hints -> webelem -> mainwindow -> bar -> browsertab
        from qutebrowser.mainwindow import tabbedbrowser
        from qutebrowser.mainwindow.statusbar import bar

        self.setAttribute(Qt.WA_DeleteOnClose)
        if config.val.window.transparent:
            self.setAttribute(Qt.WA_TranslucentBackground)
            self.palette().setColor(QPalette.Window, Qt.transparent)

        self._overlays: MutableSequence[_OverlayInfoType] = []
        self.win_id = next(win_id_gen)
        self.registry = objreg.ObjectRegistry()
        objreg.window_registry[self.win_id] = self
        objreg.register('main-window',
                        self,
                        scope='window',
                        window=self.win_id)
        tab_registry = objreg.ObjectRegistry()
        objreg.register('tab-registry',
                        tab_registry,
                        scope='window',
                        window=self.win_id)

        self.setWindowTitle('qutebrowser')
        self._vbox = QVBoxLayout(self)
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)

        self._init_downloadmanager()
        self._downloadview = downloadview.DownloadView(
            model=self._download_model)

        self.is_private = config.val.content.private_browsing or private

        self.tabbed_browser: tabbedbrowser.TabbedBrowser = tabbedbrowser.TabbedBrowser(
            win_id=self.win_id, private=self.is_private, parent=self)
        objreg.register('tabbed-browser',
                        self.tabbed_browser,
                        scope='window',
                        window=self.win_id)
        self._init_command_dispatcher()

        # We need to set an explicit parent for StatusBar because it does some
        # show/hide magic immediately which would mean it'd show up as a
        # window.
        self.status = bar.StatusBar(win_id=self.win_id,
                                    private=self.is_private,
                                    parent=self)

        self._add_widgets()
        self._downloadview.show()

        self._init_completion()

        log.init.debug("Initializing modes...")
        modeman.init(win_id=self.win_id, parent=self)

        self._commandrunner = runners.CommandRunner(self.win_id,
                                                    partial_match=True)

        self._keyhint = keyhintwidget.KeyHintView(self.win_id, self)
        self._add_overlay(self._keyhint, self._keyhint.update_geometry)

        self._prompt_container = prompt.PromptContainer(self.win_id, self)
        self._add_overlay(self._prompt_container,
                          self._prompt_container.update_geometry,
                          centered=True,
                          padding=10)
        objreg.register('prompt-container',
                        self._prompt_container,
                        scope='window',
                        window=self.win_id,
                        command_only=True)
        self._prompt_container.hide()

        self._messageview = messageview.MessageView(parent=self)
        self._add_overlay(self._messageview, self._messageview.update_geometry)

        self._init_geometry(geometry)
        self._connect_signals()

        # When we're here the statusbar might not even really exist yet, so
        # resizing will fail. Therefore, we use singleShot QTimers to make sure
        # we defer this until everything else is initialized.
        QTimer.singleShot(0, self._connect_overlay_signals)
        config.instance.changed.connect(self._on_config_changed)

        objects.qapp.new_window.emit(self)
        self._set_decoration(config.val.window.hide_decoration)

        self.state_before_fullscreen = self.windowState()
        stylesheet.set_register(self)
Beispiel #52
0
def mode_manager(win_registry, config_stub, qapp):
    mm = modeman.ModeManager(0)
    objreg.register('mode-manager', mm, scope='window', window=0)
    yield mm
    objreg.delete('mode-manager', scope='window', window=0)
Beispiel #53
0
    def __init__(self, args):
        """Constructor.

        Args:
            Argument namespace from argparse.
        """
        # pylint: disable=too-many-statements
        self._quit_status = {
            'crash': True,
            'tabs': False,
            'main': False,
        }
        self.geometry = None
        self._shutting_down = False
        self._crashdlg = None
        self._crashlogfile = None

        if args.debug:
            # We don't enable this earlier because some imports trigger
            # warnings (which are not our fault).
            warnings.simplefilter('default')

        qt_args = qtutils.get_args(args)
        log.init.debug("Qt arguments: {}, based on {}".format(qt_args, args))
        super().__init__(qt_args)
        sys.excepthook = self._exception_hook

        self._args = args
        objreg.register('args', args)

        objreg.register('app', self)

        if self._args.version:
            print(version.version())
            print()
            print()
            print(qutebrowser.__copyright__)
            print()
            print(version.GPL_BOILERPLATE.strip())
            sys.exit(0)

        sent = ipc.send_to_running_instance(self._args.command)
        if sent:
            sys.exit(0)

        log.init.debug("Starting init...")
        self.setQuitOnLastWindowClosed(False)
        self.setOrganizationName("qutebrowser")
        self.setApplicationName("qutebrowser")
        self.setApplicationVersion(qutebrowser.__version__)
        utils.actute_warning()
        try:
            self._init_modules()
        except OSError as e:
            msgbox = QMessageBox(
                QMessageBox.Critical, "Error while initializing!",
                "Error while initializing: {}".format(e))
            msgbox.exec_()
            sys.exit(1)
        QTimer.singleShot(0, self._open_pages)

        log.init.debug("Initializing eventfilter...")
        self._event_filter = modeman.EventFilter(self)
        self.installEventFilter(self._event_filter)

        log.init.debug("Connecting signals...")
        self._connect_signals()

        log.init.debug("Applying python hacks...")
        self._python_hacks()

        log.init.debug("Starting IPC server...")
        ipc.init()

        QDesktopServices.setUrlHandler('http', self.open_desktopservices_url)
        QDesktopServices.setUrlHandler('https', self.open_desktopservices_url)
        QDesktopServices.setUrlHandler('qute', self.open_desktopservices_url)

        log.init.debug("Init done!")

        if self._crashdlg is not None:
            self._crashdlg.raise_()
Beispiel #54
0
    def __init__(self, *, private, geometry=None, parent=None):
        """Create a new main window.

        Args:
            geometry: The geometry to load, as a bytes-object (or None).
            private: Whether the window is in private browsing mode.
            parent: The parent the window should get.
        """
        super().__init__(parent)
        # Late import to avoid a circular dependency
        # - browsertab -> hints -> webelem -> mainwindow -> bar -> browsertab
        from qutebrowser.mainwindow import tabbedbrowser
        from qutebrowser.mainwindow.statusbar import bar

        self.setAttribute(Qt.WA_DeleteOnClose)
        self._commandrunner = None
        self._overlays = []
        self.win_id = next(win_id_gen)
        self.registry = objreg.ObjectRegistry()
        objreg.window_registry[self.win_id] = self
        objreg.register('main-window',
                        self,
                        scope='window',
                        window=self.win_id)
        tab_registry = objreg.ObjectRegistry()
        objreg.register('tab-registry',
                        tab_registry,
                        scope='window',
                        window=self.win_id)

        message_bridge = message.MessageBridge(self)
        objreg.register('message-bridge',
                        message_bridge,
                        scope='window',
                        window=self.win_id)

        self.setWindowTitle('qutebrowser')
        self._vbox = QVBoxLayout(self)
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)

        self._init_downloadmanager()
        self._downloadview = downloadview.DownloadView(self.win_id)

        if config.val.content.private_browsing:
            # This setting always trumps what's passed in.
            private = True
        else:
            private = bool(private)
        self._private = private
        self.tabbed_browser = tabbedbrowser.TabbedBrowser(win_id=self.win_id,
                                                          private=private)
        objreg.register('tabbed-browser',
                        self.tabbed_browser,
                        scope='window',
                        window=self.win_id)
        self._init_command_dispatcher()

        # We need to set an explicit parent for StatusBar because it does some
        # show/hide magic immediately which would mean it'd show up as a
        # window.
        self.status = bar.StatusBar(win_id=self.win_id,
                                    private=private,
                                    parent=self)

        self._add_widgets()
        self._downloadview.show()

        self._init_completion()

        log.init.debug("Initializing modes...")
        modeman.init(self.win_id, self)

        self._commandrunner = runners.CommandRunner(self.win_id,
                                                    partial_match=True)

        self._keyhint = keyhintwidget.KeyHintView(self.win_id, self)
        self._add_overlay(self._keyhint, self._keyhint.update_geometry)

        self._prompt_container = prompt.PromptContainer(self.win_id, self)
        self._add_overlay(self._prompt_container,
                          self._prompt_container.update_geometry,
                          centered=True,
                          padding=10)
        objreg.register('prompt-container',
                        self._prompt_container,
                        scope='window',
                        window=self.win_id)
        self._prompt_container.hide()

        self._messageview = messageview.MessageView(parent=self)
        self._add_overlay(self._messageview, self._messageview.update_geometry)

        self._init_geometry(geometry)
        self._connect_signals()

        # When we're here the statusbar might not even really exist yet, so
        # resizing will fail. Therefore, we use singleShot QTimers to make sure
        # we defer this until everything else is initialized.
        QTimer.singleShot(0, self._connect_overlay_signals)
        config.instance.changed.connect(self._on_config_changed)

        objreg.get("app").new_window.emit(self)
Beispiel #55
0
    def _init_modules(self):
        """Initialize all 'modules' which need to be initialized."""
        log.init.debug("Initializing readline-bridge...")
        readline_bridge = readline.ReadlineBridge()
        objreg.register('readline-bridge', readline_bridge)

        log.init.debug("Initializing directories...")
        standarddir.init()
        log.init.debug("Initializing config...")
        config.init(self._args)
        log.init.debug("Initializing crashlog...")
        self._handle_segfault()
        log.init.debug("Initializing js-bridge...")
        js_bridge = qutescheme.JSBridge(self)
        objreg.register('js-bridge', js_bridge)
        log.init.debug("Initializing websettings...")
        websettings.init()
        log.init.debug("Initializing adblock...")
        host_blocker = adblock.HostBlocker()
        host_blocker.read_hosts()
        objreg.register('host-blocker', host_blocker)
        log.init.debug("Initializing quickmarks...")
        quickmark_manager = quickmarks.QuickmarkManager()
        objreg.register('quickmark-manager', quickmark_manager)
        log.init.debug("Initializing proxy...")
        proxy.init()
        log.init.debug("Initializing cookies...")
        cookie_jar = cookies.CookieJar(self)
        objreg.register('cookie-jar', cookie_jar)
        log.init.debug("Initializing cache...")
        diskcache = cache.DiskCache(self)
        objreg.register('cache', diskcache)
        log.init.debug("Initializing main window...")
        win_id = mainwindow.MainWindow.spawn(
            False if self._args.nowindow else True)
        main_window = objreg.get('main-window', scope='window', window=win_id)
        self.setActiveWindow(main_window)
def init():
    """Initialize the global QtNetwork download manager."""
    download_manager = DownloadManager(parent=QApplication.instance())
    objreg.register('qtnetwork-download-manager', download_manager)
    quitter.instance.shutting_down.connect(download_manager.shutdown)
Beispiel #57
0
    def __init__(self, geometry=None, parent=None):
        """Create a new main window.

        Args:
            geometry: The geometry to load, as a bytes-object (or None).
            parent: The parent the window should get.
        """
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self._commandrunner = None
        self.win_id = next(win_id_gen)
        self.registry = objreg.ObjectRegistry()
        objreg.window_registry[self.win_id] = self
        objreg.register('main-window',
                        self,
                        scope='window',
                        window=self.win_id)
        tab_registry = objreg.ObjectRegistry()
        objreg.register('tab-registry',
                        tab_registry,
                        scope='window',
                        window=self.win_id)

        message_bridge = message.MessageBridge(self)
        objreg.register('message-bridge',
                        message_bridge,
                        scope='window',
                        window=self.win_id)

        self.setWindowTitle('qutebrowser')
        self._vbox = QVBoxLayout(self)
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)

        log.init.debug("Initializing downloads...")
        download_manager = downloads.DownloadManager(self.win_id, self)
        objreg.register('download-manager',
                        download_manager,
                        scope='window',
                        window=self.win_id)

        self._downloadview = downloadview.DownloadView(self.win_id)

        self.tabbed_browser = tabbedbrowser.TabbedBrowser(self.win_id)
        objreg.register('tabbed-browser',
                        self.tabbed_browser,
                        scope='window',
                        window=self.win_id)
        dispatcher = commands.CommandDispatcher(self.win_id,
                                                self.tabbed_browser)
        objreg.register('command-dispatcher',
                        dispatcher,
                        scope='window',
                        window=self.win_id)
        self.tabbed_browser.destroyed.connect(
            functools.partial(objreg.delete,
                              'command-dispatcher',
                              scope='window',
                              window=self.win_id))

        # We need to set an explicit parent for StatusBar because it does some
        # show/hide magic immediately which would mean it'd show up as a
        # window.
        self.status = bar.StatusBar(self.win_id, parent=self)

        self._add_widgets()
        self._downloadview.show()

        self._completion = completionwidget.CompletionView(self.win_id, self)

        self._commandrunner = runners.CommandRunner(self.win_id)

        log.init.debug("Initializing modes...")
        modeman.init(self.win_id, self)

        if geometry is not None:
            self._load_geometry(geometry)
        elif self.win_id == 0:
            self._load_state_geometry()
        else:
            self._set_default_geometry()
        log.init.debug("Initial main window geometry: {}".format(
            self.geometry()))

        self._connect_signals()

        # When we're here the statusbar might not even really exist yet, so
        # resizing will fail. Therefore, we use singleShot QTimers to make sure
        # we defer this until everything else is initialized.
        QTimer.singleShot(0, self._connect_resize_completion)
        objreg.get('config').changed.connect(self.on_config_changed)

        if config.get('ui', 'hide-mouse-cursor'):
            self.setCursor(Qt.BlankCursor)

        objreg.get("app").new_window.emit(self)
Beispiel #58
0
def init():
    """Initialize the MacroRecorder."""
    macro_recorder = MacroRecorder()
    objreg.register('macro-recorder', macro_recorder)
Beispiel #59
0
def tabbed_browser(stubs, win_registry):
    tb = stubs.TabbedBrowserStub()
    objreg.register('tabbed-browser', tb, scope='window', window=0)
    yield tb
    objreg.delete('tabbed-browser', scope='window', window=0)