proton-gui 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- proton/__init__.py +6 -0
- proton/app.py +454 -0
- proton/browser.py +132 -0
- proton/server.py +255 -0
- proton/static/main.js +230 -0
- proton/window.py +222 -0
- proton_gui-2.0.0.dist-info/METADATA +130 -0
- proton_gui-2.0.0.dist-info/RECORD +11 -0
- proton_gui-2.0.0.dist-info/WHEEL +5 -0
- proton_gui-2.0.0.dist-info/licenses/LICENSE +21 -0
- proton_gui-2.0.0.dist-info/top_level.txt +1 -0
proton/__init__.py
ADDED
proton/app.py
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
"""The :class:`Proton` class: the public API of the library."""
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import secrets
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
import urllib.parse
|
|
14
|
+
from typing import Any, Callable, Dict, Optional, Tuple
|
|
15
|
+
|
|
16
|
+
from . import browser
|
|
17
|
+
from .server import BridgeServer, PageServer
|
|
18
|
+
from .window import Window, can_move_windows, find_window, hide_console
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger("proton")
|
|
21
|
+
|
|
22
|
+
#: Seconds to wait for the page to connect after the browser starts.
|
|
23
|
+
CONNECT_TIMEOUT = 30.0
|
|
24
|
+
#: Where the window waits, out of sight, until the page is ready (see ``hide_until_ready``).
|
|
25
|
+
OFFSCREEN_POSITION = (-32000, -32000)
|
|
26
|
+
#: Seconds to tolerate a closed socket while the page is navigating.
|
|
27
|
+
PAGE_CHANGE_GRACE = 2.0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _Request:
|
|
31
|
+
"""A pending question sent to the page, waiting for its answer."""
|
|
32
|
+
|
|
33
|
+
def __init__(self) -> None:
|
|
34
|
+
self.event = threading.Event()
|
|
35
|
+
self.value: Any = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Proton:
|
|
39
|
+
"""A Chromium window controlled from Python.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
path: HTML file shown first. Its folder becomes the web root, so images,
|
|
43
|
+
CSS and other pages next to it work with relative URLs.
|
|
44
|
+
debug: ``1`` enables verbose logging (Python and browser console).
|
|
45
|
+
init_size: initial window ``(width, height)``.
|
|
46
|
+
init_position: initial window ``(x, y)``.
|
|
47
|
+
hide_cmd: hide the console window (Windows only).
|
|
48
|
+
timeout: seconds to wait for answers to ``get_*`` calls.
|
|
49
|
+
hide_until_ready: open the window off-screen and move it into place once
|
|
50
|
+
the page has loaded, hiding the browser logo/URL flash. ``None``
|
|
51
|
+
(default) enables it only where it is reliable (Windows).
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
path: str,
|
|
57
|
+
debug: int = 0,
|
|
58
|
+
init_size: Tuple[int, int] = (400, 560),
|
|
59
|
+
init_position: Tuple[int, int] = (0, 0),
|
|
60
|
+
hide_cmd: bool = True,
|
|
61
|
+
timeout: float = 5.0,
|
|
62
|
+
hide_until_ready: Optional[bool] = None,
|
|
63
|
+
):
|
|
64
|
+
self.path = os.path.abspath(path)
|
|
65
|
+
if not os.path.isfile(self.path):
|
|
66
|
+
raise FileNotFoundError("HTML file not found: %s" % path)
|
|
67
|
+
self.root = os.path.dirname(self.path)
|
|
68
|
+
|
|
69
|
+
self.debug = debug
|
|
70
|
+
self.init_size = init_size
|
|
71
|
+
self.init_position = init_position
|
|
72
|
+
self.hide_cmd = hide_cmd
|
|
73
|
+
self.timeout = timeout
|
|
74
|
+
self.hide_until_ready = can_move_windows() if hide_until_ready is None else hide_until_ready
|
|
75
|
+
|
|
76
|
+
#: Native window controller (resize, maximize, close...). Set after start.
|
|
77
|
+
self.window: Optional[Window] = None
|
|
78
|
+
self.signals: Dict[str, Callable[[dict], Any]] = {}
|
|
79
|
+
|
|
80
|
+
self._token = secrets.token_urlsafe(24)
|
|
81
|
+
self._ids = itertools.count(1)
|
|
82
|
+
self._requests: Dict[int, _Request] = {}
|
|
83
|
+
self._page_server: Optional[PageServer] = None
|
|
84
|
+
self._bridge: Optional[BridgeServer] = None
|
|
85
|
+
self._process = None
|
|
86
|
+
self._user_data_dir: Optional[str] = None
|
|
87
|
+
|
|
88
|
+
self._connected = threading.Event()
|
|
89
|
+
self._closed = threading.Event() # close() has started
|
|
90
|
+
self._finished = threading.Event() # close() has released everything
|
|
91
|
+
self._close_lock = threading.Lock()
|
|
92
|
+
self._changing_page = False
|
|
93
|
+
self._disconnected_at = 0.0
|
|
94
|
+
self._started = False
|
|
95
|
+
|
|
96
|
+
if debug:
|
|
97
|
+
logging.getLogger("proton").setLevel(logging.DEBUG)
|
|
98
|
+
if not logging.getLogger().handlers:
|
|
99
|
+
logging.basicConfig(format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
|
100
|
+
|
|
101
|
+
# ------------------------------------------------------------ properties
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def active(self) -> bool:
|
|
105
|
+
"""``True`` while the window is open."""
|
|
106
|
+
return self._started and not self._closed.is_set()
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def port(self) -> int:
|
|
110
|
+
"""Port of the WebSocket server."""
|
|
111
|
+
return self._bridge.port if self._bridge else 0
|
|
112
|
+
|
|
113
|
+
# ------------------------------------------------------------- lifecycle
|
|
114
|
+
|
|
115
|
+
def start(self, func: Optional[Callable] = None, *args, **kwargs) -> None:
|
|
116
|
+
"""Open the window, run ``func(*args, **kwargs)`` in a thread and block until it closes."""
|
|
117
|
+
self._launch()
|
|
118
|
+
if func is not None:
|
|
119
|
+
threading.Thread(
|
|
120
|
+
target=self._run_user_code, args=(func, args, kwargs), daemon=True
|
|
121
|
+
).start()
|
|
122
|
+
self.wait()
|
|
123
|
+
|
|
124
|
+
def wait(self) -> None:
|
|
125
|
+
"""Block until the window is closed (Ctrl+C closes it)."""
|
|
126
|
+
try:
|
|
127
|
+
while not self._finished.wait(0.5):
|
|
128
|
+
pass
|
|
129
|
+
except KeyboardInterrupt:
|
|
130
|
+
log.info("interrupted")
|
|
131
|
+
self.close()
|
|
132
|
+
|
|
133
|
+
def close(self) -> None:
|
|
134
|
+
"""Close the window and release every resource. Safe to call many times."""
|
|
135
|
+
with self._close_lock:
|
|
136
|
+
if self._closed.is_set():
|
|
137
|
+
self._finished.wait(10) # another thread is already closing
|
|
138
|
+
return
|
|
139
|
+
self._closed.set()
|
|
140
|
+
try:
|
|
141
|
+
self._release()
|
|
142
|
+
finally:
|
|
143
|
+
self._finished.set()
|
|
144
|
+
|
|
145
|
+
def _release(self) -> None:
|
|
146
|
+
if self.window:
|
|
147
|
+
self.window.close()
|
|
148
|
+
if self._bridge:
|
|
149
|
+
self._bridge.stop()
|
|
150
|
+
if self._page_server:
|
|
151
|
+
self._page_server.stop()
|
|
152
|
+
if self._process:
|
|
153
|
+
self._stop_browser()
|
|
154
|
+
# Remove the temporary browser profile (retry: the browser may still hold files).
|
|
155
|
+
if self._user_data_dir:
|
|
156
|
+
for _ in range(15):
|
|
157
|
+
shutil.rmtree(self._user_data_dir, ignore_errors=True)
|
|
158
|
+
if not os.path.exists(self._user_data_dir):
|
|
159
|
+
break
|
|
160
|
+
time.sleep(0.2)
|
|
161
|
+
|
|
162
|
+
def _stop_browser(self) -> None:
|
|
163
|
+
"""Terminate the browser (and, on Windows, its child processes)."""
|
|
164
|
+
process = self._process
|
|
165
|
+
if sys.platform == "win32":
|
|
166
|
+
subprocess.run(
|
|
167
|
+
["taskkill", "/F", "/T", "/PID", str(process.pid)],
|
|
168
|
+
stdout=subprocess.DEVNULL,
|
|
169
|
+
stderr=subprocess.DEVNULL,
|
|
170
|
+
)
|
|
171
|
+
elif process.poll() is None:
|
|
172
|
+
process.terminate()
|
|
173
|
+
try:
|
|
174
|
+
process.wait(timeout=3)
|
|
175
|
+
except subprocess.TimeoutExpired:
|
|
176
|
+
process.kill()
|
|
177
|
+
|
|
178
|
+
def _run_user_code(self, func: Callable, args: tuple, kwargs: dict) -> None:
|
|
179
|
+
try:
|
|
180
|
+
func(*args, **kwargs)
|
|
181
|
+
except Exception:
|
|
182
|
+
log.exception("error in user function")
|
|
183
|
+
|
|
184
|
+
def _start_servers(self) -> None:
|
|
185
|
+
self._page_server = PageServer(self.root)
|
|
186
|
+
self._page_server.start()
|
|
187
|
+
self._bridge = BridgeServer(
|
|
188
|
+
self._token,
|
|
189
|
+
on_message=self._process_message,
|
|
190
|
+
on_connect=self._on_connect,
|
|
191
|
+
on_disconnect=self._on_disconnect,
|
|
192
|
+
)
|
|
193
|
+
self._bridge.start()
|
|
194
|
+
self._started = True
|
|
195
|
+
|
|
196
|
+
def _launch(self) -> None:
|
|
197
|
+
if self.hide_cmd:
|
|
198
|
+
hide_console()
|
|
199
|
+
try:
|
|
200
|
+
self._start_servers()
|
|
201
|
+
self._user_data_dir = tempfile.mkdtemp(prefix="proton_")
|
|
202
|
+
start_position = OFFSCREEN_POSITION if self.hide_until_ready else self.init_position
|
|
203
|
+
self._process = browser.launch(
|
|
204
|
+
self._page_url(self.path), self.init_size, start_position, self._user_data_dir
|
|
205
|
+
)
|
|
206
|
+
if not self._connected.wait(CONNECT_TIMEOUT):
|
|
207
|
+
raise TimeoutError("the browser did not connect to Proton in time")
|
|
208
|
+
self._locate_window()
|
|
209
|
+
except BaseException:
|
|
210
|
+
self.close()
|
|
211
|
+
raise
|
|
212
|
+
threading.Thread(target=self._watch, daemon=True).start()
|
|
213
|
+
|
|
214
|
+
def _locate_window(self) -> None:
|
|
215
|
+
"""Find the native window by giving the page a unique, temporary title."""
|
|
216
|
+
title = "proton_%d" % self.port
|
|
217
|
+
self._send({"action": "title", "title": title, "find": True})
|
|
218
|
+
self.window = find_window(title, self._process)
|
|
219
|
+
self._send({"action": "title", "restore": True})
|
|
220
|
+
if self.hide_until_ready:
|
|
221
|
+
self._wait_title_restored(title)
|
|
222
|
+
self.window.move(*self.init_position)
|
|
223
|
+
self.window.activate()
|
|
224
|
+
|
|
225
|
+
def _wait_title_restored(self, temporary_title: str, timeout: float = 2.0) -> None:
|
|
226
|
+
"""Wait until the temporary title is gone so it is never seen by the user."""
|
|
227
|
+
deadline = time.monotonic() + timeout
|
|
228
|
+
while time.monotonic() < deadline:
|
|
229
|
+
current = self.window.title
|
|
230
|
+
if current is None or temporary_title not in current:
|
|
231
|
+
return
|
|
232
|
+
time.sleep(0.01)
|
|
233
|
+
|
|
234
|
+
def _watch(self) -> None:
|
|
235
|
+
"""Close everything when the user closes the window."""
|
|
236
|
+
while not self._closed.is_set():
|
|
237
|
+
if not self._bridge.connected:
|
|
238
|
+
grace = PAGE_CHANGE_GRACE if self._changing_page else 0.0
|
|
239
|
+
if time.monotonic() - self._disconnected_at >= grace:
|
|
240
|
+
break
|
|
241
|
+
elif self.window is not None and not self.window.visible:
|
|
242
|
+
break
|
|
243
|
+
time.sleep(0.05)
|
|
244
|
+
self.close()
|
|
245
|
+
|
|
246
|
+
# ------------------------------------------------------ bridge callbacks
|
|
247
|
+
|
|
248
|
+
def _on_connect(self) -> None:
|
|
249
|
+
self._connected.set()
|
|
250
|
+
|
|
251
|
+
def _on_disconnect(self) -> None:
|
|
252
|
+
self._disconnected_at = time.monotonic()
|
|
253
|
+
|
|
254
|
+
def _process_message(self, data: dict) -> None:
|
|
255
|
+
action = data.get("action")
|
|
256
|
+
log.debug("<< %s", data)
|
|
257
|
+
|
|
258
|
+
if action == "response":
|
|
259
|
+
request = self._requests.pop(data.get("rid"), None)
|
|
260
|
+
if request:
|
|
261
|
+
request.value = data.get("text")
|
|
262
|
+
request.event.set()
|
|
263
|
+
return
|
|
264
|
+
if action == "success":
|
|
265
|
+
self._changing_page = False
|
|
266
|
+
return
|
|
267
|
+
|
|
268
|
+
handler = self.signals.get(action)
|
|
269
|
+
if handler is None:
|
|
270
|
+
log.debug("no signal registered for %r", action)
|
|
271
|
+
return
|
|
272
|
+
threading.Thread(target=self._run_signal, args=(handler, data), daemon=True).start()
|
|
273
|
+
|
|
274
|
+
@staticmethod
|
|
275
|
+
def _run_signal(handler: Callable, data: dict) -> None:
|
|
276
|
+
try:
|
|
277
|
+
handler(data)
|
|
278
|
+
except Exception:
|
|
279
|
+
log.exception("error in signal handler")
|
|
280
|
+
|
|
281
|
+
# ------------------------------------------------------------- messaging
|
|
282
|
+
|
|
283
|
+
def signal(self, action: str, function: Callable[[dict], Any]) -> None:
|
|
284
|
+
"""Run ``function(data)`` (in a thread) when the page sends ``{"action": action, ...}``."""
|
|
285
|
+
if not callable(function):
|
|
286
|
+
raise TypeError("function must be callable")
|
|
287
|
+
self.signals[action] = function
|
|
288
|
+
|
|
289
|
+
def send_signal(self, data: dict) -> None:
|
|
290
|
+
"""Send a raw JSON command to the page (queued until the page connects)."""
|
|
291
|
+
if self._bridge is None:
|
|
292
|
+
raise RuntimeError("Proton is not started")
|
|
293
|
+
self._send(data)
|
|
294
|
+
|
|
295
|
+
def _send(self, data: dict) -> None:
|
|
296
|
+
log.debug(">> %s", data)
|
|
297
|
+
self._bridge.send(data)
|
|
298
|
+
|
|
299
|
+
def _request(self, data: dict) -> Any:
|
|
300
|
+
"""Send ``data`` and wait (up to ``self.timeout``) for the page's answer."""
|
|
301
|
+
rid = next(self._ids)
|
|
302
|
+
request = _Request()
|
|
303
|
+
self._requests[rid] = request
|
|
304
|
+
self.send_signal(dict(data, rid=rid))
|
|
305
|
+
if not request.event.wait(self.timeout):
|
|
306
|
+
self._requests.pop(rid, None)
|
|
307
|
+
log.warning("no answer from the page for %s", data)
|
|
308
|
+
return None
|
|
309
|
+
return request.value
|
|
310
|
+
|
|
311
|
+
# ----------------------------------------------------------- reading data
|
|
312
|
+
|
|
313
|
+
def _get_by_id(self, element_id: str, kind: str, **extra) -> Any:
|
|
314
|
+
return self._request(dict(action="getById", id=element_id, type=kind, **extra))
|
|
315
|
+
|
|
316
|
+
def get_form_data(self, id: str) -> Optional[dict]:
|
|
317
|
+
"""Return the fields of a ``<form id=...>`` as a dict."""
|
|
318
|
+
return self._get_by_id(id, "getFormData")
|
|
319
|
+
|
|
320
|
+
def get_value_by_id(self, id: str) -> Any:
|
|
321
|
+
"""``element.value`` of an input/select."""
|
|
322
|
+
return self._get_by_id(id, "getValueById")
|
|
323
|
+
|
|
324
|
+
def get_text_by_id(self, id: str) -> Optional[str]:
|
|
325
|
+
"""``element.innerHTML``."""
|
|
326
|
+
return self._get_by_id(id, "getTextById")
|
|
327
|
+
|
|
328
|
+
def get_object(self, id: str, obj: str) -> Any:
|
|
329
|
+
"""Any property path of an element, e.g. ``get_object("box", "style.color")``."""
|
|
330
|
+
return self._get_by_id(id, "getObject", obj=obj)
|
|
331
|
+
|
|
332
|
+
def is_checked_id(self, id: str) -> Optional[bool]:
|
|
333
|
+
"""``element.checked`` of a checkbox."""
|
|
334
|
+
return self._get_by_id(id, "isCheckedId")
|
|
335
|
+
|
|
336
|
+
def get_radio_checked(self, name: str) -> Optional[str]:
|
|
337
|
+
"""Value of the checked radio button in the group ``name``."""
|
|
338
|
+
return self._request({"action": "getRadioChecked", "name": name})
|
|
339
|
+
|
|
340
|
+
# ----------------------------------------------------------- writing data
|
|
341
|
+
|
|
342
|
+
def _set_by_id(self, element_id: str, value: Any, kind: str, **extra) -> None:
|
|
343
|
+
self.send_signal(dict(action="setById", id=element_id, text=value, type=kind, **extra))
|
|
344
|
+
|
|
345
|
+
def set_text_by_id(self, id: str, text: str) -> None:
|
|
346
|
+
"""Set ``element.innerHTML``."""
|
|
347
|
+
self._set_by_id(id, text, "setTextById")
|
|
348
|
+
|
|
349
|
+
def set_value_by_id(self, id: str, value: Any) -> None:
|
|
350
|
+
"""Set ``element.value``."""
|
|
351
|
+
self._set_by_id(id, value, "setValueById")
|
|
352
|
+
|
|
353
|
+
def set_object(self, id: str, value: Any, obj: str) -> None:
|
|
354
|
+
"""Set any property path of an element, e.g. ``set_object("box", "red", "style.color")``."""
|
|
355
|
+
self._set_by_id(id, value, "setObject", obj=obj)
|
|
356
|
+
|
|
357
|
+
def check_id(self, id: str, checked: bool = True) -> None:
|
|
358
|
+
"""Check or uncheck a checkbox."""
|
|
359
|
+
self._set_by_id(id, checked, "checkId")
|
|
360
|
+
|
|
361
|
+
def set_radio_checked(self, name: str, value: str) -> None:
|
|
362
|
+
"""Check the radio button of group ``name`` whose value is ``value``."""
|
|
363
|
+
self.send_signal({"action": "setRadioChecked", "name": name, "value": value})
|
|
364
|
+
|
|
365
|
+
def run_function(self, function: str, args: Optional[list] = None) -> None:
|
|
366
|
+
"""Call ``function(args)`` defined in the page's JavaScript (``args`` is one value, e.g. a list)."""
|
|
367
|
+
data: Dict[str, Any] = {"action": "function", "function": function}
|
|
368
|
+
if args:
|
|
369
|
+
data["args"] = args
|
|
370
|
+
self.send_signal(data)
|
|
371
|
+
|
|
372
|
+
# ----------------------------------------------------------------- window
|
|
373
|
+
|
|
374
|
+
def set_title(self, title: str) -> None:
|
|
375
|
+
"""Change the window title."""
|
|
376
|
+
self.send_signal({"action": "title", "title": title})
|
|
377
|
+
|
|
378
|
+
def resize(self, width: int, height: int) -> None:
|
|
379
|
+
"""Resize the window (needs ``pygetwindow`` on Windows, ``xdotool`` on Linux)."""
|
|
380
|
+
self._require_window().resize(width, height)
|
|
381
|
+
|
|
382
|
+
def _require_window(self) -> Window:
|
|
383
|
+
if self.window is None:
|
|
384
|
+
raise RuntimeError("the window is not available yet")
|
|
385
|
+
return self.window
|
|
386
|
+
|
|
387
|
+
def location(self, url: str) -> None:
|
|
388
|
+
"""Navigate to a raw URL. The new page must load ``main.js`` itself, or the window closes."""
|
|
389
|
+
self.send_signal({"action": "url", "url": url})
|
|
390
|
+
|
|
391
|
+
def new_page(self, path: str) -> None:
|
|
392
|
+
"""Navigate to another HTML file located inside the web root."""
|
|
393
|
+
self._changing_page = True
|
|
394
|
+
try:
|
|
395
|
+
self.location(self._page_url(path))
|
|
396
|
+
except BaseException:
|
|
397
|
+
self._changing_page = False
|
|
398
|
+
raise
|
|
399
|
+
|
|
400
|
+
def new_page_static(self, path: str) -> None:
|
|
401
|
+
"""Replace the page body with the HTML of ``path`` (scripts are NOT executed)."""
|
|
402
|
+
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
|
403
|
+
self.send_signal({"action": "newPage", "page": handle.read()})
|
|
404
|
+
|
|
405
|
+
def _page_url(self, path: str) -> str:
|
|
406
|
+
if self._page_server is None:
|
|
407
|
+
raise RuntimeError("Proton is not started")
|
|
408
|
+
absolute = os.path.abspath(path)
|
|
409
|
+
if not os.path.isfile(absolute):
|
|
410
|
+
raise FileNotFoundError("HTML file not found: %s" % path)
|
|
411
|
+
try:
|
|
412
|
+
relative = os.path.relpath(absolute, self.root)
|
|
413
|
+
except ValueError: # different drive on Windows
|
|
414
|
+
relative = ".."
|
|
415
|
+
if relative.startswith(".."):
|
|
416
|
+
raise ValueError("%s is outside the web root (%s)" % (path, self.root))
|
|
417
|
+
query = urllib.parse.urlencode(
|
|
418
|
+
{
|
|
419
|
+
"url": "%s:%d" % (self._bridge.host, self._bridge.port),
|
|
420
|
+
"token": self._token,
|
|
421
|
+
"debug": int(bool(self.debug)),
|
|
422
|
+
}
|
|
423
|
+
)
|
|
424
|
+
return "http://%s:%d/%s?%s" % (
|
|
425
|
+
self._page_server.host,
|
|
426
|
+
self._page_server.port,
|
|
427
|
+
urllib.parse.quote(relative.replace(os.sep, "/")),
|
|
428
|
+
query,
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
# ----------------------------------------------- legacy (v1) camelCase API
|
|
432
|
+
|
|
433
|
+
getFormData = get_form_data
|
|
434
|
+
getValueById = get_value_by_id
|
|
435
|
+
getTextById = get_text_by_id
|
|
436
|
+
getObject = get_object
|
|
437
|
+
isCheckedId = is_checked_id
|
|
438
|
+
getRadioChecked = get_radio_checked
|
|
439
|
+
setTextById = set_text_by_id
|
|
440
|
+
setValueById = set_value_by_id
|
|
441
|
+
setObject = set_object
|
|
442
|
+
setRadioChecked = set_radio_checked
|
|
443
|
+
runFunction = run_function
|
|
444
|
+
setTitle = set_title
|
|
445
|
+
newPage = new_page
|
|
446
|
+
newPageStatic = new_page_static
|
|
447
|
+
|
|
448
|
+
def checkId(self, text: bool, id: str) -> None: # noqa: N802 (v1 argument order)
|
|
449
|
+
self.check_id(id, text)
|
|
450
|
+
|
|
451
|
+
@property
|
|
452
|
+
def janela(self) -> Optional[Window]:
|
|
453
|
+
"""Legacy alias of :attr:`window`."""
|
|
454
|
+
return self.window
|
proton/browser.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Locate a Chromium-based browser and launch it in app mode (Windows, Linux, macOS)."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from typing import List, Optional, Sequence, Tuple
|
|
9
|
+
|
|
10
|
+
log = logging.getLogger("proton.browser")
|
|
11
|
+
|
|
12
|
+
#: Environment variable that overrides automatic browser discovery.
|
|
13
|
+
BROWSER_ENV = "PROTON_BROWSER"
|
|
14
|
+
|
|
15
|
+
# Windows: (directory relative to a Program Files/LocalAppData root, executable name)
|
|
16
|
+
_WINDOWS_BROWSERS: Sequence[Tuple[str, str]] = (
|
|
17
|
+
("Google\\Chrome\\Application", "chrome.exe"),
|
|
18
|
+
("Microsoft\\Edge\\Application", "msedge.exe"),
|
|
19
|
+
("Chromium\\Application", "chromium.exe"),
|
|
20
|
+
("BraveSoftware\\Brave-Browser\\Application", "brave.exe"),
|
|
21
|
+
("CCleaner Browser\\Application", "CCleanerBrowser.exe"),
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Linux: executable names looked up on PATH
|
|
25
|
+
_LINUX_BINARIES: Sequence[str] = (
|
|
26
|
+
"google-chrome",
|
|
27
|
+
"google-chrome-stable",
|
|
28
|
+
"chromium",
|
|
29
|
+
"chromium-browser",
|
|
30
|
+
"brave-browser",
|
|
31
|
+
"brave",
|
|
32
|
+
"microsoft-edge",
|
|
33
|
+
"microsoft-edge-stable",
|
|
34
|
+
"vivaldi",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
_MACOS_PATHS: Sequence[str] = (
|
|
38
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
39
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
40
|
+
"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
|
|
41
|
+
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BrowserNotFoundError(RuntimeError):
|
|
46
|
+
"""Raised when no supported browser can be located."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _windows_roots() -> List[str]:
|
|
50
|
+
roots: List[str] = []
|
|
51
|
+
for var in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"):
|
|
52
|
+
value = os.environ.get(var)
|
|
53
|
+
if value and value not in roots:
|
|
54
|
+
roots.append(value)
|
|
55
|
+
return roots
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def find_browser() -> Optional[str]:
|
|
59
|
+
"""Return the path of the first supported browser found, or ``None``.
|
|
60
|
+
|
|
61
|
+
``$PROTON_BROWSER`` (a path or a command name) always wins.
|
|
62
|
+
"""
|
|
63
|
+
override = os.environ.get(BROWSER_ENV)
|
|
64
|
+
if override:
|
|
65
|
+
resolved = shutil.which(override)
|
|
66
|
+
if resolved:
|
|
67
|
+
return resolved
|
|
68
|
+
log.warning("%s=%r was not found, falling back to auto-detection", BROWSER_ENV, override)
|
|
69
|
+
|
|
70
|
+
if sys.platform == "win32":
|
|
71
|
+
for directory, exe in _WINDOWS_BROWSERS:
|
|
72
|
+
for root in _windows_roots():
|
|
73
|
+
candidate = os.path.join(root, directory, exe)
|
|
74
|
+
if os.path.exists(candidate):
|
|
75
|
+
return candidate
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
if sys.platform == "darwin":
|
|
79
|
+
for candidate in _MACOS_PATHS:
|
|
80
|
+
if os.path.exists(candidate):
|
|
81
|
+
return candidate
|
|
82
|
+
|
|
83
|
+
for name in _LINUX_BINARIES:
|
|
84
|
+
resolved = shutil.which(name)
|
|
85
|
+
if resolved:
|
|
86
|
+
return resolved
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def build_command(
|
|
91
|
+
executable: str,
|
|
92
|
+
url: str,
|
|
93
|
+
size: Tuple[int, int],
|
|
94
|
+
position: Tuple[int, int],
|
|
95
|
+
user_data_dir: str,
|
|
96
|
+
) -> List[str]:
|
|
97
|
+
"""Build the argument list that opens ``url`` as a standalone app window."""
|
|
98
|
+
command = [
|
|
99
|
+
executable,
|
|
100
|
+
"--app=" + url,
|
|
101
|
+
"--window-size=%d,%d" % tuple(size),
|
|
102
|
+
"--window-position=%d,%d" % tuple(position),
|
|
103
|
+
"--user-data-dir=" + user_data_dir,
|
|
104
|
+
"--incognito",
|
|
105
|
+
"--disable-extensions",
|
|
106
|
+
"--disable-restore-session-state",
|
|
107
|
+
"--no-first-run",
|
|
108
|
+
"--no-default-browser-check",
|
|
109
|
+
]
|
|
110
|
+
# Chromium refuses to start as root (e.g. inside containers) without this.
|
|
111
|
+
if hasattr(os, "geteuid") and os.geteuid() == 0:
|
|
112
|
+
log.warning("running as root: adding --no-sandbox")
|
|
113
|
+
command.append("--no-sandbox")
|
|
114
|
+
return command
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def launch(
|
|
118
|
+
url: str,
|
|
119
|
+
size: Tuple[int, int],
|
|
120
|
+
position: Tuple[int, int],
|
|
121
|
+
user_data_dir: str,
|
|
122
|
+
) -> "subprocess.Popen":
|
|
123
|
+
"""Start the browser and return its process handle."""
|
|
124
|
+
executable = find_browser()
|
|
125
|
+
if executable is None:
|
|
126
|
+
raise BrowserNotFoundError(
|
|
127
|
+
"No Chromium-based browser found. Install Chrome, Chromium, Edge or Brave, "
|
|
128
|
+
"or set the %s environment variable." % BROWSER_ENV
|
|
129
|
+
)
|
|
130
|
+
command = build_command(executable, url, size, position, user_data_dir)
|
|
131
|
+
log.debug("launching browser: %s", command)
|
|
132
|
+
return subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|