diff --git a/qt/aqt/editor.py b/qt/aqt/editor.py index 77e89ac77..b269df969 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"]),