| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import inspect |
| 4 |
import logging |
| 5 |
import os |
| 6 |
from collections.abc import Mapping, Sequence |
| 7 |
from enum import Flag, auto |
| 8 |
from functools import wraps |
| 9 |
from threading import Lock |
| 10 |
from typing import Any, Callable, TypeVar |
| 11 |
from urllib.parse import urljoin |
| 12 |
from uuid import uuid1 |
| 13 |
|
| 14 |
from typing_extensions import Concatenate, ParamSpec, TypeAlias |
| 15 |
|
| 16 |
import webview.http as http |
| 17 |
from webview.dom.dom import DOM |
| 18 |
from webview.errors import JavascriptException, WebViewException |
| 19 |
from webview.event import Event, EventContainer |
| 20 |
from webview.localization import original_localization |
| 21 |
from webview.menu import Menu |
| 22 |
from webview.screen import Screen |
| 23 |
from webview.state import State |
| 24 |
from webview.util import base_uri, escape_string, is_app, is_local_url, parse_file_type |
| 25 |
|
| 26 |
P = ParamSpec('P') |
| 27 |
T = TypeVar('T') |
| 28 |
|
| 29 |
logger = logging.getLogger('pywebview') |
| 30 |
|
| 31 |
|
| 32 |
def _api_call(function: WindowFunc[P, T], event_type: str) -> WindowFunc[P, T]: |
| 33 |
""" |
| 34 |
Decorator to call a pywebview API, checking for _webview_ready and raisings |
| 35 |
appropriate Exceptions on failure. |
| 36 |
""" |
| 37 |
|
| 38 |
@wraps(function) |
| 39 |
def wrapper(self: Window, *args: P.args, **kwargs: P.kwargs) -> T: |
| 40 |
event = getattr(self.events, event_type) |
| 41 |
|
| 42 |
try: |
| 43 |
if not event.wait(20): |
| 44 |
raise WebViewException('Main window failed to start') |
| 45 |
|
| 46 |
if self.gui is None: |
| 47 |
raise WebViewException('GUI is not initialized') |
| 48 |
|
| 49 |
return function(self, *args, **kwargs) |
| 50 |
except NameError: |
| 51 |
raise WebViewException('Create a web view window first, before invoking this function') |
| 52 |
|
| 53 |
return wrapper |
| 54 |
|
| 55 |
|
| 56 |
def _shown_call(function: Callable[P, T]) -> Callable[P, T]: |
| 57 |
return _api_call(function, 'shown') |
| 58 |
|
| 59 |
|
| 60 |
def _loaded_call(function: Callable[P, T]) -> Callable[P, T]: |
| 61 |
return _api_call(function, 'loaded') |
| 62 |
|
| 63 |
|
| 64 |
def _before_load_call(function: Callable[P, T]) -> Callable[P, T]: |
| 65 |
return _api_call(function, 'before_load') |
| 66 |
|
| 67 |
|
| 68 |
def _pywebview_ready_call(function: Callable[P, T]) -> Callable[P, T]: |
| 69 |
return _api_call(function, '_pywebviewready') |
| 70 |
|
| 71 |
|
| 72 |
class FixPoint(Flag): |
| 73 |
NORTH = auto() |
| 74 |
WEST = auto() |
| 75 |
EAST = auto() |
| 76 |
SOUTH = auto() |
| 77 |
|
| 78 |
|
| 79 |
class Window: |
| 80 |
def __init__( |
| 81 |
self, |
| 82 |
uid: str, |
| 83 |
title: str, |
| 84 |
url: str | None, |
| 85 |
html: str = '', |
| 86 |
width: int = 800, |
| 87 |
height: int = 600, |
| 88 |
x: int | None = None, |
| 89 |
y: int | None = None, |
| 90 |
resizable: bool = True, |
| 91 |
fullscreen: bool = False, |
| 92 |
min_size: tuple[int, int] = (200, 100), |
| 93 |
hidden: bool = False, |
| 94 |
frameless: bool = False, |
| 95 |
easy_drag: bool = True, |
| 96 |
shadow: bool = True, |
| 97 |
focus: bool = True, |
| 98 |
minimized: bool = False, |
| 99 |
maximized: bool = False, |
| 100 |
on_top: bool = False, |
| 101 |
confirm_close: bool = False, |
| 102 |
background_color: str = '#FFFFFF', |
| 103 |
js_api: Any = None, |
| 104 |
text_select: bool = False, |
| 105 |
transparent: bool = False, |
| 106 |
zoomable: bool = False, |
| 107 |
draggable: bool = False, |
| 108 |
vibrancy: bool = False, |
| 109 |
menu: list[Menu] = [], |
| 110 |
localization: Mapping[str, str] | None = None, |
| 111 |
http_port: int | None = None, |
| 112 |
server: type[http.ServerType] | None = None, |
| 113 |
server_args: http.ServerArgs = {}, |
| 114 |
screen: Screen = None, |
| 115 |
) -> None: |
| 116 |
self.uid = uid |
| 117 |
self._title = title |
| 118 |
self.original_url = None if html else url # original URL provided by user |
| 119 |
self.real_url = None |
| 120 |
self.html = html |
| 121 |
self.initial_width = width |
| 122 |
self.initial_height = height |
| 123 |
self.initial_x = x |
| 124 |
self.initial_y = y |
| 125 |
self.resizable = resizable |
| 126 |
self.fullscreen = fullscreen |
| 127 |
self.min_size = min_size |
| 128 |
self.confirm_close = confirm_close |
| 129 |
self.background_color = background_color |
| 130 |
self.text_select = text_select |
| 131 |
self.frameless = frameless |
| 132 |
self.easy_drag = easy_drag |
| 133 |
self.shadow = shadow |
| 134 |
self.focus = focus |
| 135 |
self.hidden = hidden |
| 136 |
self.on_top = on_top |
| 137 |
self.minimized = minimized |
| 138 |
self.maximized = maximized |
| 139 |
self.transparent = transparent |
| 140 |
self.zoomable = zoomable |
| 141 |
self.draggable = draggable |
| 142 |
self.localization_override = localization |
| 143 |
self.vibrancy = vibrancy |
| 144 |
self.screen = screen |
| 145 |
self.menu = menu |
| 146 |
|
| 147 |
# Server config |
| 148 |
self._http_port = http_port |
| 149 |
self._server = server |
| 150 |
self._server_args = server_args |
| 151 |
|
| 152 |
# HTTP server path magic |
| 153 |
self._url_prefix = None |
| 154 |
self._common_path = None |
| 155 |
self._server = None |
| 156 |
|
| 157 |
self._js_api = js_api |
| 158 |
self._functions: dict[str, Callable[..., Any]] = {} |
| 159 |
self._callbacks: dict[str, Callable[..., Any] | None] = {} |
| 160 |
|
| 161 |
self.events = EventContainer() |
| 162 |
self.events.closed = Event(self) |
| 163 |
self.events.closing = Event(self, True) |
| 164 |
self.events.loaded = Event(self) |
| 165 |
self.events.before_load = Event(self, True) |
| 166 |
self.events.before_show = Event(self, True) |
| 167 |
self.events.initialized = Event(self, True) |
| 168 |
self.events.shown = Event(self) |
| 169 |
self.events.minimized = Event(self) |
| 170 |
self.events.maximized = Event(self) |
| 171 |
self.events.restored = Event(self) |
| 172 |
self.events.resized = Event(self) |
| 173 |
self.events.moved = Event(self) |
| 174 |
self.events.request_sent = Event(self) |
| 175 |
self.events.response_received = Event(self) |
| 176 |
|
| 177 |
self.events._pywebviewready = Event(self) |
| 178 |
|
| 179 |
self._expose_lock = Lock() |
| 180 |
self.dom = DOM(self) |
| 181 |
self.gui = None |
| 182 |
self.native = None # set in the gui after window creation |
| 183 |
self._state = State(self) |
| 184 |
|
| 185 |
def _initialize( |
| 186 |
self, gui, server: http.BottleServer | None = None, server_args: http.ServerArgs = dict |
| 187 |
): |
| 188 |
self.gui = gui |
| 189 |
|
| 190 |
self.localization = original_localization.copy() |
| 191 |
if self.localization_override: |
| 192 |
self.localization.update(self.localization_override) |
| 193 |
|
| 194 |
if is_app(self.original_url) and (server is None or server == http.global_server): |
| 195 |
*_, server = http.start_server( |
| 196 |
urls=[self.original_url], |
| 197 |
http_port=self._http_port, |
| 198 |
server=self._server, |
| 199 |
**(self._server_args or server_args), |
| 200 |
) |
| 201 |
elif server is None: |
| 202 |
server = http.global_server |
| 203 |
|
| 204 |
self._url_prefix = server.address if server is not None else None |
| 205 |
self._common_path = server.common_path if server is not None else None |
| 206 |
self._server = server |
| 207 |
self.js_api_endpoint = ( |
| 208 |
http.global_server.js_api_endpoint if http.global_server is not None else None |
| 209 |
) |
| 210 |
self.real_url = self._resolve_url(self.original_url) |
| 211 |
|
| 212 |
abort = self.events.initialized.set(gui.renderer) |
| 213 |
return not abort |
| 214 |
|
| 215 |
@property |
| 216 |
def width(self) -> int: |
| 217 |
self.events.shown.wait(15) |
| 218 |
width, _ = self.gui.get_size(self.uid) |
| 219 |
return width |
| 220 |
|
| 221 |
@property |
| 222 |
def height(self) -> int: |
| 223 |
self.events.shown.wait(15) |
| 224 |
_, height = self.gui.get_size(self.uid) |
| 225 |
return height |
| 226 |
|
| 227 |
@property |
| 228 |
def state(self) -> State: |
| 229 |
return self._state |
| 230 |
|
| 231 |
@state.setter |
| 232 |
def state(self, state: State) -> None: |
| 233 |
if not isinstance(state, State): |
| 234 |
raise TypeError('State must be an instance of State class') |
| 235 |
self._state = state |
| 236 |
|
| 237 |
@property |
| 238 |
def title(self) -> str: |
| 239 |
return self._title |
| 240 |
|
| 241 |
@title.setter |
| 242 |
def title(self, title: str) -> None: |
| 243 |
self.events.loaded.wait(15) |
| 244 |
self._title = title |
| 245 |
self.gui.set_title(title, self.uid) |
| 246 |
|
| 247 |
@property |
| 248 |
def x(self) -> int: |
| 249 |
self.events.shown.wait(15) |
| 250 |
x, _ = self.gui.get_position(self.uid) |
| 251 |
return x |
| 252 |
|
| 253 |
@property |
| 254 |
def y(self) -> int: |
| 255 |
self.events.shown.wait(15) |
| 256 |
_, y = self.gui.get_position(self.uid) |
| 257 |
return y |
| 258 |
|
| 259 |
@property |
| 260 |
def on_top(self) -> bool: |
| 261 |
return self.__on_top |
| 262 |
|
| 263 |
@on_top.setter |
| 264 |
def on_top(self, on_top: bool) -> None: |
| 265 |
self.__on_top = on_top |
| 266 |
if hasattr(self, 'gui') and self.gui is not None: |
| 267 |
self.gui.set_on_top(self.uid, on_top) |
| 268 |
|
| 269 |
@_shown_call |
| 270 |
def load_url(self, url: str) -> None: |
| 271 |
""" |
| 272 |
Load a new URL into a previously created WebView window. This function must be invoked after WebView windows is |
| 273 |
created with create_window(). Otherwise an exception is thrown. |
| 274 |
:param url: url to load |
| 275 |
:param uid: uid of the target instance |
| 276 |
""" |
| 277 |
if ((self._server is None) or (not self._server.running)) and ( |
| 278 |
is_app(url) or is_local_url(url) |
| 279 |
): |
| 280 |
self._url_prefix, self._common_path, self.server = http.start_server([url]) |
| 281 |
|
| 282 |
self.real_url = self._resolve_url(url) |
| 283 |
self.events.loaded.clear() |
| 284 |
self.events.before_load.clear() |
| 285 |
self.events._pywebviewready.clear() |
| 286 |
|
| 287 |
logger.debug(f'Loading URL: {self.real_url}') |
| 288 |
self.gui.load_url(self.real_url, self.uid) |
| 289 |
|
| 290 |
@_shown_call |
| 291 |
def load_html(self, html: str, base_uri: str = base_uri()) -> None: |
| 292 |
""" |
| 293 |
Load a new HTML content into a previously created WebView window. This function must be invoked after WebView windows is |
| 294 |
created with create_window(). Otherwise an exception is thrown. |
| 295 |
:param html: HTML content to load. |
| 296 |
:param base_uri: Base URI for resolving links. Default is the directory of the application entry point. |
| 297 |
""" |
| 298 |
self.events.loaded.clear() |
| 299 |
self.events.before_load.clear() |
| 300 |
self.events._pywebviewready.clear() |
| 301 |
logger.debug(f'Loading HTML: {html[:30]}') |
| 302 |
self.gui.load_html(html, base_uri, self.uid) |
| 303 |
|
| 304 |
@_loaded_call |
| 305 |
def load_css(self, stylesheet: str) -> None: |
| 306 |
""" " |
| 307 |
Load a CSS stylesheet into the current web view window |
| 308 |
""" |
| 309 |
sanitized_css = stylesheet.replace('\n', '').replace('\r', '').replace('"', "'") |
| 310 |
js_code = f'pywebview._loadCss("{sanitized_css}")' |
| 311 |
self.run_js(js_code) |
| 312 |
|
| 313 |
@_shown_call |
| 314 |
def set_title(self, title: str) -> None: |
| 315 |
""" |
| 316 |
Set a new title of the window |
| 317 |
""" |
| 318 |
self._title = title |
| 319 |
self.gui.set_title(title, self.uid) |
| 320 |
|
| 321 |
@_loaded_call |
| 322 |
def clear_cookies(self): |
| 323 |
""" |
| 324 |
Clear all the cookies |
| 325 |
""" |
| 326 |
return self.gui.clear_cookies(self.uid) |
| 327 |
|
| 328 |
@_loaded_call |
| 329 |
def get_cookies(self): |
| 330 |
""" |
| 331 |
Get cookies for the current website |
| 332 |
""" |
| 333 |
return self.gui.get_cookies(self.uid) |
| 334 |
|
| 335 |
@_loaded_call |
| 336 |
def get_current_url(self) -> str | None: |
| 337 |
""" |
| 338 |
Get the URL currently loaded in the target webview |
| 339 |
""" |
| 340 |
return self.gui.get_current_url(self.uid) |
| 341 |
|
| 342 |
@_shown_call |
| 343 |
def destroy(self) -> None: |
| 344 |
""" |
| 345 |
Destroy a web view window |
| 346 |
""" |
| 347 |
self.gui.destroy_window(self.uid) |
| 348 |
|
| 349 |
@_shown_call |
| 350 |
def show(self) -> None: |
| 351 |
""" |
| 352 |
Show a web view window. |
| 353 |
""" |
| 354 |
self.gui.show(self.uid) |
| 355 |
|
| 356 |
@_shown_call |
| 357 |
def hide(self) -> None: |
| 358 |
""" |
| 359 |
Hide a web view window. |
| 360 |
""" |
| 361 |
self.gui.hide(self.uid) |
| 362 |
|
| 363 |
@_shown_call |
| 364 |
def set_window_size(self, width: int, height: int) -> None: |
| 365 |
""" |
| 366 |
Resize window |
| 367 |
:param width: desired width of target window |
| 368 |
:param height: desired height of target window |
| 369 |
""" |
| 370 |
logger.warning( |
| 371 |
'This function is deprecated and will be removed in future releases. Use resize() instead' |
| 372 |
) |
| 373 |
self.resize(width, height) |
| 374 |
|
| 375 |
@_shown_call |
| 376 |
def resize( |
| 377 |
self, width: int, height: int, fix_point: FixPoint = FixPoint.NORTH | FixPoint.WEST |
| 378 |
) -> None: |
| 379 |
""" |
| 380 |
Resize window |
| 381 |
:param width: desired width of target window |
| 382 |
:param height: desired height of target window |
| 383 |
:param fix_point: Fix window to specified point during resize. |
| 384 |
Must be of type FixPoint. Different points can be combined |
| 385 |
with bitwise operators. |
| 386 |
Example: FixPoint.NORTH | FixPoint.WEST |
| 387 |
""" |
| 388 |
self.gui.resize(width, height, self.uid, fix_point) |
| 389 |
|
| 390 |
@_shown_call |
| 391 |
def maximize(self) -> None: |
| 392 |
""" |
| 393 |
Maximize window. |
| 394 |
""" |
| 395 |
self.gui.maximize(self.uid) |
| 396 |
|
| 397 |
@_shown_call |
| 398 |
def minimize(self) -> None: |
| 399 |
""" |
| 400 |
Minimize window. |
| 401 |
""" |
| 402 |
self.gui.minimize(self.uid) |
| 403 |
|
| 404 |
@_shown_call |
| 405 |
def restore(self) -> None: |
| 406 |
""" |
| 407 |
Restore minimized window. |
| 408 |
""" |
| 409 |
self.gui.restore(self.uid) |
| 410 |
|
| 411 |
@_shown_call |
| 412 |
def toggle_fullscreen(self) -> None: |
| 413 |
""" |
| 414 |
Toggle fullscreen mode |
| 415 |
""" |
| 416 |
self.gui.toggle_fullscreen(self.uid) |
| 417 |
|
| 418 |
@_shown_call |
| 419 |
def move(self, x: int, y: int) -> None: |
| 420 |
""" |
| 421 |
Move Window |
| 422 |
:param x: desired x coordinate of target window |
| 423 |
:param y: desired y coordinate of target window |
| 424 |
""" |
| 425 |
self.gui.move(x, y, self.uid) |
| 426 |
|
| 427 |
@_before_load_call |
| 428 |
def run_js(self, script: str) -> Any: |
| 429 |
""" |
| 430 |
Run JavaScript code as is without any modifications. Result of the code is |
| 431 |
not guaranteed to be returned and depends on the platform |
| 432 |
:param script: JavaScript code to run |
| 433 |
""" |
| 434 |
return self.gui.evaluate_js(script, self.uid, False) |
| 435 |
|
| 436 |
@_pywebview_ready_call |
| 437 |
def evaluate_js(self, script: str, callback: Callable[..., Any] | None = None) -> Any: |
| 438 |
""" |
| 439 |
Evaluate given JavaScript code and return the result. The code is executed in eval statement |
| 440 |
in order to support returning the last evaluated value in the script without the return statement. |
| 441 |
Promises are supported and resolved values are returned to the callback function. |
| 442 |
Exceptions are caught and rethrown as JavascriptException in Python code. Javascript code is |
| 443 |
evaluated synchronously and the result is returned to the caller. |
| 444 |
:param script: The JavaScript code to be evaluated |
| 445 |
:callback: Optional callback function that will be called for resolved promises |
| 446 |
:return: Return value of the evaluated code |
| 447 |
|
| 448 |
""" |
| 449 |
unique_id = uuid1().hex |
| 450 |
self._callbacks[unique_id] = callback |
| 451 |
|
| 452 |
if self.gui.renderer == 'cef': |
| 453 |
return_result = ( |
| 454 |
f'window.external.return_result(pywebview.stringify(value), "{unique_id}");' |
| 455 |
) |
| 456 |
elif self.gui.renderer == 'android-webkit': |
| 457 |
return_result = 'return pywebview.stringify(value);' |
| 458 |
else: |
| 459 |
return_result = 'pywebview.stringify(value);' |
| 460 |
|
| 461 |
if callback: |
| 462 |
escaped_script = f""" |
| 463 |
var value = eval("{escape_string(script)}"); |
| 464 |
if (pywebview._isPromise(value)) {{ |
| 465 |
value.then(function evaluate_async(result) {{ |
| 466 |
pywebview._asyncCallback(pywebview.stringify(result), "{unique_id}") |
| 467 |
}}).catch(function evaluate_async(error) {{ |
| 468 |
pywebview._asyncCallback(pywebview.stringify(error), "{unique_id}") |
| 469 |
}}); |
| 470 |
"true"; |
| 471 |
}} else {{ {return_result} }} |
| 472 |
""" |
| 473 |
else: |
| 474 |
escaped_script = f""" |
| 475 |
var value; |
| 476 |
try {{ |
| 477 |
value = eval("{escape_string(script)}"); |
| 478 |
}} catch (e) {{ |
| 479 |
value = {{ |
| 480 |
name: e.name, |
| 481 |
pywebviewJavascriptError420: true, |
| 482 |
}} |
| 483 |
var keys = Object.getOwnPropertyNames(e); |
| 484 |
keys.forEach(function(key) {{ value[key] = e[key] }}) |
| 485 |
}} |
| 486 |
{return_result}; |
| 487 |
""" |
| 488 |
|
| 489 |
if self.gui.renderer == 'cef': |
| 490 |
result = self.gui.evaluate_js(escaped_script, self.uid, True, unique_id) |
| 491 |
elif self.gui.renderer == 'android-webkit': |
| 492 |
escaped_script = f""" |
| 493 |
(function() {{ |
| 494 |
{escaped_script} |
| 495 |
}})() |
| 496 |
""" |
| 497 |
result = self.gui.evaluate_js(escaped_script, self.uid, True) |
| 498 |
else: |
| 499 |
result = self.gui.evaluate_js(escaped_script, self.uid, True) |
| 500 |
|
| 501 |
if isinstance(result, dict) and result.get('pywebviewJavascriptError420'): |
| 502 |
del result['pywebviewJavascriptError420'] |
| 503 |
raise JavascriptException(result) |
| 504 |
else: |
| 505 |
return result |
| 506 |
|
| 507 |
@_shown_call |
| 508 |
def create_confirmation_dialog(self, title: str, message: str) -> bool: |
| 509 |
""" |
| 510 |
Create a confirmation dialog |
| 511 |
:param title: Dialog title |
| 512 |
:param message: Dialog detail message |
| 513 |
:return: True for OK, False for Cancel |
| 514 |
""" |
| 515 |
|
| 516 |
return self.gui.create_confirmation_dialog(title, message, self.uid) |
| 517 |
|
| 518 |
@_shown_call |
| 519 |
def create_file_dialog( |
| 520 |
self, |
| 521 |
dialog_type: int = 10, |
| 522 |
directory: str = '', |
| 523 |
allow_multiple: bool = False, |
| 524 |
save_filename: str = '', |
| 525 |
file_types: Sequence[str] = tuple(), |
| 526 |
) -> Sequence[str] | None: |
| 527 |
""" |
| 528 |
Create a file dialog |
| 529 |
:param dialog_type: Dialog type: open file (FileDialog.OPEN), save file (FileDialog.SAVE), open folder (FileDialog.FOLDER). Default |
| 530 |
is open file. |
| 531 |
:param directory: Initial directory |
| 532 |
:param allow_multiple: Allow multiple selection. Default is false. |
| 533 |
:param save_filename: Default filename for save file dialog. |
| 534 |
:param file_types: Allowed file types in open file dialog. Should be a tuple of strings in the format: |
| 535 |
filetypes = ('Description (*.extension[;*.extension[;...]])', ...) |
| 536 |
:return: A tuple of selected files, None if cancelled. |
| 537 |
""" |
| 538 |
for f in file_types: |
| 539 |
parse_file_type(f) |
| 540 |
|
| 541 |
if not os.path.exists(directory): |
| 542 |
directory = '' |
| 543 |
|
| 544 |
return self.gui.create_file_dialog( |
| 545 |
dialog_type, directory, allow_multiple, save_filename, file_types, self.uid |
| 546 |
) |
| 547 |
|
| 548 |
def expose(self, *functions: Callable[..., Any]) -> None: |
| 549 |
if not all(map(callable, functions)): |
| 550 |
raise TypeError('Parameter must be a function') |
| 551 |
|
| 552 |
func_list: list[dict[str, Any]] = [] |
| 553 |
|
| 554 |
with self._expose_lock: |
| 555 |
for func in functions: |
| 556 |
name = func.__name__ |
| 557 |
self._functions[name] = func |
| 558 |
params = list(inspect.getfullargspec(func).args) |
| 559 |
func_list.append({'func': name, 'params': params}) |
| 560 |
|
| 561 |
if self.events.loaded.is_set(): |
| 562 |
self.run_js(f'window.pywebview._createApi({func_list})') |
| 563 |
|
| 564 |
def _resolve_url(self, url: str) -> str | None: |
| 565 |
if is_app(url): |
| 566 |
return self._url_prefix |
| 567 |
if is_local_url(url) and self._url_prefix and self._common_path is not None: |
| 568 |
filename = os.path.relpath(url, self._common_path) |
| 569 |
return urljoin(self._url_prefix, filename) |
| 570 |
else: |
| 571 |
return url |
| 572 |
|
| 573 |
|
| 574 |
WindowFunc: TypeAlias = Callable[Concatenate[Window, P], T] |