Debian Codegraph @

tests/android/webview/__init__.py

raw
1 """
2 pywebview is a lightweight cross-platform wrapper around a webview component that allows to display HTML content in its
3 own dedicated window. Works on Windows, OS X and Linux and compatible with Python 2 and 3.
4
5 (C) 2014-2019 Roman Sirokov and contributors
6 Licensed under BSD license
7
8 http://github.com/r0x0r/pywebview/
9 """
10
11 from __future__ import annotations
12
13 import datetime
14 import enum
15 import logging
16 import os
17 import re
18 import tempfile
19 import threading
20 from collections.abc import Iterable, Mapping
21 from typing import Any, Callable
22 from uuid import uuid4
23
24 import webview.http as http
25 from webview.errors import JavascriptException, WebViewException
26 from webview.event import Event
27 from webview.guilib import GUIType, initialize
28 from webview.localization import original_localization
29 from webview.menu import Menu
30 from webview.screen import Screen
31 from webview.util import _TOKEN, ImmutableDict, abspath, is_app, is_local_url
32 from webview.window import Window
33
34 __all__ = (
35 # Stuff that's here
36 'active_window',
37 'start',
38 'create_window',
39 'token',
40 'renderer',
41 'screens',
42 'settings',
43 # From event
44 'Event',
45 # from util '
46 'JavascriptException',
47 'WebViewException',
48 # from screen
49 'Screen',
50 # from window
51 'Window',
52 )
53
54
55 def _setup_logger():
56 """Setup logger with console handler and appropriate log level."""
57
58 logger = logging.getLogger('pywebview')
59
60 # Avoid duplicate setup
61 if logger.handlers:
62 return logger
63
64 # Create and configure handler
65 handler = logging.StreamHandler()
66 formatter = logging.Formatter('[pywebview] %(message)s')
67 handler.setFormatter(formatter)
68 logger.addHandler(handler)
69
70 # Set log level from environment variable with validation
71 log_level_name = os.environ.get('PYWEBVIEW_LOG', 'INFO').upper()
72 try:
73 log_level = getattr(logging, log_level_name)
74 logger.setLevel(log_level)
75 except AttributeError:
76 # Fallback to INFO if invalid level specified
77 logger.setLevel(logging.INFO)
78 logger.warning(f"Invalid log level '{log_level_name}', using INFO instead")
79
80 return logger
81
82
83 logger = _setup_logger()
84
85
86 def OPEN_DIALOG():
87 logger.warning(
88 "OPEN_DIALOG is deprecated and will be removed in a future version. Use 'FileDialog.OPEN' instead."
89 )
90 return 10
91
92
93 def FOLDER_DIALOG():
94 logger.warning(
95 "FOLDER_DIALOG is deprecated and will be removed in a future version. Use 'FileDialog.FOLDER' instead."
96 )
97 return 20
98
99
100 def SAVE_DIALOG():
101 logger.warning(
102 "SAVE_DIALOG is deprecated and will be removed in a future version. Use 'FileDialog.SAVE' instead."
103 )
104 return 30
105
106
107 class FileDialog(enum.IntEnum):
108 OPEN = 10
109 FOLDER = 20
110 SAVE = 30
111
112
113 settings = ImmutableDict(
114 {
115 'ALLOW_DOWNLOADS': False,
116 'ALLOW_FILE_URLS': True,
117 'DRAG_REGION_SELECTOR': '.pywebview-drag-region',
118 'DRAG_REGION_DIRECT_TARGET_ONLY': False,
119 'DEFAULT_HTTP_PORT': 42001,
120 'OPEN_EXTERNAL_LINKS_IN_BROWSER': True,
121 'OPEN_DEVTOOLS_IN_DEBUG': True,
122 'REMOTE_DEBUGGING_PORT': None,
123 'IGNORE_SSL_ERRORS': False,
124 'SHOW_DEFAULT_MENUS': True,
125 'WEBVIEW2_RUNTIME_PATH': None,
126 }
127 )
128
129
130 _state = ImmutableDict(
131 {
132 'debug': False,
133 'storage_path': None,
134 'private_mode': True,
135 'user_agent': None,
136 'http_server': False,
137 'ssl': False,
138 'icon': None,
139 'menu': None,
140 }
141 )
142
143
144 def DRAG_REGION_SELECTOR():
145 logger.warning(
146 'DRAG_REGION_SELECTOR is deprecated and will be removed in a future version. Use \'settings["DRAG_REGION_SELECTOR"]\' instead.'
147 )
148 return settings['DRAG_REGION_SELECTOR']
149
150
151 guilib = None
152
153 token = _TOKEN
154 windows: list[Window] = []
155 renderer: str | None = None
156
157
158 def start(
159 func: Callable[..., None] | None = None,
160 args: Iterable[Any] | None = None,
161 localization: dict[str, str] = {},
162 gui: GUIType | None = None,
163 debug: bool = False,
164 http_server: bool = False,
165 http_port: int | None = None,
166 user_agent: str | None = None,
167 private_mode: bool = True,
168 storage_path: str | None = None,
169 menu: list[Menu] = [],
170 server: type[http.ServerType] = http.BottleServer,
171 server_args: dict[Any, Any] = {},
172 ssl: bool = False,
173 icon: str | None = None,
174 ):
175 """
176 Start a GUI loop and display previously created windows. This function must
177 be called from a main thread.
178
179 :param func: Function to invoke upon starting the GUI loop.
180 :param args: Function arguments. Can be either a single value or a tuple of
181 values.
182 :param localization: A dictionary with localized strings. Default strings
183 and their keys are defined in localization.py.
184 :param gui: Force a specific GUI. Allowed values are ``cef``, ``qt``,
185 ``gtk``, ``mshtml`` or ``edgechromium`` depending on a platform.
186 :param debug: Enable debug mode. Default is False.
187 :param http_server: Enable built-in HTTP server. If enabled, local files
188 will be served using a local HTTP server on a random port. For each
189 window, a separate HTTP server is spawned. This option is ignored for
190 non-local URLs.
191 :param user_agent: Change user agent string.
192 :param private_mode: Enable private mode. In private mode, cookies and local storage are not preserved.
193 Default is True.
194 :param storage_path: Custom location for cookies and other website data
195 :param menu: List of menus to be included in the app menu
196 :param server: Server class. Defaults to BottleServer
197 :param server_args: Dictionary of arguments to pass through to the server instantiation
198 :param ssl: Enable SSL for local HTTP server. Default is False.
199 :param icon: Path to the icon file. Supported only on GTK/QT.
200 """
201 global guilib, renderer
202
203 def _create_children(other_windows):
204 if not windows[0].events.shown.wait(10):
205 raise WebViewException('Main window failed to load')
206
207 for window in other_windows:
208 guilib.create_window(window)
209
210 _state['debug'] = debug
211 _state['user_agent'] = user_agent
212 _state['http_server'] = http_server
213 _state['private_mode'] = private_mode
214
215 if icon:
216 _state['icon'] = abspath(icon)
217
218 if storage_path:
219 __set_storage_path(storage_path)
220
221 if debug and not os.environ.get('PYWEBVIEW_LOG'):
222 logger.setLevel(logging.DEBUG)
223
224 if (
225 _state['storage_path']
226 and _state['private_mode']
227 and not os.path.exists(_state['storage_path'])
228 ):
229 os.makedirs(_state['storage_path'])
230
231 original_localization.update(localization)
232
233 if threading.current_thread().name != 'MainThread':
234 raise WebViewException('pywebview must be run on a main thread.')
235
236 if len(windows) == 0:
237 raise WebViewException('You must create a window first before calling this function.')
238
239 if menu:
240 _state['menu'] = menu
241
242 guilib = initialize(gui)
243 renderer = guilib.renderer
244
245 if ssl:
246 if not server_args or 'keyfile' not in server_args or 'certfile' not in server_args:
247 # generate SSL certs and tell the windows to use them
248 keyfile, certfile = __generate_ssl_cert()
249 server_args['keyfile'] = keyfile
250 server_args['certfile'] = certfile
251 else:
252 keyfile = server_args['keyfile']
253 certfile = server_args['certfile']
254 if not os.path.exists(keyfile):
255 raise WebViewException(f'The {keyfile} does not exist.')
256 if not os.path.exists(certfile):
257 raise WebViewException(f'The {certfile} does not exist.')
258
259 _state['ssl'] = True
260 else:
261 keyfile, certfile = None, None
262 server_args.pop('keyfile', None)
263 server_args.pop('certfile', None)
264
265 urls = [w.original_url for w in windows]
266 has_local_urls = not not [w.original_url for w in windows if is_local_url(w.original_url)]
267 # start the global server if it's not running and we need it
268 if (http.global_server is None) and (http_server or has_local_urls):
269 if not _state['private_mode'] and not http_port:
270 http_port = settings['DEFAULT_HTTP_PORT']
271 *_, server = http.start_global_server(
272 http_port=http_port, urls=urls, server=server, **server_args
273 )
274
275 for window in windows:
276 should_initialize = not window._initialize(guilib, server_args=server_args)
277 if should_initialize:
278 return
279
280 if ssl:
281 for window in windows:
282 window.gui.add_tls_cert(certfile)
283
284 if len(windows) > 1:
285 thread = threading.Thread(target=_create_children, args=(windows[1:],))
286 thread.start()
287
288 if func:
289 if args is not None:
290 if not hasattr(args, '__iter__'):
291 args = (args,)
292 thread = threading.Thread(target=func, args=args)
293 else:
294 thread = threading.Thread(target=func)
295 thread.start()
296
297 guilib.create_window(windows[0])
298 # keyfile is deleted by the ServerAdapter right after wrap_socket()
299 if certfile:
300 os.unlink(certfile)
301
302
303 def create_window(
304 title: str,
305 url: str | callable | None = None,
306 html: str | None = None,
307 js_api: Any = None,
308 width: int = 800,
309 height: int = 600,
310 x: int | None = None,
311 y: int | None = None,
312 screen: Screen | None = None,
313 resizable: bool = True,
314 fullscreen: bool = False,
315 min_size: tuple[int, int] = (200, 100),
316 hidden: bool = False,
317 frameless: bool = False,
318 easy_drag: bool = True,
319 shadow: bool = True,
320 focus: bool = True,
321 minimized: bool = False,
322 maximized: bool = False,
323 on_top: bool = False,
324 confirm_close: bool = False,
325 background_color: str = '#FFFFFF',
326 transparent: bool = False,
327 text_select: bool = False,
328 zoomable: bool = False,
329 draggable: bool = False,
330 vibrancy: bool = False,
331 menu: list[Menu] = [],
332 localization: Mapping[str, str] | None = None,
333 server: type[http.ServerType] = http.BottleServer,
334 http_port: int | None = None,
335 server_args: http.ServerArgs = {},
336 ) -> Window | None:
337 """
338 Create a web view window using a native GUI. The execution blocks after this function is invoked, so other
339 program logic must be executed in a separate thread.
340 :param title: Window title
341 :param url: URL or WSGI/ASGI app to load
342 :param html: HTML content to load
343 :param width: window width. Default is 800px
344 :param height: window height. Default is 600px
345 :param screen: Screen to display the window on.
346 :param resizable: True if window can be resized, False otherwise. Default is True
347 :param fullscreen: True if start in fullscreen mode. Default is False
348 :param min_size: a (width, height) tuple that specifies a minimum window size. Default is 200x100
349 :param hidden: Whether the window should be hidden.
350 :param frameless: Whether the window should have a frame.
351 :param easy_drag: Easy window drag mode when window is frameless.
352 :param shadow: Whether the window should have a frame border (shadows and Windows rounded edges).
353 :param focus: Whether to activate the window when user opens it. Window can be controlled with mouse but keyboard input will go to another (active) window and not this one.
354 :param minimized: Display window minimized
355 :param maximized: Display window maximized
356 :param on_top: Keep window above other windows (required OS: Windows)
357 :param confirm_close: Display a window close confirmation dialog. Default is False
358 :param background_color: Background color as a hex string that is displayed before the content of webview is loaded. Default is white.
359 :param text_select: Allow text selection on page. Default is False.
360 :param transparent: Don't draw window background.
361 :param menu: List of menus to be included in the window menu
362 :param server: Server class. Defaults to BottleServer
363 :param server_args: Dictionary of arguments to pass through to the server instantiation
364 :return: window object or None if window initialization is cancelled in the window.events.initialized event
365 """
366
367 valid_color = r'^#(?:[0-9a-fA-F]{3}){1,2}$'
368 if not re.match(valid_color, background_color):
369 raise ValueError(f'{background_color} is not a valid hex triplet color')
370
371 uid = 'master' if len(windows) == 0 else 'child_' + uuid4().hex[:8]
372
373 window = Window(
374 uid,
375 title,
376 url,
377 html,
378 width,
379 height,
380 x,
381 y,
382 resizable,
383 fullscreen,
384 min_size,
385 hidden,
386 frameless,
387 easy_drag,
388 shadow,
389 focus,
390 minimized,
391 maximized,
392 on_top,
393 confirm_close,
394 background_color,
395 js_api,
396 text_select,
397 transparent,
398 zoomable,
399 draggable,
400 vibrancy,
401 menu,
402 localization,
403 server=server,
404 http_port=http_port,
405 server_args=server_args,
406 screen=screen,
407 )
408
409 windows.append(window)
410
411 # This immediately creates the window only if `start` has already been called
412 if threading.current_thread().name != 'MainThread' and guilib:
413 if is_app(url) or is_local_url(url) and not server.is_running:
414 _, _, server = http.start_server([url], server=server, **server_args)
415 else:
416 server = None
417
418 if not window._initialize(gui=guilib, server=server):
419 return
420 guilib.create_window(window)
421
422 return window
423
424
425 def __generate_ssl_cert():
426 try:
427 # https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate
428 from cryptography import x509
429 from cryptography.hazmat.backends import default_backend
430 from cryptography.hazmat.primitives import hashes, serialization
431 from cryptography.hazmat.primitives.asymmetric import rsa
432 from cryptography.x509.oid import NameOID
433 except ImportError:
434 raise WebViewException(
435 'SSL support requires cryptography package. Please install it with "pip install cryptography" or "pip install pywebview[ssl]"'
436 )
437
438 with tempfile.NamedTemporaryFile(prefix='keyfile_', suffix='.pem', delete=False) as f:
439 keyfile = f.name
440 key = rsa.generate_private_key(
441 public_exponent=65537, key_size=2048, backend=default_backend()
442 )
443 key_pem = key.private_bytes(
444 encoding=serialization.Encoding.PEM,
445 format=serialization.PrivateFormat.TraditionalOpenSSL,
446 encryption_algorithm=serialization.NoEncryption(), # BestAvailableEncryption(b"passphrase"),
447 )
448 f.write(key_pem)
449
450 with tempfile.NamedTemporaryFile(prefix='certfile_', suffix='.pem', delete=False) as f:
451 certfile = f.name
452 subject = issuer = x509.Name(
453 [
454 x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),
455 x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, 'California'),
456 x509.NameAttribute(NameOID.LOCALITY_NAME, 'San Francisco'),
457 x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'pywebview'),
458 x509.NameAttribute(NameOID.COMMON_NAME, '127.0.0.1'),
459 ]
460 )
461 cert = (
462 x509.CertificateBuilder()
463 .subject_name(subject)
464 .issuer_name(issuer)
465 .public_key(key.public_key())
466 .serial_number(x509.random_serial_number())
467 .not_valid_before(datetime.datetime.utcnow())
468 .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=365))
469 .add_extension(
470 x509.SubjectAlternativeName([x509.DNSName('localhost')]),
471 critical=False,
472 )
473 .sign(key, hashes.SHA256(), backend=default_backend())
474 )
475 cert_pem = cert.public_bytes(serialization.Encoding.PEM)
476 f.write(cert_pem)
477
478 return keyfile, certfile
479
480
481 def __set_storage_path(storage_path):
482 e = WebViewException(f'Storage path {storage_path} is not writable')
483
484 if not os.path.exists(storage_path):
485 try:
486 os.makedirs(storage_path)
487 except OSError:
488 raise e
489 if not os.access(storage_path, os.W_OK):
490 raise e
491
492 _state['storage_path'] = storage_path
493
494
495 def active_window() -> Window | None:
496 """
497 Get the active window
498
499 :return: window object or None
500 """
501 if guilib:
502 return guilib.get_active_window()
503 return None
504
505
506 def screens() -> list[Screen]:
507 global renderer, guilib
508
509 if not guilib:
510 guilib = initialize()
511 renderer = guilib.renderer
512
513 screens = guilib.get_screens()
514 return screens