Reorganize input modules into keyinput subpackage

This commit is contained in:
Florian Bruhin 2014-04-24 21:03:45 +02:00
parent ecdd887664
commit c674d96cfe
8 changed files with 102 additions and 81 deletions

View File

@ -52,11 +52,11 @@ import qutebrowser.commands.utils as cmdutils
import qutebrowser.config.style as style import qutebrowser.config.style as style
import qutebrowser.config.config as config import qutebrowser.config.config as config
import qutebrowser.network.qutescheme as qutescheme import qutebrowser.network.qutescheme as qutescheme
import qutebrowser.keyinput.modes as modes
import qutebrowser.utils.message as message import qutebrowser.utils.message as message
import qutebrowser.utils.modemanager as modemanager
from qutebrowser.widgets.mainwindow import MainWindow from qutebrowser.widgets.mainwindow import MainWindow
from qutebrowser.widgets.crash import CrashDialog from qutebrowser.widgets.crash import CrashDialog
from qutebrowser.commands.keys import CommandKeyParser from qutebrowser.keyinput.commandmode import CommandKeyParser
from qutebrowser.commands.parsers import CommandParser, SearchParser from qutebrowser.commands.parsers import CommandParser, SearchParser
from qutebrowser.browser.hints import HintKeyParser from qutebrowser.browser.hints import HintKeyParser
from qutebrowser.utils.appdirs import AppDirs from qutebrowser.utils.appdirs import AppDirs
@ -129,17 +129,16 @@ class QuteBrowser(QApplication):
} }
self._init_cmds() self._init_cmds()
self.mainwindow = MainWindow() self.mainwindow = MainWindow()
modemanager.init(self) modes.init(self)
modemanager.manager.register("normal", modes.manager.register("normal", self._keyparsers["normal"].handle)
self._keyparsers["normal"].handle) modes.manager.register("hint", self._keyparsers["hint"].handle)
modemanager.manager.register("hint", self._keyparsers["hint"].handle) modes.manager.register("insert", None, passthrough=True)
modemanager.manager.register("insert", None, passthrough=True) modes.manager.register("command", None, passthrough=True)
modemanager.manager.register("command", None, passthrough=True) self.installEventFilter(modes.manager)
self.installEventFilter(modemanager.manager)
self.setQuitOnLastWindowClosed(False) self.setQuitOnLastWindowClosed(False)
self._connect_signals() self._connect_signals()
modemanager.enter("normal") modes.enter("normal")
self.mainwindow.show() self.mainwindow.show()
self._python_hacks() self._python_hacks()
@ -255,10 +254,10 @@ class QuteBrowser(QApplication):
tabs.currentChanged.connect(self.mainwindow.update_inspector) tabs.currentChanged.connect(self.mainwindow.update_inspector)
# status bar # status bar
modemanager.manager.entered.connect(status.on_mode_entered) modes.manager.entered.connect(status.on_mode_entered)
modemanager.manager.left.connect(status.on_mode_left) modes.manager.left.connect(status.on_mode_left)
# FIXME what to do here? # FIXME what to do here?
modemanager.manager.key_pressed.connect(status.on_key_pressed) modes.manager.key_pressed.connect(status.on_key_pressed)
for obj in [kp["normal"], tabs]: for obj in [kp["normal"], tabs]:
obj.set_cmd_text.connect(cmd.set_cmd_text) obj.set_cmd_text.connect(cmd.set_cmd_text)
@ -284,7 +283,7 @@ class QuteBrowser(QApplication):
# config # config
self.config.style_changed.connect(style.invalidate_caches) self.config.style_changed.connect(style.invalidate_caches)
for obj in [tabs, completion, self.mainwindow, config.cmd_history, for obj in [tabs, completion, self.mainwindow, config.cmd_history,
websettings, kp["normal"], modemanager.manager]: websettings, kp["normal"], modes.manager]:
self.config.changed.connect(obj.on_config_changed) self.config.changed.connect(obj.on_config_changed)
# statusbar # statusbar

View File

