|
| 1 | +"""chromium.py provides a class proving tools for running chromium browsers.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import platform |
| 5 | +import sys |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +# TODO(Andrew): move this to its own subpackage comm # noqa: FIX002, TD003 |
| 9 | +from choreographer._pipe import Pipe, WebSocket |
| 10 | + |
| 11 | +if platform.system() == "Windows": |
| 12 | + import msvcrt |
| 13 | + |
| 14 | + |
| 15 | +class Chromium: |
| 16 | + def __init__(self, pipe): |
| 17 | + self._comm = pipe |
| 18 | + # extra information from pipe |
| 19 | + |
| 20 | + # where do we get user data dir |
| 21 | + def get_cli(self, temp_dir, **kwargs): |
| 22 | + gpu_enabled = kwargs.pop("with_gpu", False) |
| 23 | + headless = kwargs.pop("headless", True) |
| 24 | + sandbox = kwargs.pop("with_sandbox", False) |
| 25 | + if kwargs: |
| 26 | + raise RuntimeError( |
| 27 | + "Chromium.get_cli() received " f"invalid args: {kwargs.keys()}", |
| 28 | + ) |
| 29 | + path = None # TODO(Andrew): not legit # noqa: FIX002,TD003 |
| 30 | + chromium_wrapper_path = Path(__file__).resolve().parent / "chromium_wrapper.py" |
| 31 | + if platform.system() != "Windows": |
| 32 | + cli = [ |
| 33 | + sys.executable, |
| 34 | + chromium_wrapper_path, |
| 35 | + path, |
| 36 | + ] |
| 37 | + else: |
| 38 | + cli = [ |
| 39 | + path, |
| 40 | + ] |
| 41 | + |
| 42 | + cli.extend( |
| 43 | + [ |
| 44 | + "--disable-breakpad", |
| 45 | + "--allow-file-access-from-files", |
| 46 | + "--enable-logging=stderr", |
| 47 | + f"--user-data-dir={temp_dir}", |
| 48 | + "--no-first-run", |
| 49 | + "--enable-unsafe-swiftshader", |
| 50 | + ], |
| 51 | + ) |
| 52 | + if not gpu_enabled: |
| 53 | + cli.append("--disable-gpu") |
| 54 | + if headless: |
| 55 | + cli.append("--headless") |
| 56 | + if not sandbox: |
| 57 | + cli.append("--no-sandbox") |
| 58 | + |
| 59 | + if isinstance(self._comm, Pipe): |
| 60 | + cli.append("--remote-debugging-pipe") |
| 61 | + if platform.system() == "Windows": |
| 62 | + _inheritable = True |
| 63 | + write_handle = msvcrt.get_osfhandle(self._comm.from_choreo_to_external) |
| 64 | + read_handle = msvcrt.get_osfhandle(self._comm.from_external_to_choreo) |
| 65 | + os.set_handle_inheritable(write_handle, _inheritable) |
| 66 | + os.set_handle_inheritable(read_handle, _inheritable) |
| 67 | + cli += [ |
| 68 | + f"--remote-debugging-io-pipes={read_handle!s},{write_handle!s}", |
| 69 | + ] |
| 70 | + elif isinstance(self._comm, WebSocket): |
| 71 | + raise NotImplementedError("Websocket style comms are not implemented yet") |
| 72 | + |
| 73 | + |
| 74 | +def get_env(): |
| 75 | + return os.environ().copy() |
0 commit comments