From 31f18e3c94ede16e299185d845017f1518032978 Mon Sep 17 00:00:00 2001 From: Arthur Milchior Date: Tue, 24 Mar 2020 10:17:01 +0100 Subject: [PATCH] Hook editor_note_will_load A current problem I have is that there is nothing similar to hook inside of javascript. It seems that it would be easier to be able to add other methods in javascript and call them in loadNote. Currently I simply redefined loadNote, which is far from perfect --- qt/aqt/editor.py | 1 + qt/aqt/gui_hooks.py | 34 ++++++++++++++++++++++++++++++++++ qt/tools/genhooks_gui.py | 7 +++++++ 3 files changed, 42 insertions(+) diff --git a/qt/aqt/editor.py b/qt/aqt/editor.py index 31c5d3b8f..3d5341e73 100644 --- a/qt/aqt/editor.py +++ b/qt/aqt/editor.py @@ -456,6 +456,7 @@ class Editor: json.dumps(focusTo), json.dumps(self.note.id), ) + js = gui_hooks.editor_will_load_note(js, self.note, self) self.web.evalWithCallback(js, oncallback) def fonts(self) -> List[Tuple[str, int, bool]]: diff --git a/qt/aqt/gui_hooks.py b/qt/aqt/gui_hooks.py index 0115ef948..aecaaec3c 100644 --- a/qt/aqt/gui_hooks.py +++ b/qt/aqt/gui_hooks.py @@ -1207,6 +1207,40 @@ class _EditorWebViewDidInitHook: editor_web_view_did_init = _EditorWebViewDidInitHook() +class _EditorWillLoadNoteFilter: + """Allows changing the javascript commands to load note before + executing it and do change in the QT editor.""" + + _hooks: List[Callable[[str, "anki.notes.Note", "aqt.editor.Editor"], str]] = [] + + def append( + self, cb: Callable[[str, "anki.notes.Note", "aqt.editor.Editor"], str] + ) -> None: + """(js: str, note: anki.notes.Note, editor: aqt.editor.Editor)""" + self._hooks.append(cb) + + def remove( + self, cb: Callable[[str, "anki.notes.Note", "aqt.editor.Editor"], str] + ) -> None: + if cb in self._hooks: + self._hooks.remove(cb) + + def __call__( + self, js: str, note: anki.notes.Note, editor: aqt.editor.Editor + ) -> str: + for filter in self._hooks: + try: + js = filter(js, note, editor) + except: + # if the hook fails, remove it + self._hooks.remove(filter) + raise + return js + + +editor_will_load_note = _EditorWillLoadNoteFilter() + + class _EditorWillShowContextMenuHook: _hooks: List[Callable[["aqt.editor.EditorWebView", QMenu], None]] = [] diff --git a/qt/tools/genhooks_gui.py b/qt/tools/genhooks_gui.py index 1dd08c430..a8887e10b 100644 --- a/qt/tools/genhooks_gui.py +++ b/qt/tools/genhooks_gui.py @@ -498,6 +498,13 @@ def emptyNewCard(): args=["editor_web_view: aqt.editor.EditorWebView"], ), Hook(name="editor_did_init", args=["editor: aqt.editor.Editor"],), + Hook( + name="editor_will_load_note", + args=["js: str", "note: anki.notes.Note", "editor: aqt.editor.Editor"], + return_type="str", + doc="""Allows changing the javascript commands to load note before + executing it and do change in the QT editor.""", + ), # Sound/video ################### Hook(name="av_player_will_play", args=["tag: anki.sound.AVTag"]),