Add ability to tag legacy pages with a context

Will allow us to identify which of our screens requests are coming in
through, until we can migrate them to separate entrypoints.
This commit is contained in:
Damien Elmes 2023-11-08 10:02:04 +10:00
parent 454ca6ce2c
commit 780ebac3aa
2 changed files with 51 additions and 11 deletions

View file

@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
import enum
import logging import logging
import mimetypes import mimetypes
import os import os
@ -63,6 +64,17 @@ class NotFound:
DynamicRequest = Callable[[], Response] DynamicRequest = Callable[[], Response]
class LegacyPageContext(enum.Enum):
OTHER = 0
EDITOR = 1
@dataclass
class LegacyPage:
html: str
context: LegacyPageContext
class MediaServer(threading.Thread): class MediaServer(threading.Thread):
_ready = threading.Event() _ready = threading.Event()
daemon = True daemon = True
@ -71,7 +83,7 @@ class MediaServer(threading.Thread):
super().__init__() super().__init__()
self.is_shutdown = False self.is_shutdown = False
# map of webview ids to pages # map of webview ids to pages
self._page_html: dict[int, str] = {} self._legacy_pages: dict[int, LegacyPage] = {}
def run(self) -> None: def run(self) -> None:
try: try:
@ -113,15 +125,26 @@ class MediaServer(threading.Thread):
self._ready.wait() self._ready.wait()
return int(self.server.effective_port) # type: ignore return int(self.server.effective_port) # type: ignore
def set_page_html(self, id: int, html: str) -> None: def set_page_html(
self._page_html[id] = html self, id: int, html: str, context: LegacyPageContext = LegacyPageContext.OTHER
) -> None:
self._legacy_pages[id] = LegacyPage(html, context)
def get_page_html(self, id: int) -> str | None: def get_page_html(self, id: int) -> str | None:
return self._page_html.get(id) if page := self._legacy_pages.get(id):
return page.html
else:
return None
def get_page_context(self, id: int) -> LegacyPageContext | None:
if page := self._legacy_pages.get(id):
return page.context
else:
return None
def clear_page_html(self, id: int) -> None: def clear_page_html(self, id: int) -> None:
try: try:
del self._page_html[id] del self._legacy_pages[id]
except KeyError: except KeyError:
pass pass

View file

@ -8,7 +8,7 @@ import json
import re import re
import sys import sys
from enum import Enum from enum import Enum
from typing import Any, Callable, Optional, Sequence, cast from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, cast
import anki import anki
import anki.lang import anki.lang
@ -22,6 +22,10 @@ from aqt.utils import askUser, is_gesture_or_zoom_event, openLink, showInfo, tr
serverbaseurl = re.compile(r"^.+:\/\/[^\/]+") serverbaseurl = re.compile(r"^.+:\/\/[^\/]+")
if TYPE_CHECKING:
from aqt.mediasrv import LegacyPageContext
# Page for debug messages # Page for debug messages
########################################################################## ##########################################################################
@ -378,16 +382,22 @@ class AnkiWebView(QWebEngineView):
if self.allow_drops: if self.allow_drops:
super().dropEvent(evt) super().dropEvent(evt)
def setHtml(self, html: str) -> None: # type: ignore def setHtml( # type: ignore[override]
self, html: str, context: LegacyPageContext | None = None
) -> None:
from aqt.mediasrv import LegacyPageContext
# discard any previous pending actions # discard any previous pending actions
self._pendingActions = [] self._pendingActions = []
self._domDone = True self._domDone = True
self._queueAction("setHtml", html) if context is None:
context = LegacyPageContext.OTHER
self._queueAction("setHtml", html, context)
self.set_open_links_externally(True) self.set_open_links_externally(True)
self.allow_drops = False self.allow_drops = False
self.show() self.show()
def _setHtml(self, html: str) -> None: def _setHtml(self, html: str, context: LegacyPageContext) -> None:
"""Send page data to media server, then surf to it. """Send page data to media server, then surf to it.
This function used to be implemented by QWebEngine's This function used to be implemented by QWebEngine's
@ -400,7 +410,7 @@ class AnkiWebView(QWebEngineView):
self._domDone = False self._domDone = False
webview_id = id(self) webview_id = id(self)
mw.mediaServer.set_page_html(webview_id, html) mw.mediaServer.set_page_html(webview_id, html, context)
self.load_url(QUrl(f"{mw.serverURL()}_anki/legacyPageData?id={webview_id}")) self.load_url(QUrl(f"{mw.serverURL()}_anki/legacyPageData?id={webview_id}"))
# work around webengine stealing focus on setHtml() # work around webengine stealing focus on setHtml()
@ -571,7 +581,14 @@ html {{ {font} }}
{web_content.body}</body> {web_content.body}</body>
</html>""" </html>"""
# print(html) # print(html)
self.setHtml(html) import aqt.editor
from aqt.mediasrv import LegacyPageContext
if isinstance(context, aqt.editor.Editor):
page_context = LegacyPageContext.EDITOR
else:
page_context = LegacyPageContext.OTHER
self.setHtml(html, page_context)
@classmethod @classmethod
def webBundlePath(cls, path: str) -> str: def webBundlePath(cls, path: str) -> str: