qutebrowser/qutebrowser/mainwindow/mainwindow.py

366 lines
14 KiB
Python
Raw Normal View History

2014-06-19 09:04:37 +02:00
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
2015-01-03 15:51:31 +01:00
# Copyright 2014-2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
2014-02-06 14:01:23 +01:00
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
2014-06-04 14:52:12 +02:00
"""The main window of qutebrowser."""
2014-02-17 12:23:52 +01:00
import binascii
2014-08-26 19:10:14 +02:00
import base64
2014-09-28 22:13:14 +02:00
import itertools
2014-09-28 22:13:14 +02:00
from PyQt5.QtCore import pyqtSlot, QRect, QPoint, QTimer, Qt
from PyQt5.QtWidgets import QWidget, QVBoxLayout
2014-01-21 17:54:21 +01:00
2014-09-28 22:13:14 +02:00
from qutebrowser.commands import runners, cmdutils
2014-08-26 19:10:14 +02:00
from qutebrowser.config import config
2014-09-26 15:48:24 +02:00
from qutebrowser.utils import message, log, usertypes, qtutils, objreg, utils
from qutebrowser.mainwindow import tabbedbrowser
from qutebrowser.mainwindow.statusbar import bar
from qutebrowser.completion import completionwidget
2014-09-28 22:13:14 +02:00
from qutebrowser.keyinput import modeman
from qutebrowser.browser import hints, downloads, downloadview
2014-09-28 22:13:14 +02:00
win_id_gen = itertools.count(0)
2014-01-28 23:04:02 +01:00
2014-02-18 14:21:39 +01:00
2014-02-12 20:51:50 +01:00
class MainWindow(QWidget):
2014-02-07 20:21:50 +01:00
2014-06-04 14:52:12 +02:00
"""The main window of qutebrowser.
2014-01-29 15:30:19 +01:00
Adds all needed components to a vbox, initializes subwidgets and connects
signals.
2014-02-07 20:21:50 +01:00
2014-02-18 16:38:13 +01:00
Attributes:
status: The StatusBar widget.
_downloadview: The DownloadView widget.
2014-09-23 23:05:55 +02:00
_tabbed_browser: The TabbedBrowser widget.
2014-02-18 16:38:13 +01:00
_vbox: The main QVBoxLayout.
2014-09-28 22:13:14 +02:00
_commandrunner: The main CommandRunner instance.
2014-02-18 16:38:13 +01:00
"""
2014-09-28 22:13:14 +02:00
def __init__(self, win_id, parent=None):
2014-06-17 07:17:21 +02:00
super().__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
2014-09-28 22:13:14 +02:00
self._commandrunner = None
self.win_id = win_id
self.registry = objreg.ObjectRegistry()
objreg.window_registry[win_id] = self
2014-09-28 22:13:14 +02:00
objreg.register('main-window', self, scope='window', window=win_id)
tab_registry = objreg.ObjectRegistry()
objreg.register('tab-registry', tab_registry, scope='window',
window=win_id)
2014-09-28 22:13:14 +02:00
message_bridge = message.MessageBridge(self)
objreg.register('message-bridge', message_bridge, scope='window',
window=win_id)
2014-01-21 09:05:31 +01:00
self.setWindowTitle('qutebrowser')
2014-09-28 22:13:14 +02:00
if win_id == 0:
self._load_geometry()
2014-02-18 11:57:35 +01:00
else:
2014-09-28 22:13:14 +02:00
self._set_default_geometry()
log.init.debug("Initial mainwindow geometry: {}".format(
self.geometry()))
2014-02-18 16:38:13 +01:00
self._vbox = QVBoxLayout(self)
self._vbox.setContentsMargins(0, 0, 0, 0)
self._vbox.setSpacing(0)
log.init.debug("Initializing downloads...")
download_manager = downloads.DownloadManager(win_id, self)
objreg.register('download-manager', download_manager, scope='window',
window=win_id)
self._downloadview = downloadview.DownloadView(win_id)
self._vbox.addWidget(self._downloadview)
self._downloadview.show()
2014-06-12 08:02:44 +02:00
2014-09-28 22:13:14 +02:00
self._tabbed_browser = tabbedbrowser.TabbedBrowser(win_id)
objreg.register('tabbed-browser', self._tabbed_browser, scope='window',
window=win_id)
2014-09-23 23:05:55 +02:00
self._vbox.addWidget(self._tabbed_browser)
2014-06-12 10:19:45 +02:00
2014-09-28 22:13:14 +02:00
self.status = bar.StatusBar(win_id)
2014-02-18 16:38:13 +01:00
self._vbox.addWidget(self.status)
2014-09-28 22:13:14 +02:00
self._completion = completionwidget.CompletionView(win_id, self)
2014-09-28 22:13:14 +02:00
self._commandrunner = runners.CommandRunner(win_id)
log.init.debug("Initializing search...")
search_runner = runners.SearchRunner(self)
objreg.register('search-runner', search_runner, scope='window',
window=win_id)
log.init.debug("Initializing modes...")
2014-10-07 23:10:58 +02:00
modeman.init(self.win_id, self)
2014-09-28 22:13:14 +02:00
self._connect_signals()
2014-06-23 06:23:33 +02:00
# 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.
2014-09-23 23:17:36 +02:00
QTimer.singleShot(0, self._connect_resize_completion)
objreg.get('config').changed.connect(self.on_config_changed)
#self.retranslateUi(MainWindow)
#self.tabWidget.setCurrentIndex(0)
#QtCore.QMetaObject.connectSlotsByName(MainWindow)
def __repr__(self):
2014-09-26 15:48:24 +02:00
return utils.get_repr(self)
@pyqtSlot(str, str)
def on_config_changed(self, section, option):
"""Resize the completion if related config options changed."""
if section == 'completion' and option in ('height', 'shrink'):
self.resize_completion()
2014-10-06 21:24:07 +02:00
@classmethod
def spawn(cls, show=True):
"""Create a new main window.
Args:
show: Show the window after creating.
Return:
The new window id.
"""
win_id = next(win_id_gen)
win = MainWindow(win_id)
if show:
win.show()
return win_id
2014-09-28 22:13:14 +02:00
def _load_geometry(self):
"""Load the geometry from the state file."""
state_config = objreg.get('state-config')
try:
data = state_config['geometry']['mainwindow']
log.init.debug("Restoring mainwindow from {}".format(data))
geom = base64.b64decode(data, validate=True)
except KeyError:
# First start
self._set_default_geometry()
except binascii.Error:
log.init.exception("Error while reading geometry")
self._set_default_geometry()
else:
try:
ok = self.restoreGeometry(geom)
except KeyError:
log.init.exception("Error while restoring geometry.")
self._set_default_geometry()
if not ok:
log.init.warning("Error while restoring geometry.")
self._set_default_geometry()
2014-09-23 23:17:36 +02:00
def _connect_resize_completion(self):
"""Connect the resize_completion signal and resize it once."""
self._completion.resize_completion.connect(self.resize_completion)
self.resize_completion()
2014-04-17 17:44:27 +02:00
def _set_default_geometry(self):
"""Set some sensible default geometry."""
self.setGeometry(QRect(50, 50, 800, 600))
2014-09-28 22:13:14 +02:00
def _get_object(self, name):
"""Get an object for this window in the object registry."""
return objreg.get(name, scope='window', window=self.win_id)
def _connect_signals(self):
"""Connect all mainwindow signals."""
2014-09-28 22:23:37 +02:00
# pylint: disable=too-many-locals,too-many-statements
2014-09-28 22:13:14 +02:00
key_config = objreg.get('key-config')
status = self._get_object('statusbar')
keyparsers = self._get_object('keyparsers')
2014-09-28 22:23:37 +02:00
completion_obj = self._get_object('completion')
2014-09-28 22:13:14 +02:00
tabs = self._get_object('tabbed-browser')
cmd = self._get_object('status-command')
completer = self._get_object('completer')
search_runner = self._get_object('search-runner')
message_bridge = self._get_object('message-bridge')
mode_manager = self._get_object('mode-manager')
prompter = self._get_object('prompter')
# misc
self._tabbed_browser.close_window.connect(self.close)
2014-09-28 22:13:14 +02:00
mode_manager.entered.connect(hints.on_mode_entered)
# status bar
mode_manager.entered.connect(status.on_mode_entered)
mode_manager.left.connect(status.on_mode_left)
mode_manager.left.connect(cmd.on_mode_left)
mode_manager.left.connect(prompter.on_mode_left)
# commands
keyparsers[usertypes.KeyMode.normal].keystring_updated.connect(
status.keystring.setText)
cmd.got_cmd.connect(self._commandrunner.run_safely)
cmd.got_search.connect(search_runner.search)
cmd.got_search_rev.connect(search_runner.search_rev)
cmd.returnPressed.connect(tabs.on_cmd_return_pressed)
2014-09-28 22:13:14 +02:00
search_runner.do_search.connect(tabs.search)
tabs.got_cmd.connect(self._commandrunner.run_safely)
# config
for obj in keyparsers.values():
key_config.changed.connect(obj.on_keyconfig_changed)
# messages
message_bridge.s_error.connect(status.disp_error)
message_bridge.s_warning.connect(status.disp_warning)
2014-09-28 22:13:14 +02:00
message_bridge.s_info.connect(status.disp_temp_text)
message_bridge.s_set_text.connect(status.set_text)
message_bridge.s_maybe_reset_text.connect(status.txt.maybe_reset_text)
message_bridge.s_set_cmd_text.connect(cmd.set_cmd_text)
message_bridge.s_question.connect(prompter.ask_question,
Qt.DirectConnection)
# statusbar
# FIXME some of these probably only should be triggered on mainframe
# loadStarted.
# https://github.com/The-Compiler/qutebrowser/issues/112
2014-09-28 22:13:14 +02:00
tabs.current_tab_changed.connect(status.prog.on_tab_changed)
tabs.cur_progress.connect(status.prog.setValue)
tabs.cur_load_finished.connect(status.prog.hide)
tabs.cur_load_started.connect(status.prog.on_load_started)
tabs.current_tab_changed.connect(status.percentage.on_tab_changed)
tabs.cur_scroll_perc_changed.connect(status.percentage.set_perc)
tabs.current_tab_changed.connect(status.txt.on_tab_changed)
tabs.cur_statusbar_message.connect(status.txt.on_statusbar_message)
tabs.cur_load_started.connect(status.txt.on_load_started)
tabs.current_tab_changed.connect(status.url.on_tab_changed)
tabs.cur_url_text_changed.connect(status.url.set_url)
tabs.cur_link_hovered.connect(status.url.set_hover_url)
tabs.cur_load_status_changed.connect(status.url.on_load_status_changed)
# command input / completion
mode_manager.left.connect(tabs.on_mode_left)
cmd.clear_completion_selection.connect(
2014-09-28 22:23:37 +02:00
completion_obj.on_clear_completion_selection)
cmd.hide_completion.connect(completion_obj.hide)
2014-09-28 22:13:14 +02:00
2014-10-18 22:00:28 +02:00
# quickmark completion
quickmark_manager = objreg.get('quickmark-manager')
quickmark_manager.changed.connect(completer.init_quickmark_completions)
@pyqtSlot()
def resize_completion(self):
"""Adjust completion according to config."""
if not self._completion.isVisible():
# It doesn't make sense to resize the completion as long as it's
# not shown anyways.
return
# Get the configured height/percentage.
2014-04-27 21:21:14 +02:00
confheight = str(config.get('completion', 'height'))
2014-02-26 21:18:53 +01:00
if confheight.endswith('%'):
perc = int(confheight.rstrip('%'))
height = self.height() * perc / 100
else:
height = int(confheight)
# Shrink to content size if needed and shrinking is enabled
if config.get('completion', 'shrink'):
contents_height = (
2014-09-23 21:49:22 +02:00
self._completion.viewportSizeHint().height() +
self._completion.horizontalScrollBar().sizeHint().height())
if contents_height <= height:
height = contents_height
2014-06-22 23:52:50 +02:00
else:
contents_height = -1
2014-02-26 21:18:53 +01:00
# hpoint now would be the bottom-left edge of the widget if it was on
# the top of the main window.
topleft_y = self.height() - self.status.height() - height
2014-08-26 19:10:14 +02:00
topleft_y = qtutils.check_overflow(topleft_y, 'int', fatal=False)
topleft = QPoint(0, topleft_y)
2014-02-26 21:18:53 +01:00
bottomright = self.status.geometry().topRight()
2014-06-21 16:42:58 +02:00
rect = QRect(topleft, bottomright)
2015-01-28 22:15:57 +01:00
log.misc.debug('completion rect: {}'.format(rect))
if rect.isValid():
2014-09-23 21:49:22 +02:00
self._completion.setGeometry(rect)
2014-09-28 22:13:14 +02:00
@cmdutils.register(instance='main-window', scope='window')
@pyqtSlot()
def close(self):
2014-09-28 22:13:14 +02:00
"""Close the current window.
//
Extend close() so we can register it as a command.
"""
super().close()
2014-12-22 22:56:52 +01:00
@cmdutils.register(instance='main-window', scope='window')
def fullscreen(self):
"""Toggle fullscreen mode."""
if self.isFullScreen():
self.showNormal()
else:
self.showFullScreen()
def resizeEvent(self, e):
"""Extend resizewindow's resizeEvent to adjust completion.
Args:
e: The QResizeEvent
"""
super().resizeEvent(e)
self.resize_completion()
self._downloadview.updateGeometry()
2014-09-23 23:05:55 +02:00
self._tabbed_browser.tabBar().refresh()
def closeEvent(self, e):
"""Override closeEvent to display a confirmation if needed."""
confirm_quit = config.get('ui', 'confirm-quit')
2015-01-02 05:32:39 +01:00
tab_count = self._tabbed_browser.count()
download_manager = objreg.get('download-manager', scope='window',
window=self.win_id)
download_count = download_manager.rowCount()
2015-01-05 08:01:22 +01:00
quit_texts = []
2015-01-06 11:03:21 +01:00
# Close if set to never ask for confirmation
if 'never' in confirm_quit:
2014-10-05 23:09:04 +02:00
pass
2015-01-02 05:32:39 +01:00
# Ask if multiple-tabs are open
if 'multiple-tabs' in confirm_quit and tab_count > 1:
2015-01-05 08:01:22 +01:00
quit_texts.append("{} {} open.".format(
tab_count, "tab is" if tab_count == 1 else "tabs are"))
2015-01-02 05:32:39 +01:00
# Ask if multiple downloads running
if 'downloads' in confirm_quit and download_count > 0:
2015-01-05 08:01:22 +01:00
quit_texts.append("{} {} running.".format(
tab_count,
"download is" if tab_count == 1 else "downloads are"))
2015-01-02 05:32:39 +01:00
# Process all quit messages that user must confirm
2015-01-05 08:01:22 +01:00
if quit_texts or 'always' in confirm_quit:
text = '\n'.join(['Really quit?'] + quit_texts)
confirmed = message.ask(self.win_id, text,
usertypes.PromptMode.yesno,
default=True)
# Stop asking if the user cancels
if not confirmed:
2015-01-06 11:03:21 +01:00
log.destroy.debug("Cancelling closing of window {}".format(
2015-01-05 08:01:22 +01:00
self.win_id))
e.ignore()
return
2014-10-05 23:09:04 +02:00
e.accept()
objreg.get('app').geometry = bytes(self.saveGeometry())
2014-10-07 21:36:25 +02:00
log.destroy.debug("Closing window {}".format(self.win_id))
self._tabbed_browser.shutdown()