@ -26,64 +26,16 @@ from PyQt5.QtGui import QMouseEvent, QClipboard
from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QApplication
import qutebrowser.config.config as config import qutebrowser.config.config as config
import qutebrowser.keyinput.modes as modes
import qutebrowser.utils.message as message import qutebrowser.utils.message as message
import qutebrowser.utils.url as urlutils import qutebrowser.utils.url as urlutils
import qutebrowser.utils.modemanager as modemanager
import qutebrowser.utils.webelem as webelem import qutebrowser.utils.webelem as webelem
from qutebrowser.utils.keyparser import KeyChainParser from qutebrowser.keyinput.hintmode import HintKeyParser
ElemTuple = namedtuple('ElemTuple', 'elem, label') ElemTuple = namedtuple('ElemTuple', 'elem, label')
class HintKeyParser(KeyChainParser):
"""KeyChainParser for hints.
Class attributes:
supports_count: If the keyparser should support counts.
Signals:
fire_hint: When a hint keybinding was completed.
Arg: the keystring/hint string pressed.
abort_hinting: Esc pressed, so abort hinting.
"""
supports_count = False
fire_hint = pyqtSignal(str)
abort_hinting = pyqtSignal()
def _handle_special_key(self, e):
"""Handle the escape key.
FIXME make this more generic
Emit:
abort_hinting: Emitted if hinting was aborted.
"""
if e.key() == Qt.Key_Escape:
self._keystring = ''
self.abort_hinting.emit()
return True
return False
def execute(self, cmdstr, count=None):
"""Handle a completed keychain.
Emit:
fire_hint: Always emitted.
"""
self.fire_hint.emit(cmdstr)
def on_hint_strings_updated(self, strings):
"""Handler for HintManager's hint_strings_updated.
Args:
strings: A list of hint strings.
"""
self.bindings = {s: s for s in strings}
class HintManager(QObject): class HintManager(QObject):
"""Manage drawing hints over links or other elements. """Manage drawing hints over links or other elements.
@ -364,7 +316,7 @@ class HintManager(QObject):
self._elems[string] = ElemTuple(e, label) self._elems[string] = ElemTuple(e, label)
frame.contentsSizeChanged.connect(self.on_contents_size_changed) frame.contentsSizeChanged.connect(self.on_contents_size_changed)
self.hint_strings_updated.emit(strings) self.hint_strings_updated.emit(strings)
modemanager.enter("hint") modes.enter("hint")
def stop(self): def stop(self):
"""Stop hinting.""" """Stop hinting."""
@ -375,7 +327,7 @@ class HintManager(QObject):
self._elems = {} self._elems = {}
self._target = None self._target = None
self._frame = None self._frame = None
modemanager.leave("hint") modes.leave("hint")
message.clear() message.clear()
def handle_partial_key(self, keystr): def handle_partial_key(self, keystr):

View File

@ -25,7 +25,7 @@ import logging
from PyQt5.QtCore import pyqtSignal from PyQt5.QtCore import pyqtSignal
from qutebrowser.utils.keyparser import KeyChainParser from qutebrowser.keyinput.keyparser import KeyChainParser
from qutebrowser.commands.parsers import (CommandParser, ArgumentCountError, from qutebrowser.commands.parsers import (CommandParser, ArgumentCountError,
NoSuchCommandError) NoSuchCommandError)

View File

@ -0,0 +1,70 @@
# Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# 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/>.
"""KeyChainParser for "hint" mode."""
from PyQt5.QtCore import pyqtSignal, Qt
from qutebrowser.keyinput.keyparser import KeyChainParser
class HintKeyParser(KeyChainParser):
"""KeyChainParser for hints.
Class attributes:
supports_count: If the keyparser should support counts.
Signals:
fire_hint: When a hint keybinding was completed.
Arg: the keystring/hint string pressed.
abort_hinting: Esc pressed, so abort hinting.
"""
supports_count = False
fire_hint = pyqtSignal(str)
abort_hinting = pyqtSignal()
def _handle_special_key(self, e):
"""Handle the escape key.
FIXME make this more generic
Emit:
abort_hinting: Emitted if hinting was aborted.
"""
if e.key() == Qt.Key_Escape:
self._keystring = ''
self.abort_hinting.emit()
return True
return False
def execute(self, cmdstr, count=None):
"""Handle a completed keychain.
Emit:
fire_hint: Always emitted.
"""
self.fire_hint.emit(cmdstr)
def on_hint_strings_updated(self, strings):
"""Handler for HintManager's hint_strings_updated.
Args:
strings: A list of hint strings.
"""
self.bindings = {s: s for s in strings}

View File

@ -27,8 +27,8 @@ from PyQt5.QtWebKitWidgets import QWebView, QWebPage
import qutebrowser.utils.url as urlutils import qutebrowser.utils.url as urlutils
import qutebrowser.config.config as config import qutebrowser.config.config as config
import qutebrowser.keyinput.modes as modes
import qutebrowser.utils.message as message import qutebrowser.utils.message as message
import qutebrowser.utils.modemanager as modemanager
import qutebrowser.utils.webelem as webelem import qutebrowser.utils.webelem as webelem
from qutebrowser.browser.webpage import BrowserPage from qutebrowser.browser.webpage import BrowserPage
from qutebrowser.browser.hints import HintManager from qutebrowser.browser.hints import HintManager
@ -86,7 +86,7 @@ class BrowserTab(QWebView):
self.page_.setLinkDelegationPolicy(QWebPage.DelegateAllLinks) self.page_.setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
self.page_.linkHovered.connect(self.linkHovered) self.page_.linkHovered.connect(self.linkHovered)
self.linkClicked.connect(self.on_link_clicked) self.linkClicked.connect(self.on_link_clicked)
self.loadStarted.connect(lambda: modemanager.maybe_leave("insert")) self.loadStarted.connect(lambda: modes.maybe_leave("insert"))
self.loadFinished.connect(self.on_load_finished) self.loadFinished.connect(self.on_load_finished)
# FIXME find some way to hide scrollbars without setScrollBarPolicy # FIXME find some way to hide scrollbars without setScrollBarPolicy
@ -255,9 +255,9 @@ class BrowserTab(QWebView):
webelem.SELECTORS['editable_focused']) webelem.SELECTORS['editable_focused'])
logging.debug("focus element: {}".format(not elem.isNull())) logging.debug("focus element: {}".format(not elem.isNull()))
if elem.isNull(): if elem.isNull():
modemanager.maybe_leave("insert") modes.maybe_leave("insert")
else: else:
modemanager.enter("insert") modes.enter("insert")
@pyqtSlot(str) @pyqtSlot(str)
def set_force_open_target(self, target): def set_force_open_target(self, target):
@ -319,11 +319,11 @@ class BrowserTab(QWebView):
hitresult = frame.hitTestContent(pos) hitresult = frame.hitTestContent(pos)
if self._is_editable(hitresult): if self._is_editable(hitresult):
logging.debug("Clicked editable element!") logging.debug("Clicked editable element!")
modemanager.enter("insert") modes.enter("insert")
else: else:
logging.debug("Clicked non-editable element!") logging.debug("Clicked non-editable element!")
try: try:
modemanager.leave("insert") modes.leave("insert")
except ValueError: except ValueError:
pass pass

