qutebrowser/qutebrowser/keyinput/modeparsers.py

321 lines
11 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:
2016-01-04 07:12:39 +01:00
# Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
2014-04-25 12:34:17 +02: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/>.
"""KeyChainParser for "hint" and "normal" modes.
Module attributes:
STARTCHARS: Possible chars for starting a commandline input.
"""
2014-09-25 07:58:08 +02:00
from PyQt5.QtCore import pyqtSlot, Qt
2014-04-25 12:34:17 +02:00
2016-04-13 04:00:29 +02:00
from qutebrowser.utils import message
2014-08-26 19:10:14 +02:00
from qutebrowser.config import config
from qutebrowser.keyinput import keyparser
2014-09-26 15:48:24 +02:00
from qutebrowser.utils import usertypes, log, objreg, utils
2014-04-25 12:34:17 +02:00
STARTCHARS = ":/?"
LastPress = usertypes.enum('LastPress', ['none', 'filtertext', 'keystring'])
2014-04-25 12:34:17 +02:00
2014-08-26 19:10:14 +02:00
class NormalKeyParser(keyparser.CommandKeyParser):
2014-04-25 12:34:17 +02:00
2015-03-31 20:49:29 +02:00
"""KeyParser for normal mode with added STARTCHARS detection and more.
Attributes:
_partial_timer: Timer to clear partial keypresses.
"""
2014-04-25 12:34:17 +02:00
2014-09-28 22:13:14 +02:00
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent, supports_count=True,
supports_chains=True)
2014-09-09 07:43:27 +02:00
self.read_config('normal')
self._partial_timer = usertypes.Timer(self, 'partial-match')
self._partial_timer.setSingleShot(True)
2015-12-16 19:41:07 +01:00
self._inhibited = False
self._inhibited_timer = usertypes.Timer(self, 'normal-inhibited')
self._inhibited_timer.setSingleShot(True)
2014-04-25 12:34:17 +02:00
def __repr__(self):
2014-09-26 15:48:24 +02:00
return utils.get_repr(self)
2014-04-25 12:34:17 +02:00
def _handle_single_key(self, e):
"""Override _handle_single_key to abort if the key is a startchar.
Args:
e: the KeyPressEvent from Qt.
Return:
A self.Match member.
2014-04-25 12:34:17 +02:00
"""
txt = e.text().strip()
2016-06-07 15:42:59 +02:00
if self._inhibited:
2015-12-16 19:41:07 +01:00
self._debug_log("Ignoring key '{}', because the normal mode is "
"currently inhibited.".format(txt))
return self.Match.none
2014-04-25 12:34:17 +02:00
if not self._keystring and any(txt == c for c in STARTCHARS):
2014-09-28 22:13:14 +02:00
message.set_cmd_text(self._win_id, txt)
return self.Match.definitive
match = super()._handle_single_key(e)
if match == self.Match.partial:
timeout = config.get('input', 'partial-timeout')
if timeout != 0:
self._partial_timer.setInterval(timeout)
self._partial_timer.timeout.connect(self._clear_partial_match)
self._partial_timer.start()
return match
2015-12-16 19:41:07 +01:00
def set_inhibited_timeout(self, timeout):
if timeout != 0:
self._debug_log("Inhibiting the normal mode for {}ms.".format(
timeout))
self._inhibited = True
self._inhibited_timer.setInterval(timeout)
self._inhibited_timer.timeout.connect(self._clear_inhibited)
self._inhibited_timer.start()
@pyqtSlot()
def _clear_partial_match(self):
"""Clear a partial keystring after a timeout."""
self._debug_log("Clearing partial keystring {}".format(
self._keystring))
self._keystring = ''
self.keystring_updated.emit(self._keystring)
2015-12-16 19:41:07 +01:00
@pyqtSlot()
def _clear_inhibited(self):
"""Reset inhibition state after a timeout."""
self._debug_log("Releasing inhibition state of normal mode.")
self._inhibited = False
@pyqtSlot()
def _stop_timers(self):
super()._stop_timers()
self._partial_timer.stop()
try:
self._partial_timer.timeout.disconnect(self._clear_partial_match)
except TypeError:
# no connections
pass
2015-12-16 19:41:07 +01:00
self._inhibited_timer.stop()
try:
self._inhibited_timer.timeout.disconnect(self._clear_inhibited)
except TypeError:
# no connections
pass
2014-04-25 12:34:17 +02:00
2014-08-26 19:10:14 +02:00
class PromptKeyParser(keyparser.CommandKeyParser):
2014-05-20 12:05:14 +02:00
"""KeyParser for yes/no prompts."""
2014-09-28 22:13:14 +02:00
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent, supports_count=False,
supports_chains=True)
2014-05-20 12:05:14 +02:00
# We don't want an extra section for this in the config, so we just
2014-09-09 07:43:27 +02:00
# abuse the prompt section.
self.read_config('prompt')
2014-05-20 12:05:14 +02:00
def __repr__(self):
2014-09-26 15:48:24 +02:00
return utils.get_repr(self)
2014-05-20 12:05:14 +02:00
2014-08-26 19:10:14 +02:00
class HintKeyParser(keyparser.CommandKeyParser):
2014-04-25 12:34:17 +02:00
"""KeyChainParser for hints.
2014-05-02 17:53:16 +02:00
Attributes:
_filtertext: The text to filter with.
_last_press: The nature of the last keypress, a LastPress member.
2014-04-25 12:34:17 +02:00
"""
2014-09-28 22:13:14 +02:00
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent, supports_count=False,
supports_chains=True)
2014-05-02 17:53:16 +02:00
self._filtertext = ''
self._last_press = LastPress.none
2014-09-09 07:43:27 +02:00
self.read_config('hint')
2014-09-25 07:44:11 +02:00
self.keystring_updated.connect(self.on_keystring_updated)
2014-04-25 12:34:17 +02:00
2014-05-02 17:53:16 +02:00
def _handle_special_key(self, e):
"""Override _handle_special_key to handle string filtering.
Return True if the keypress has been handled, and False if not.
Args:
e: the KeyPressEvent from Qt.
Return:
True if event has been handled, False otherwise.
"""
2014-08-26 20:15:41 +02:00
log.keyboard.debug("Got special key 0x{:x} text {}".format(
2014-07-03 06:30:50 +02:00
e.key(), e.text()))
hintmanager = objreg.get('hintmanager', scope='tab',
window=self._win_id, tab='current')
if e.key() == Qt.Key_Backspace:
2014-08-26 20:15:41 +02:00
log.keyboard.debug("Got backspace, mode {}, filtertext '{}', "
"keystring '{}'".format(self._last_press,
2014-08-26 20:15:41 +02:00
self._filtertext,
self._keystring))
if self._last_press == LastPress.filtertext and self._filtertext:
2014-05-02 17:53:16 +02:00
self._filtertext = self._filtertext[:-1]
2014-09-25 07:44:11 +02:00
hintmanager.filter_hints(self._filtertext)
return True
elif self._last_press == LastPress.keystring and self._keystring:
self._keystring = self._keystring[:-1]
self.keystring_updated.emit(self._keystring)
if not self._keystring and self._filtertext:
# Switch back to hint filtering mode (this can happen only
# in numeric mode after the number has been deleted).
hintmanager.filter_hints(self._filtertext)
self._last_press = LastPress.filtertext
return True
else:
return super()._handle_special_key(e)
elif config.get('hints', 'mode') != 'number':
return super()._handle_special_key(e)
2014-05-02 17:53:16 +02:00
elif not e.text():
return super()._handle_special_key(e)
else:
self._filtertext += e.text()
2014-09-25 07:44:11 +02:00
hintmanager.filter_hints(self._filtertext)
self._last_press = LastPress.filtertext
2014-05-02 17:53:16 +02:00
return True
def handle(self, e):
"""Handle a new keypress and call the respective handlers.
Args:
e: the KeyPressEvent from Qt
Returns:
True if the match has been handled, False otherwise.
2014-05-02 17:53:16 +02:00
"""
match = self._handle_single_key(e)
if match == self.Match.partial:
2014-05-02 17:53:16 +02:00
self.keystring_updated.emit(self._keystring)
self._last_press = LastPress.keystring
return True
elif match == self.Match.definitive:
self._last_press = LastPress.none
return True
elif match == self.Match.other:
pass
elif match == self.Match.none:
2014-06-13 14:52:54 +02:00
# We couldn't find a keychain so we check if it's a special key.
return self._handle_special_key(e)
else:
raise ValueError("Got invalid match type {}!".format(match))
2014-05-02 17:53:16 +02:00
2014-04-25 12:34:17 +02:00
def execute(self, cmdstr, keytype, count=None):
2014-09-25 07:44:11 +02:00
"""Handle a completed keychain."""
2014-07-29 00:23:20 +02:00
if not isinstance(keytype, self.Type):
raise TypeError("Type {} is no Type member!".format(keytype))
2014-05-05 07:45:36 +02:00
if keytype == self.Type.chain:
hintmanager = objreg.get('hintmanager', scope='tab',
2014-10-06 19:53:50 +02:00
window=self._win_id, tab='current')
hintmanager.fire(cmdstr)
2014-04-25 12:34:17 +02:00
else:
# execute as command
super().execute(cmdstr, keytype, count)
def update_bindings(self, strings, preserve_filter=False):
2014-09-25 07:44:11 +02:00
"""Update bindings when the hint strings changed.
2014-04-25 12:34:17 +02:00
Args:
strings: A list of hint strings.
preserve_filter: Whether to keep the current value of
`self._filtertext`.
2014-04-25 12:34:17 +02:00
"""
self.bindings = {s: s for s in strings}
2016-06-07 15:42:59 +02:00
if not preserve_filter:
self._filtertext = ''
2014-09-25 07:44:11 +02:00
@pyqtSlot(str)
def on_keystring_updated(self, keystr):
"""Update hintmanager when the keystring was updated."""
hintmanager = objreg.get('hintmanager', scope='tab',
window=self._win_id, tab='current')
hintmanager.handle_partial_key(keystr)
2015-04-28 16:50:42 +02:00
class CaretKeyParser(keyparser.CommandKeyParser):
2015-05-13 22:29:21 +02:00
"""KeyParser for caret mode."""
passthrough = True
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent, supports_count=True,
supports_chains=True)
self.read_config('caret')
2016-04-13 04:00:29 +02:00
class MarkKeyParser(keyparser.BaseKeyParser):
"""KeyParser for set_mark and jump_mark mode.
Attributes:
_mode: Either KeyMode.set_mark or KeyMode.jump_mark.
"""
def __init__(self, win_id, mode, parent=None):
super().__init__(win_id, parent, supports_count=False,
supports_chains=False)
self._mode = mode
def handle(self, e):
2016-04-13 04:00:29 +02:00
"""Override handle to always match the next key and create a mark.
Args:
e: the KeyPressEvent from Qt.
Return:
True if event has been handled, False otherwise.
"""
if utils.keyevent_to_string(e) is None:
# this is a modifier key, let it pass and keep going
return False
key = e.text()
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window=self._win_id)
if self._mode == usertypes.KeyMode.set_mark:
tabbed_browser.set_mark(key)
elif self._mode == usertypes.KeyMode.jump_mark:
tabbed_browser.jump_mark(key)
else:
2016-04-13 04:00:29 +02:00
raise ValueError("{} is not a valid mark mode".format(self._mode))
self.request_leave.emit(self._mode, "valid mark key")
return True
@pyqtSlot(str)
def on_keyconfig_changed(self, mode):
"""MarkKeyParser has no config section (no bindable keys)."""
pass
def execute(self, cmdstr, _keytype, count=None):
"""Should never be called on MarkKeyParser."""
assert False