lycheedev 1.2.0 → 2.0.0

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 (118) hide show
  1. package/LICENSE +49 -0
  2. package/README.md +45 -0
  3. package/THIRD_PARTY_NOTICES +812 -0
  4. package/bin/lycheedev.mjs +56 -0
  5. package/native/windows-amd64/lycheedev.exe +0 -0
  6. package/package.json +12 -33
  7. package/payload/addon/Bridge/CaptureWriter.lua +154 -0
  8. package/payload/addon/Bridge/Definitions.lua +3 -0
  9. package/payload/addon/Bridge/Identity.lua +127 -0
  10. package/{vendor/addon/Libs/AutomationQR.lua → payload/addon/Bridge/MatrixSymbol.lua} +23 -30
  11. package/payload/addon/Bridge/ProbeQueue.lua +136 -0
  12. package/payload/addon/Bridge/ProbeRunner.lua +128 -0
  13. package/payload/addon/Bridge/ReceiptView.lua +160 -0
  14. package/payload/addon/Bridge/Reentry.lua +192 -0
  15. package/payload/addon/Bridge/ReportStore.lua +153 -0
  16. package/payload/addon/Bridge/Session.lua +163 -0
  17. package/payload/addon/Clients/Evergreen.lua +2 -0
  18. package/payload/addon/Clients/Live.lua +2 -0
  19. package/payload/addon/Clients/Pandaria.lua +2 -0
  20. package/payload/addon/Clients/Titan.lua +2 -0
  21. package/payload/addon/Core/Compat.lua +59 -0
  22. package/payload/addon/Core/Controls.lua +168 -0
  23. package/{vendor/addon/Core/Bootstrap.lua → payload/addon/Core/Execute.lua} +12 -23
  24. package/{vendor → payload}/addon/Core/Inspector.lua +19 -235
  25. package/{vendor → payload}/addon/Core/Locale.lua +128 -93
  26. package/{vendor → payload}/addon/Core/Locale_enUS.lua +128 -95
  27. package/payload/addon/Core/Persistence.lua +58 -0
  28. package/payload/addon/Core/Platform.lua +58 -0
  29. package/payload/addon/Core/Runtime.lua +25 -0
  30. package/payload/addon/Core/Safety.lua +56 -0
  31. package/{vendor → payload}/addon/Core/Serializer.lua +18 -6
  32. package/payload/addon/Core/Stores.lua +611 -0
  33. package/payload/addon/Lychee Dev_Forever.toc +52 -0
  34. package/payload/addon/Lychee Dev_Mainline.toc +52 -0
  35. package/payload/addon/Lychee Dev_Mists.toc +52 -0
  36. package/payload/addon/Lychee Dev_Wrath.toc +52 -0
  37. package/payload/addon/Modules/AutomationView.lua +393 -0
  38. package/{vendor → payload}/addon/Modules/Diagnostics.lua +92 -36
  39. package/{vendor → payload}/addon/Modules/Events/Catalog.lua +9 -0
  40. package/{vendor → payload}/addon/Modules/Events/Monitor.lua +45 -5
  41. package/payload/addon/Modules/FunctionTrace.lua +150 -0
  42. package/{vendor → payload}/addon/Modules/ObjectInspector.lua +105 -31
  43. package/{vendor → payload}/addon/UI/Export.lua +64 -34
  44. package/{vendor → payload}/addon/UI/Pages/About.lua +26 -14
  45. package/payload/addon/UI/Pages/Automation.lua +446 -0
  46. package/payload/addon/UI/Pages/Diagnostics.lua +402 -0
  47. package/{vendor/addon/UI/Features.lua → payload/addon/UI/Pages/Events.lua} +192 -302
  48. package/{vendor → payload}/addon/UI/Pages/ExportRecords.lua +213 -132
  49. package/{vendor → payload}/addon/UI/Pages/Object.lua +229 -121
  50. package/payload/addon/UI/Pages/Run.lua +423 -0
  51. package/payload/addon/UI/Pages/Trace.lua +314 -0
  52. package/payload/addon/UI/TreeView.lua +246 -0
  53. package/{vendor/addon/UI/MainWindow.lua → payload/addon/UI/Widgets.lua} +89 -529
  54. package/payload/addon/UI/Window.lua +425 -0
  55. package/payload/skill/SKILL.md +87 -0
  56. package/payload/skill/agents/openai.yaml +7 -0
  57. package/payload/skill/references/addon-validation.md +42 -0
  58. package/payload/skill/references/asset-export.md +109 -0
  59. package/payload/skill/references/commands.md +169 -0
  60. package/payload/skill/references/data-investigation.md +242 -0
  61. package/payload/skill/references/error-diagnosis.md +41 -0
  62. package/payload/skill/references/installation.md +18 -0
  63. package/payload/skill/references/live-investigation.md +129 -0
  64. package/payload/skill/references/source-research.md +82 -0
  65. package/payload/skill/scripts/lycheedev.mjs +59 -0
  66. package/release.json +346 -0
  67. package/bin/lycheedev.js +0 -746
  68. package/src/addon.js +0 -95
  69. package/src/config.js +0 -68
  70. package/src/doctor.js +0 -126
  71. package/src/install.js +0 -145
  72. package/src/paths.js +0 -93
  73. package/src/py/instances.py +0 -165
  74. package/src/python.js +0 -111
  75. package/src/skill.js +0 -48
  76. package/src/wow.js +0 -541
  77. package/vendor/addon/Core/Clients/Forever.lua +0 -9
  78. package/vendor/addon/Core/Clients/Mainline.lua +0 -9
  79. package/vendor/addon/Core/Clients/Mists.lua +0 -9
  80. package/vendor/addon/Core/Clients/Titan.lua +0 -9
  81. package/vendor/addon/Core/Compatibility.lua +0 -43
  82. package/vendor/addon/Core/Database.lua +0 -859
  83. package/vendor/addon/Core/Safety.lua +0 -42
  84. package/vendor/addon/Lychee Dev_Forever.toc +0 -44
  85. package/vendor/addon/Lychee Dev_Mainline.toc +0 -44
  86. package/vendor/addon/Lychee Dev_Mists.toc +0 -44
  87. package/vendor/addon/Lychee Dev_Wrath.toc +0 -44
  88. package/vendor/addon/Modules/Automation/Controller.lua +0 -896
  89. package/vendor/addon/Modules/Automation/Reload.lua +0 -101
  90. package/vendor/addon/Modules/Automation/Report.lua +0 -409
  91. package/vendor/addon/Modules/Automation/auto/auto.lua +0 -12
  92. package/vendor/addon/Modules/FunctionTrace.lua +0 -85
  93. package/vendor/addon/UI/AutomationOverlay.lua +0 -253
  94. package/vendor/addon/UI/Pages/Automation.lua +0 -417
  95. package/vendor/addon/UI/Pages/Diagnostics.lua +0 -289
  96. package/vendor/addon/UI/Pages/Trace.lua +0 -165
  97. package/vendor/skill/SKILL.md +0 -44
  98. package/vendor/skill/agents/openai.yaml +0 -4
  99. package/vendor/skill/references/automation.md +0 -130
  100. package/vendor/skill/references/clients.md +0 -51
  101. package/vendor/skill/references/runtime-investigations.md +0 -104
  102. package/vendor/skill/scripts/automation/__init__.py +0 -1
  103. package/vendor/skill/scripts/automation/registry.py +0 -516
  104. package/vendor/skill/scripts/automation/reload.py +0 -121
  105. package/vendor/skill/scripts/automation/saved_variables.py +0 -438
  106. package/vendor/skill/scripts/automation/session.py +0 -207
  107. package/vendor/skill/scripts/automation/windows.py +0 -792
  108. package/vendor/skill/scripts/automation.py +0 -1067
  109. package/vendor/skill/scripts/requirements.txt +0 -13
  110. package/vendor/skill/scripts/selftest_offline.py +0 -1061
  111. package/vendor/skill/scripts/test_input_safety.py +0 -132
  112. package/vendor/skill/scripts/test_reload.py +0 -120
  113. /package/{vendor → payload}/addon/Media/GitHub.png +0 -0
  114. /package/{vendor → payload}/addon/Media/Logo.png +0 -0
  115. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Forever.lua +0 -0
  116. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Mainline.lua +0 -0
  117. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Mists.lua +0 -0
  118. /package/{vendor → payload}/addon/Modules/Events/CatalogData_Titan.lua +0 -0
