From 4b34e71030e8aa8ef12c83fc1eacd7a0f28fafc0 Mon Sep 17 00:00:00 2001 From: Arthur Milchior Date: Tue, 31 Mar 2020 15:00:26 +0200 Subject: [PATCH] hook tag_editor_received_a_key I expect it to be useful for add-ons such as https://github.com/fonol/anki-search-inside-add-card which interact with the tag line --- qt/aqt/gui_hooks.py | 27 ++++++++++++++++++++++++++- qt/aqt/tagedit.py | 2 ++ qt/tools/genhooks_gui.py | 3 +++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/qt/aqt/gui_hooks.py b/qt/aqt/gui_hooks.py index 93d15b445..2e40815de 100644 --- a/qt/aqt/gui_hooks.py +++ b/qt/aqt/gui_hooks.py @@ -13,7 +13,8 @@ import anki import aqt from anki.cards import Card from anki.hooks import runFilter, runHook -from aqt.qt import QDialog, QMenu +from aqt.qt import QDialog, QEvent, QMenu +from aqt.tagedit import TagEdit # New hook/filter handling ############################################################################## @@ -1927,6 +1928,30 @@ class _StyleDidInitFilter: style_did_init = _StyleDidInitFilter() +class _TagEditorReceivedAKeyHook: + _hooks: List[Callable[[TagEdit, QEvent], None]] = [] + + def append(self, cb: Callable[[TagEdit, QEvent], None]) -> None: + """(tag_edit: TagEdit, evt: QEvent)""" + self._hooks.append(cb) + + def remove(self, cb: Callable[[TagEdit, QEvent], None]) -> None: + if cb in self._hooks: + self._hooks.remove(cb) + + def __call__(self, tag_edit: TagEdit, evt: QEvent) -> None: + for hook in self._hooks: + try: + hook(tag_edit, evt) + except: + # if the hook fails, remove it + self._hooks.remove(hook) + raise + + +tag_editor_received_a_key = _TagEditorReceivedAKeyHook() + + class _TopToolbarDidInitLinksHook: """Used to modify or add links in the top toolbar of Anki's main window diff --git a/qt/aqt/tagedit.py b/qt/aqt/tagedit.py index 6a5f4b374..2289ca737 100644 --- a/qt/aqt/tagedit.py +++ b/qt/aqt/tagedit.py @@ -3,6 +3,7 @@ import re +from aqt import gui_hooks from aqt.qt import * @@ -76,6 +77,7 @@ class TagEdit(QLineEdit): Qt.Key_Delete, ): self.showCompleter() + gui_hooks.tag_editor_received_a_key(self, evt) def showCompleter(self): self.completer.setCompletionPrefix(self.text()) diff --git a/qt/tools/genhooks_gui.py b/qt/tools/genhooks_gui.py index c2f0a0702..e92055157 100644 --- a/qt/tools/genhooks_gui.py +++ b/qt/tools/genhooks_gui.py @@ -509,6 +509,9 @@ def emptyNewCard(): doc="""Allows changing the javascript commands to load note before executing it and do change in the QT editor.""", ), + # Tag + ################### + Hook(name="tag_editor_received_a_key", args=["tag_edit: TagEdit", "evt: QEvent"]), # Sound/video ################### Hook(name="av_player_will_play", args=["tag: anki.sound.AVTag"]),