playwright-desktop 0.2.0__tar.gz

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.
Files changed (34) hide show
  1. playwright_desktop-0.2.0/PKG-INFO +109 -0
  2. playwright_desktop-0.2.0/README.md +97 -0
  3. playwright_desktop-0.2.0/pyproject.toml +26 -0
  4. playwright_desktop-0.2.0/python/playwright_desktop/__init__.py +28 -0
  5. playwright_desktop-0.2.0/python/playwright_desktop/_async.py +285 -0
  6. playwright_desktop-0.2.0/python/playwright_desktop/_backend.py +30 -0
  7. playwright_desktop-0.2.0/python/playwright_desktop/_errors.py +62 -0
  8. playwright_desktop-0.2.0/python/playwright_desktop/_facade.py +113 -0
  9. playwright_desktop-0.2.0/python/playwright_desktop/_models.py +116 -0
  10. playwright_desktop-0.2.0/python/playwright_desktop/_native.pyi +29 -0
  11. playwright_desktop-0.2.0/python/playwright_desktop/_patch.py +86 -0
  12. playwright_desktop-0.2.0/python/playwright_desktop/_platform.py +30 -0
  13. playwright_desktop-0.2.0/python/playwright_desktop/_runtime.py +236 -0
  14. playwright_desktop-0.2.0/python/playwright_desktop/_sync.py +283 -0
  15. playwright_desktop-0.2.0/python/playwright_desktop/_timing.py +22 -0
  16. playwright_desktop-0.2.0/python/playwright_desktop/py.typed +0 -0
  17. playwright_desktop-0.2.0/python/playwright_desktop/typing.py +32 -0
  18. playwright_desktop-0.2.0/rust/Cargo.lock +254 -0
  19. playwright_desktop-0.2.0/rust/Cargo.toml +30 -0
  20. playwright_desktop-0.2.0/rust/src/backend/tests.rs +98 -0
  21. playwright_desktop-0.2.0/rust/src/backend.rs +140 -0
  22. playwright_desktop-0.2.0/rust/src/engine/platform.rs +155 -0
  23. playwright_desktop-0.2.0/rust/src/engine/tests.rs +560 -0
  24. playwright_desktop-0.2.0/rust/src/engine/windows_platform.rs +380 -0
  25. playwright_desktop-0.2.0/rust/src/engine.rs +823 -0
  26. playwright_desktop-0.2.0/rust/src/error.rs +13 -0
  27. playwright_desktop-0.2.0/rust/src/jab/ffi.rs +101 -0
  28. playwright_desktop-0.2.0/rust/src/jab/loader.rs +96 -0
  29. playwright_desktop-0.2.0/rust/src/jab/mod.rs +179 -0
  30. playwright_desktop-0.2.0/rust/src/jab/tests.rs +196 -0
  31. playwright_desktop-0.2.0/rust/src/lib.rs +29 -0
  32. playwright_desktop-0.2.0/rust/src/uia.rs +236 -0
  33. playwright_desktop-0.2.0/rust/src/windows.rs +145 -0
  34. playwright_desktop-0.2.0/rust/tests/abi_layout.c +15 -0
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: playwright-desktop
3
+ Version: 0.2.0
4
+ Classifier: Operating System :: Microsoft :: Windows
5
+ Classifier: Programming Language :: Python :: 3
6
+ Classifier: Programming Language :: Rust
7
+ Requires-Dist: playwright>=1.63,<1.66
8
+ Summary: Desktop interactions for Playwright Python
9
+ Requires-Python: >=3.10, <3.15
10
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
11
+
12
+ # playwright-desktop
13
+
14
+ Añade `page.expect_app()` al `Page` oficial de Playwright Python para automatizar aplicaciones de escritorio a través de `DesktopContext`, `App`, `Window` y `Alert`.
15
+
16
+ ## Instalación
17
+
18
+ ```shell
19
+ pip install playwright-desktop
20
+ ```
21
+
22
+ La versión mínima de Python es 3.10.
23
+
24
+ ## Compatibilidad actual
25
+
26
+ | SO | Nativo | JVM |
27
+ | ------- | ------ | --- |
28
+ | Windows | X | X |
29
+ | macOS | | |
30
+ | Linux | | |
31
+
32
+ En Windows x64, la librería selecciona el motor de cada ventana automáticamente. Usa UI Automation para accionar botones, enlaces y opciones de menú en aplicaciones nativas, y Java Access Bridge para Java Swing cuando el bridge está habilitado.
33
+
34
+ ## Sintaxis básica
35
+
36
+ Sobre un `page` de Playwright, coloca dentro de `with` la acción web que abre la aplicación de escritorio y recupera la instancia `App` con `.value` al salir del bloque.
37
+
38
+ ```python
39
+ import playwright_desktop
40
+
41
+ with page.expect_app(title="Información del equipo") as app_info:
42
+ page.get_by_role("button", name="Obtener información").click()
43
+
44
+ app = app_info.value
45
+ app.get_by_role("textbox", name="Alias").fill("QA")
46
+ app.get_by_role("button", name="Confirmar").click()
47
+ app.wait_for_closed() # espera a que la ventana se cierre tras confirmar
48
+ ```
49
+
50
+ Playwright usa exactamente el mismo patrón con `page.expect_popup()` para abrir una pestaña o ventana nueva del navegador:
51
+
52
+ ```python
53
+ with page.expect_popup() as popup_info:
54
+ page.get_by_role("link", name="Abrir reporte").click()
55
+
56
+ popup = popup_info.value
57
+ ```
58
+
59
+ Con Playwright asíncrono, usa `async with`, `app = await app_info.value` y `await` en las acciones sobre `App`, `Window`, `Alert` y `DesktopContext`.
60
+
61
+ ## Ventanas abiertas y avisos intermedios
62
+
63
+ Mientras se abre la app principal dentro de `with page.expect_app(...)`, usa `app_info.context` (`DesktopContext`, compartido por todas las páginas del mismo `BrowserContext`) para interactuar con ventanas ya abiertas o diálogos intermedios:
64
+
65
+ ```python
66
+ with page.expect_app(title="Información del equipo") as app_info:
67
+ dcontext = app_info.context
68
+ page.get_by_role("button", name="Obtener información").click()
69
+ dcontext.app(title_prefix="Microsoft Edge").get_by_role("button", name="Abrir").click()
70
+ ```
71
+
72
+ En `dcontext.app(...)` puedes filtrar por `title`, `title_prefix`, `pid`, `has_text` y `only_new=True` (ignora ventanas que ya estaban abiertas antes de iniciar el `DesktopContext`).
73
+
74
+ ## Idioma del sistema operativo
75
+
76
+ `dcontext.os_language` y `playwright_desktop.os_language()` devuelven el idioma de interfaz del sistema en formato BCP-47 (por ejemplo `"es-ES"` o `"en-US"`):
77
+
78
+ ```python
79
+ if dcontext.os_language.startswith("es"):
80
+ dcontext.app(has_text="Seguridad de Windows", only_new=True).get_by_role("button", name="Ejecutar").click()
81
+ ```
82
+
83
+ ## Ventanas secundarias, alertas y cierre
84
+
85
+ Desde una `App` ya capturada puedes esperar sus propias ventanas hijas o alertas:
86
+
87
+ ```python
88
+ with app.expect_alert(title="Confirmación") as alert_info:
89
+ app.get_by_role("button", name="Guardar").click()
90
+
91
+ alert_info.value.get_by_role("button", name="Aceptar").click()
92
+ ```
93
+
94
+ - `app.expect_window(...)` y `app.expect_alert(...)`: devuelven `Window` o `Alert` filtrados automáticamente al `pid` de `app`.
95
+ - `app.expect_child_app(...)`: captura otra `App` independiente lanzada desde `app`.
96
+ - `bring_to_front()`, `wait_for_closed()` y `close()`: disponibles en `App`, `Window` y `Alert`. Cerrar la parte desktop (`app.close()` o `dcontext.close()`) no cierra el navegador; al cerrar `page.context`, la sesión desktop se libera automáticamente.
97
+
98
+ ## Configuración opcional
99
+
100
+ `playwright_desktop` es el módulo importado en tu script; úsalo solo si necesitas fijar valores globales en milisegundos o la ruta del JDK antes de iniciar sesión:
101
+
102
+ ```python
103
+ import playwright_desktop
104
+
105
+ playwright_desktop.configure(timeout=15_000, java_home=r"C:\Program Files\Java\jdk-17")
106
+ ```
107
+
108
+ También puedes cambiar el timeout de una sesión específica con `dcontext.set_default_timeout(15_000)`.
109
+
@@ -0,0 +1,97 @@
1
+ # playwright-desktop
2
+
3
+ Añade `page.expect_app()` al `Page` oficial de Playwright Python para automatizar aplicaciones de escritorio a través de `DesktopContext`, `App`, `Window` y `Alert`.
4
+
5
+ ## Instalación
6
+
7
+ ```shell
8
+ pip install playwright-desktop
9
+ ```
10
+
11
+ La versión mínima de Python es 3.10.
12
+
13
+ ## Compatibilidad actual
14
+
15
+ | SO | Nativo | JVM |
16
+ | ------- | ------ | --- |
17
+ | Windows | X | X |
18
+ | macOS | | |
19
+ | Linux | | |
20
+
21
+ En Windows x64, la librería selecciona el motor de cada ventana automáticamente. Usa UI Automation para accionar botones, enlaces y opciones de menú en aplicaciones nativas, y Java Access Bridge para Java Swing cuando el bridge está habilitado.
22
+
23
+ ## Sintaxis básica
24
+
25
+ Sobre un `page` de Playwright, coloca dentro de `with` la acción web que abre la aplicación de escritorio y recupera la instancia `App` con `.value` al salir del bloque.
26
+
27
+ ```python
28
+ import playwright_desktop
29
+
30
+ with page.expect_app(title="Información del equipo") as app_info:
31
+ page.get_by_role("button", name="Obtener información").click()
32
+
33
+ app = app_info.value
34
+ app.get_by_role("textbox", name="Alias").fill("QA")
35
+ app.get_by_role("button", name="Confirmar").click()
36
+ app.wait_for_closed() # espera a que la ventana se cierre tras confirmar
37
+ ```
38
+
39
+ Playwright usa exactamente el mismo patrón con `page.expect_popup()` para abrir una pestaña o ventana nueva del navegador:
40
+
41
+ ```python
42
+ with page.expect_popup() as popup_info:
43
+ page.get_by_role("link", name="Abrir reporte").click()
44
+
45
+ popup = popup_info.value
46
+ ```
47
+
48
+ Con Playwright asíncrono, usa `async with`, `app = await app_info.value` y `await` en las acciones sobre `App`, `Window`, `Alert` y `DesktopContext`.
49
+
50
+ ## Ventanas abiertas y avisos intermedios
51
+
52
+ Mientras se abre la app principal dentro de `with page.expect_app(...)`, usa `app_info.context` (`DesktopContext`, compartido por todas las páginas del mismo `BrowserContext`) para interactuar con ventanas ya abiertas o diálogos intermedios:
53
+
54
+ ```python
55
+ with page.expect_app(title="Información del equipo") as app_info:
56
+ dcontext = app_info.context
57
+ page.get_by_role("button", name="Obtener información").click()
58
+ dcontext.app(title_prefix="Microsoft Edge").get_by_role("button", name="Abrir").click()
59
+ ```
60
+
61
+ En `dcontext.app(...)` puedes filtrar por `title`, `title_prefix`, `pid`, `has_text` y `only_new=True` (ignora ventanas que ya estaban abiertas antes de iniciar el `DesktopContext`).
62
+
63
+ ## Idioma del sistema operativo
64
+
65
+ `dcontext.os_language` y `playwright_desktop.os_language()` devuelven el idioma de interfaz del sistema en formato BCP-47 (por ejemplo `"es-ES"` o `"en-US"`):
66
+
67
+ ```python
68
+ if dcontext.os_language.startswith("es"):
69
+ dcontext.app(has_text="Seguridad de Windows", only_new=True).get_by_role("button", name="Ejecutar").click()
70
+ ```
71
+
72
+ ## Ventanas secundarias, alertas y cierre
73
+
74
+ Desde una `App` ya capturada puedes esperar sus propias ventanas hijas o alertas:
75
+
76
+ ```python
77
+ with app.expect_alert(title="Confirmación") as alert_info:
78
+ app.get_by_role("button", name="Guardar").click()
79
+
80
+ alert_info.value.get_by_role("button", name="Aceptar").click()
81
+ ```
82
+
83
+ - `app.expect_window(...)` y `app.expect_alert(...)`: devuelven `Window` o `Alert` filtrados automáticamente al `pid` de `app`.
84
+ - `app.expect_child_app(...)`: captura otra `App` independiente lanzada desde `app`.
85
+ - `bring_to_front()`, `wait_for_closed()` y `close()`: disponibles en `App`, `Window` y `Alert`. Cerrar la parte desktop (`app.close()` o `dcontext.close()`) no cierra el navegador; al cerrar `page.context`, la sesión desktop se libera automáticamente.
86
+
87
+ ## Configuración opcional
88
+
89
+ `playwright_desktop` es el módulo importado en tu script; úsalo solo si necesitas fijar valores globales en milisegundos o la ruta del JDK antes de iniciar sesión:
90
+
91
+ ```python
92
+ import playwright_desktop
93
+
94
+ playwright_desktop.configure(timeout=15_000, java_home=r"C:\Program Files\Java\jdk-17")
95
+ ```
96
+
97
+ También puedes cambiar el timeout de una sesión específica con `dcontext.set_default_timeout(15_000)`.
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["maturin>=1.16,<2"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "playwright-desktop"
7
+ dynamic = ["version"]
8
+ description = "Desktop interactions for Playwright Python"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10,<3.15"
11
+ dependencies = ["playwright>=1.63,<1.66"]
12
+ classifiers = [
13
+ "Operating System :: Microsoft :: Windows",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Rust",
16
+ ]
17
+
18
+ [tool.maturin]
19
+ manifest-path = "rust/Cargo.toml"
20
+ python-source = "python"
21
+ module-name = "playwright_desktop._native"
22
+ bindings = "pyo3"
23
+ strip = true
24
+
25
+ [tool.maturin.sbom]
26
+ rust = false
@@ -0,0 +1,28 @@
1
+ """Native desktop interactions for Playwright Python."""
2
+
3
+ from importlib.metadata import PackageNotFoundError as _PackageNotFoundError, version as _package_version
4
+
5
+ try:
6
+ __version__ = _package_version("playwright-desktop")
7
+ except _PackageNotFoundError:
8
+ __version__ = "0.0.0"
9
+
10
+ from ._errors import (
11
+ AmbiguousMatchError, BridgeUnavailableError, DesktopActionError, DesktopBusyError,
12
+ DesktopClosedError, DesktopConfigurationError, DesktopError, DesktopTimeoutError,
13
+ PatchConflictError, StaleWindowError, UnsupportedPlatformError,
14
+ )
15
+ from ._patch import install, uninstall
16
+ from ._platform import os_language
17
+ from ._runtime import configure
18
+ from ._sync import Alert, App, DesktopContext, Window
19
+
20
+ install()
21
+
22
+ __all__ = [
23
+ "Alert", "App", "DesktopContext", "Window",
24
+ "configure", "install", "os_language", "uninstall", "DesktopError", "DesktopTimeoutError",
25
+ "PatchConflictError", "DesktopConfigurationError", "BridgeUnavailableError", "AmbiguousMatchError",
26
+ "StaleWindowError", "DesktopActionError", "DesktopBusyError", "DesktopClosedError",
27
+ "UnsupportedPlatformError",
28
+ ]
@@ -0,0 +1,285 @@
1
+ """Async native desktop API aligned with Playwright BrowserContext/Page."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Generic, TypeVar
6
+
7
+ from ._facade import _DesktopContextBase, _WindowBase, _accept_captured
8
+ from ._models import (
9
+ WindowQuery,
10
+ query_parameters,
11
+ validate_action_role,
12
+ validate_click_role,
13
+ validate_control,
14
+ validate_predicate,
15
+ validate_scope,
16
+ validate_text,
17
+ )
18
+ from ._timing import Deadline
19
+
20
+ _T = TypeVar("_T")
21
+
22
+
23
+ class DesktopContext(_DesktopContextBase):
24
+ """Async desktop environment correlated 1:1 with a Playwright BrowserContext."""
25
+
26
+ def app(
27
+ self,
28
+ *,
29
+ title: str | None = None,
30
+ pid: int | None = None,
31
+ title_prefix: str | None = None,
32
+ has_text: str | None = None,
33
+ only_new: bool = False,
34
+ ) -> App:
35
+ return App(self._session, self, WindowQuery(title, pid, title_prefix, has_text, only_new=only_new))
36
+
37
+ def expect_app(
38
+ self,
39
+ *,
40
+ title: str | None = None,
41
+ pid: int | None = None,
42
+ title_prefix: str | None = None,
43
+ has_text: str | None = None,
44
+ predicate: Callable[[App], bool] | None = None,
45
+ timeout: float | None = None,
46
+ ) -> _AsyncExpectation[App]:
47
+ query = WindowQuery.capture(title=title, pid=pid, title_prefix=title_prefix, has_text=has_text)
48
+ validate_predicate(predicate)
49
+ return _AsyncExpectation(
50
+ self._session,
51
+ self,
52
+ query,
53
+ timeout,
54
+ lambda reply: App(
55
+ self._session,
56
+ self,
57
+ query,
58
+ handle=reply.handle,
59
+ pid=getattr(reply, "pid", None),
60
+ title=getattr(reply, "title", None),
61
+ ),
62
+ predicate=predicate,
63
+ register=self._register_app,
64
+ )
65
+
66
+ async def close(self) -> None:
67
+ self._clear_apps()
68
+ self._session.close_nowait()
69
+
70
+
71
+ class _AsyncWindow(_WindowBase):
72
+ def get_by_role(self, role: str, *, name: str) -> Locator:
73
+ validate_control(role, name)
74
+ return Locator(self, role, name)
75
+
76
+ async def _call(self, operation: str, timeout: float | None = None, **parameters):
77
+ reply = await self._session.call_async(
78
+ operation,
79
+ window_id=self._handle,
80
+ **query_parameters(self._query),
81
+ timeout=timeout,
82
+ **parameters,
83
+ )
84
+ self._apply_reply(reply)
85
+ return reply
86
+
87
+ async def bring_to_front(self, *, timeout: float | None = None) -> None:
88
+ await self._call("bring_to_front", timeout)
89
+
90
+ async def wait_for_closed(self, *, timeout: float | None = None) -> None:
91
+ await self._call("wait_closed", timeout)
92
+
93
+ def _on_closed(self) -> None:
94
+ pass
95
+
96
+ async def close(self, *, timeout: float | None = None) -> None:
97
+ await self._call("close_window", timeout)
98
+ self._on_closed()
99
+
100
+
101
+ class Window(_AsyncWindow):
102
+ """Secondary or modal window belonging to an App."""
103
+
104
+ def __init__(self, session, dcontext: DesktopContext, app: App, query: WindowQuery, handle: int = 0, *, pid=None, title=None):
105
+ super().__init__(session, dcontext, query, handle, pid=pid, title=title)
106
+ self._app = app
107
+
108
+ @property
109
+ def app(self) -> App:
110
+ return self._app
111
+
112
+
113
+ class Alert(Window):
114
+ """Alert or dialog modal window belonging to an App."""
115
+
116
+
117
+ class App(_AsyncWindow):
118
+ """Desktop application (primary window / process) linked to a DesktopContext."""
119
+
120
+ def _on_closed(self) -> None:
121
+ self._dcontext._unregister_app(self._handle)
122
+
123
+ def expect_child_app(
124
+ self,
125
+ *,
126
+ title: str | None = None,
127
+ pid: int | None = None,
128
+ title_prefix: str | None = None,
129
+ has_text: str | None = None,
130
+ predicate: Callable[[App], bool] | None = None,
131
+ timeout: float | None = None,
132
+ ) -> _AsyncExpectation[App]:
133
+ return self._dcontext.expect_app(
134
+ title=title,
135
+ pid=pid,
136
+ title_prefix=title_prefix,
137
+ has_text=has_text,
138
+ predicate=predicate,
139
+ timeout=timeout,
140
+ )
141
+
142
+ def _expect_owned_window(
143
+ self,
144
+ window_cls: type[_T],
145
+ *,
146
+ title: str | None = None,
147
+ title_prefix: str | None = None,
148
+ has_text: str | None = None,
149
+ predicate: Callable[[_T], bool] | None = None,
150
+ timeout: float | None = None,
151
+ ) -> _AsyncExpectation[_T]:
152
+ query = WindowQuery.capture(
153
+ title=title, pid=self._pid, title_prefix=title_prefix, has_text=has_text
154
+ )
155
+ validate_predicate(predicate)
156
+ return _AsyncExpectation(
157
+ self._session,
158
+ self._dcontext,
159
+ query,
160
+ timeout,
161
+ lambda reply: window_cls(
162
+ self._session,
163
+ self._dcontext,
164
+ self,
165
+ query,
166
+ handle=reply.handle,
167
+ pid=getattr(reply, "pid", None),
168
+ title=getattr(reply, "title", None),
169
+ ),
170
+ predicate=predicate,
171
+ )
172
+
173
+ def expect_window(
174
+ self,
175
+ *,
176
+ title: str | None = None,
177
+ title_prefix: str | None = None,
178
+ has_text: str | None = None,
179
+ predicate: Callable[[Window], bool] | None = None,
180
+ timeout: float | None = None,
181
+ ) -> _AsyncExpectation[Window]:
182
+ return self._expect_owned_window(
183
+ Window,
184
+ title=title,
185
+ title_prefix=title_prefix,
186
+ has_text=has_text,
187
+ predicate=predicate,
188
+ timeout=timeout,
189
+ )
190
+
191
+ def expect_alert(
192
+ self,
193
+ *,
194
+ title: str | None = None,
195
+ title_prefix: str | None = None,
196
+ has_text: str | None = None,
197
+ predicate: Callable[[Alert], bool] | None = None,
198
+ timeout: float | None = None,
199
+ ) -> _AsyncExpectation[Alert]:
200
+ return self._expect_owned_window(
201
+ Alert,
202
+ title=title,
203
+ title_prefix=title_prefix,
204
+ has_text=has_text,
205
+ predicate=predicate,
206
+ timeout=timeout,
207
+ )
208
+
209
+
210
+ class Locator:
211
+ def __init__(self, window: _AsyncWindow, role: str, name: str, scope=None):
212
+ self._window, self._role, self._name = window, role, name
213
+ self._scope = scope
214
+
215
+ def get_by_role(self, role: str, *, name: str) -> Locator:
216
+ validate_control(role, name)
217
+ scope = validate_scope(self._role, self._name, self._scope)
218
+ return Locator(self._window, role, name, scope)
219
+
220
+ async def _call(self, operation: str, timeout: float | None = None, **parameters):
221
+ if self._scope is not None:
222
+ parameters.update(scope_role=self._scope[0], scope_name=self._scope[1])
223
+ return await self._window._call(operation, timeout, role=self._role, name=self._name, **parameters)
224
+
225
+ async def wait_for(self, *, timeout: float | None = None) -> None:
226
+ await self._call("wait_visible", timeout)
227
+
228
+ async def fill(self, text: str, *, timeout: float | None = None) -> None:
229
+ validate_action_role(self._role, "textbox", "fill")
230
+ validate_text(text)
231
+ await self._call("fill", timeout, text=text)
232
+
233
+ async def input_value(self, *, timeout: float | None = None) -> str:
234
+ validate_action_role(self._role, "textbox", "input_value")
235
+ return (await self._call("read_text", timeout)).text
236
+
237
+ async def click(self, *, timeout: float | None = None) -> None:
238
+ validate_click_role(self._role)
239
+ await self._call("click", timeout)
240
+
241
+
242
+ class AsyncEventInfo(Generic[_T]):
243
+ def __init__(self, dcontext: DesktopContext):
244
+ self._dcontext = dcontext
245
+ self._value: _T | None = None
246
+
247
+ @property
248
+ def context(self) -> DesktopContext:
249
+ return self._dcontext
250
+
251
+ @property
252
+ def value(self):
253
+ async def result() -> _T:
254
+ if self._value is None:
255
+ raise RuntimeError("Await event.value after leaving the expect context.")
256
+ return self._value
257
+ return result()
258
+
259
+
260
+ class _AsyncExpectation(Generic[_T]):
261
+ def __init__(self, session, dcontext: DesktopContext, query: WindowQuery, timeout, factory, *, predicate=None, register=None):
262
+ self._session = session
263
+ self._query = query
264
+ self._timeout = session.timeout(timeout)
265
+ self._factory = factory
266
+ self._predicate = predicate
267
+ self._register = register
268
+ self._info: AsyncEventInfo[_T] = AsyncEventInfo(dcontext)
269
+ self._capture = None
270
+
271
+ async def __aenter__(self) -> AsyncEventInfo[_T]:
272
+ self._deadline = Deadline(self._timeout)
273
+ reply = await self._session.call_async("prepare", **query_parameters(self._query), timeout=self._timeout)
274
+ self._capture = reply.handle
275
+ return self._info
276
+
277
+ async def __aexit__(self, exc_type, exc, traceback):
278
+ if exc_type is not None:
279
+ self._session.cancel_capture(self._capture)
280
+ return False
281
+ with self._session.capture_completion(self._capture, self._deadline) as remaining:
282
+ reply = await self._session.call_async("capture", capture_id=self._capture, timeout=remaining)
283
+ candidate = self._factory(reply)
284
+ self._info._value = _accept_captured(candidate, self._predicate, register=self._register)
285
+ return False
@@ -0,0 +1,30 @@
1
+ """Load the desktop extension and resolve Java Access Bridge settings."""
2
+
3
+ from importlib import import_module
4
+ import os
5
+ from pathlib import Path
6
+
7
+ from ._errors import DesktopError
8
+ from ._platform import require_supported_platform
9
+
10
+ def load_extension():
11
+ require_supported_platform()
12
+ try:
13
+ return import_module("playwright_desktop._native")
14
+ except ImportError as error:
15
+ raise DesktopError("The native extension is not installed. Build and install the playwright-desktop wheel.") from error
16
+
17
+
18
+ def normalize_java_home(java_home: str | os.PathLike[str]) -> str:
19
+ path = os.fspath(java_home)
20
+ if not isinstance(path, str) or not path or "\0" in path:
21
+ raise ValueError("java_home must be a nonempty filesystem path.")
22
+ return str(Path(path).expanduser().absolute())
23
+
24
+
25
+ def session_argument(java_home: str | None) -> str | None:
26
+ if java_home is not None:
27
+ return java_home
28
+ if configured := os.environ.get("JAVA_HOME"):
29
+ return normalize_java_home(configured)
30
+ return None
@@ -0,0 +1,62 @@
1
+ """Public desktop errors, compatible with Playwright's error hierarchy."""
2
+
3
+ from playwright.sync_api import Error, TimeoutError as PlaywrightTimeoutError
4
+
5
+
6
+ class DesktopError(Error):
7
+ pass
8
+
9
+
10
+ class DesktopTimeoutError(DesktopError, PlaywrightTimeoutError):
11
+ pass
12
+
13
+
14
+ class PatchConflictError(DesktopError):
15
+ pass
16
+
17
+
18
+ class DesktopConfigurationError(DesktopError):
19
+ pass
20
+
21
+
22
+ class BridgeUnavailableError(DesktopError):
23
+ pass
24
+
25
+
26
+ class AmbiguousMatchError(DesktopError):
27
+ pass
28
+
29
+
30
+ class StaleWindowError(DesktopError):
31
+ pass
32
+
33
+
34
+ class DesktopActionError(DesktopError):
35
+ pass
36
+
37
+
38
+ class DesktopBusyError(DesktopError):
39
+ pass
40
+
41
+
42
+ class DesktopClosedError(DesktopError):
43
+ pass
44
+
45
+
46
+ class UnsupportedPlatformError(DesktopError):
47
+ pass
48
+
49
+
50
+ NATIVE_ERRORS = {
51
+ "INVALID_ARGUMENT": ValueError,
52
+ "TIMEOUT": DesktopTimeoutError,
53
+ "CONFIGURATION": DesktopConfigurationError,
54
+ "BRIDGE": BridgeUnavailableError,
55
+ "AMBIGUOUS": AmbiguousMatchError,
56
+ "STALE": StaleWindowError,
57
+ "ACTION": DesktopActionError,
58
+ "BUSY": DesktopBusyError,
59
+ "CLOSED": DesktopClosedError,
60
+ "CANCELLED": DesktopClosedError,
61
+ "UNSUPPORTED": UnsupportedPlatformError,
62
+ }