native_mode.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import _thread
  2. import multiprocessing
  3. import socket
  4. import tempfile
  5. import time
  6. import warnings
  7. from threading import Thread
  8. from . import globals, helpers
  9. with warnings.catch_warnings():
  10. # webview depends on bottle which uses the deprecated CGI function (https://github.com/bottlepy/bottle/issues/1403)
  11. warnings.filterwarnings('ignore', category=DeprecationWarning)
  12. import webview
  13. def open_window(host: str, port: int, title: str, width: int, height: int, fullscreen: bool) -> None:
  14. while not helpers.is_port_open(host, port):
  15. time.sleep(0.1)
  16. window_kwargs = dict(url=f'http://{host}:{port}', title=title, width=width, height=height, fullscreen=fullscreen)
  17. window_kwargs.update(globals.app.native.window_args)
  18. webview.create_window(**window_kwargs)
  19. webview.start(storage_path=tempfile.mkdtemp(), **globals.app.native.start_args)
  20. def activate(host: str, port: int, title: str, width: int, height: int, fullscreen: bool) -> None:
  21. def check_shutdown() -> None:
  22. while process.is_alive():
  23. time.sleep(0.1)
  24. globals.server.should_exit = True
  25. while globals.state != globals.State.STOPPED:
  26. time.sleep(0.1)
  27. _thread.interrupt_main()
  28. multiprocessing.freeze_support()
  29. process = multiprocessing.Process(target=open_window, args=(host, port, title, width, height, fullscreen),
  30. daemon=False)
  31. process.start()
  32. Thread(target=check_shutdown, daemon=True).start()
  33. def find_open_port(start_port: int = 8000, end_port: int = 8999) -> int:
  34. """Reliably find an open port in a given range.
  35. This function will actually try to open the port to ensure no firewall blocks it.
  36. This is better than, e.g., passing port=0 to uvicorn.
  37. """
  38. for port in range(start_port, end_port + 1):
  39. try:
  40. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  41. s.bind(('localhost', port))
  42. return port
  43. except OSError:
  44. pass
  45. raise OSError('No open port found')