| 1 |
""" |
| 2 |
(C) 2014-2019 Roman Sirokov and contributors |
| 3 |
Licensed under BSD license |
| 4 |
|
| 5 |
http://github.com/r0x0r/pywebview/ |
| 6 |
""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import inspect |
| 11 |
import json |
| 12 |
import logging |
| 13 |
import os |
| 14 |
import re |
| 15 |
import sys |
| 16 |
import traceback |
| 17 |
import urllib.parse |
| 18 |
from collections import UserDict |
| 19 |
from glob import glob |
| 20 |
from http.cookies import SimpleCookie |
| 21 |
from platform import architecture |
| 22 |
from threading import Thread |
| 23 |
from typing import TYPE_CHECKING, Any |
| 24 |
from uuid import uuid4 |
| 25 |
|
| 26 |
import webview |
| 27 |
from webview.dom import _dnd_state |
| 28 |
from webview.errors import WebViewException |
| 29 |
|
| 30 |
if TYPE_CHECKING: |
| 31 |
from webview.window import Window |
| 32 |
|
| 33 |
_TOKEN = uuid4().hex |
| 34 |
|
| 35 |
DEFAULT_HTML = """ |
| 36 |
<!doctype html> |
| 37 |
<html> |
| 38 |
<head> |
| 39 |
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0"> |
| 40 |
</head> |
| 41 |
<body></body> |
| 42 |
</html> |
| 43 |
""" |
| 44 |
|
| 45 |
logger = logging.getLogger('pywebview') |
| 46 |
|
| 47 |
|
| 48 |
class ImmutableDict(UserDict): |
| 49 |
""" " |
| 50 |
A dictionary that does not allow adding new keys or deleting existing ones. |
| 51 |
Only existing keys can be modified. |
| 52 |
""" |
| 53 |
|
| 54 |
def __init__(self, initial_data=None, **kwargs): |
| 55 |
self.data = {} |
| 56 |
if initial_data: |
| 57 |
self.data.update(initial_data) |
| 58 |
if kwargs: |
| 59 |
self.data.update(kwargs) |
| 60 |
|
| 61 |
def __setitem__(self, key, value): |
| 62 |
if key not in self.data: |
| 63 |
raise KeyError(f"Cannot add new key '{key}'. Only existing keys can be modified.") |
| 64 |
super().__setitem__(key, value) |
| 65 |
|
| 66 |
def __delitem__(self, key): |
| 67 |
raise KeyError('Deleting keys is not allowed.') |
| 68 |
|
| 69 |
|
| 70 |
def is_app(url: str | callable | None) -> bool: |
| 71 |
"""Returns true if 'url' is a WSGI or ASGI app.""" |
| 72 |
return callable(url) |
| 73 |
|
| 74 |
|
| 75 |
def is_local_url(url: str | callable | None) -> bool: |
| 76 |
return not ( |
| 77 |
(is_app(url)) |
| 78 |
or ( |
| 79 |
(not url) |
| 80 |
or (url.startswith('http://')) |
| 81 |
or (url.startswith('https://')) |
| 82 |
or url.startswith('file://') |
| 83 |
) |
| 84 |
) |
| 85 |
|
| 86 |
|
| 87 |
def needs_server(urls: list[str]) -> bool: |
| 88 |
return bool([url for url in urls if (is_app(url) or is_local_url(url))]) |
| 89 |
|
| 90 |
|
| 91 |
def get_app_root() -> str: |
| 92 |
""" |
| 93 |
Gets the file root of the application. |
| 94 |
""" |
| 95 |
|
| 96 |
if hasattr(sys, '_MEIPASS'): # Pyinstaller |
| 97 |
return sys._MEIPASS |
| 98 |
|
| 99 |
if os.getenv('RESOURCEPATH'): # py2app |
| 100 |
return os.getenv('RESOURCEPATH') |
| 101 |
|
| 102 |
if getattr(sys, 'frozen', False): # cx_freeze |
| 103 |
return os.path.dirname(sys.executable) |
| 104 |
|
| 105 |
if 'pytest' in sys.modules and os.getenv('PYWEBVIEW_TEST'): |
| 106 |
return os.path.join(os.path.dirname(__file__), '..', 'tests') |
| 107 |
|
| 108 |
if hasattr(sys, 'getandroidapilevel'): |
| 109 |
return os.getenv('ANDROID_APP_PATH') |
| 110 |
|
| 111 |
return os.path.dirname(os.path.realpath(sys.argv[0])) |
| 112 |
|
| 113 |
|
| 114 |
def abspath(path: str) -> str: |
| 115 |
""" |
| 116 |
Make path absolute, using the application root |
| 117 |
""" |
| 118 |
path = os.fspath(path) |
| 119 |
if not os.path.isabs(path): |
| 120 |
path = os.path.join(get_app_root(), path) |
| 121 |
return os.path.normpath(path) |
| 122 |
|
| 123 |
|
| 124 |
def base_uri(relative_path: str = '') -> str: |
| 125 |
"""Get absolute path to resource, works for dev and for PyInstaller""" |
| 126 |
base_path = get_app_root() |
| 127 |
if not os.path.exists(base_path): |
| 128 |
raise ValueError(f'Path {base_path} does not exist') |
| 129 |
|
| 130 |
return f'file://{os.path.join(base_path, relative_path)}' |
| 131 |
|
| 132 |
|
| 133 |
def create_cookie(input_: dict[Any, Any] | str) -> SimpleCookie[str]: |
| 134 |
if isinstance(input_, dict): |
| 135 |
cookie = SimpleCookie() |
| 136 |
name = input_['name'] |
| 137 |
cookie[name] = input_['value'] |
| 138 |
cookie[name]['path'] = input_['path'] |
| 139 |
cookie[name]['domain'] = input_['domain'] |
| 140 |
cookie[name]['expires'] = input_['expires'] |
| 141 |
cookie[name]['secure'] = input_['secure'] |
| 142 |
cookie[name]['httponly'] = input_['httponly'] |
| 143 |
|
| 144 |
if sys.version_info.major >= 3 and sys.version_info.minor >= 8: |
| 145 |
cookie[name]['samesite'] = input_.get('samesite') |
| 146 |
|
| 147 |
return cookie |
| 148 |
|
| 149 |
if isinstance(input_, str): |
| 150 |
return SimpleCookie(input_) |
| 151 |
|
| 152 |
raise WebViewException('Unknown input to create_cookie') |
| 153 |
|
| 154 |
|
| 155 |
def parse_file_type(file_type: str) -> tuple[str, str]: |
| 156 |
""" |
| 157 |
:param file_type: file type string 'description (*.file_extension1;*.file_extension2)' as required by file filter in create_file_dialog |
| 158 |
:return: (description, file extensions) tuple |
| 159 |
""" |
| 160 |
valid_file_filter = r'^([\w ]+)\((\*(?:\.(?:\w+|\*))*(?:;\*(?:\.(?:\w+|\*))*)*)\)$' |
| 161 |
match = re.search(valid_file_filter, file_type) |
| 162 |
|
| 163 |
if match: |
| 164 |
return match.group(1).rstrip(), match.group(2) |
| 165 |
raise ValueError(f'{file_type} is not a valid file filter') |
| 166 |
|
| 167 |
|
| 168 |
def inject_pywebview(platform: str, window: Window) -> str: |
| 169 |
""" " |
| 170 |
Generates and injects a global window.pywebview object. The object contains exposed API functions |
| 171 |
as well as utility functions required by pywebview. The function fires before_load event before |
| 172 |
injecting the object and loaded event after the object is injected. |
| 173 |
""" |
| 174 |
exposed_objects = [] |
| 175 |
|
| 176 |
def get_args(func: object): |
| 177 |
params = list(inspect.getfullargspec(func).args) |
| 178 |
return params |
| 179 |
|
| 180 |
def get_functions(obj: object, base_name: str = '', functions: dict[str, object] = None): |
| 181 |
obj_id = id(obj) |
| 182 |
if obj_id in exposed_objects: |
| 183 |
return functions |
| 184 |
else: |
| 185 |
exposed_objects.append(obj_id) |
| 186 |
|
| 187 |
if functions is None: |
| 188 |
functions = {} |
| 189 |
|
| 190 |
for name in dir(obj): |
| 191 |
try: |
| 192 |
full_name = f'{base_name}.{name}' if base_name else name |
| 193 |
if name.startswith('_'): |
| 194 |
continue |
| 195 |
|
| 196 |
attr = getattr(obj, name) |
| 197 |
if not getattr(attr, '_serializable', True): |
| 198 |
continue |
| 199 |
|
| 200 |
if inspect.ismethod(attr) or inspect.isfunction(attr): |
| 201 |
functions[full_name] = get_args(attr)[1:] |
| 202 |
# If the attribute is a class or a non-callable object, make a recursive call |
| 203 |
elif inspect.isclass(attr) or ( |
| 204 |
isinstance(attr, object) and not callable(attr) and hasattr(attr, '__module__') |
| 205 |
): |
| 206 |
get_functions(attr, full_name, functions) |
| 207 |
except Exception as e: |
| 208 |
logger.error(f'Error while processing {full_name}: {e}') |
| 209 |
continue |
| 210 |
|
| 211 |
return functions |
| 212 |
|
| 213 |
def generate_func(): |
| 214 |
functions = get_functions(window._js_api) |
| 215 |
|
| 216 |
if len(window._functions) > 0: |
| 217 |
expose_functions = {name: get_args(f) for name, f in window._functions.items()} |
| 218 |
else: |
| 219 |
expose_functions = {} |
| 220 |
|
| 221 |
functions.update(expose_functions) |
| 222 |
|
| 223 |
return [{'func': name, 'params': params} for name, params in functions.items()] |
| 224 |
|
| 225 |
def generate_js_object(): |
| 226 |
window.run_js(js_code) |
| 227 |
logger.debug('_pywebviewready event fired') |
| 228 |
|
| 229 |
try: |
| 230 |
with window._expose_lock: |
| 231 |
func_list = generate_func() |
| 232 |
window.run_js(finish_script % {'functions': json.dumps(func_list)}) |
| 233 |
window.events._pywebviewready.set() |
| 234 |
window.events.loaded.set() |
| 235 |
logger.debug('loaded event fired') |
| 236 |
except Exception as e: |
| 237 |
logger.exception(e) |
| 238 |
window.events.loaded.set() |
| 239 |
|
| 240 |
window.events.before_load.set() |
| 241 |
logger.debug('before_load event fired. injecting pywebview object') |
| 242 |
js_code, finish_script = load_js_files(window, platform) |
| 243 |
thread = Thread(target=generate_js_object) |
| 244 |
thread.start() |
| 245 |
|
| 246 |
|
| 247 |
def js_bridge_call(window: Window, func_name: str, param: Any, value_id: str) -> None: |
| 248 |
""" |
| 249 |
Calls a function from the JS API and executes it in Python. The function is executed in a separate |
| 250 |
thread to prevent blocking the UI thread. The result is then passed back to the JS API. |
| 251 |
""" |
| 252 |
|
| 253 |
def _call(): |
| 254 |
try: |
| 255 |
result = func(*func_params) |
| 256 |
result = json.dumps(result).replace('\\', '\\\\').replace("'", "\\'") |
| 257 |
retval = f"{{value: '{result}'}}" |
| 258 |
except Exception as e: |
| 259 |
logger.error(traceback.format_exc()) |
| 260 |
error = {'message': str(e), 'name': type(e).__name__, 'stack': traceback.format_exc()} |
| 261 |
result = json.dumps(error).replace('\\', '\\\\').replace("'", "\\'") |
| 262 |
retval = f"{{isError: true, value: '{result}'}}" |
| 263 |
|
| 264 |
window.evaluate_js( |
| 265 |
f'window.pywebview._returnValuesCallbacks["{func_name}"]["{value_id}"]({retval})' |
| 266 |
) |
| 267 |
|
| 268 |
def get_nested_attribute(obj: object, attr_str: str): |
| 269 |
attributes = attr_str.split('.') |
| 270 |
for attr in attributes: |
| 271 |
obj = getattr(obj, attr, None) |
| 272 |
if obj is None: |
| 273 |
return None |
| 274 |
return obj |
| 275 |
|
| 276 |
if func_name == 'pywebviewMoveWindow': |
| 277 |
window.move(*param) |
| 278 |
return |
| 279 |
|
| 280 |
if func_name == 'pywebviewEventHandler': |
| 281 |
event = param['event'] |
| 282 |
node_id = param['nodeId'] |
| 283 |
element = window.dom._elements.get(node_id) |
| 284 |
|
| 285 |
if not element: |
| 286 |
return |
| 287 |
|
| 288 |
if event['type'] == 'drop': |
| 289 |
files = event['dataTransfer'].get('files', []) |
| 290 |
for file in files: |
| 291 |
path = [ |
| 292 |
item |
| 293 |
for item in _dnd_state['paths'] |
| 294 |
if urllib.parse.unquote(item[0]) == file['name'] |
| 295 |
] |
| 296 |
if len(path) == 0: |
| 297 |
continue |
| 298 |
|
| 299 |
file['pywebviewFullPath'] = urllib.parse.unquote(path[0][1]) |
| 300 |
_dnd_state['paths'].remove(path[0]) |
| 301 |
|
| 302 |
for handler in element._event_handlers.get(event['type'], []): |
| 303 |
thread = Thread(target=handler, args=(event,)) |
| 304 |
thread.start() |
| 305 |
|
| 306 |
return |
| 307 |
|
| 308 |
if func_name == 'pywebviewAsyncCallback': |
| 309 |
value = json.loads(param) if param is not None else None |
| 310 |
|
| 311 |
if callable(window._callbacks[value_id]): |
| 312 |
window._callbacks[value_id](value) |
| 313 |
else: |
| 314 |
logger.error( |
| 315 |
f'Async function executed and callback is not callable. Returned value {value}' |
| 316 |
) |
| 317 |
|
| 318 |
del window._callbacks[value_id] |
| 319 |
return |
| 320 |
|
| 321 |
if func_name == 'pywebviewStateUpdate': |
| 322 |
window.state.__setattr__(param['key'], param['value'], False) |
| 323 |
return |
| 324 |
|
| 325 |
if func_name == 'pywebviewStateDelete': |
| 326 |
special_key = '__pywebviewHaltUpdate__' + param |
| 327 |
delattr(window.state, special_key) |
| 328 |
return |
| 329 |
|
| 330 |
func = window._functions.get(func_name) or get_nested_attribute(window._js_api, func_name) |
| 331 |
|
| 332 |
if func is not None: |
| 333 |
try: |
| 334 |
func_params = param |
| 335 |
thread = Thread(target=_call) |
| 336 |
thread.start() |
| 337 |
except Exception: |
| 338 |
logger.exception('Error occurred while evaluating function %s', func_name) |
| 339 |
else: |
| 340 |
logger.error('Function %s() does not exist', func_name) |
| 341 |
|
| 342 |
|
| 343 |
def load_js_files(window: Window, platform: str) -> str: |
| 344 |
""" |
| 345 |
Load JS files in the order they should be loaded. |
| 346 |
The order is polyfill, api, the rest and finish.js. |
| 347 |
Return the concatenated JS code and the finish script, which must be loaded last and |
| 348 |
separately in order to |
| 349 |
""" |
| 350 |
js_dir = get_js_dir() |
| 351 |
logger.debug('Loading JS files from %s', js_dir) |
| 352 |
js_files = glob(os.path.join(js_dir, '**', '*.js'), recursive=True) |
| 353 |
ordered_js_files = sort_js_files(js_files) |
| 354 |
js_code = '' |
| 355 |
finish_script = '' |
| 356 |
|
| 357 |
for file in ordered_js_files: |
| 358 |
with open(file) as f: |
| 359 |
name = os.path.splitext(os.path.basename(file))[0] |
| 360 |
content = f.read() |
| 361 |
params = {} |
| 362 |
|
| 363 |
if name == 'api': |
| 364 |
params = { |
| 365 |
'token': _TOKEN, |
| 366 |
'platform': platform, |
| 367 |
'uid': window.uid, |
| 368 |
'js_api_endpoint': window.js_api_endpoint, |
| 369 |
} |
| 370 |
elif name == 'customize': |
| 371 |
params = { |
| 372 |
'text_select': str(window.text_select), |
| 373 |
'drag_selector': webview.settings['DRAG_REGION_SELECTOR'], |
| 374 |
'drag_region_direct_target_only': str( |
| 375 |
webview.settings['DRAG_REGION_DIRECT_TARGET_ONLY'] |
| 376 |
), |
| 377 |
'zoomable': str(window.zoomable), |
| 378 |
'draggable': str(window.draggable), |
| 379 |
'easy_drag': str( |
| 380 |
platform == 'edgechromium' and window.easy_drag and window.frameless |
| 381 |
), |
| 382 |
} |
| 383 |
elif name == 'state': |
| 384 |
params = {'state': json.dumps(window.state)} |
| 385 |
elif name == 'finish': |
| 386 |
finish_script = content |
| 387 |
continue |
| 388 |
elif name == 'polyfill' and platform != 'mshtml': |
| 389 |
continue |
| 390 |
|
| 391 |
js_code += content % params |
| 392 |
|
| 393 |
return js_code, finish_script |
| 394 |
|
| 395 |
|
| 396 |
def get_js_dir() -> str: |
| 397 |
""" |
| 398 |
Get the path to the directory with Javascript files. |
| 399 |
""" |
| 400 |
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'js') |
| 401 |
|
| 402 |
if os.path.exists(path): |
| 403 |
return path |
| 404 |
|
| 405 |
# try py2app frozen path. This is hacky, but it works. |
| 406 |
# See https://github.com/r0x0r/pywebview/issues/1565 |
| 407 |
if '.zip' in path: |
| 408 |
base_path = path.split('.zip')[0] |
| 409 |
dir = os.path.dirname(base_path) |
| 410 |
|
| 411 |
for file in os.listdir(dir): |
| 412 |
if file.startswith('python') and os.path.isdir(os.path.join(dir, file)): |
| 413 |
js_path = os.path.join(dir, file, 'webview', 'js') |
| 414 |
if os.path.exists(js_path): |
| 415 |
return js_path |
| 416 |
|
| 417 |
raise FileNotFoundError(f'Cannot find JS directory in {path}') |
| 418 |
|
| 419 |
|
| 420 |
def sort_js_files(js_files: list[str]) -> list[str]: |
| 421 |
""" |
| 422 |
Sorts JS files in the order they should be loaded. Polyfill first, then API, then the rest and |
| 423 |
finally finish.js that fires a pywebviewready event. |
| 424 |
""" |
| 425 |
LOAD_ORDER = {'polyfill': 0, 'api': 1, 'state': 2} |
| 426 |
|
| 427 |
ordered_js_files = [] |
| 428 |
remaining_js_files = [] |
| 429 |
|
| 430 |
for file in js_files: |
| 431 |
basename = os.path.splitext(os.path.basename(file))[0] |
| 432 |
if basename not in LOAD_ORDER: |
| 433 |
ordered_js_files.append(file) |
| 434 |
else: |
| 435 |
remaining_js_files.append((basename, file)) |
| 436 |
|
| 437 |
for basename, file in sorted(remaining_js_files, key=lambda x: LOAD_ORDER[x[0]]): |
| 438 |
ordered_js_files.insert(LOAD_ORDER[basename], file) |
| 439 |
|
| 440 |
return ordered_js_files |
| 441 |
|
| 442 |
|
| 443 |
def escape_string(string: str) -> str: |
| 444 |
return ( |
| 445 |
string.replace('\\', '\\\\') |
| 446 |
.replace('"', r'\"') |
| 447 |
.replace('\n', r'\n') |
| 448 |
.replace('\r', r'\r') |
| 449 |
.replace("'", r'\'') |
| 450 |
) |
| 451 |
|
| 452 |
|
| 453 |
def inject_base_uri(content: str, base_uri: str) -> str: |
| 454 |
pattern = r'<%s(?:[\s]+[^>]*|)>' |
| 455 |
base_tag = f'<base href="{base_uri}">' |
| 456 |
|
| 457 |
match = re.search(pattern % 'base', content) |
| 458 |
|
| 459 |
if match: |
| 460 |
return content |
| 461 |
|
| 462 |
match = re.search(pattern % 'head', content) |
| 463 |
if match: |
| 464 |
tag = match.group() |
| 465 |
return content.replace(tag, tag + base_tag) |
| 466 |
|
| 467 |
match = re.search(pattern % 'html', content) |
| 468 |
if match: |
| 469 |
tag = match.group() |
| 470 |
return content.replace(tag, tag + base_tag) |
| 471 |
|
| 472 |
match = re.search(pattern % 'body', content) |
| 473 |
if match: |
| 474 |
tag = match.group() |
| 475 |
return content.replace(tag, base_tag + tag) |
| 476 |
|
| 477 |
return base_tag + content |
| 478 |
|
| 479 |
|
| 480 |
def interop_dll_path(dll_name: str) -> str: |
| 481 |
if dll_name == 'WebBrowserInterop.dll': |
| 482 |
dll_name = ( |
| 483 |
'WebBrowserInterop.x64.dll' |
| 484 |
if architecture()[0] == '64bit' |
| 485 |
else 'WebBrowserInterop.x86.dll' |
| 486 |
) |
| 487 |
|
| 488 |
# Unfrozen path |
| 489 |
dll_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib', dll_name) |
| 490 |
if os.path.exists(dll_path): |
| 491 |
return dll_path |
| 492 |
|
| 493 |
dll_path = os.path.join( |
| 494 |
os.path.dirname(os.path.realpath(__file__)), 'lib', 'runtimes', dll_name, 'native' |
| 495 |
) |
| 496 |
if os.path.exists(dll_path): |
| 497 |
return dll_path |
| 498 |
|
| 499 |
# Frozen path, dll in the same dir as the executable |
| 500 |
dll_path = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), dll_name) |
| 501 |
if os.path.exists(dll_path): |
| 502 |
return dll_path |
| 503 |
|
| 504 |
try: |
| 505 |
# Frozen path packed as onefile |
| 506 |
if hasattr(sys, '_MEIPASS'): # Pyinstaller |
| 507 |
dll_path = os.path.join(sys._MEIPASS, dll_name) |
| 508 |
|
| 509 |
elif getattr(sys, 'frozen', False): # cx_freeze |
| 510 |
dll_path = os.path.join(sys.executable, dll_name) |
| 511 |
|
| 512 |
if os.path.exists(dll_path): |
| 513 |
return dll_path |
| 514 |
except Exception: |
| 515 |
pass |
| 516 |
|
| 517 |
raise FileNotFoundError(f'Cannot find {dll_name}') |
| 518 |
|
| 519 |
|
| 520 |
def environ_append(key: str, *values: str, sep=' ') -> None: |
| 521 |
"""Append values to an environment variable, separated by sep""" |
| 522 |
values = list(values) |
| 523 |
|
| 524 |
existing = os.environ.get(key, '') |
| 525 |
if existing: |
| 526 |
values = [existing] + values |
| 527 |
|
| 528 |
os.environ[key] = sep.join(values) |
| 529 |
|
| 530 |
|
| 531 |
def css_to_camel(css_case_string: str) -> str: |
| 532 |
words = css_case_string.split('-') |
| 533 |
camel_case_string = words[0] + ''.join(word.capitalize() for word in words[1:]) |
| 534 |
return camel_case_string |
| 535 |
|
| 536 |
|
| 537 |
def android_jar_path() -> str: |
| 538 |
return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib', 'pywebview-android.jar') |
| 539 |
|
| 540 |
|
| 541 |
def stringify_headers(headers: dict[str, Any]) -> dict[str, str]: |
| 542 |
return {k: str(v) for k, v in headers.items()} |