sim-cli-core 0.2.4__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.
- sim/__init__.py +11 -0
- sim/__main__.py +24 -0
- sim/_plugin_install.py +451 -0
- sim/_timeout.py +115 -0
- sim/cli.py +1353 -0
- sim/compat.py +411 -0
- sim/config.py +380 -0
- sim/describe.py +346 -0
- sim/driver.py +190 -0
- sim/drivers/__init__.py +161 -0
- sim/drivers/coolprop/__init__.py +3 -0
- sim/drivers/coolprop/driver.py +183 -0
- sim/drivers/openfoam/__init__.py +4 -0
- sim/drivers/openfoam/compatibility.yaml +37 -0
- sim/drivers/openfoam/driver.py +432 -0
- sim/gui/LICENSES/ATTRIBUTION.md +24 -0
- sim/gui/__init__.py +230 -0
- sim/gui/_pywinauto_tools.py +452 -0
- sim/gui/_win32_dialog.py +148 -0
- sim/history.py +170 -0
- sim/inspect.py +1088 -0
- sim/plugins.py +468 -0
- sim/runner.py +195 -0
- sim/server.py +547 -0
- sim/session.py +224 -0
- sim/testing/__init__.py +30 -0
- sim/testing/protocol_conformance.py +264 -0
- sim_cli_core-0.2.4.dist-info/METADATA +309 -0
- sim_cli_core-0.2.4.dist-info/RECORD +33 -0
- sim_cli_core-0.2.4.dist-info/WHEEL +4 -0
- sim_cli_core-0.2.4.dist-info/entry_points.txt +2 -0
- sim_cli_core-0.2.4.dist-info/licenses/LICENSE +190 -0
- sim_cli_core-0.2.4.dist-info/licenses/NOTICE +72 -0
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"""Pywinauto-based UIA helpers run in isolated subprocesses.
|
|
2
|
+
|
|
3
|
+
Why subprocess isolation?
|
|
4
|
+
pywinauto's UIA backend uses COM under the hood. ``invoke()`` on a
|
|
5
|
+
menu/button throws ``COMError`` and can pollute the COM apartment of
|
|
6
|
+
the calling process. flotherm's driver proved this the hard way and
|
|
7
|
+
solved it by spawning every UIA call as a one-shot ``python -c``
|
|
8
|
+
subprocess. We reuse that pattern here for every cross-driver GUI
|
|
9
|
+
action: main process stays clean, each call is stateless.
|
|
10
|
+
|
|
11
|
+
Design inspiration:
|
|
12
|
+
* subprocess isolation + Windows file-dialog fallback: developed
|
|
13
|
+
in this project's GUI-driving work for solvers without batch APIs.
|
|
14
|
+
* tool catalog (find/click/type/close/screenshot/snapshot):
|
|
15
|
+
sandraschi/pywinauto-mcp (MIT).
|
|
16
|
+
https://github.com/sandraschi/pywinauto-mcp
|
|
17
|
+
|
|
18
|
+
We call pywinauto directly (already a dep on Windows) instead of
|
|
19
|
+
vendoring pywinauto-mcp's MCP-decorated wrappers — the MCP layer only
|
|
20
|
+
adds value when exposing tools over the MCP protocol, which sim does
|
|
21
|
+
not use.
|
|
22
|
+
|
|
23
|
+
Every public helper returns a JSON-serialisable dict with at minimum
|
|
24
|
+
``ok: bool``. Failures set ``ok=False`` + ``error: str`` — they do not
|
|
25
|
+
raise — so higher layers can decide whether to escalate.
|
|
26
|
+
"""
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import subprocess
|
|
32
|
+
import sys
|
|
33
|
+
import tempfile
|
|
34
|
+
import textwrap
|
|
35
|
+
|
|
36
|
+
# Default subprocess wall-clock per UIA call (seconds).
|
|
37
|
+
_DEFAULT_TIMEOUT = 10.0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def pywinauto_available() -> bool:
|
|
41
|
+
"""Return True iff a subprocess can ``import pywinauto``.
|
|
42
|
+
|
|
43
|
+
We check via subprocess (not ``import pywinauto`` in-process) so we
|
|
44
|
+
avoid importing pywinauto into sim serve's main process. Returns
|
|
45
|
+
False off-Windows.
|
|
46
|
+
"""
|
|
47
|
+
if os.name != "nt":
|
|
48
|
+
return False
|
|
49
|
+
try:
|
|
50
|
+
r = subprocess.run(
|
|
51
|
+
[sys.executable, "-c", "import pywinauto"],
|
|
52
|
+
capture_output=True, timeout=5,
|
|
53
|
+
)
|
|
54
|
+
return r.returncode == 0
|
|
55
|
+
except Exception:
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ── subprocess runner ────────────────────────────────────────────────────────
|
|
60
|
+
|
|
61
|
+
def _run_uia(code: str, timeout_s: float = _DEFAULT_TIMEOUT) -> dict:
|
|
62
|
+
"""Run ``code`` as a ``python -c`` subprocess.
|
|
63
|
+
|
|
64
|
+
The subprocess is expected to print exactly **one** line of JSON on
|
|
65
|
+
stdout — its result dict. Any uncaught exception turns into
|
|
66
|
+
``{ok: false, error: "<stderr or message>"}``.
|
|
67
|
+
"""
|
|
68
|
+
if os.name != "nt":
|
|
69
|
+
return {"ok": False, "error": "pywinauto helpers require Windows"}
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
proc = subprocess.run(
|
|
73
|
+
[sys.executable, "-c", code],
|
|
74
|
+
capture_output=True,
|
|
75
|
+
timeout=timeout_s,
|
|
76
|
+
text=True,
|
|
77
|
+
encoding="utf-8",
|
|
78
|
+
errors="replace",
|
|
79
|
+
)
|
|
80
|
+
except subprocess.TimeoutExpired:
|
|
81
|
+
return {"ok": False, "error": f"UIA subprocess timed out after {timeout_s}s"}
|
|
82
|
+
except Exception as exc:
|
|
83
|
+
return {"ok": False, "error": f"UIA subprocess launch failed: {exc}"}
|
|
84
|
+
|
|
85
|
+
if proc.returncode != 0:
|
|
86
|
+
err = (proc.stderr or "").strip() or f"exit {proc.returncode}"
|
|
87
|
+
return {"ok": False, "error": err, "stdout": (proc.stdout or "").strip()}
|
|
88
|
+
|
|
89
|
+
# Parse last non-empty stdout line as JSON. Some pywinauto builds
|
|
90
|
+
# occasionally emit noise on stdout that we ignore.
|
|
91
|
+
lines = [ln for ln in (proc.stdout or "").splitlines() if ln.strip()]
|
|
92
|
+
if not lines:
|
|
93
|
+
return {"ok": False, "error": "no stdout from UIA subprocess"}
|
|
94
|
+
try:
|
|
95
|
+
return json.loads(lines[-1])
|
|
96
|
+
except json.JSONDecodeError:
|
|
97
|
+
return {"ok": False, "error": f"UIA subprocess did not emit JSON: {lines[-1]!r}"}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# ── Templates ───────────────────────────────────────────────────────────────
|
|
101
|
+
#
|
|
102
|
+
# Each template expects a ``PARAMS`` JSON dict passed as the first arg to
|
|
103
|
+
# python (``python -c '<template>' <params-json>``). We pre-format the
|
|
104
|
+
# params inline to keep shell quoting simple.
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _render(template: str, params: dict) -> str:
|
|
108
|
+
"""Inject params dict + json + sys imports into a UIA subprocess script."""
|
|
109
|
+
header = textwrap.dedent(f"""
|
|
110
|
+
import io, json, sys, time
|
|
111
|
+
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
|
112
|
+
PARAMS = {json.dumps(params)}
|
|
113
|
+
def _emit(d):
|
|
114
|
+
print(json.dumps(d, ensure_ascii=False))
|
|
115
|
+
try:
|
|
116
|
+
from pywinauto import Desktop, Application
|
|
117
|
+
from pywinauto.findwindows import ElementNotFoundError
|
|
118
|
+
except Exception as e:
|
|
119
|
+
_emit({{"ok": False, "error": f"pywinauto import failed: {{e}}"}})
|
|
120
|
+
raise SystemExit(0)
|
|
121
|
+
""").lstrip()
|
|
122
|
+
return header + template
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ── public helpers ──────────────────────────────────────────────────────────
|
|
126
|
+
|
|
127
|
+
_LIST_WINDOWS_BODY = textwrap.dedent("""
|
|
128
|
+
proc_sub = tuple(s.lower() for s in PARAMS.get('process_name_substrings') or ())
|
|
129
|
+
out = []
|
|
130
|
+
try:
|
|
131
|
+
for w in Desktop(backend='uia').windows():
|
|
132
|
+
try:
|
|
133
|
+
if not w.is_visible():
|
|
134
|
+
continue
|
|
135
|
+
title = w.window_text() or ''
|
|
136
|
+
try:
|
|
137
|
+
pid = w.process_id()
|
|
138
|
+
except Exception:
|
|
139
|
+
pid = 0
|
|
140
|
+
try:
|
|
141
|
+
import psutil
|
|
142
|
+
try:
|
|
143
|
+
proc_name = psutil.Process(pid).name()
|
|
144
|
+
except Exception:
|
|
145
|
+
proc_name = ''
|
|
146
|
+
except Exception:
|
|
147
|
+
proc_name = ''
|
|
148
|
+
if proc_sub:
|
|
149
|
+
if not any(s in proc_name.lower() for s in proc_sub):
|
|
150
|
+
continue
|
|
151
|
+
try:
|
|
152
|
+
r = w.rectangle()
|
|
153
|
+
rect = [r.left, r.top, r.right, r.bottom]
|
|
154
|
+
except Exception:
|
|
155
|
+
rect = None
|
|
156
|
+
out.append({'hwnd': w.handle, 'pid': pid, 'proc': proc_name, 'title': title, 'rect': rect})
|
|
157
|
+
except Exception:
|
|
158
|
+
continue
|
|
159
|
+
except Exception as e:
|
|
160
|
+
_emit({'ok': False, 'error': f'list_windows: {e}'})
|
|
161
|
+
raise SystemExit(0)
|
|
162
|
+
_emit({'ok': True, 'windows': out})
|
|
163
|
+
""")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def list_windows(process_name_substrings: tuple[str, ...] = ()) -> dict:
|
|
167
|
+
"""Return visible top-level windows, optionally filtered by process name."""
|
|
168
|
+
return _run_uia(_render(_LIST_WINDOWS_BODY, {
|
|
169
|
+
"process_name_substrings": list(process_name_substrings),
|
|
170
|
+
}))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
_FIND_WINDOW_BODY = textwrap.dedent("""
|
|
174
|
+
title_sub = PARAMS.get('title_contains') or ''
|
|
175
|
+
proc_sub = tuple(s.lower() for s in PARAMS.get('process_name_substrings') or ())
|
|
176
|
+
deadline = time.monotonic() + float(PARAMS.get('timeout_s', 5))
|
|
177
|
+
match = None
|
|
178
|
+
while time.monotonic() < deadline and match is None:
|
|
179
|
+
try:
|
|
180
|
+
for w in Desktop(backend='uia').windows():
|
|
181
|
+
try:
|
|
182
|
+
if not w.is_visible():
|
|
183
|
+
continue
|
|
184
|
+
title = w.window_text() or ''
|
|
185
|
+
if title_sub and title_sub not in title:
|
|
186
|
+
continue
|
|
187
|
+
try:
|
|
188
|
+
pid = w.process_id()
|
|
189
|
+
except Exception:
|
|
190
|
+
pid = 0
|
|
191
|
+
proc_name = ''
|
|
192
|
+
try:
|
|
193
|
+
import psutil
|
|
194
|
+
proc_name = psutil.Process(pid).name() if pid else ''
|
|
195
|
+
except Exception:
|
|
196
|
+
proc_name = ''
|
|
197
|
+
if proc_sub and not any(s in proc_name.lower() for s in proc_sub):
|
|
198
|
+
continue
|
|
199
|
+
try:
|
|
200
|
+
r = w.rectangle()
|
|
201
|
+
rect = [r.left, r.top, r.right, r.bottom]
|
|
202
|
+
except Exception:
|
|
203
|
+
rect = None
|
|
204
|
+
match = {'hwnd': w.handle, 'pid': pid, 'proc': proc_name, 'title': title, 'rect': rect}
|
|
205
|
+
break
|
|
206
|
+
except Exception:
|
|
207
|
+
continue
|
|
208
|
+
except Exception:
|
|
209
|
+
pass
|
|
210
|
+
if match is None:
|
|
211
|
+
time.sleep(0.3)
|
|
212
|
+
if match is None:
|
|
213
|
+
_emit({'ok': True, 'window': None})
|
|
214
|
+
else:
|
|
215
|
+
_emit({'ok': True, 'window': match})
|
|
216
|
+
""")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def find_window(
|
|
220
|
+
title_contains: str = "",
|
|
221
|
+
process_name_substrings: tuple[str, ...] = (),
|
|
222
|
+
timeout_s: float = 5.0,
|
|
223
|
+
) -> dict:
|
|
224
|
+
"""Poll until a visible window with matching title+process is found, or timeout."""
|
|
225
|
+
return _run_uia(_render(_FIND_WINDOW_BODY, {
|
|
226
|
+
"title_contains": title_contains,
|
|
227
|
+
"process_name_substrings": list(process_name_substrings),
|
|
228
|
+
"timeout_s": float(timeout_s),
|
|
229
|
+
}), timeout_s=float(timeout_s) + 5)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
_CLICK_BODY = textwrap.dedent("""
|
|
233
|
+
hwnd = int(PARAMS['hwnd'])
|
|
234
|
+
label = PARAMS['label']
|
|
235
|
+
timeout_s = float(PARAMS.get('timeout_s', 5))
|
|
236
|
+
try:
|
|
237
|
+
app = Application(backend='uia').connect(handle=hwnd)
|
|
238
|
+
win = app.window(handle=hwnd)
|
|
239
|
+
except Exception as e:
|
|
240
|
+
_emit({'ok': False, 'error': f'connect(handle={hwnd}) failed: {e}'})
|
|
241
|
+
raise SystemExit(0)
|
|
242
|
+
# try button by label first
|
|
243
|
+
try:
|
|
244
|
+
btn = win.child_window(title=label, control_type='Button')
|
|
245
|
+
btn.wait('visible', timeout=timeout_s)
|
|
246
|
+
btn.invoke() if hasattr(btn, 'invoke') else btn.click_input()
|
|
247
|
+
_emit({'ok': True, 'clicked': label, 'strategy': 'button_by_title'})
|
|
248
|
+
raise SystemExit(0)
|
|
249
|
+
except SystemExit:
|
|
250
|
+
raise
|
|
251
|
+
except Exception:
|
|
252
|
+
pass
|
|
253
|
+
# fallback: any control whose name matches
|
|
254
|
+
try:
|
|
255
|
+
ctl = win.child_window(title=label)
|
|
256
|
+
ctl.wait('visible', timeout=timeout_s)
|
|
257
|
+
ctl.click_input()
|
|
258
|
+
_emit({'ok': True, 'clicked': label, 'strategy': 'any_control_by_title'})
|
|
259
|
+
raise SystemExit(0)
|
|
260
|
+
except SystemExit:
|
|
261
|
+
raise
|
|
262
|
+
except Exception as e:
|
|
263
|
+
_emit({'ok': False, 'error': f'no control titled {label!r} in hwnd={hwnd}: {e}'})
|
|
264
|
+
""")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def click_by_name(hwnd: int, label: str, timeout_s: float = 5.0) -> dict:
|
|
268
|
+
"""Click the control titled ``label`` inside the window ``hwnd``."""
|
|
269
|
+
return _run_uia(_render(_CLICK_BODY, {
|
|
270
|
+
"hwnd": int(hwnd),
|
|
271
|
+
"label": label,
|
|
272
|
+
"timeout_s": float(timeout_s),
|
|
273
|
+
}), timeout_s=float(timeout_s) + 5)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
_SEND_TEXT_BODY = textwrap.dedent("""
|
|
277
|
+
hwnd = int(PARAMS['hwnd'])
|
|
278
|
+
text = PARAMS['text']
|
|
279
|
+
field = PARAMS.get('field') or ''
|
|
280
|
+
timeout_s = float(PARAMS.get('timeout_s', 5))
|
|
281
|
+
try:
|
|
282
|
+
app = Application(backend='uia').connect(handle=hwnd)
|
|
283
|
+
win = app.window(handle=hwnd)
|
|
284
|
+
except Exception as e:
|
|
285
|
+
_emit({'ok': False, 'error': f'connect failed: {e}'})
|
|
286
|
+
raise SystemExit(0)
|
|
287
|
+
try:
|
|
288
|
+
if field:
|
|
289
|
+
edit = win.child_window(title=field, control_type='Edit')
|
|
290
|
+
else:
|
|
291
|
+
# no field specified -> first editable control
|
|
292
|
+
edit = win.child_window(control_type='Edit', found_index=0)
|
|
293
|
+
edit.wait('visible', timeout=timeout_s)
|
|
294
|
+
try:
|
|
295
|
+
edit.set_edit_text(text)
|
|
296
|
+
except Exception:
|
|
297
|
+
edit.type_keys(text, with_spaces=True, with_tabs=True, with_newlines=True)
|
|
298
|
+
_emit({'ok': True, 'field': field or '<first_edit>'})
|
|
299
|
+
except Exception as e:
|
|
300
|
+
_emit({'ok': False, 'error': f'send_text failed: {e}'})
|
|
301
|
+
""")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def send_text(hwnd: int, text: str, field: str = "", timeout_s: float = 5.0) -> dict:
|
|
305
|
+
"""Type ``text`` into an Edit control, optionally matching by accessible name."""
|
|
306
|
+
return _run_uia(_render(_SEND_TEXT_BODY, {
|
|
307
|
+
"hwnd": int(hwnd),
|
|
308
|
+
"text": text,
|
|
309
|
+
"field": field,
|
|
310
|
+
"timeout_s": float(timeout_s),
|
|
311
|
+
}), timeout_s=float(timeout_s) + 5)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
_CLOSE_BODY = textwrap.dedent("""
|
|
315
|
+
hwnd = int(PARAMS['hwnd'])
|
|
316
|
+
try:
|
|
317
|
+
app = Application(backend='uia').connect(handle=hwnd)
|
|
318
|
+
app.window(handle=hwnd).close()
|
|
319
|
+
_emit({'ok': True})
|
|
320
|
+
except Exception as e:
|
|
321
|
+
_emit({'ok': False, 'error': f'close failed: {e}'})
|
|
322
|
+
""")
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def close_window(hwnd: int) -> dict:
|
|
326
|
+
"""Close the window ``hwnd`` (semantically equivalent to Alt+F4)."""
|
|
327
|
+
return _run_uia(_render(_CLOSE_BODY, {"hwnd": int(hwnd)}))
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
_ACTIVATE_BODY = textwrap.dedent("""
|
|
331
|
+
hwnd = int(PARAMS['hwnd'])
|
|
332
|
+
try:
|
|
333
|
+
app = Application(backend='uia').connect(handle=hwnd)
|
|
334
|
+
win = app.window(handle=hwnd)
|
|
335
|
+
win.set_focus()
|
|
336
|
+
_emit({'ok': True})
|
|
337
|
+
except Exception as e:
|
|
338
|
+
_emit({'ok': False, 'error': f'activate failed: {e}'})
|
|
339
|
+
""")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def activate_window(hwnd: int) -> dict:
|
|
343
|
+
"""Bring ``hwnd`` to the foreground."""
|
|
344
|
+
return _run_uia(_render(_ACTIVATE_BODY, {"hwnd": int(hwnd)}))
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
_SCREENSHOT_BODY = textwrap.dedent("""
|
|
348
|
+
hwnd = int(PARAMS['hwnd'])
|
|
349
|
+
out_path = PARAMS['out_path']
|
|
350
|
+
try:
|
|
351
|
+
app = Application(backend='uia').connect(handle=hwnd)
|
|
352
|
+
win = app.window(handle=hwnd)
|
|
353
|
+
img = win.capture_as_image()
|
|
354
|
+
img.save(out_path, 'PNG')
|
|
355
|
+
_emit({'ok': True, 'path': out_path, 'width': img.width, 'height': img.height})
|
|
356
|
+
except Exception as e:
|
|
357
|
+
_emit({'ok': False, 'error': f'screenshot failed: {e}'})
|
|
358
|
+
""")
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def screenshot_window(hwnd: int, out_path: str) -> dict:
|
|
362
|
+
"""Capture ``hwnd`` (window-only, not full desktop) to ``out_path`` as PNG."""
|
|
363
|
+
return _run_uia(_render(_SCREENSHOT_BODY, {
|
|
364
|
+
"hwnd": int(hwnd),
|
|
365
|
+
"out_path": str(out_path),
|
|
366
|
+
}))
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
_SNAPSHOT_BODY = textwrap.dedent("""
|
|
370
|
+
proc_sub = tuple(s.lower() for s in PARAMS.get('process_name_substrings') or ())
|
|
371
|
+
max_depth = int(PARAMS.get('max_depth', 3))
|
|
372
|
+
windows_out = []
|
|
373
|
+
try:
|
|
374
|
+
for w in Desktop(backend='uia').windows():
|
|
375
|
+
try:
|
|
376
|
+
if not w.is_visible():
|
|
377
|
+
continue
|
|
378
|
+
try:
|
|
379
|
+
pid = w.process_id()
|
|
380
|
+
except Exception:
|
|
381
|
+
pid = 0
|
|
382
|
+
proc_name = ''
|
|
383
|
+
try:
|
|
384
|
+
import psutil
|
|
385
|
+
proc_name = psutil.Process(pid).name() if pid else ''
|
|
386
|
+
except Exception:
|
|
387
|
+
proc_name = ''
|
|
388
|
+
if proc_sub and not any(s in proc_name.lower() for s in proc_sub):
|
|
389
|
+
continue
|
|
390
|
+
def walk(el, depth):
|
|
391
|
+
if depth > max_depth:
|
|
392
|
+
return []
|
|
393
|
+
kids = []
|
|
394
|
+
try:
|
|
395
|
+
for c in el.children():
|
|
396
|
+
try:
|
|
397
|
+
info = {
|
|
398
|
+
'name': c.window_text() or '',
|
|
399
|
+
'control_type': c.element_info.control_type or '',
|
|
400
|
+
'handle': c.handle or 0,
|
|
401
|
+
}
|
|
402
|
+
sub = walk(c, depth + 1)
|
|
403
|
+
if sub:
|
|
404
|
+
info['children'] = sub
|
|
405
|
+
kids.append(info)
|
|
406
|
+
except Exception:
|
|
407
|
+
continue
|
|
408
|
+
except Exception:
|
|
409
|
+
pass
|
|
410
|
+
return kids
|
|
411
|
+
windows_out.append({
|
|
412
|
+
'hwnd': w.handle,
|
|
413
|
+
'pid': pid,
|
|
414
|
+
'proc': proc_name,
|
|
415
|
+
'title': w.window_text() or '',
|
|
416
|
+
'controls': walk(w, 1),
|
|
417
|
+
})
|
|
418
|
+
except Exception:
|
|
419
|
+
continue
|
|
420
|
+
except Exception as e:
|
|
421
|
+
_emit({'ok': False, 'error': f'snapshot: {e}'})
|
|
422
|
+
raise SystemExit(0)
|
|
423
|
+
_emit({'ok': True, 'windows': windows_out})
|
|
424
|
+
""")
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def snapshot_uia_tree(
|
|
428
|
+
process_name_substrings: tuple[str, ...] = (),
|
|
429
|
+
max_depth: int = 3,
|
|
430
|
+
) -> dict:
|
|
431
|
+
"""Return the UIA tree of every matching window down to ``max_depth``."""
|
|
432
|
+
return _run_uia(_render(_SNAPSHOT_BODY, {
|
|
433
|
+
"process_name_substrings": list(process_name_substrings),
|
|
434
|
+
"max_depth": int(max_depth),
|
|
435
|
+
}), timeout_s=30.0)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
# ── util ────────────────────────────────────────────────────────────────────
|
|
439
|
+
|
|
440
|
+
def workdir_screenshot_path(workdir: str | os.PathLike, label: str) -> str:
|
|
441
|
+
"""Build a PNG path under ``<workdir>/screenshots/`` ensuring the dir exists.
|
|
442
|
+
|
|
443
|
+
Not pywinauto-specific but kept here because ``SimWindow.screenshot`` is
|
|
444
|
+
the sole user.
|
|
445
|
+
"""
|
|
446
|
+
base = os.path.join(str(workdir), "screenshots")
|
|
447
|
+
os.makedirs(base, exist_ok=True)
|
|
448
|
+
# sanitise label for filesystem safety
|
|
449
|
+
safe = "".join(c if c.isalnum() or c in "._-" else "_" for c in label)[:64] or "shot"
|
|
450
|
+
fd, path = tempfile.mkstemp(prefix=f"{safe}_", suffix=".png", dir=base)
|
|
451
|
+
os.close(fd)
|
|
452
|
+
return path
|
sim/gui/_win32_dialog.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Generic Win32 ctypes helpers for standard Windows dialogs.
|
|
2
|
+
|
|
3
|
+
A shared backend so every driver can reuse the same path for interacting
|
|
4
|
+
with modal dialogs without vendoring its own copy.
|
|
5
|
+
|
|
6
|
+
The scope is deliberately narrow:
|
|
7
|
+
|
|
8
|
+
* enumerate top-level visible windows by title,
|
|
9
|
+
* wait for a dialog whose title contains a substring,
|
|
10
|
+
* fill a standard Windows file-open/save dialog (edit ctl 1148 + OK btn 1)
|
|
11
|
+
using WM_SETTEXT + BM_CLICK,
|
|
12
|
+
* send WM_CLOSE to a window,
|
|
13
|
+
* send a plain button click by dialog-item id.
|
|
14
|
+
|
|
15
|
+
These primitives do **not** depend on the UIA backend — they only use
|
|
16
|
+
raw user32 messages. Higher-level semantic operations (find button by
|
|
17
|
+
text, navigate menus, etc.) belong in ``_pywinauto_tools.py``.
|
|
18
|
+
|
|
19
|
+
Non-Windows platforms: ``user32`` stays ``None`` and helpers return
|
|
20
|
+
safe defaults (``False`` / empty list) so import never explodes.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import ctypes
|
|
25
|
+
import ctypes.wintypes
|
|
26
|
+
import os
|
|
27
|
+
import time
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
user32 = ctypes.windll.user32 if os.name == "nt" else None
|
|
31
|
+
|
|
32
|
+
# Windows messages we use
|
|
33
|
+
WM_SETTEXT = 0x000C
|
|
34
|
+
BM_CLICK = 0x00F5
|
|
35
|
+
WM_CLOSE = 0x0010
|
|
36
|
+
|
|
37
|
+
# Standard control ids for the common Windows file-open/save dialog template.
|
|
38
|
+
FILE_DIALOG_EDIT_CTL_ID = 1148
|
|
39
|
+
FILE_DIALOG_OK_BTN_ID = 1
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def enum_visible_windows() -> list[tuple[int, str]]:
|
|
43
|
+
"""Return ``[(hwnd, title)]`` for all visible top-level windows.
|
|
44
|
+
|
|
45
|
+
Returns an empty list off-Windows or if the enumeration fails.
|
|
46
|
+
"""
|
|
47
|
+
if user32 is None:
|
|
48
|
+
return []
|
|
49
|
+
|
|
50
|
+
hwnds: list[int] = []
|
|
51
|
+
|
|
52
|
+
@ctypes.WINFUNCTYPE(ctypes.wintypes.BOOL, ctypes.wintypes.HWND, ctypes.wintypes.LPARAM)
|
|
53
|
+
def _cb(hwnd, _lp):
|
|
54
|
+
hwnds.append(hwnd)
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
user32.EnumWindows(_cb, 0)
|
|
58
|
+
|
|
59
|
+
out: list[tuple[int, str]] = []
|
|
60
|
+
for hwnd in hwnds:
|
|
61
|
+
if not user32.IsWindowVisible(hwnd):
|
|
62
|
+
continue
|
|
63
|
+
buf = ctypes.create_unicode_buffer(256)
|
|
64
|
+
user32.GetWindowTextW(hwnd, buf, 256)
|
|
65
|
+
if buf.value:
|
|
66
|
+
out.append((hwnd, buf.value))
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def find_dialog_by_title(title_substring: str, timeout: float = 10.0) -> int | None:
|
|
71
|
+
"""Poll the desktop for a visible window whose title contains
|
|
72
|
+
``title_substring``.
|
|
73
|
+
|
|
74
|
+
Returns the first matching hwnd, or ``None`` on timeout.
|
|
75
|
+
"""
|
|
76
|
+
if user32 is None:
|
|
77
|
+
return None
|
|
78
|
+
deadline = time.monotonic() + timeout
|
|
79
|
+
while time.monotonic() < deadline:
|
|
80
|
+
for hwnd, title in enum_visible_windows():
|
|
81
|
+
if title_substring in title:
|
|
82
|
+
return hwnd
|
|
83
|
+
time.sleep(0.3)
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def fill_file_dialog(dialog_hwnd: int, file_path: str) -> bool:
|
|
88
|
+
"""Set ``file_path`` into the edit control and click OK on a standard
|
|
89
|
+
Windows file-open/save dialog.
|
|
90
|
+
|
|
91
|
+
Uses control ids 1148 (edit) and 1 (OK button) that are stable across
|
|
92
|
+
the classic Win32 file dialog template. Returns ``True`` on success,
|
|
93
|
+
``False`` if either control is not found.
|
|
94
|
+
"""
|
|
95
|
+
if user32 is None:
|
|
96
|
+
return False
|
|
97
|
+
edit = user32.GetDlgItem(dialog_hwnd, FILE_DIALOG_EDIT_CTL_ID)
|
|
98
|
+
if not edit:
|
|
99
|
+
return False
|
|
100
|
+
user32.SendMessageW(edit, WM_SETTEXT, 0, ctypes.create_unicode_buffer(file_path))
|
|
101
|
+
time.sleep(0.3)
|
|
102
|
+
ok_btn = user32.GetDlgItem(dialog_hwnd, FILE_DIALOG_OK_BTN_ID)
|
|
103
|
+
if not ok_btn:
|
|
104
|
+
return False
|
|
105
|
+
user32.SendMessageW(ok_btn, BM_CLICK, 0, 0)
|
|
106
|
+
return True
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def click_dialog_item(dialog_hwnd: int, ctl_id: int) -> bool:
|
|
110
|
+
"""Send BM_CLICK to the child control identified by ``ctl_id``.
|
|
111
|
+
|
|
112
|
+
Generic counterpart to :func:`fill_file_dialog` for dialogs that only
|
|
113
|
+
need a button click (OK, Cancel, Yes, No) and no text entry.
|
|
114
|
+
"""
|
|
115
|
+
if user32 is None:
|
|
116
|
+
return False
|
|
117
|
+
btn = user32.GetDlgItem(dialog_hwnd, ctl_id)
|
|
118
|
+
if not btn:
|
|
119
|
+
return False
|
|
120
|
+
user32.SendMessageW(btn, BM_CLICK, 0, 0)
|
|
121
|
+
return True
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def close_window(hwnd: int) -> bool:
|
|
125
|
+
"""Post WM_CLOSE to ``hwnd``. Returns ``True`` if the message was posted."""
|
|
126
|
+
if user32 is None:
|
|
127
|
+
return False
|
|
128
|
+
return bool(user32.PostMessageW(hwnd, WM_CLOSE, 0, 0))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def dismiss_windows_by_title_fragment(fragment: str) -> list[str]:
|
|
132
|
+
"""Close every visible window whose title contains ``fragment`` via
|
|
133
|
+
WM_CLOSE. Returns the titles that were dismissed.
|
|
134
|
+
|
|
135
|
+
Intended for nuisance dialogs the caller knows the title pattern of
|
|
136
|
+
(flotherm's 'Message', Fluent's 'Question', etc.). For semantic "click
|
|
137
|
+
the OK button" use :mod:`sim.gui._pywinauto_tools` instead.
|
|
138
|
+
"""
|
|
139
|
+
if user32 is None:
|
|
140
|
+
return []
|
|
141
|
+
dismissed: list[str] = []
|
|
142
|
+
for hwnd, title in enum_visible_windows():
|
|
143
|
+
if fragment in title:
|
|
144
|
+
if close_window(hwnd):
|
|
145
|
+
dismissed.append(title)
|
|
146
|
+
if dismissed:
|
|
147
|
+
time.sleep(0.5)
|
|
148
|
+
return dismissed
|