lycheedev 1.0.6 → 1.1.1

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.
@@ -1,9 +1,8 @@
1
1
  """Window identity, capture and controlled command input for Windows.
2
2
 
3
3
  Window identity is never guessed from the title alone: every use confirms the
4
- HWND against pid, process executable path and (best effort) the process
5
- creation time. Command input uses the controlled focus-verify-paste-confirm
6
- sequence; WGC capture and QR decoding are optional heavy imports that fail
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
7
6
  with explicit messages when their packages are missing.
8
7
 
9
8
  The capture session is long lived: a task can run far longer than one frame, so
@@ -23,8 +22,12 @@ from __future__ import annotations
23
22
 
24
23
  import ctypes
25
24
  import ctypes.wintypes as wt
25
+ import json
26
+ import ntpath
27
+ import uuid
26
28
  import time
27
29
  from collections import deque
30
+ from concurrent.futures import ThreadPoolExecutor
28
31
  from dataclasses import dataclass
29
32
 
30
33
  user32 = ctypes.WinDLL("user32", use_last_error=True)
@@ -35,6 +38,10 @@ KEYEVENTF_KEYUP = 0x0002
35
38
  VK_CONTROL = 0x11
36
39
  VK_RETURN = 0x0D
37
40
  VK_V = 0x56
41
+ VK_A = 0x41
42
+ VK_C = 0x43
43
+ VK_ESCAPE = 0x1B
44
+ VK_OEM_2 = 0xBF
38
45
  VK_MENU = 0x12
39
46
  WM_CHAR = 0x0102
40
47
  WM_KEYDOWN = 0x0100
@@ -72,7 +79,9 @@ class WindowIdentity:
72
79
  def matches(self, *, pid: int | None = None, exe_path: str | None = None) -> bool:
73
80
  if pid is not None and self.pid != pid:
74
81
  return False
75
- if exe_path is not None and (self.exe_path or "").lower() != exe_path.lower():
82
+ if exe_path is not None and (
83
+ ntpath.normcase(ntpath.normpath(self.exe_path or ""))
84
+ != ntpath.normcase(ntpath.normpath(exe_path))):
76
85
  return False
77
86
  return True
78
87
 
@@ -233,53 +242,84 @@ def _send_key(vk: int, *, ctrl: bool = False) -> None:
233
242
 
234
243
  def send_command(hwnd: int, command: str, *, pid: int | None = None,
235
244
  exe_path: str | None = None, clipboard=None,
236
- mode: str = "foreground") -> None:
237
- """Deliver one slash command through the game chat box.
245
+ mode: str = "messages") -> None:
246
+ """Replace a chat draft and verify the copied edit text before submitting.
238
247
 
239
- ``mode`` selects the injection strategy:
240
-
241
- - ``"foreground"`` (default): focus the window, open chat with Return,
242
- paste from the clipboard, submit with Return. Uses ``SendInput``, which
243
- only reaches the foreground window, so the window is focused first.
244
- - ``"messages"``: post the keystrokes straight into the target window's
245
- message queue. This needs no foreground at all, but the client only
246
- reacts when its chat edit box is already open and focused, and a client
247
- that reads raw input may ignore posted messages entirely.
248
-
249
- Both modes run the game's own command parser, so a slash command that the
250
- client cannot run (locked UI, unknown command) still fails inside the game.
251
-
252
- ``clipboard`` may be injected for tests; it needs ``copy_text``,
253
- ``read_text`` and ``clear``. The previous clipboard content is restored
254
- when it still belongs to this operation.
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.
255
251
  """
256
-
257
252
  if mode not in ("foreground", "messages"):
258
253
  raise InputError(f"unknown delivery mode: {mode}")
259
-
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")
260
258
  if mode == "messages":
261
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
262
- send_command_messages(hwnd, command)
259
+ send_command_messages(hwnd, command, pid=pid, exe_path=exe_path)
263
260
  return
264
-
265
261
  if clipboard is None:
266
262
  clipboard = Clipboard()
267
- confirm_window(hwnd, pid=pid, exe_path=exe_path)
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
268
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()
269
281
 
270
282
  previous = clipboard.read_text()
271
- clipboard.copy_text(command)
272
- if clipboard.read_text() != command:
273
- raise InputError("the clipboard did not accept the command text")
283
+ sentinel = "lycheedev-readback-" + uuid.uuid4().hex
284
+ owned = {command, sentinel}
274
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()
275
311
  _send_key(VK_RETURN)
276
- time.sleep(0.15)
277
- _send_key(VK_V, ctrl=True)
278
- time.sleep(0.15)
279
- _send_key(VK_RETURN)
280
- time.sleep(0.05)
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
281
321
  finally:
282
- if clipboard.read_text() == command:
322
+ if clipboard.read_text() in owned:
283
323
  if previous is None:
284
324
  clipboard.clear()
285
325
  else:
@@ -302,6 +342,7 @@ def focus_window(hwnd: int, *, pid: int | None = None,
302
342
  if user32.SetForegroundWindow(hwnd):
303
343
  time.sleep(0.10)
304
344
  if is_foreground(hwnd):
345
+ confirm_window(hwnd, pid=pid, exe_path=exe_path)
305
346
  return
306
347
  if attempt == attempts - 1:
307
348
  break
@@ -316,7 +357,7 @@ def focus_window(hwnd: int, *, pid: int | None = None,
316
357
  if not is_foreground(hwnd):
317
358
  raise InputError(
318
359
  "could not bring the game window to the foreground; click the game "
319
- "window once, or use `send --mode messages`")
360
+ "window once and retry the command")
320
361
 
321
362
 
322
363
  def _key_lparam(vk: int, *, up: bool = False) -> int:
@@ -329,21 +370,51 @@ def _key_lparam(vk: int, *, up: bool = False) -> int:
329
370
  return lparam
330
371
 
331
372
 
332
- def send_command_messages(hwnd: int, command: str, *, delay: float = 0.03) -> None:
333
- """Type ``command`` into ``hwnd`` by posting messages; no focus needed.
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.
334
376
 
335
- The chat edit box must already be open and focused in the game, because the
336
- client routes posted keys to whatever widget has focus. Characters go out
337
- as WM_CHAR (the client re-encodes them for IME), and Return submits.
377
+ PostMessage acceptance only means queued input. It cannot prove chat focus
378
+ or text consumption; callers must wait for a matching game receipt.
338
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)
339
399
 
340
- for char in command:
341
- if not user32.PostMessageW(hwnd, WM_CHAR, ord(char), 0):
342
- raise InputError("the client window rejected a character message")
343
- time.sleep(delay)
344
- if not user32.PostMessageW(hwnd, WM_KEYDOWN, VK_RETURN, _key_lparam(VK_RETURN)):
345
- raise InputError("the client window rejected the submit key")
346
- user32.PostMessageW(hwnd, WM_KEYUP, VK_RETURN, _key_lparam(VK_RETURN, up=True))
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
347
418
 
348
419
 
349
420
  class Clipboard:
@@ -571,3 +642,151 @@ def decode_qr(image, zxingcpp_module=None) -> list[str]:
571
642
  return payloads
572
643
 
573
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
+