native_mode.py 5.2 KB

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