sideview 0.4.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sideview/__init__.py +10 -0
- sideview/_backend.py +522 -0
- sideview/py.typed +1 -0
- sideview/sideview_native.dll +0 -0
- sideview/widget.py +681 -0
- sideview-0.4.0.dist-info/METADATA +359 -0
- sideview-0.4.0.dist-info/RECORD +9 -0
- sideview-0.4.0.dist-info/WHEEL +5 -0
- sideview-0.4.0.dist-info/licenses/LICENSE +21 -0
sideview/widget.py
ADDED
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from contextlib import suppress
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from uuid import NAMESPACE_URL, uuid5
|
|
9
|
+
|
|
10
|
+
import shiboken6
|
|
11
|
+
from PySide6 import QtCore, QtGui, QtWidgets
|
|
12
|
+
|
|
13
|
+
from ._backend import NativeBackend, NativeCookie, NativeOptions, NativeWebViewError
|
|
14
|
+
|
|
15
|
+
DownloadPolicy = Callable[[str], bool]
|
|
16
|
+
MIN_ZOOM_FACTOR = 0.25
|
|
17
|
+
MAX_ZOOM_FACTOR = 5.0
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class _EventBridge(QtCore.QObject):
|
|
21
|
+
received = QtCore.Signal(int, str)
|
|
22
|
+
captureReceived = QtCore.Signal(int, bool, bytes, str)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class NativeWebView(QtWidgets.QWidget):
|
|
26
|
+
ready = QtCore.Signal()
|
|
27
|
+
navigationStarted = QtCore.Signal(str)
|
|
28
|
+
navigationFinished = QtCore.Signal(str)
|
|
29
|
+
navigationFailed = QtCore.Signal(str)
|
|
30
|
+
titleChanged = QtCore.Signal(str)
|
|
31
|
+
downloadRequested = QtCore.Signal(str)
|
|
32
|
+
newWindowRequested = QtCore.Signal(str)
|
|
33
|
+
scriptMessageReceived = QtCore.Signal(str)
|
|
34
|
+
contextMenuRequested = QtCore.Signal(dict)
|
|
35
|
+
captureCompleted = QtCore.Signal(int, bytes)
|
|
36
|
+
captureFailed = QtCore.Signal(int, str)
|
|
37
|
+
frameStreamFrame = QtCore.Signal(bytes)
|
|
38
|
+
frameStreamFailed = QtCore.Signal(str)
|
|
39
|
+
zoomFactorChanged = QtCore.Signal(float)
|
|
40
|
+
zoomFactorRequested = QtCore.Signal(float)
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
parent: QtWidgets.QWidget | None = None,
|
|
45
|
+
*,
|
|
46
|
+
url: str | None = None,
|
|
47
|
+
html: str | None = None,
|
|
48
|
+
session_id: str | None = None,
|
|
49
|
+
session_data_root: str | Path | None = None,
|
|
50
|
+
user_data_folder: str | None = None,
|
|
51
|
+
runtime_path: str | None = None,
|
|
52
|
+
transparent: bool = False,
|
|
53
|
+
) -> None:
|
|
54
|
+
super().__init__(parent)
|
|
55
|
+
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_NativeWindow, True)
|
|
56
|
+
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_DontCreateNativeAncestors, False)
|
|
57
|
+
self.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)
|
|
58
|
+
|
|
59
|
+
self._backend = NativeBackend()
|
|
60
|
+
self._handle = 0
|
|
61
|
+
self._created = False
|
|
62
|
+
self._native_ready = False
|
|
63
|
+
self._disposed = False
|
|
64
|
+
self._create_pending = False
|
|
65
|
+
self._creation_error: NativeWebViewError | None = None
|
|
66
|
+
self._foreign_window: QtGui.QWindow | None = None
|
|
67
|
+
self._native_container: QtWidgets.QWidget | None = None
|
|
68
|
+
self._native_surface_visible = True
|
|
69
|
+
self._lifecycle_parent: QtCore.QObject | None = None
|
|
70
|
+
self._pending_url = url
|
|
71
|
+
self._pending_html = html
|
|
72
|
+
self._pending_base_url: str | None = None
|
|
73
|
+
self._pending_cookies: list[NativeCookie] = []
|
|
74
|
+
self._pending_clear_cookies = False
|
|
75
|
+
self._pending_document_scripts: list[str] = []
|
|
76
|
+
self._pending_default_context_menu_enabled: bool | None = None
|
|
77
|
+
self._pending_devtools_enabled: bool | None = None
|
|
78
|
+
self._pending_zoom_factor: float | None = None
|
|
79
|
+
self._zoom_factor = 1.0
|
|
80
|
+
self._next_capture_request_id = 1
|
|
81
|
+
self._download_policy: DownloadPolicy | None = None
|
|
82
|
+
resolved_session_id = session_id or "default"
|
|
83
|
+
self._options = NativeOptions(
|
|
84
|
+
user_data_folder=user_data_folder
|
|
85
|
+
or self._session_data_folder(resolved_session_id, session_data_root),
|
|
86
|
+
runtime_path=runtime_path,
|
|
87
|
+
session_id=str(uuid5(NAMESPACE_URL, f"sideview:{resolved_session_id}")),
|
|
88
|
+
transparent=transparent,
|
|
89
|
+
)
|
|
90
|
+
self._bridge = _EventBridge(self)
|
|
91
|
+
self._bridge.received.connect(
|
|
92
|
+
self._handle_native_event, QtCore.Qt.ConnectionType.QueuedConnection
|
|
93
|
+
)
|
|
94
|
+
self._bridge.captureReceived.connect(
|
|
95
|
+
self._handle_capture_event, QtCore.Qt.ConnectionType.QueuedConnection
|
|
96
|
+
)
|
|
97
|
+
self._bind_parent_lifecycle()
|
|
98
|
+
|
|
99
|
+
def navigate(self, url: str) -> None:
|
|
100
|
+
if not self._created or not self._native_ready:
|
|
101
|
+
self._pending_url = url
|
|
102
|
+
self._pending_html = None
|
|
103
|
+
return
|
|
104
|
+
if not self._backend.navigate(self._handle, url):
|
|
105
|
+
raise NativeWebViewError(f"Failed to navigate to {url!r}.")
|
|
106
|
+
|
|
107
|
+
def set_html(self, html: str, base_url: str | None = None) -> None:
|
|
108
|
+
if not self._created or not self._native_ready:
|
|
109
|
+
self._pending_html = html
|
|
110
|
+
self._pending_url = None
|
|
111
|
+
self._pending_base_url = base_url
|
|
112
|
+
return
|
|
113
|
+
if not self._backend.set_html(self._handle, html, base_url):
|
|
114
|
+
raise NativeWebViewError("Failed to set HTML content.")
|
|
115
|
+
|
|
116
|
+
def reload(self) -> None:
|
|
117
|
+
self._require_created()
|
|
118
|
+
self._backend.reload(self._handle)
|
|
119
|
+
|
|
120
|
+
def go_back(self) -> None:
|
|
121
|
+
self._require_created()
|
|
122
|
+
self._backend.go_back(self._handle)
|
|
123
|
+
|
|
124
|
+
def go_forward(self) -> None:
|
|
125
|
+
self._require_created()
|
|
126
|
+
self._backend.go_forward(self._handle)
|
|
127
|
+
|
|
128
|
+
def eval_js(self, script: str) -> None:
|
|
129
|
+
self._require_created()
|
|
130
|
+
if not self._backend.eval_js(self._handle, script):
|
|
131
|
+
raise NativeWebViewError("Failed to evaluate JavaScript.")
|
|
132
|
+
|
|
133
|
+
def add_document_script(self, script: str) -> None:
|
|
134
|
+
"""Inject JavaScript at document creation for every future navigation."""
|
|
135
|
+
if not self._created or not self._native_ready:
|
|
136
|
+
self._pending_document_scripts.append(script)
|
|
137
|
+
return
|
|
138
|
+
if not self._backend.add_document_script(self._handle, script):
|
|
139
|
+
raise NativeWebViewError("Failed to add document script.")
|
|
140
|
+
|
|
141
|
+
def install_script_bridge(self) -> None:
|
|
142
|
+
"""Expose window.nativeWebView.postMessage(message) to page scripts."""
|
|
143
|
+
script = """
|
|
144
|
+
(() => {
|
|
145
|
+
if (window.nativeWebView && window.nativeWebView.postMessage) return;
|
|
146
|
+
window.nativeWebView = {
|
|
147
|
+
postMessage(message) {
|
|
148
|
+
const value = typeof message === "string" ? message : JSON.stringify(message);
|
|
149
|
+
if (window.chrome && window.chrome.webview) {
|
|
150
|
+
window.chrome.webview.postMessage(value);
|
|
151
|
+
} else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.nativeWebView) {
|
|
152
|
+
window.webkit.messageHandlers.nativeWebView.postMessage(value);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
})();
|
|
157
|
+
""".strip()
|
|
158
|
+
self.add_document_script(script)
|
|
159
|
+
if self._created and self._native_ready:
|
|
160
|
+
self.eval_js(script)
|
|
161
|
+
|
|
162
|
+
def install_context_menu_bridge(self) -> None:
|
|
163
|
+
"""Disable the native context menu and emit contextMenuRequested payloads."""
|
|
164
|
+
self.set_default_context_menu_enabled(False)
|
|
165
|
+
self.install_script_bridge()
|
|
166
|
+
script = """
|
|
167
|
+
document.addEventListener("contextmenu", function(event) {
|
|
168
|
+
event.preventDefault();
|
|
169
|
+
const target = event.target;
|
|
170
|
+
const anchor = target && target.closest ? target.closest("a[href]") : null;
|
|
171
|
+
const image = target && target.closest ? target.closest("img[src]") : null;
|
|
172
|
+
window.nativeWebView.postMessage({
|
|
173
|
+
type: "contextmenu",
|
|
174
|
+
x: event.clientX,
|
|
175
|
+
y: event.clientY,
|
|
176
|
+
href: anchor ? anchor.href : "",
|
|
177
|
+
src: image ? (image.currentSrc || image.src || "") : "",
|
|
178
|
+
text: target && target.innerText ? target.innerText.slice(0, 500) : ""
|
|
179
|
+
});
|
|
180
|
+
}, true);
|
|
181
|
+
""".strip()
|
|
182
|
+
self.add_document_script(script)
|
|
183
|
+
if self._created and self._native_ready:
|
|
184
|
+
self.eval_js(script)
|
|
185
|
+
|
|
186
|
+
def set_default_context_menu_enabled(self, enabled: bool) -> None:
|
|
187
|
+
if not self._created or not self._native_ready:
|
|
188
|
+
self._pending_default_context_menu_enabled = enabled
|
|
189
|
+
return
|
|
190
|
+
if not self._backend.set_default_context_menu_enabled(self._handle, enabled):
|
|
191
|
+
raise NativeWebViewError("Failed to update native context menu setting.")
|
|
192
|
+
|
|
193
|
+
def set_devtools_enabled(self, enabled: bool) -> None:
|
|
194
|
+
if not self._created or not self._native_ready:
|
|
195
|
+
self._pending_devtools_enabled = enabled
|
|
196
|
+
return
|
|
197
|
+
if not self._backend.set_devtools_enabled(self._handle, enabled):
|
|
198
|
+
raise NativeWebViewError("Failed to update devtools setting.")
|
|
199
|
+
|
|
200
|
+
def set_zoom_factor(self, factor: float) -> None:
|
|
201
|
+
factor = self._validated_zoom_factor(factor)
|
|
202
|
+
if not self._created or not self._native_ready:
|
|
203
|
+
self._pending_zoom_factor = factor
|
|
204
|
+
self._zoom_factor = factor
|
|
205
|
+
return
|
|
206
|
+
if not self._backend.set_zoom_factor(self._handle, factor):
|
|
207
|
+
raise NativeWebViewError("Failed to update native zoom factor.")
|
|
208
|
+
self._zoom_factor = factor
|
|
209
|
+
|
|
210
|
+
def zoom_factor(self) -> float:
|
|
211
|
+
if self._created and self._native_ready:
|
|
212
|
+
factor = self._backend.get_zoom_factor(self._handle)
|
|
213
|
+
if MIN_ZOOM_FACTOR <= factor <= MAX_ZOOM_FACTOR:
|
|
214
|
+
self._zoom_factor = factor
|
|
215
|
+
return self._zoom_factor
|
|
216
|
+
|
|
217
|
+
def set_native_surface_visible(self, visible: bool) -> None:
|
|
218
|
+
"""Show or hide only the embedded foreign surface on Linux.
|
|
219
|
+
|
|
220
|
+
The webview backend remains alive, so navigation, media state, and
|
|
221
|
+
off-screen snapshots are preserved while a Qt overlay covers it.
|
|
222
|
+
"""
|
|
223
|
+
self._native_surface_visible = bool(visible)
|
|
224
|
+
if self._native_container is not None:
|
|
225
|
+
self._native_container.setVisible(self._native_surface_visible)
|
|
226
|
+
|
|
227
|
+
def capture_frame(self) -> int:
|
|
228
|
+
"""Capture the visible webview viewport as PNG bytes.
|
|
229
|
+
|
|
230
|
+
Returns a request id. Listen to captureCompleted(request_id, bytes)
|
|
231
|
+
or captureFailed(request_id, error).
|
|
232
|
+
"""
|
|
233
|
+
return self._capture_png(0, 0, 0, 0)
|
|
234
|
+
|
|
235
|
+
def capture_frame_jpeg(self) -> int:
|
|
236
|
+
"""Capture the visible webview viewport as JPEG bytes.
|
|
237
|
+
|
|
238
|
+
This is intended for live projection where throughput matters more
|
|
239
|
+
than lossless still-image quality.
|
|
240
|
+
"""
|
|
241
|
+
self._require_created()
|
|
242
|
+
if not self._native_ready:
|
|
243
|
+
raise NativeWebViewError("Native webview is not ready for capture yet.")
|
|
244
|
+
|
|
245
|
+
request_id = self._next_capture_request_id
|
|
246
|
+
self._next_capture_request_id += 1
|
|
247
|
+
if not self._backend.capture_jpeg(self._handle, request_id):
|
|
248
|
+
raise NativeWebViewError("Failed to start native JPEG capture.")
|
|
249
|
+
return request_id
|
|
250
|
+
|
|
251
|
+
def capture_region(self, x: int, y: int, width: int, height: int) -> int:
|
|
252
|
+
"""Capture a viewport-relative region as PNG bytes.
|
|
253
|
+
|
|
254
|
+
Coordinates are in widget pixels, using a top-left origin.
|
|
255
|
+
"""
|
|
256
|
+
if width <= 0 or height <= 0:
|
|
257
|
+
raise ValueError("Capture region width and height must be greater than zero.")
|
|
258
|
+
return self._capture_png(x, y, width, height)
|
|
259
|
+
|
|
260
|
+
def start_frame_stream(
|
|
261
|
+
self,
|
|
262
|
+
*,
|
|
263
|
+
quality: int = 75,
|
|
264
|
+
max_width: int = 0,
|
|
265
|
+
max_height: int = 0,
|
|
266
|
+
every_nth_frame: int = 1,
|
|
267
|
+
) -> bool:
|
|
268
|
+
"""Start a native JPEG frame stream when the platform supports it.
|
|
269
|
+
|
|
270
|
+
Frames are emitted through frameStreamFrame(bytes). On unsupported
|
|
271
|
+
platforms this returns False so callers can use capture_frame_jpeg().
|
|
272
|
+
"""
|
|
273
|
+
self._require_created()
|
|
274
|
+
if not self._native_ready:
|
|
275
|
+
raise NativeWebViewError("Native webview is not ready for frame streaming yet.")
|
|
276
|
+
|
|
277
|
+
return self._backend.start_frame_stream(
|
|
278
|
+
self._handle,
|
|
279
|
+
int(quality),
|
|
280
|
+
int(max_width),
|
|
281
|
+
int(max_height),
|
|
282
|
+
int(every_nth_frame),
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
def stop_frame_stream(self) -> None:
|
|
286
|
+
if self._handle:
|
|
287
|
+
self._backend.stop_frame_stream(self._handle)
|
|
288
|
+
|
|
289
|
+
def set_download_policy(self, callback: DownloadPolicy | None) -> None:
|
|
290
|
+
"""Set a synchronous whitelist callback for native downloads.
|
|
291
|
+
|
|
292
|
+
Return True to allow the browser engine to continue the download.
|
|
293
|
+
Return False to cancel it so the application can handle the URL itself.
|
|
294
|
+
"""
|
|
295
|
+
self._download_policy = callback
|
|
296
|
+
if self._created:
|
|
297
|
+
self._backend.set_policy_callback(self._handle, self._handle_policy_request)
|
|
298
|
+
|
|
299
|
+
def set_cookie(
|
|
300
|
+
self,
|
|
301
|
+
*,
|
|
302
|
+
name: str,
|
|
303
|
+
value: str,
|
|
304
|
+
domain: str,
|
|
305
|
+
path: str = "/",
|
|
306
|
+
expires: float = 0,
|
|
307
|
+
secure: bool = False,
|
|
308
|
+
http_only: bool = False,
|
|
309
|
+
same_site: str = "lax",
|
|
310
|
+
) -> None:
|
|
311
|
+
cookie = NativeCookie(
|
|
312
|
+
name=name,
|
|
313
|
+
value=value,
|
|
314
|
+
domain=domain,
|
|
315
|
+
path=path,
|
|
316
|
+
expires=expires,
|
|
317
|
+
secure=secure,
|
|
318
|
+
http_only=http_only,
|
|
319
|
+
same_site=same_site,
|
|
320
|
+
)
|
|
321
|
+
if not self._created or not self._native_ready:
|
|
322
|
+
self._pending_cookies.append(cookie)
|
|
323
|
+
return
|
|
324
|
+
if not self._backend.set_cookie(self._handle, cookie):
|
|
325
|
+
raise NativeWebViewError(f"Failed to set cookie {name!r} for {domain!r}.")
|
|
326
|
+
|
|
327
|
+
def clear_cookies(self) -> None:
|
|
328
|
+
self._pending_cookies.clear()
|
|
329
|
+
if not self._created or not self._native_ready:
|
|
330
|
+
self._pending_clear_cookies = True
|
|
331
|
+
return
|
|
332
|
+
self._require_created()
|
|
333
|
+
if not self._backend.clear_cookies(self._handle):
|
|
334
|
+
raise NativeWebViewError("Failed to clear cookies.")
|
|
335
|
+
|
|
336
|
+
def can_go_back(self) -> bool:
|
|
337
|
+
return self._created and self._backend.can_go_back(self._handle)
|
|
338
|
+
|
|
339
|
+
def can_go_forward(self) -> bool:
|
|
340
|
+
return self._created and self._backend.can_go_forward(self._handle)
|
|
341
|
+
|
|
342
|
+
def showEvent(self, event: QtGui.QShowEvent) -> None: # type: ignore[name-defined]
|
|
343
|
+
super().showEvent(event)
|
|
344
|
+
self._schedule_ensure_created()
|
|
345
|
+
|
|
346
|
+
def event(self, event: QtCore.QEvent) -> bool:
|
|
347
|
+
if event.type() == QtCore.QEvent.Type.DeferredDelete:
|
|
348
|
+
self.dispose()
|
|
349
|
+
handled = super().event(event)
|
|
350
|
+
if event.type() == QtCore.QEvent.Type.ParentChange and hasattr(self, "_lifecycle_parent"):
|
|
351
|
+
self._bind_parent_lifecycle()
|
|
352
|
+
return handled
|
|
353
|
+
|
|
354
|
+
def resizeEvent(self, event: QtGui.QResizeEvent) -> None: # type: ignore[name-defined]
|
|
355
|
+
super().resizeEvent(event)
|
|
356
|
+
if self._created:
|
|
357
|
+
size = event.size()
|
|
358
|
+
self._backend.resize(self._handle, size.width(), size.height())
|
|
359
|
+
if self._native_container is not None:
|
|
360
|
+
self._native_container.setGeometry(self.rect())
|
|
361
|
+
elif self.isVisible():
|
|
362
|
+
self._schedule_ensure_created()
|
|
363
|
+
|
|
364
|
+
def closeEvent(self, event: QtGui.QCloseEvent) -> None: # type: ignore[name-defined]
|
|
365
|
+
self.dispose()
|
|
366
|
+
super().closeEvent(event)
|
|
367
|
+
|
|
368
|
+
def dispose(self) -> None:
|
|
369
|
+
if self._disposed:
|
|
370
|
+
return
|
|
371
|
+
self._disposed = True
|
|
372
|
+
self._create_pending = False
|
|
373
|
+
if self._handle:
|
|
374
|
+
self._backend.stop_frame_stream(self._handle)
|
|
375
|
+
self._destroy_native_container()
|
|
376
|
+
if self._handle:
|
|
377
|
+
self._backend.destroy(self._handle)
|
|
378
|
+
self._handle = 0
|
|
379
|
+
self._created = False
|
|
380
|
+
self._native_ready = False
|
|
381
|
+
|
|
382
|
+
def _schedule_ensure_created(self) -> None:
|
|
383
|
+
if self._created or self._disposed or self._create_pending or self._creation_error:
|
|
384
|
+
return
|
|
385
|
+
self._create_pending = True
|
|
386
|
+
QtCore.QTimer.singleShot(0, self._ensure_created_if_ready)
|
|
387
|
+
|
|
388
|
+
def _ensure_created_if_ready(self) -> None:
|
|
389
|
+
self._create_pending = False
|
|
390
|
+
if self._created or self._disposed or not self.isVisible():
|
|
391
|
+
return
|
|
392
|
+
if self.width() <= 0 or self.height() <= 0:
|
|
393
|
+
return
|
|
394
|
+
try:
|
|
395
|
+
self._ensure_created()
|
|
396
|
+
except NativeWebViewError as exc:
|
|
397
|
+
self._creation_error = exc
|
|
398
|
+
self.navigationFailed.emit(str(exc))
|
|
399
|
+
|
|
400
|
+
def _ensure_created(self) -> None:
|
|
401
|
+
if self._created:
|
|
402
|
+
return
|
|
403
|
+
if self._disposed:
|
|
404
|
+
raise NativeWebViewError("This native webview has already been disposed.")
|
|
405
|
+
if self._creation_error is not None:
|
|
406
|
+
raise self._creation_error
|
|
407
|
+
|
|
408
|
+
self._create_pending = False
|
|
409
|
+
self.ensurePolished()
|
|
410
|
+
width = max(1, self.width())
|
|
411
|
+
height = max(1, self.height())
|
|
412
|
+
|
|
413
|
+
if self._backend.uses_foreign_window:
|
|
414
|
+
qt_platform = QtGui.QGuiApplication.platformName().lower()
|
|
415
|
+
if qt_platform != "xcb":
|
|
416
|
+
raise NativeWebViewError(
|
|
417
|
+
"The Linux WebKitGTK backend requires Qt's X11/XCB platform. "
|
|
418
|
+
"On a Wayland desktop, start the application with QT_QPA_PLATFORM=xcb."
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
parent_handle = 0 if self._backend.uses_foreign_window else int(self.winId())
|
|
422
|
+
handle = self._backend.create(parent_handle, self._options, self._emit_native_event)
|
|
423
|
+
foreign_window: QtGui.QWindow | None = None
|
|
424
|
+
native_container: QtWidgets.QWidget | None = None
|
|
425
|
+
try:
|
|
426
|
+
if self._backend.uses_foreign_window:
|
|
427
|
+
native_view = self._backend.native_view(handle)
|
|
428
|
+
if not native_view:
|
|
429
|
+
raise NativeWebViewError(
|
|
430
|
+
"WebKitGTK did not expose an X11 window for embedding."
|
|
431
|
+
)
|
|
432
|
+
foreign_window = QtGui.QWindow.fromWinId(native_view)
|
|
433
|
+
if foreign_window is None:
|
|
434
|
+
raise NativeWebViewError("Qt could not wrap the WebKitGTK X11 window.")
|
|
435
|
+
native_container = QtWidgets.QWidget.createWindowContainer(
|
|
436
|
+
foreign_window,
|
|
437
|
+
self,
|
|
438
|
+
)
|
|
439
|
+
native_container.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)
|
|
440
|
+
native_container.setGeometry(self.rect())
|
|
441
|
+
native_container.setVisible(self._native_surface_visible)
|
|
442
|
+
self._foreign_window = foreign_window
|
|
443
|
+
self._native_container = native_container
|
|
444
|
+
self.setFocusProxy(native_container)
|
|
445
|
+
except Exception as exc:
|
|
446
|
+
self._destroy_foreign_window(native_container, foreign_window)
|
|
447
|
+
self._native_container = None
|
|
448
|
+
self._foreign_window = None
|
|
449
|
+
self.setFocusProxy(None)
|
|
450
|
+
self._backend.destroy(handle)
|
|
451
|
+
if isinstance(exc, NativeWebViewError):
|
|
452
|
+
raise
|
|
453
|
+
raise NativeWebViewError(f"Failed to embed the native webview window: {exc}") from exc
|
|
454
|
+
|
|
455
|
+
self._handle = handle
|
|
456
|
+
self._created = True
|
|
457
|
+
self._backend.set_policy_callback(self._handle, self._handle_policy_request)
|
|
458
|
+
self._backend.set_capture_callback(self._handle, self._emit_capture_event)
|
|
459
|
+
self._backend.resize(self._handle, width, height)
|
|
460
|
+
|
|
461
|
+
def _destroy_native_container(self) -> None:
|
|
462
|
+
self.setFocusProxy(None)
|
|
463
|
+
native_container = self._native_container
|
|
464
|
+
foreign_window = self._foreign_window
|
|
465
|
+
self._native_container = None
|
|
466
|
+
self._foreign_window = None
|
|
467
|
+
self._destroy_foreign_window(native_container, foreign_window)
|
|
468
|
+
|
|
469
|
+
def _bind_parent_lifecycle(self) -> None:
|
|
470
|
+
parent = self.parent()
|
|
471
|
+
if parent is self._lifecycle_parent:
|
|
472
|
+
return
|
|
473
|
+
if self._lifecycle_parent is not None:
|
|
474
|
+
with suppress(RuntimeError, TypeError):
|
|
475
|
+
self._lifecycle_parent.destroyed.disconnect(self._on_parent_destroyed)
|
|
476
|
+
self._lifecycle_parent = parent
|
|
477
|
+
if parent is not None:
|
|
478
|
+
parent.destroyed.connect(self._on_parent_destroyed)
|
|
479
|
+
|
|
480
|
+
def _on_parent_destroyed(self, *_args: object) -> None:
|
|
481
|
+
self._lifecycle_parent = None
|
|
482
|
+
self.dispose()
|
|
483
|
+
|
|
484
|
+
@staticmethod
|
|
485
|
+
def _destroy_foreign_window(
|
|
486
|
+
native_container: QtWidgets.QWidget | None,
|
|
487
|
+
foreign_window: QtGui.QWindow | None,
|
|
488
|
+
) -> None:
|
|
489
|
+
if native_container is not None and shiboken6.isValid(native_container):
|
|
490
|
+
# Qt may delete the native child while tearing down its parent.
|
|
491
|
+
with suppress(RuntimeError):
|
|
492
|
+
native_container.hide()
|
|
493
|
+
native_container.deleteLater()
|
|
494
|
+
elif foreign_window is not None and shiboken6.isValid(foreign_window):
|
|
495
|
+
with suppress(RuntimeError):
|
|
496
|
+
foreign_window.deleteLater()
|
|
497
|
+
|
|
498
|
+
def _require_created(self) -> None:
|
|
499
|
+
if not self._created:
|
|
500
|
+
self._ensure_created()
|
|
501
|
+
|
|
502
|
+
def _emit_native_event(self, event_type: int, message: str) -> None:
|
|
503
|
+
if (
|
|
504
|
+
self._backend.uses_foreign_window
|
|
505
|
+
and event_type
|
|
506
|
+
in {
|
|
507
|
+
NativeBackend.EVENT_ZOOM_FACTOR_CHANGED,
|
|
508
|
+
NativeBackend.EVENT_ZOOM_FACTOR_REQUESTED,
|
|
509
|
+
}
|
|
510
|
+
and QtCore.QThread.currentThread() == self.thread()
|
|
511
|
+
):
|
|
512
|
+
self._handle_native_event(event_type, message)
|
|
513
|
+
return
|
|
514
|
+
self._bridge.received.emit(event_type, message)
|
|
515
|
+
|
|
516
|
+
def _emit_capture_event(self, request_id: int, success: bool, data: bytes, error: str) -> None:
|
|
517
|
+
self._bridge.captureReceived.emit(request_id, success, data, error)
|
|
518
|
+
|
|
519
|
+
def _handle_native_event(self, event_type: int, message: str) -> None:
|
|
520
|
+
if self._disposed or not self._created:
|
|
521
|
+
return
|
|
522
|
+
if event_type == NativeBackend.EVENT_READY:
|
|
523
|
+
self._native_ready = True
|
|
524
|
+
self.ready.emit()
|
|
525
|
+
self._flush_pending_settings()
|
|
526
|
+
self._flush_pending_document_scripts()
|
|
527
|
+
self._flush_pending_clear_cookies()
|
|
528
|
+
self._flush_pending_cookies()
|
|
529
|
+
self._flush_pending_load()
|
|
530
|
+
elif event_type == NativeBackend.EVENT_NAVIGATION_STARTED:
|
|
531
|
+
self.navigationStarted.emit(message)
|
|
532
|
+
elif event_type == NativeBackend.EVENT_NAVIGATION_FINISHED:
|
|
533
|
+
self.navigationFinished.emit(message)
|
|
534
|
+
elif event_type == NativeBackend.EVENT_NAVIGATION_FAILED:
|
|
535
|
+
self.navigationFailed.emit(message)
|
|
536
|
+
elif event_type == NativeBackend.EVENT_TITLE_CHANGED:
|
|
537
|
+
self.titleChanged.emit(message)
|
|
538
|
+
elif event_type == NativeBackend.EVENT_DOWNLOAD_REQUESTED:
|
|
539
|
+
self.downloadRequested.emit(message)
|
|
540
|
+
elif event_type == NativeBackend.EVENT_NEW_WINDOW_REQUESTED:
|
|
541
|
+
self.newWindowRequested.emit(message)
|
|
542
|
+
elif event_type == NativeBackend.EVENT_SCRIPT_MESSAGE:
|
|
543
|
+
self.scriptMessageReceived.emit(message)
|
|
544
|
+
self._handle_script_message(message)
|
|
545
|
+
elif event_type == NativeBackend.EVENT_ZOOM_FACTOR_CHANGED:
|
|
546
|
+
try:
|
|
547
|
+
factor = self._validated_zoom_factor(float(message))
|
|
548
|
+
except (TypeError, ValueError):
|
|
549
|
+
return
|
|
550
|
+
changed = not math.isclose(
|
|
551
|
+
self._zoom_factor,
|
|
552
|
+
factor,
|
|
553
|
+
rel_tol=0.0,
|
|
554
|
+
abs_tol=1e-6,
|
|
555
|
+
)
|
|
556
|
+
self._zoom_factor = factor
|
|
557
|
+
if changed:
|
|
558
|
+
self.zoomFactorChanged.emit(factor)
|
|
559
|
+
elif event_type == NativeBackend.EVENT_ZOOM_FACTOR_REQUESTED:
|
|
560
|
+
try:
|
|
561
|
+
factor = self._validated_zoom_factor(float(message))
|
|
562
|
+
except (TypeError, ValueError):
|
|
563
|
+
return
|
|
564
|
+
if not math.isclose(
|
|
565
|
+
self._zoom_factor,
|
|
566
|
+
factor,
|
|
567
|
+
rel_tol=0.0,
|
|
568
|
+
abs_tol=1e-6,
|
|
569
|
+
):
|
|
570
|
+
self.set_zoom_factor(factor)
|
|
571
|
+
self.zoomFactorRequested.emit(factor)
|
|
572
|
+
|
|
573
|
+
def _handle_policy_request(self, event_type: int, message: str) -> bool:
|
|
574
|
+
if event_type == NativeBackend.EVENT_DOWNLOAD_REQUESTED:
|
|
575
|
+
return bool(self._download_policy and self._download_policy(message))
|
|
576
|
+
return False
|
|
577
|
+
|
|
578
|
+
def _flush_pending_load(self) -> None:
|
|
579
|
+
if self._pending_html is not None:
|
|
580
|
+
html = self._pending_html
|
|
581
|
+
base_url = self._pending_base_url
|
|
582
|
+
self._pending_html = None
|
|
583
|
+
self._pending_base_url = None
|
|
584
|
+
if not self._backend.set_html(self._handle, html, base_url):
|
|
585
|
+
self.navigationFailed.emit("Failed to set pending HTML content.")
|
|
586
|
+
elif self._pending_url is not None:
|
|
587
|
+
url = self._pending_url
|
|
588
|
+
self._pending_url = None
|
|
589
|
+
if not self._backend.navigate(self._handle, url):
|
|
590
|
+
self.navigationFailed.emit(f"Failed to navigate to {url!r}.")
|
|
591
|
+
|
|
592
|
+
def _flush_pending_cookies(self) -> None:
|
|
593
|
+
pending = self._pending_cookies
|
|
594
|
+
self._pending_cookies = []
|
|
595
|
+
for cookie in pending:
|
|
596
|
+
if not self._backend.set_cookie(self._handle, cookie):
|
|
597
|
+
self.navigationFailed.emit(f"Failed to set pending cookie {cookie.name!r}.")
|
|
598
|
+
|
|
599
|
+
def _flush_pending_clear_cookies(self) -> None:
|
|
600
|
+
if not self._pending_clear_cookies:
|
|
601
|
+
return
|
|
602
|
+
self._pending_clear_cookies = False
|
|
603
|
+
if not self._backend.clear_cookies(self._handle):
|
|
604
|
+
self.navigationFailed.emit("Failed to clear pending cookies.")
|
|
605
|
+
|
|
606
|
+
def _flush_pending_document_scripts(self) -> None:
|
|
607
|
+
pending = self._pending_document_scripts
|
|
608
|
+
self._pending_document_scripts = []
|
|
609
|
+
for script in pending:
|
|
610
|
+
if not self._backend.add_document_script(self._handle, script):
|
|
611
|
+
self.navigationFailed.emit("Failed to add pending document script.")
|
|
612
|
+
|
|
613
|
+
def _flush_pending_settings(self) -> None:
|
|
614
|
+
if self._pending_default_context_menu_enabled is not None:
|
|
615
|
+
enabled = self._pending_default_context_menu_enabled
|
|
616
|
+
self._pending_default_context_menu_enabled = None
|
|
617
|
+
if not self._backend.set_default_context_menu_enabled(self._handle, enabled):
|
|
618
|
+
self.navigationFailed.emit("Failed to apply context menu setting.")
|
|
619
|
+
if self._pending_devtools_enabled is not None:
|
|
620
|
+
enabled = self._pending_devtools_enabled
|
|
621
|
+
self._pending_devtools_enabled = None
|
|
622
|
+
if not self._backend.set_devtools_enabled(self._handle, enabled):
|
|
623
|
+
self.navigationFailed.emit("Failed to apply devtools setting.")
|
|
624
|
+
if self._pending_zoom_factor is not None:
|
|
625
|
+
factor = self._pending_zoom_factor
|
|
626
|
+
self._pending_zoom_factor = None
|
|
627
|
+
if not self._backend.set_zoom_factor(self._handle, factor):
|
|
628
|
+
self.navigationFailed.emit("Failed to apply native zoom factor.")
|
|
629
|
+
|
|
630
|
+
def _handle_script_message(self, message: str) -> None:
|
|
631
|
+
try:
|
|
632
|
+
payload = json.loads(message)
|
|
633
|
+
except json.JSONDecodeError:
|
|
634
|
+
return
|
|
635
|
+
if isinstance(payload, dict) and payload.get("type") == "contextmenu":
|
|
636
|
+
self.contextMenuRequested.emit(payload)
|
|
637
|
+
|
|
638
|
+
@staticmethod
|
|
639
|
+
def _validated_zoom_factor(factor: float) -> float:
|
|
640
|
+
factor = float(factor)
|
|
641
|
+
if not math.isfinite(factor) or not MIN_ZOOM_FACTOR <= factor <= MAX_ZOOM_FACTOR:
|
|
642
|
+
raise ValueError(
|
|
643
|
+
f"Zoom factor must be between {MIN_ZOOM_FACTOR} and {MAX_ZOOM_FACTOR}."
|
|
644
|
+
)
|
|
645
|
+
return factor
|
|
646
|
+
|
|
647
|
+
def _capture_png(self, x: int, y: int, width: int, height: int) -> int:
|
|
648
|
+
self._require_created()
|
|
649
|
+
if not self._native_ready:
|
|
650
|
+
raise NativeWebViewError("Native webview is not ready for capture yet.")
|
|
651
|
+
|
|
652
|
+
request_id = self._next_capture_request_id
|
|
653
|
+
self._next_capture_request_id += 1
|
|
654
|
+
if not self._backend.capture_png(self._handle, request_id, x, y, width, height):
|
|
655
|
+
raise NativeWebViewError("Failed to start native PNG capture.")
|
|
656
|
+
return request_id
|
|
657
|
+
|
|
658
|
+
def _handle_capture_event(
|
|
659
|
+
self, request_id: int, success: bool, data: bytes, error: str
|
|
660
|
+
) -> None:
|
|
661
|
+
if self._disposed or not self._created:
|
|
662
|
+
return
|
|
663
|
+
if request_id == 0:
|
|
664
|
+
if success:
|
|
665
|
+
self.frameStreamFrame.emit(data)
|
|
666
|
+
else:
|
|
667
|
+
self.frameStreamFailed.emit(error or "Native frame stream failed.")
|
|
668
|
+
return
|
|
669
|
+
|
|
670
|
+
if success:
|
|
671
|
+
self.captureCompleted.emit(request_id, data)
|
|
672
|
+
else:
|
|
673
|
+
self.captureFailed.emit(request_id, error or "Native capture failed.")
|
|
674
|
+
|
|
675
|
+
@staticmethod
|
|
676
|
+
def _session_data_folder(session_id: str, session_data_root: str | Path | None) -> str:
|
|
677
|
+
root = Path(session_data_root) if session_data_root else Path.home() / ".sideview"
|
|
678
|
+
safe_session = "".join(
|
|
679
|
+
ch if ch.isalnum() or ch in ("-", "_", ".") else "_" for ch in session_id
|
|
680
|
+
)
|
|
681
|
+
return str(root / "sessions" / safe_session)
|