|
| 1 | +import platform |
| 2 | +from pathlib import Path |
| 3 | +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit |
| 4 | + |
| 5 | +from .前端API import 山彥API |
| 6 | + |
| 7 | + |
| 8 | +橋腳本 = Path(__file__).parent / '前端/pywebview橋.js' |
| 9 | + |
| 10 | + |
| 11 | +class WebView窗口: |
| 12 | + def __init__(self, webview, url, icon, title, size, storage_path): |
| 13 | + self._webview = webview |
| 14 | + self._url = _本地網址(url) |
| 15 | + self._icon = str(icon) if icon else None |
| 16 | + self._title = title |
| 17 | + self._size = tuple(size) |
| 18 | + self._storage_path = str(storage_path) if storage_path else None |
| 19 | + self._api = None |
| 20 | + self._window = None |
| 21 | + |
| 22 | + def 綁定(self, 山彥): |
| 23 | + self._api = 山彥API(山彥) |
| 24 | + |
| 25 | + def 執行js(self, script): |
| 26 | + return self._window.evaluate_js(script) |
| 27 | + |
| 28 | + def 切換全屏(self): |
| 29 | + return self._window.toggle_fullscreen() |
| 30 | + |
| 31 | + def 運行(self): |
| 32 | + if self._api is None: |
| 33 | + raise RuntimeError('啓動窗口前必須綁定山彥') |
| 34 | + |
| 35 | + width, height = self._窗口尺寸() |
| 36 | + self._window = self._webview.create_window( |
| 37 | + title=self._title, |
| 38 | + url=self._url, |
| 39 | + js_api=self._api, |
| 40 | + width=width, |
| 41 | + height=height, |
| 42 | + ) |
| 43 | + self._window.events.loaded += self._注入橋 |
| 44 | + self._webview.start( |
| 45 | + private_mode=False, |
| 46 | + storage_path=self._storage_path, |
| 47 | + icon=self._icon, |
| 48 | + ) |
| 49 | + |
| 50 | + def _窗口尺寸(self): |
| 51 | + if platform.system() != 'Darwin': |
| 52 | + return self._size |
| 53 | + |
| 54 | + import AppKit |
| 55 | + |
| 56 | + 內容寬, 內容高 = self._size |
| 57 | + 樣式 = ( |
| 58 | + AppKit.NSWindowStyleMaskTitled |
| 59 | + | AppKit.NSWindowStyleMaskClosable |
| 60 | + | AppKit.NSWindowStyleMaskMiniaturizable |
| 61 | + | AppKit.NSWindowStyleMaskResizable |
| 62 | + ) |
| 63 | + 內容矩形 = AppKit.NSMakeRect(0, 0, 內容寬, 內容高) |
| 64 | + 外框矩形 = AppKit.NSWindow.frameRectForContentRect_styleMask_(內容矩形, 樣式) |
| 65 | + return round(外框矩形.size.width), round(外框矩形.size.height) |
| 66 | + |
| 67 | + def _注入橋(self): |
| 68 | + 當前網址 = urlsplit(self._window.get_current_url()) |
| 69 | + if dict(parse_qsl(當前網址.query)).get('_librian_exit') == '1': |
| 70 | + self._window.destroy() |
| 71 | + else: |
| 72 | + self._window.run_js(橋腳本.read_text(encoding='utf8')) |
| 73 | + |
| 74 | + |
| 75 | +def _本地網址(url): |
| 76 | + 區段 = urlsplit(str(url)) |
| 77 | + 查詢 = parse_qsl(區段.query, keep_blank_values=True) |
| 78 | + 查詢.append(('_librian_webview', '1')) |
| 79 | + return urlunsplit(區段._replace(query=urlencode(查詢))) |
| 80 | + |
| 81 | + |
| 82 | +def 創建窗口(url, icon, title, size, storage_path): |
| 83 | + import webview |
| 84 | + |
| 85 | + return WebView窗口(webview, url, icon, title, size, storage_path) |
0 commit comments