View File

@ -23,8 +23,8 @@ from PyQt5.QtWidgets import (QWidget, QLineEdit, QProgressBar, QLabel,
QShortcut) QShortcut)
from PyQt5.QtGui import QPainter, QKeySequence, QValidator from PyQt5.QtGui import QPainter, QKeySequence, QValidator
import qutebrowser.commands.keys as keys import qutebrowser.keyinput.modes as modes
import qutebrowser.utils.modemanager as modemanager from qutebrowser.keyinput.commandmode import STARTCHARS
from qutebrowser.config.style import set_register_stylesheet, get_stylesheet from qutebrowser.config.style import set_register_stylesheet, get_stylesheet
from qutebrowser.utils.url import urlstring from qutebrowser.utils.url import urlstring
from qutebrowser.commands.parsers import split_cmdline from qutebrowser.commands.parsers import split_cmdline
@ -173,13 +173,13 @@ class StatusBar(QWidget):
@pyqtSlot(str) @pyqtSlot(str)
def on_mode_entered(self, mode): def on_mode_entered(self, mode):
"""Mark certain modes in the commandline.""" """Mark certain modes in the commandline."""
if mode in modemanager.manager.passthrough: if mode in modes.manager.passthrough:
self.txt.normaltext = "-- {} MODE --".format(mode.upper()) self.txt.normaltext = "-- {} MODE --".format(mode.upper())
@pyqtSlot(str) @pyqtSlot(str)
def on_mode_left(self, mode): def on_mode_left(self, mode):
"""Clear marked mode.""" """Clear marked mode."""
if mode in modemanager.manager.passthrough: if mode in modes.manager.passthrough:
self.txt.normaltext = "" self.txt.normaltext = ""
def resizeEvent(self, e): def resizeEvent(self, e):
@ -344,7 +344,7 @@ class _Command(QLineEdit):
""" """
# FIXME we should consider the cursor position. # FIXME we should consider the cursor position.
text = self.text() text = self.text()
if text[0] in keys.STARTCHARS: if text[0] in STARTCHARS:
prefix = text[0] prefix = text[0]
text = text[1:] text = text[1:]
else: else:
@ -357,7 +357,7 @@ class _Command(QLineEdit):
def focusInEvent(self, e): def focusInEvent(self, e):
"""Extend focusInEvent to enter command mode.""" """Extend focusInEvent to enter command mode."""
modemanager.enter("command") modes.enter("command")
super().focusInEvent(e) super().focusInEvent(e)
def focusOutEvent(self, e): def focusOutEvent(self, e):
@ -375,7 +375,7 @@ class _Command(QLineEdit):
clear_completion_selection: Always emitted. clear_completion_selection: Always emitted.
hide_completion: Always emitted so the completion is hidden. hide_completion: Always emitted so the completion is hidden.
""" """
modemanager.leave("command") modes.leave("command")
if e.reason() in [Qt.MouseFocusReason, Qt.TabFocusReason, if e.reason() in [Qt.MouseFocusReason, Qt.TabFocusReason,
Qt.BacktabFocusReason, Qt.OtherFocusReason]: Qt.BacktabFocusReason, Qt.OtherFocusReason]:
self.setText('') self.setText('')
@ -400,7 +400,7 @@ class _CommandValidator(QValidator):
Return: Return:
A tuple (status, string, pos) as a QValidator should. A tuple (status, string, pos) as a QValidator should.
""" """
if any(string.startswith(c) for c in keys.STARTCHARS): if any(string.startswith(c) for c in STARTCHARS):
return (QValidator.Acceptable, string, pos) return (QValidator.Acceptable, string, pos)
else: else:
return (QValidator.Invalid, string, pos) return (QValidator.Invalid, string, pos)