Refactor KeySequence initialization

This commit is contained in:
Florian Bruhin 2018-02-26 11:10:05 +01:00
parent f92bb16408
commit 16940db834
3 changed files with 25 additions and 35 deletions

View File

@ -264,16 +264,13 @@ class KeySequence:
_MAX_LEN = 4 _MAX_LEN = 4
def __init__(self, strings=None): def __init__(self, *keys):
self._sequences = [] self._sequences = []
if strings is None: for sub in utils.chunk(keys, self._MAX_LEN):
strings = [] sequence = QKeySequence(*sub)
for sub in utils.chunk(strings, 4):
# Catch old API usage FIXME
assert all(isinstance(s, str) for s in sub)
sequence = QKeySequence(', '.join(sub))
self._sequences.append(sequence) self._sequences.append(sequence)
if keys:
assert len(self) > 0
self._validate() self._validate()
def __str__(self): def __str__(self):
@ -287,7 +284,7 @@ class KeySequence:
modifier_mask = int(Qt.ShiftModifier | Qt.ControlModifier | modifier_mask = int(Qt.ShiftModifier | Qt.ControlModifier |
Qt.AltModifier | Qt.MetaModifier | Qt.AltModifier | Qt.MetaModifier |
Qt.KeypadModifier | Qt.GroupSwitchModifier) Qt.KeypadModifier | Qt.GroupSwitchModifier)
for key in itertools.chain.from_iterable(self._sequences): for key in self._iter_keys():
yield KeyInfo( yield KeyInfo(
key=int(key) & ~modifier_mask, key=int(key) & ~modifier_mask,
modifiers=Qt.KeyboardModifiers(int(key) & modifier_mask)) modifiers=Qt.KeyboardModifiers(int(key) & modifier_mask))
@ -314,6 +311,13 @@ class KeySequence:
def __len__(self): def __len__(self):
return sum(len(seq) for seq in self._sequences) return sum(len(seq) for seq in self._sequences)
def __getitem__(self, item):
keys = list(self._iter_keys())
return self.__class__(*keys[item])
def _iter_keys(self):
return itertools.chain.from_iterable(self._sequences)
def _validate(self): def _validate(self):
for info in self: for info in self:
assert info.key != Qt.Key_unknown assert info.key != Qt.Key_unknown
@ -347,39 +351,25 @@ class KeySequence:
FIXME: create test cases! FIXME: create test cases!
""" """
# pylint: disable=protected-access # pylint: disable=protected-access
new = self.__class__()
new._sequences = self._sequences[:]
modifiers = ev.modifiers() modifiers = ev.modifiers()
if (modifiers == Qt.ShiftModifier and if (modifiers == Qt.ShiftModifier and
ev.text() and ev.text() and
unicodedata.category(ev.text()) != 'Lu'): unicodedata.category(ev.text()) != 'Lu'):
modifiers = Qt.KeyboardModifiers() modifiers = Qt.KeyboardModifiers()
if new._sequences and len(new._sequences[-1]) < self._MAX_LEN: keys = list(self._iter_keys())
new._sequences[-1] = QKeySequence(*new._sequences[-1], keys.append(ev.key() | int(modifiers))
ev.key() | int(modifiers))
else:
new._sequences.append(QKeySequence(ev.key() | int(modifiers)))
new._validate() return self.__class__(*keys)
return new
def remove_last(self):
"""Create a new KeySequence with the last key removed."""
new = self.__class__()
new._sequences = self._sequeces[:]
if len(new._sequences[-1]) == 1:
del new._sequences[-1]
else:
new._sequences[-1] = QKeySequence(*new._sequences[-1][:-1])
new._validate()
return new
@classmethod @classmethod
def parse(cls, keystr): def parse(cls, keystr):
"""Parse a keystring like <Ctrl-x> or xyz and return a KeySequence.""" """Parse a keystring like <Ctrl-x> or xyz and return a KeySequence."""
parts = list(_parse_keystring(keystr)) new = cls()
new = cls(parts) strings = list(_parse_keystring(keystr))
for sub in utils.chunk(strings, cls._MAX_LEN):
sequence = QKeySequence(', '.join(sub))
new._sequences.append(sequence)
assert len(new) > 0 assert len(new) > 0
new._validate()
return new return new

View File

@ -183,7 +183,7 @@ class HintKeyParser(keyparser.CommandKeyParser):
hintmanager.filter_hints(self._filtertext) hintmanager.filter_hints(self._filtertext)
return True return True
elif self._last_press == LastPress.keystring and self._sequence: elif self._last_press == LastPress.keystring and self._sequence:
self._sequence = self._sequence.remove_last() self._sequence = self._sequence[:-1]
self.keystring_updated.emit(str(self._sequence)) self.keystring_updated.emit(str(self._sequence))
if not self._sequence and self._filtertext: if not self._sequence and self._filtertext:
# Switch back to hint filtering mode (this can happen only # Switch back to hint filtering mode (this can happen only
@ -254,7 +254,7 @@ class HintKeyParser(keyparser.CommandKeyParser):
`self._filtertext`. `self._filtertext`.
""" """
self._read_config() self._read_config()
self.bindings.update({keyutils.KeySequence(s): self.bindings.update({keyutils.KeySequence.parse(s):
'follow-hint ' + s for s in strings}) 'follow-hint ' + s for s in strings})
if not preserve_filter: if not preserve_filter:
self._filtertext = '' self._filtertext = ''

View File

@ -107,7 +107,7 @@ class KeyHintView(QLabel):
bindings_dict = config.key_instance.get_bindings_for(modename) bindings_dict = config.key_instance.get_bindings_for(modename)
bindings = [(k, v) for (k, v) in sorted(bindings_dict.items()) bindings = [(k, v) for (k, v) in sorted(bindings_dict.items())
if k.matches(keyutils.KeySequence(prefix)) and # FIXME if k.matches(keyutils.KeySequence.parse(prefix)) and # FIXME
not blacklisted(k) and not blacklisted(k) and
(takes_count(v) or not countstr)] (takes_count(v) or not countstr)]