native_mode.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. from __future__ import annotations
  2. import _thread
  3. import logging
  4. import multiprocessing as mp
  5. import queue
  6. import socket
  7. import sys
  8. import tempfile
  9. import time
  10. import warnings
  11. from threading import Event, Thread
  12. from typing import Any, Callable, Dict, List, Tuple
  13. from . import globals, helpers, native
  14. try:
  15. with warnings.catch_warnings():
  16. # webview depends on bottle which uses the deprecated CGI function (https://github.com/bottlepy/bottle/issues/1403)
  17. warnings.filterwarnings('ignore', category=DeprecationWarning)
  18. import webview
  19. globals.optional_features.add('native')
  20. except ModuleNotFoundError:
  21. pass
  22. def open_window(
  23. host: str, port: int, title: str, width: int, height: int, fullscreen: bool, frameless: bool,
  24. method_queue: mp.Queue, response_queue: mp.Queue,
  25. ) -> None:
  26. while not helpers.is_port_open(host, port):
  27. time.sleep(0.1)
  28. window_kwargs = dict(
  29. url=f'http://{host}:{port}',
  30. title=title,
  31. width=width,
  32. height=height,
  33. fullscreen=fullscreen,
  34. frameless=frameless,
  35. )
  36. window_kwargs.update(globals.app.native.window_args)
  37. window = webview.create_window(**window_kwargs)
  38. closed = Event()
  39. window.events.closed += closed.set
  40. start_window_method_executor(window, method_queue, response_queue, closed)
  41. webview.start(storage_path=tempfile.mkdtemp(), **globals.app.native.start_args)
  42. def start_window_method_executor(
  43. window: webview.Window, method_queue: mp.Queue, response_queue: mp.Queue, closed: Event
  44. ) -> None:
  45. def execute(method: Callable, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> None:
  46. try:
  47. response = method(*args, **kwargs)
  48. if response is not None or 'dialog' in method.__name__:
  49. response_queue.put(response)
  50. except Exception:
  51. logging.exception(f'error in window.{method.__name__}')
  52. def window_method_executor() -> None:
  53. pending_executions: List[Thread] = []
  54. while not closed.is_set():
  55. try:
  56. method_name, args, kwargs = method_queue.get(block=False)
  57. if method_name == 'signal_server_shutdown':
  58. if pending_executions:
  59. logging.warning('shutdown is possibly blocked by opened dialogs like a file picker')
  60. while pending_executions:
  61. pending_executions.pop().join()
  62. elif method_name == 'get_always_on_top':
  63. response_queue.put(window.on_top)
  64. elif method_name == 'set_always_on_top':
  65. window.on_top = args[0]
  66. elif method_name == 'get_position':
  67. response_queue.put((int(window.x), int(window.y)))
  68. elif method_name == 'get_size':
  69. response_queue.put((int(window.width), int(window.height)))
  70. else:
  71. method = getattr(window, method_name)
  72. if callable(method):
  73. pending_executions.append(Thread(target=execute, args=(method, args, kwargs)))
  74. pending_executions[-1].start()
  75. else:
  76. logging.error(f'window.{method_name} is not callable')
  77. except queue.Empty:
  78. time.sleep(0.01)
  79. except Exception:
  80. logging.exception(f'error in window.{method_name}')
  81. Thread(target=window_method_executor).start()
  82. def activate(host: str, port: int, title: str, width: int, height: int, fullscreen: bool, frameless: bool) -> None:
  83. def check_shutdown() -> None:
  84. while process.is_alive():
  85. time.sleep(0.1)
  86. globals.server.should_exit = True
  87. while globals.state != globals.State.STOPPED:
  88. time.sleep(0.1)
  89. _thread.interrupt_main()
  90. if 'native' not in globals.optional_features:
  91. logging.error('Native mode is not supported in this configuration.\n'
  92. 'Please run "pip install pywebview" to use it.')
  93. sys.exit(1)
  94. mp.freeze_support()
  95. args = host, port, title, width, height, fullscreen, frameless, native.method_queue, native.response_queue
  96. process = mp.Process(target=open_window, args=args, daemon=False)
  97. process.start()
  98. Thread(target=check_shutdown, daemon=True).start()
  99. def find_open_port(start_port: int = 8000, end_port: int = 8999) -> int:
  100. """Reliably find an open port in a given range.
  101. This function will actually try to open the port to ensure no firewall blocks it.
  102. This is better than, e.g., passing port=0 to uvicorn.
  103. """
  104. for port in range(start_port, end_port + 1):
  105. try:
  106. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  107. s.bind(('localhost', port))
  108. return port
  109. except OSError:
  110. pass
  111. raise OSError('No open port found')