@@ -1,792 +0,0 @@
1
- """Window identity, capture and controlled command input for Windows.
2
-
3
- Window identity is never guessed from the title alone: every use confirms the
4
- HWND against pid and process executable path. Command input uses a controlled
5
- focus-verify-paste-confirm sequence; WGC capture and QR decoding are optional heavy imports that fail
6
- with explicit messages when their packages are missing.
7
-
8
- The capture session is long lived: a task can run far longer than one frame, so
9
- ``open_notice_capture`` returns a context manager that keeps one WGC session
10
- open, keeps only the newest ROI, and is polled by the caller until its own
11
- deadline expires. Every ctypes entry point used here has an explicit prototype,
12
- because on 64-bit hosts the default ``c_int`` return type truncates handles and
13
- pointers.
14
-
15
- Verified behavior gaps (design section 11): SendInput success does not prove
16
- the game processed the command, and minimization/occlusion/HDR support must be
17
- measured before being claimed. The host log, not this module, decides when a
18
- reload may be repeated.
19
- """
20
-
21
- from __future__ import annotations
22
-
23
- import ctypes
24
- import ctypes.wintypes as wt
25
- import json
26
- import ntpath
27
- import uuid
28
- import time
29
- from collections import deque
30
- from concurrent.futures import ThreadPoolExecutor
31
- from dataclasses import dataclass
32
-
33
- user32 = ctypes.WinDLL("user32", use_last_error=True)
34
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
35
-
36
- INPUT_KEYBOARD = 1
37
- KEYEVENTF_KEYUP = 0x0002
38
- VK_CONTROL = 0x11
39
- VK_RETURN = 0x0D
40
- VK_V = 0x56
41
- VK_A = 0x41
42
- VK_C = 0x43
43
- VK_ESCAPE = 0x1B
44
- VK_OEM_2 = 0xBF
45
- VK_MENU = 0x12
46
- WM_CHAR = 0x0102
47
- WM_KEYDOWN = 0x0100
48
- WM_KEYUP = 0x0101
49
-
50
- PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
51
-
52
- # Top-left notice region as (top, left, bottom, right) fractions of the captured
53
- # frame. The completion notice is drawn at the top-left corner (see
54
- # UI/AutomationOverlay.lua), so the scan area covers that corner with room for
55
- # the QR quiet zone and a few DPI increments. Recalibrate here when the notice
56
- # anchor, DPI, window size or capture origin changes (design section 6.1).
57
- NOTICE_ROI_FRACTIONS = (0.0, 0.0, 0.30, 0.30)
58
-
59
-
60
- class WindowIdentityError(Exception):
61
- pass
62
-
63
-
64
- class InputError(Exception):
65
- pass
66
-
67
-
68
- class CaptureDependencyError(Exception):
69
- pass
70
-
71
-
72
- @dataclass
73
- class WindowIdentity:
74
- hwnd: int
75
- pid: int
76
- exe_path: str | None
77
- title: str
78
-
79
- def matches(self, *, pid: int | None = None, exe_path: str | None = None) -> bool:
80
- if pid is not None and self.pid != pid:
81
- return False
82
- if exe_path is not None and (
83
- ntpath.normcase(ntpath.normpath(self.exe_path or ""))
84
- != ntpath.normcase(ntpath.normpath(exe_path))):
85
- return False
86
- return True
87
-
88
-
89
- class KEYBDINPUT(ctypes.Structure):
90
- _fields_ = [("wVk", wt.WORD), ("wScan", wt.WORD), ("dwFlags", wt.DWORD),
91
- ("time", wt.DWORD), ("dwExtraInfo", ctypes.c_void_p)]
92
-
93
-
94
- class MOUSEINPUT(ctypes.Structure):
95
- _fields_ = [("dx", wt.LONG), ("dy", wt.LONG), ("mouseData", wt.DWORD),
96
- ("dwFlags", wt.DWORD), ("time", wt.DWORD),
97
- ("dwExtraInfo", ctypes.c_void_p)]
98
-
99
-
100
- class HARDWAREINPUT(ctypes.Structure):
101
- _fields_ = [("uMsg", wt.DWORD), ("wParamL", wt.WORD), ("wParamH", wt.WORD)]
102
-
103
-
104
- class _INPUTUNION(ctypes.Union):
105
- # The union size must follow the real largest member: 32 bytes on 64-bit and
106
- # 24 bytes on 32-bit, which is why the padding shortcut was wrong.
107
- _fields_ = [("ki", KEYBDINPUT), ("mi", MOUSEINPUT), ("hi", HARDWAREINPUT)]
108
-
109
-
110
- class INPUT(ctypes.Structure):
111
- _anonymous_ = ("u",)
112
- _fields_ = [("type", wt.DWORD), ("u", _INPUTUNION)]
113
-
114
-
115
- INPUT_SIZE = ctypes.sizeof(INPUT)
116
-
117
- WNDENUMPROC = ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM)
118
-
119
-
120
- def _prototype(function, restype, argtypes):
121
- function.restype = restype
122
- function.argtypes = list(argtypes)
123
- return function
124
-
125
-
126
- _prototype(kernel32.OpenProcess,
127
- wt.HANDLE, (wt.DWORD, wt.BOOL, wt.DWORD))
128
- _prototype(kernel32.QueryFullProcessImageNameW,
129
- wt.BOOL, (wt.HANDLE, wt.DWORD, wt.LPWSTR, ctypes.POINTER(wt.DWORD)))
130
- _prototype(kernel32.CloseHandle, wt.BOOL, (wt.HANDLE,))
131
- _prototype(kernel32.GlobalLock, ctypes.c_void_p, (ctypes.c_void_p,))
132
- _prototype(kernel32.GlobalUnlock, wt.BOOL, (ctypes.c_void_p,))
133
- _prototype(kernel32.GlobalAlloc, ctypes.c_void_p, (wt.UINT, ctypes.c_size_t))
134
- _prototype(kernel32.GlobalFree, ctypes.c_void_p, (ctypes.c_void_p,))
135
- _prototype(ctypes.memmove, ctypes.c_void_p,
136
- (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t))
137
-
138
- _prototype(user32.IsWindow, wt.BOOL, (wt.HWND,))
139
- _prototype(user32.IsWindowVisible, wt.BOOL, (wt.HWND,))
140
- _prototype(user32.GetWindowThreadProcessId,
141
- wt.DWORD, (wt.HWND, ctypes.POINTER(wt.DWORD)))
142
- _prototype(user32.GetWindowTextLengthW, ctypes.c_int, (wt.HWND,))
143
- _prototype(user32.GetWindowTextW, ctypes.c_int, (wt.HWND, wt.LPWSTR, ctypes.c_int))
144
- _prototype(user32.EnumWindows, wt.BOOL, (WNDENUMPROC, wt.LPARAM))
145
- _prototype(user32.GetForegroundWindow, wt.HWND, ())
146
- _prototype(user32.SetForegroundWindow, wt.BOOL, (wt.HWND,))
147
- _prototype(user32.OpenClipboard, wt.BOOL, (wt.HWND,))
148
- _prototype(user32.CloseClipboard, wt.BOOL, ())
149
- _prototype(user32.EmptyClipboard, wt.BOOL, ())
150
- _prototype(user32.IsClipboardFormatAvailable, wt.BOOL, (wt.UINT,))
151
- _prototype(user32.GetClipboardData, wt.HANDLE, (wt.UINT,))
152
- _prototype(user32.SetClipboardData, wt.HANDLE, (wt.UINT, wt.HANDLE))
153
- _prototype(user32.SendInput, wt.UINT, (wt.UINT, ctypes.POINTER(INPUT), ctypes.c_int))
154
- _prototype(user32.keybd_event, None, (wt.BYTE, wt.BYTE, wt.DWORD, ctypes.c_void_p))
155
- _prototype(user32.MapVirtualKeyW, wt.UINT, (wt.UINT, wt.UINT))
156
- _prototype(user32.PostMessageW, wt.BOOL,
157
- (wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM))
158
-
159
-
160
- def _query_process_image(pid: int) -> str | None:
161
- handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
162
- if not handle:
163
- return None
164
- try:
165
- size = wt.DWORD(1024)
166
- buffer = ctypes.create_unicode_buffer(size.value)
167
- if kernel32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)):
168
- return buffer.value
169
- return None
170
- finally:
171
- kernel32.CloseHandle(handle)
172
-
173
-
174
- def identify_window(hwnd: int) -> WindowIdentity:
175
- if not user32.IsWindow(hwnd):
176
- raise WindowIdentityError(f"hwnd {hwnd} is no longer a live window")
177
- pid = wt.DWORD(0)
178
- user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
179
- length = user32.GetWindowTextLengthW(hwnd)
180
- buffer = ctypes.create_unicode_buffer(max(length + 1, 1))
181
- user32.GetWindowTextW(hwnd, buffer, length + 1)
182
- return WindowIdentity(
183
- hwnd=hwnd,
184
- pid=pid.value,
185
- exe_path=_query_process_image(pid.value),
186
- title=buffer.value,
187
- )
188
-
189
-
190
- def confirm_window(hwnd: int, *, pid: int | None = None, exe_path: str | None = None) -> WindowIdentity:
191
- """Re-verify the window identity immediately before any use."""
192
-
193
- identity = identify_window(hwnd)
194
- if not identity.matches(pid=pid, exe_path=exe_path):
195
- raise WindowIdentityError(
196
- f"window identity changed: hwnd {hwnd} now pid {identity.pid} "
197
- f"exe {identity.exe_path!r}")
198
- return identity
199
-
200
-
201
- def find_windows_by_pid(pid: int) -> list[WindowIdentity]:
202
- found: list[WindowIdentity] = []
203
-
204
- @WNDENUMPROC
205
- def callback(hwnd, _lparam):
206
- window_pid = wt.DWORD(0)
207
- user32.GetWindowThreadProcessId(hwnd, ctypes.byref(window_pid))
208
- if window_pid.value == pid and user32.IsWindowVisible(hwnd):
209
- try:
210
- found.append(identify_window(hwnd))
211
- except WindowIdentityError:
212
- pass
213
- return True
214
-
215
- user32.EnumWindows(callback, 0)
216
- return found
217
-
218
-
219
- def is_foreground(hwnd: int) -> bool:
220
- return user32.GetForegroundWindow() == hwnd
221
-
222
-
223
- def _send_key(vk: int, *, ctrl: bool = False) -> None:
224
- def make(vkey: int, flags: int) -> INPUT:
225
- item = INPUT()
226
- item.type = INPUT_KEYBOARD
227
- item.ki = KEYBDINPUT(vkey, 0, flags, 0, None)
228
- return item
229
-
230
- sequence: list[INPUT] = []
231
- if ctrl:
232
- sequence.append(make(VK_CONTROL, 0))
233
- sequence.append(make(vk, 0))
234
- sequence.append(make(vk, KEYEVENTF_KEYUP))
235
- if ctrl:
236
- sequence.append(make(VK_CONTROL, KEYEVENTF_KEYUP))
237
- array = (INPUT * len(sequence))(*sequence)
238
- sent = user32.SendInput(len(sequence), array, ctypes.sizeof(INPUT))
239
- if sent != len(sequence):
240
- raise InputError("SendInput did not accept the full key sequence")
241
-
242
-
243
- def send_command(hwnd: int, command: str, *, pid: int | None = None,
244
- exe_path: str | None = None, clipboard=None,
245
- mode: str = "messages") -> None:
246
- """Replace a chat draft and verify the copied edit text before submitting.
247
-
248
- A successful return means keyboard submission, not game execution. Callers
249
- must correlate the game's receipt. Messages mode is a separate HWND-bound
250
- background transport and does not use focus or the clipboard.
251
- """
252
- if mode not in ("foreground", "messages"):
253
- raise InputError(f"unknown delivery mode: {mode}")
254
- if (not isinstance(command, str) or not command.startswith("/")
255
- or len(command.encode("utf-8")) > 255
256
- or any(ord(char) < 32 or ord(char) == 127 for char in command)):
257
- raise InputError("expected one slash command of at most 255 UTF-8 bytes")
258
- if mode == "messages":
259
- send_command_messages(hwnd, command, pid=pid, exe_path=exe_path)
260
- return
261
- if clipboard is None:
262
- clipboard = Clipboard()
263
- identity = confirm_window(hwnd, pid=pid, exe_path=exe_path)
264
- # Freeze inferred identity too: callers need not supply both fields.
265
- pid, exe_path = identity.pid, identity.exe_path
266
- focus_window(hwnd, pid=pid, exe_path=exe_path)
267
- deadline = time.monotonic() + 5.0
268
-
269
- def guard():
270
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
271
- if not is_foreground(hwnd):
272
- raise InputError("game lost foreground; input cancelled without retry")
273
- if time.monotonic() >= deadline:
274
- raise InputError("command input timed out; input cancelled without retry")
275
-
276
- def key(vk, *, ctrl=False):
277
- guard()
278
- _send_key(vk, ctrl=ctrl)
279
- time.sleep(0.10)
280
- guard()
281
-
282
- previous = clipboard.read_text()
283
- sentinel = "lycheedev-readback-" + uuid.uuid4().hex
284
- owned = {command, sentinel}
285
- try:
286
- # Open chat through the slash binding, never an initial Return: even
287
- # an ignored Escape must not submit an existing public-chat draft.
288
- key(VK_ESCAPE)
289
- key(VK_OEM_2)
290
- key(VK_A, ctrl=True)
291
- clipboard.copy_text(command)
292
- if clipboard.read_text() != command:
293
- raise InputError("the clipboard did not accept the command text")
294
- key(VK_V, ctrl=True)
295
- key(VK_A, ctrl=True)
296
- # Reading back the original clipboard would prove nothing. A unique
297
- # sentinel makes missing/ignored Ctrl+C distinguishable from success.
298
- clipboard.copy_text(sentinel)
299
- key(VK_C, ctrl=True)
300
- for _ in range(20):
301
- guard()
302
- copied = clipboard.read_text()
303
- if copied == command:
304
- break
305
- if copied != sentinel:
306
- raise InputError("chat edit text differs from the prepared command")
307
- time.sleep(0.025)
308
- else:
309
- raise InputError("could not verify chat edit text before submission")
310
- guard()
311
- _send_key(VK_RETURN)
312
- except BaseException:
313
- # Never send cleanup keys into another app or resume a deferred submit.
314
- try:
315
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
316
- if is_foreground(hwnd):
317
- _send_key(VK_ESCAPE)
318
- except (WindowIdentityError, InputError):
319
- pass
320
- raise
321
- finally:
322
- if clipboard.read_text() in owned:
323
- if previous is None:
324
- clipboard.clear()
325
- else:
326
- clipboard.copy_text(previous)
327
-
328
-
329
- def focus_window(hwnd: int, *, pid: int | None = None,
330
- exe_path: str | None = None, attempts: int = 3) -> None:
331
- """Bring ``hwnd`` to the foreground, or fail without sending any input.
332
-
333
- ``SetForegroundWindow`` is refused while another process owns the
334
- foreground, which is the normal state after the user clicks elsewhere.
335
- Windows releases that restriction when the foreground change follows user
336
- input, so a one-shot ALT press is used as the documented unlock and the
337
- result is always re-verified; a window that still is not foreground raises
338
- instead of typing into whatever else has focus.
339
- """
340
-
341
- for attempt in range(attempts):
342
- if user32.SetForegroundWindow(hwnd):
343
- time.sleep(0.10)
344
- if is_foreground(hwnd):
345
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
346
- return
347
- if attempt == attempts - 1:
348
- break
349
- # A synthetic ALT is delivered by this process, so the next
350
- # SetForegroundWindow is allowed through the foreground lock.
351
- user32.keybd_event(VK_MENU, 0, 0, 0)
352
- time.sleep(0.05)
353
- user32.keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0)
354
- time.sleep(0.15)
355
-
356
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
357
- if not is_foreground(hwnd):
358
- raise InputError(
359
- "could not bring the game window to the foreground; click the game "
360
- "window once and retry the command")
361
-
362
-
363
- def _key_lparam(vk: int, *, up: bool = False) -> int:
364
- """Pack a WM_KEYDOWN/WM_KEYUP lParam for a virtual key."""
365
-
366
- scan = user32.MapVirtualKeyW(vk, 0)
367
- lparam = 1 | (scan << 16)
368
- if up:
369
- lparam |= 1 << 30 | 1 << 31
370
- return lparam
371
-
372
-
373
- def send_command_messages(hwnd: int, command: str, *, delay: float = 0.05,
374
- pid: int | None = None, exe_path: str | None = None) -> None:
375
- """Submit through the target HWND's queue without changing foreground.
376
-
377
- PostMessage acceptance only means queued input. It cannot prove chat focus
378
- or text consumption; callers must wait for a matching game receipt.
379
- """
380
- if (not isinstance(command, str) or not command.startswith("/")
381
- or len(command.encode("utf-8")) > 255
382
- or any(ord(char) < 32 or ord(char) == 127 for char in command)):
383
- raise InputError("expected one slash command of at most 255 UTF-8 bytes")
384
- identity = confirm_window(hwnd, pid=pid, exe_path=exe_path)
385
- pid, exe_path = identity.pid, identity.exe_path
386
- deadline = time.monotonic() + 20.0
387
-
388
- def post(message, value, lparam):
389
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
390
- if time.monotonic() >= deadline:
391
- raise InputError("background input timed out; submission is unresolved")
392
- if not user32.PostMessageW(hwnd, message, value, lparam):
393
- raise InputError("target rejected background input; submission is unresolved")
394
-
395
- def key(vk):
396
- post(WM_KEYDOWN, vk, _key_lparam(vk))
397
- post(WM_KEYUP, vk, _key_lparam(vk, up=True))
398
- time.sleep(0.15)
399
-
400
- try:
401
- key(VK_ESCAPE)
402
- key(VK_RETURN)
403
- # WM_CHAR carries UTF-16 code units, not Python's Unicode code points.
404
- encoded = command.encode("utf-16-le")
405
- for offset in range(0, len(encoded), 2):
406
- post(WM_CHAR, int.from_bytes(encoded[offset:offset + 2], "little"), 1)
407
- time.sleep(delay)
408
- key(VK_RETURN)
409
- except BaseException:
410
- # Queue cleanup only to the still-bound HWND, never to the foreground.
411
- try:
412
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
413
- user32.PostMessageW(hwnd, WM_KEYDOWN, VK_ESCAPE, _key_lparam(VK_ESCAPE))
414
- user32.PostMessageW(hwnd, WM_KEYUP, VK_ESCAPE, _key_lparam(VK_ESCAPE, up=True))
415
- except WindowIdentityError:
416
- pass
417
- raise
418
-
419
-
420
- class Clipboard:
421
- """Minimal CF_UNICODETEXT clipboard via user32; no third-party dependency."""
422
-
423
- CF_UNICODETEXT = 13
424
- GMEM_MOVEABLE = 0x0002
425
-
426
- def _open(self, retries: int = 8) -> None:
427
- for attempt in range(retries):
428
- if user32.OpenClipboard(0):
429
- return
430
- time.sleep(0.05 * (attempt + 1))
431
- raise InputError("could not open the clipboard")
432
-
433
- def read_text(self) -> str | None:
434
- self._open()
435
- try:
436
- if not user32.IsClipboardFormatAvailable(self.CF_UNICODETEXT):
437
- return None
438
- handle = user32.GetClipboardData(self.CF_UNICODETEXT)
439
- if not handle:
440
- return None
441
- pointer = kernel32.GlobalLock(handle)
442
- if not pointer:
443
- return None
444
- try:
445
- return ctypes.wstring_at(pointer)
446
- finally:
447
- kernel32.GlobalUnlock(handle)
448
- finally:
449
- user32.CloseClipboard()
450
-
451
- def copy_text(self, text: str) -> None:
452
- self._open()
453
- try:
454
- user32.EmptyClipboard()
455
- size = (len(text) + 1) * 2
456
- handle = kernel32.GlobalAlloc(self.GMEM_MOVEABLE, size)
457
- if not handle:
458
- raise InputError("GlobalAlloc failed for clipboard data")
459
- pointer = kernel32.GlobalLock(handle)
460
- if not pointer:
461
- raise InputError("GlobalLock failed for clipboard data")
462
- try:
463
- source = ctypes.create_unicode_buffer(text)
464
- ctypes.memmove(pointer, ctypes.cast(source, ctypes.c_void_p), size)
465
- finally:
466
- kernel32.GlobalUnlock(handle)
467
- if not user32.SetClipboardData(self.CF_UNICODETEXT, handle):
468
- kernel32.GlobalFree(handle)
469
- raise InputError("SetClipboardData failed")
470
- finally:
471
- user32.CloseClipboard()
472
-
473
- def clear(self) -> None:
474
- self._open()
475
- try:
476
- user32.EmptyClipboard()
477
- finally:
478
- user32.CloseClipboard()
479
-
480
-
481
- # --- capture (optional dependencies) -----------------------------------------
482
-
483
- def load_decode_module():
484
- """Import zxing-cpp, the only QR reader this tooling supports."""
485
-
486
- try:
487
- import zxingcpp
488
- except ImportError as error: # pragma: no cover - depends on host packages
489
- raise CaptureDependencyError(
490
- f"QR decoding dependency missing ({error}); install zxing-cpp 3.1.1"
491
- ) from error
492
- if not callable(getattr(zxingcpp, "read_barcodes", None)):
493
- raise CaptureDependencyError(
494
- "installed zxing-cpp has no read_barcodes(); zxing-cpp 3.x is required")
495
- return zxingcpp
496
-
497
-
498
- def load_capture_modules():
499
- """Import windows-capture plus numpy for the live frame path."""
500
-
501
- try:
502
- import numpy
503
- import windows_capture
504
- except ImportError as error: # pragma: no cover - depends on host packages
505
- raise CaptureDependencyError(
506
- f"capture dependencies missing ({error}); install windows-capture "
507
- "2.0.1 and numpy") from error
508
- return numpy, windows_capture
509
-
510
-
511
- class NoticeCapture:
512
- """One open WGC window capture keeping only the newest notice ROI.
513
-
514
- The session stays open for as long as the caller needs it: a task can take
515
- far longer than a single frame. ``latest_roi()`` returns the newest copied
516
- ROI or ``None``; the frame buffer is copied before the native frame is
517
- released. Use it as a context manager.
518
- """
519
-
520
- def __init__(self, capture, numpy_module, *, hwnd: int,
521
- roi_fractions=NOTICE_ROI_FRACTIONS):
522
- self.capture = capture
523
- self.hwnd = hwnd
524
- self.roi_fractions = tuple(roi_fractions)
525
- self.window_closed = False
526
- self.last_frame_error: str | None = None
527
- self._numpy = numpy_module
528
- self._frames: deque = deque(maxlen=1)
529
- self._control = None
530
- self._closed = False
531
- capture.frame_handler = self._on_frame
532
- capture.closed_handler = self._on_closed
533
-
534
- # -- windows-capture callbacks -----------------------------------------
535
-
536
- def _frame_bgr(self, frame):
537
- convert = getattr(frame, "convert_to_bgr", None)
538
- if callable(convert):
539
- return convert().frame_buffer
540
- return frame.frame_buffer
541
-
542
- def _on_frame(self, frame, _control=None) -> None:
543
- try:
544
- image = self._frame_bgr(frame)
545
- height, width = int(image.shape[0]), int(image.shape[1])
546
- top, left, bottom, right = self.roi_fractions
547
- roi = image[int(height * top):int(height * bottom),
548
- int(width * left):int(width * right)]
549
- self._frames.append(self._numpy.ascontiguousarray(roi))
550
- except Exception as error: # a bad frame must never stop the thread
551
- self.last_frame_error = str(error)
552
-
553
- def _on_closed(self) -> None:
554
- self.window_closed = True
555
-
556
- # -- lifecycle ---------------------------------------------------------
557
-
558
- def start(self) -> NoticeCapture:
559
- self._control = self.capture.start_free_threaded()
560
- return self
561
-
562
- def latest_roi(self):
563
- return self._frames[-1] if self._frames else None
564
-
565
- def close(self, timeout: float = 2.0) -> None:
566
- if self._closed:
567
- return
568
- self._closed = True
569
- control = self._control
570
- if control is None:
571
- return
572
- try:
573
- control.stop()
574
- except Exception:
575
- return
576
- deadline = time.monotonic() + timeout
577
- while time.monotonic() < deadline and not control.is_finished():
578
- time.sleep(0.02)
579
-
580
- def __enter__(self) -> NoticeCapture:
581
- return self.start()
582
-
583
- def __exit__(self, *_exc) -> bool:
584
- self.close()
585
- return False
586
-
587
-
588
- def open_notice_capture(hwnd: int, *, pid: int | None = None,
589
- exe_path: str | None = None,
590
- interval: float = 0.1,
591
- minimum_update_interval_ms: int | None = None,
592
- roi_fractions=NOTICE_ROI_FRACTIONS) -> NoticeCapture:
593
- """Confirm the window identity, then open one WGC session for the notice.
594
-
595
- The caller owns the returned session and must close it (the context manager
596
- does that). Raises WindowIdentityError for a stale/reused hwnd and
597
- CaptureDependencyError when the optional packages are missing.
598
- """
599
-
600
- numpy_module, windows_capture = load_capture_modules()
601
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
602
- if minimum_update_interval_ms is None:
603
- minimum_update_interval_ms = max(int(round(interval * 1000)), 0)
604
- kwargs = {"window_hwnd": hwnd}
605
- if minimum_update_interval_ms:
606
- kwargs["minimum_update_interval"] = minimum_update_interval_ms
607
- try:
608
- capture = windows_capture.WindowsCapture(**kwargs)
609
- except TypeError:
610
- # Older releases may not accept the update-interval keyword.
611
- capture = windows_capture.WindowsCapture(window_hwnd=hwnd)
612
- return NoticeCapture(capture, numpy_module, hwnd=hwnd,
613
- roi_fractions=roi_fractions)
614
-
615
-
616
- def decode_qr(image, zxingcpp_module=None) -> list[str]:
617
- """Decode QR payloads from one image; returns the raw strings found.
618
-
619
- Only ``read_barcodes`` exists in zxing-cpp 3.x; it is restricted to QR codes
620
- so the notice scan stays cheap, invalid results are dropped, and a
621
- dependency without that entry point fails explicitly instead of raising a
622
- bare AttributeError.
623
- """
624
-
625
- module = zxingcpp_module if zxingcpp_module is not None else load_decode_module()
626
- reader = getattr(module, "read_barcodes", None)
627
- if not callable(reader):
628
- raise CaptureDependencyError(
629
- "installed zxing-cpp has no read_barcodes(); zxing-cpp 3.x is required")
630
- formats = getattr(getattr(module, "BarcodeFormat", None), "QRCode", None)
631
- try:
632
- results = reader(image, formats=formats) if formats is not None else reader(image)
633
- except TypeError:
634
- results = reader(image)
635
- payloads: list[str] = []
636
- for result in results or ():
637
- if getattr(result, "valid", True) is False:
638
- continue
639
- text = getattr(result, "text", None)
640
- if isinstance(text, str) and text:
641
- payloads.append(text)
642
- return payloads
643
-
644
-
645
- def _identity_payload(payloads) -> dict | None:
646
- """Pick the identity marker out of decoded payloads.
647
-
648
- A window may show the completion notice instead of an identity marker, and
649
- both are JSON with a ``v`` field, so the shape is checked rather than
650
- assumed: an identity marker carries a character id, a notice carries a
651
- ticket.
652
- """
653
-
654
- for text in payloads:
655
- try:
656
- value = json.loads(text)
657
- except (TypeError, ValueError):
658
- continue
659
- if not isinstance(value, dict) or "id" not in value:
660
- continue
661
- if "ticket" in value:
662
- continue
663
- return value
664
- return None
665
-
666
-
667
- # The identity probe's waiting budget, sized from measurement rather than guess:
668
- # on a live window Windows.Graphics.Capture delivers the first frame in 78-94 ms
669
- # (234 ms cold) and decoding an empty ROI costs about 3 ms. The grace therefore
670
- # only has to cover a slow first frame, and the timeout only a window that never
671
- # delivers one at all.
672
- IDENTITY_FIRST_FRAME_GRACE = 0.35
673
- IDENTITY_TIMEOUT = 1.5
674
-
675
-
676
- def read_identity(hwnd: int, *, pid: int | None = None, exe_path: str | None = None,
677
- timeout: float = IDENTITY_TIMEOUT, interval: float = 0.03,
678
- first_frame_grace: float = IDENTITY_FIRST_FRAME_GRACE,
679
- minimum_update_interval_ms: int | None = None) -> dict | None:
680
- """Read the in-game identity marker from one window, or None.
681
-
682
- This exists because nothing observable from outside the game says which
683
- character is behind which window. With one window that does not matter; with
684
- several it decides where a slash command may be typed. The window does not
685
- need to be in the foreground, because Windows.Graphics.Capture reads the
686
- window surface directly, which is what makes this usable before any input is
687
- sent.
688
-
689
- "No marker" is the ordinary state, not a failure: the user shows one on
690
- request. The wait therefore ends as soon as one frame has been decoded
691
- without finding a marker and no newer frame follows, so an unmarked window
692
- costs ``first_frame_grace`` rather than the whole ``timeout``. The timeout
693
- remains the ceiling for a window that never delivers a frame at all.
694
-
695
- Returns the decoded marker, or None. Raises WindowIdentityError for a stale
696
- hwnd and CaptureDependencyError when the optional packages are missing.
697
- """
698
-
699
- deadline = time.monotonic() + max(0.0, timeout)
700
- grace = max(0.0, first_frame_grace)
701
- last_attempted = None
702
- first_frame_at = None
703
- with open_notice_capture(hwnd, pid=pid, exe_path=exe_path, interval=interval,
704
- minimum_update_interval_ms=minimum_update_interval_ms) as session:
705
- while time.monotonic() < deadline:
706
- roi = session.latest_roi()
707
- # The session keeps the newest frame until a newer one arrives, so
708
- # decode each distinct frame once: re-decoding an unchanged image
709
- # every interval would burn the whole timeout on one picture.
710
- if roi is not None and roi is not last_attempted:
711
- if first_frame_at is None:
712
- first_frame_at = time.monotonic()
713
- last_attempted = roi
714
- marker = _identity_payload(decode_qr(roi))
715
- if marker is not None:
716
- return marker
717
- if session.window_closed:
718
- return None
719
- if first_frame_at is not None and time.monotonic() - first_frame_at >= grace:
720
- # Frames are arriving and none carried a marker, so waiting
721
- # longer cannot change the answer.
722
- return None
723
- time.sleep(interval)
724
- return None
725
-
726
-
727
- def _probe_one(window, timeout: float, interval: float,
728
- first_frame_grace: float, reader=None) -> dict:
729
- """Probe one window and return its result entry, never raising."""
730
-
731
- entry = {
732
- "hwnd": window.get("hwnd"),
733
- "pid": window.get("pid"),
734
- "flavorFolder": window.get("flavorFolder"),
735
- "flavorId": window.get("flavorId"),
736
- "flavorLabel": window.get("flavorLabel"),
737
- "identity": None,
738
- "error": None,
739
- }
740
- probe = reader if reader is not None else read_identity
741
- try:
742
- entry["identity"] = probe(
743
- int(window["hwnd"]),
744
- pid=window.get("pid"),
745
- exe_path=window.get("exePath"),
746
- timeout=timeout,
747
- interval=interval,
748
- first_frame_grace=first_frame_grace,
749
- )
750
- except (WindowIdentityError, CaptureDependencyError) as error:
751
- # These say something about the request or the environment rather than
752
- # about one window, so report them and keep going; the caller decides
753
- # whether an unreadable set is fatal.
754
- entry["error"] = str(error)
755
- except (OSError, RuntimeError, ValueError) as error:
756
- # One window being uncooperative (closed, minimized, denied) must not
757
- # abort the probe of the remaining windows.
758
- entry["error"] = str(error)
759
- return entry
760
-
761
-
762
- def read_identities(windows, *, timeout: float = IDENTITY_TIMEOUT, interval: float = 0.03,
763
- first_frame_grace: float = IDENTITY_FIRST_FRAME_GRACE,
764
- reader=None) -> list[dict]:
765
- """Probe several windows for their identity marker, in the given order.
766
-
767
- The windows are probed concurrently. Each call owns its own capture session,
768
- the frame callback only touches that session's queue, and the waiting is
769
- sleep-bound, so the probe costs one window's latency instead of the sum of
770
- all of them. With one window this is exactly the old behavior.
771
-
772
- A window without a visible marker yields an entry with ``identity`` set to
773
- None rather than an error, because "no marker" is the expected state until
774
- the user asks the game to show one. ``reader`` exists so the concurrency and
775
- error isolation can be tested without a game window.
776
- """
777
-
778
- items = list(windows)
779
- if not items:
780
- return []
781
-
782
- def probe(window: dict) -> dict:
783
- return _probe_one(window, timeout, interval, first_frame_grace, reader)
784
-
785
- # Threads rather than processes: the work is blocking waits and small
786
- # decodes, so the GIL is not the constraint, and every entry stays picklable
787
- # for callers that serialize the result.
788
- workers = min(len(items), 8)
789
- with ThreadPoolExecutor(max_workers=workers) as pool:
790
- return list(pool.map(probe, items))
791
-
792
-