lycheedev 1.0.5 → 1.1.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.
@@ -23,8 +23,10 @@ from __future__ import annotations
23
23
 
24
24
  import ctypes
25
25
  import ctypes.wintypes as wt
26
+ import json
26
27
  import time
27
28
  from collections import deque
29
+ from concurrent.futures import ThreadPoolExecutor
28
30
  from dataclasses import dataclass
29
31
 
30
32
  user32 = ctypes.WinDLL("user32", use_last_error=True)
@@ -571,3 +573,151 @@ def decode_qr(image, zxingcpp_module=None) -> list[str]:
571
573
  return payloads
572
574
 
573
575
 
576
+ def _identity_payload(payloads) -> dict | None:
577
+ """Pick the identity marker out of decoded payloads.
578
+
579
+ A window may show the completion notice instead of an identity marker, and
580
+ both are JSON with a ``v`` field, so the shape is checked rather than
581
+ assumed: an identity marker carries a character id, a notice carries a
582
+ ticket.
583
+ """
584
+
585
+ for text in payloads:
586
+ try:
587
+ value = json.loads(text)
588
+ except (TypeError, ValueError):
589
+ continue
590
+ if not isinstance(value, dict) or "id" not in value:
591
+ continue
592
+ if "ticket" in value:
593
+ continue
594
+ return value
595
+ return None
596
+
597
+
598
+ # The identity probe's waiting budget, sized from measurement rather than guess:
599
+ # on a live window Windows.Graphics.Capture delivers the first frame in 78-94 ms
600
+ # (234 ms cold) and decoding an empty ROI costs about 3 ms. The grace therefore
601
+ # only has to cover a slow first frame, and the timeout only a window that never
602
+ # delivers one at all.
603
+ IDENTITY_FIRST_FRAME_GRACE = 0.35
604
+ IDENTITY_TIMEOUT = 1.5
605
+
606
+
607
+ def read_identity(hwnd: int, *, pid: int | None = None, exe_path: str | None = None,
608
+ timeout: float = IDENTITY_TIMEOUT, interval: float = 0.03,
609
+ first_frame_grace: float = IDENTITY_FIRST_FRAME_GRACE,
610
+ minimum_update_interval_ms: int | None = None) -> dict | None:
611
+ """Read the in-game identity marker from one window, or None.
612
+
613
+ This exists because nothing observable from outside the game says which
614
+ character is behind which window. With one window that does not matter; with
615
+ several it decides where a slash command may be typed. The window does not
616
+ need to be in the foreground, because Windows.Graphics.Capture reads the
617
+ window surface directly, which is what makes this usable before any input is
618
+ sent.
619
+
620
+ "No marker" is the ordinary state, not a failure: the user shows one on
621
+ request. The wait therefore ends as soon as one frame has been decoded
622
+ without finding a marker and no newer frame follows, so an unmarked window
623
+ costs ``first_frame_grace`` rather than the whole ``timeout``. The timeout
624
+ remains the ceiling for a window that never delivers a frame at all.
625
+
626
+ Returns the decoded marker, or None. Raises WindowIdentityError for a stale
627
+ hwnd and CaptureDependencyError when the optional packages are missing.
628
+ """
629
+
630
+ deadline = time.monotonic() + max(0.0, timeout)
631
+ grace = max(0.0, first_frame_grace)
632
+ last_attempted = None
633
+ first_frame_at = None
634
+ with open_notice_capture(hwnd, pid=pid, exe_path=exe_path, interval=interval,
635
+ minimum_update_interval_ms=minimum_update_interval_ms) as session:
636
+ while time.monotonic() < deadline:
637
+ roi = session.latest_roi()
638
+ # The session keeps the newest frame until a newer one arrives, so
639
+ # decode each distinct frame once: re-decoding an unchanged image
640
+ # every interval would burn the whole timeout on one picture.
641
+ if roi is not None and roi is not last_attempted:
642
+ if first_frame_at is None:
643
+ first_frame_at = time.monotonic()
644
+ last_attempted = roi
645
+ marker = _identity_payload(decode_qr(roi))
646
+ if marker is not None:
647
+ return marker
648
+ if session.window_closed:
649
+ return None
650
+ if first_frame_at is not None and time.monotonic() - first_frame_at >= grace:
651
+ # Frames are arriving and none carried a marker, so waiting
652
+ # longer cannot change the answer.
653
+ return None
654
+ time.sleep(interval)
655
+ return None
656
+
657
+
658
+ def _probe_one(window, timeout: float, interval: float,
659
+ first_frame_grace: float, reader=None) -> dict:
660
+ """Probe one window and return its result entry, never raising."""
661
+
662
+ entry = {
663
+ "hwnd": window.get("hwnd"),
664
+ "pid": window.get("pid"),
665
+ "flavorFolder": window.get("flavorFolder"),
666
+ "flavorId": window.get("flavorId"),
667
+ "flavorLabel": window.get("flavorLabel"),
668
+ "identity": None,
669
+ "error": None,
670
+ }
671
+ probe = reader if reader is not None else read_identity
672
+ try:
673
+ entry["identity"] = probe(
674
+ int(window["hwnd"]),
675
+ pid=window.get("pid"),
676
+ exe_path=window.get("exePath"),
677
+ timeout=timeout,
678
+ interval=interval,
679
+ first_frame_grace=first_frame_grace,
680
+ )
681
+ except (WindowIdentityError, CaptureDependencyError) as error:
682
+ # These say something about the request or the environment rather than
683
+ # about one window, so report them and keep going; the caller decides
684
+ # whether an unreadable set is fatal.
685
+ entry["error"] = str(error)
686
+ except (OSError, RuntimeError, ValueError) as error:
687
+ # One window being uncooperative (closed, minimized, denied) must not
688
+ # abort the probe of the remaining windows.
689
+ entry["error"] = str(error)
690
+ return entry
691
+
692
+
693
+ def read_identities(windows, *, timeout: float = IDENTITY_TIMEOUT, interval: float = 0.03,
694
+ first_frame_grace: float = IDENTITY_FIRST_FRAME_GRACE,
695
+ reader=None) -> list[dict]:
696
+ """Probe several windows for their identity marker, in the given order.
697
+
698
+ The windows are probed concurrently. Each call owns its own capture session,
699
+ the frame callback only touches that session's queue, and the waiting is
700
+ sleep-bound, so the probe costs one window's latency instead of the sum of
701
+ all of them. With one window this is exactly the old behavior.
702
+
703
+ A window without a visible marker yields an entry with ``identity`` set to
704
+ None rather than an error, because "no marker" is the expected state until
705
+ the user asks the game to show one. ``reader`` exists so the concurrency and
706
+ error isolation can be tested without a game window.
707
+ """
708
+
709
+ items = list(windows)
710
+ if not items:
711
+ return []
712
+
713
+ def probe(window: dict) -> dict:
714
+ return _probe_one(window, timeout, interval, first_frame_grace, reader)
715
+
716
+ # Threads rather than processes: the work is blocking waits and small
717
+ # decodes, so the GIL is not the constraint, and every entry stays picklable
718
+ # for callers that serialize the result.
719
+ workers = min(len(items), 8)
720
+ with ThreadPoolExecutor(max_workers=workers) as pool:
721
+ return list(pool.map(probe, items))
722
+
723
+
@@ -47,7 +47,17 @@ from automation.saved_variables import SavedVariablesError # noqa: E402
47
47
 
48
48
  NOTICE_MAX_BYTES = 512
49
49
  BUG_TASK_ID = "bug"
50
- CLIENT_FOLDERS = {"retail": "_retail_", "classic": "_classic_", "titan": "_classic_titan_"}
50
+ # Client -> candidate install folders, in the order to try. A folder name is a
51
+ # location rather than an identity: the launcher reuses a test folder for
52
+ # whatever is on the test track, so WoW: Forever currently lives in
53
+ # `_classic_beta_` while a dedicated `_forever_` folder is also accepted. The
54
+ # right folder is decided by what exists under the WoW root, not by the name.
55
+ CLIENT_FOLDERS = {
56
+ "retail": ("_retail_",),
57
+ "classic": ("_classic_",),
58
+ "titan": ("_classic_titan_",),
59
+ "forever": ("_classic_beta_", "_forever_"),
60
+ }
51
61
  DEFAULT_TIMEOUT = 120.0
52
62
  DEFAULT_INTERVAL = 0.1
53
63
  SV_READ_RETRIES = 3
@@ -173,9 +183,13 @@ def cmd_profile(args) -> int:
173
183
  raise CliError(f"addon directory not found: {args.addon_dir}")
174
184
  if not os.path.isdir(args.wow_root):
175
185
  raise CliError(f"WoW root directory not found: {args.wow_root}")
186
+ folders = CLIENT_FOLDERS[args.client]
176
187
  profile = {
177
188
  "client": args.client,
178
- "clientFolder": CLIENT_FOLDERS[args.client],
189
+ # The first entry is the default; clientFolders keeps every accepted
190
+ # location so a client that moved folders still resolves.
191
+ "clientFolder": folders[0],
192
+ "clientFolders": list(folders),
179
193
  "wow_root": os.path.abspath(args.wow_root),
180
194
  "addon_dir": os.path.abspath(args.addon_dir),
181
195
  "sv_path": os.path.abspath(args.sv_path) if args.sv_path else None,
@@ -192,15 +206,25 @@ def resolve_client_root(profile: dict) -> str:
192
206
  """Resolve the client folder (`_retail_`, ...) under the configured WoW root.
193
207
 
194
208
  A profile may point either at the WoW root that contains ``_retail_`` or at
195
- the client folder itself; the account tree decides which one is right.
209
+ the client folder itself; the account tree decides which one is right. Every
210
+ accepted folder for the client is tried, so a build that moved folders still
211
+ resolves without rewriting the profile.
196
212
  """
197
213
 
198
214
  root = os.path.abspath(profile.get("wow_root") or "")
199
- folder = profile.get("clientFolder") or CLIENT_FOLDERS.get(profile.get("client"))
215
+ recorded = profile.get("clientFolders")
216
+ if not recorded:
217
+ recorded = [profile.get("clientFolder")] if profile.get("clientFolder") else []
218
+ folders = list(recorded) + list(CLIENT_FOLDERS.get(profile.get("client"), ()))
200
219
  candidates = []
201
- if folder:
202
- candidates.append(os.path.join(root, folder))
203
- candidates.append(root)
220
+ for folder in folders:
221
+ if not folder:
222
+ continue
223
+ path = os.path.join(root, folder)
224
+ if path not in candidates:
225
+ candidates.append(path)
226
+ if root not in candidates:
227
+ candidates.append(root)
204
228
  for candidate in candidates:
205
229
  if os.path.isdir(os.path.join(candidate, "WTF", "Account")):
206
230
  return candidate
@@ -520,6 +544,73 @@ def cmd_capture(args) -> int:
520
544
  return 0
521
545
 
522
546
 
547
+ def cmd_identify(args) -> int:
548
+ """Read the in-game identity marker from one or more game windows.
549
+
550
+ Nothing observable from outside the game says which character sits behind
551
+ which window, so with several windows open a slash command cannot be aimed
552
+ without guessing. The addon can display a marker on request
553
+ (``/dev auto identify``); this reads it out of each window so the caller can
554
+ offer the user a character-based choice instead of an arbitrary index.
555
+
556
+ Capture does not need the foreground, so this is safe before any input is
557
+ sent. A window with no visible marker is reported with ``identity: null``
558
+ rather than treated as an error: that is the normal state until the user
559
+ asks the game to show one.
560
+ """
561
+
562
+ windows = _window_module()
563
+ targets = _identify_targets(args)
564
+ if not targets:
565
+ raise CliError("identify needs at least one window: pass --hwnd, or "
566
+ "--windows-json with the instances list")
567
+
568
+ # Only forward an explicit timeout: passing None would override the helper's
569
+ # own measured default rather than selecting it.
570
+ options = {"interval": args.interval}
571
+ if args.timeout is not None:
572
+ options["timeout"] = args.timeout
573
+ results = windows.read_identities(targets, **options)
574
+ print(json.dumps(results, ensure_ascii=False, sort_keys=True))
575
+ # Every window unreadable is a real failure; a partly readable set is not.
576
+ if results and all(entry["identity"] is None and entry["error"] for entry in results):
577
+ return EXIT_NOTICE_TIMEOUT
578
+ return 0
579
+
580
+
581
+ def _identify_targets(args) -> list[dict]:
582
+ """Build the probe list from repeated --hwnd flags or a windows JSON file."""
583
+
584
+ targets: list[dict] = []
585
+ if args.windows_json:
586
+ try:
587
+ with open(args.windows_json, encoding="utf-8") as handle:
588
+ loaded = json.load(handle)
589
+ except OSError as error:
590
+ raise CliError(f"could not read --windows-json: {error}") from error
591
+ except ValueError as error:
592
+ raise CliError(f"--windows-json is not valid JSON: {error}") from error
593
+ if not isinstance(loaded, list):
594
+ raise CliError("--windows-json must contain a JSON array of windows")
595
+ for entry in loaded:
596
+ if not isinstance(entry, dict) or entry.get("hwnd") is None:
597
+ raise CliError("every --windows-json entry needs an 'hwnd'")
598
+ targets.append({
599
+ "hwnd": entry.get("hwnd"),
600
+ "pid": entry.get("pid"),
601
+ "exePath": entry.get("exePath"),
602
+ "flavorFolder": entry.get("flavorFolder"),
603
+ "flavorId": entry.get("flavorId"),
604
+ "flavorLabel": entry.get("flavorLabel"),
605
+ })
606
+ return targets
607
+
608
+ for hwnd in args.hwnd or ():
609
+ targets.append({"hwnd": hwnd, "pid": args.pid, "exePath": args.exe_path,
610
+ "flavorFolder": None, "flavorId": None, "flavorLabel": None})
611
+ return targets
612
+
613
+
523
614
  # --- orchestrated flows ---------------------------------------------------------
524
615
 
525
616
  def _notice_to_sv(session: session_mod.Session, windows, notice: dict, args,
@@ -696,7 +787,8 @@ def build_parser() -> argparse.ArgumentParser:
696
787
  profile.add_argument("profile_command", choices=["set", "show"])
697
788
  profile.add_argument("--name", required=True, help="profile name")
698
789
  profile.add_argument("--client", choices=sorted(CLIENT_FOLDERS),
699
- help="client type: retail, classic or titan")
790
+ help="client type: retail, classic, titan or forever; the "
791
+ "client folder is resolved from the WoW root")
700
792
  profile.add_argument("--wow-root", help="WoW root that contains the client folder")
701
793
  profile.add_argument("--addon-dir", help="installed addon directory")
702
794
  profile.add_argument("--sv-path", help="exact 'Lychee Dev.lua' path to read")
@@ -760,6 +852,24 @@ def build_parser() -> argparse.ArgumentParser:
760
852
  help="poll the window and decode the notice QR")
761
853
  capture.set_defaults(func=cmd_capture)
762
854
 
855
+ identify = sub.add_parser(
856
+ "identify",
857
+ help="read the character/build identity marker from game windows")
858
+ identify.add_argument("--hwnd", type=lambda value: int(value, 0), action="append",
859
+ help="a window to probe; repeat for several windows")
860
+ identify.add_argument("--windows-json",
861
+ help="JSON file with the instance list to probe instead "
862
+ "of --hwnd (the shape 'lycheedev instances' prints)")
863
+ identify.add_argument("--pid", type=int, help="expected process id")
864
+ identify.add_argument("--exe-path", help="expected executable path")
865
+ identify.add_argument("--timeout", type=float, default=None,
866
+ help="seconds to wait per window for its marker "
867
+ "(default: the helper's measured budget)")
868
+ identify.add_argument("--interval", type=float, default=DEFAULT_INTERVAL,
869
+ help=f"seconds between polls per window "
870
+ f"(default: {DEFAULT_INTERVAL})")
871
+ identify.set_defaults(func=cmd_identify)
872
+
763
873
  run = sub.add_parser("run", parents=[window, polling],
764
874
  help="deliver and resolve one task run")
765
875
  run.add_argument("--task", required=True, help="task id to run")
@@ -574,6 +574,47 @@ else:
574
574
  "the Lua notice still anchors to TOPRIGHT while the ROI scans TOPLEFT"
575
575
  print("Lua notice anchor and Python ROI agree on the top-left corner OK")
576
576
 
577
+ # The identity probe reads a marker from every running window so the caller
578
+ # can name the window before typing into it. Probing must keep the input
579
+ # order, isolate one bad window, and treat "no marker" as ordinary rather
580
+ # than as an error.
581
+ probe_delay = 0.3
582
+
583
+ def fake_identity_reader(hwnd, **_kwargs):
584
+ time.sleep(probe_delay)
585
+ if hwnd == 3:
586
+ raise winmod.WindowIdentityError("stale window")
587
+ if hwnd == 4:
588
+ return None
589
+ return {"v": 1, "id": f"char{hwnd}", "realm": "realm", "client": "retail"}
590
+
591
+ probe_windows = [{"hwnd": 1, "pid": 11}, {"hwnd": 2, "pid": 22},
592
+ {"hwnd": 3, "pid": 33}, {"hwnd": 4, "pid": 44}]
593
+ probe_start = time.monotonic()
594
+ probe_results = winmod.read_identities(probe_windows, reader=fake_identity_reader)
595
+ probe_elapsed = time.monotonic() - probe_start
596
+
597
+ assert [entry["hwnd"] for entry in probe_results] == [1, 2, 3, 4], probe_results
598
+ assert probe_results[0]["identity"]["id"] == "char1", probe_results[0]
599
+ assert probe_results[1]["identity"]["id"] == "char2", probe_results[1]
600
+ assert probe_results[2]["error"] == "stale window", probe_results[2]
601
+ assert probe_results[2]["identity"] is None, probe_results[2]
602
+ assert probe_results[3]["identity"] is None and probe_results[3]["error"] is None, \
603
+ probe_results[3]
604
+ # Windows are probed concurrently, so four delayed probes must cost far less
605
+ # than four sequential waits.
606
+ assert probe_elapsed < probe_delay * 2, probe_elapsed
607
+ assert winmod.read_identities([]) == []
608
+ # A found marker must return at once instead of waiting out the grace period.
609
+ instant_start = time.monotonic()
610
+ winmod.read_identities(probe_windows[:1],
611
+ reader=lambda _hwnd, **_kw: {"v": 1, "id": "fast"})
612
+ assert time.monotonic() - instant_start < probe_delay, "a found marker waited"
613
+ # The waiting budget must stay small: it is paid per window on every probe.
614
+ assert 0 < winmod.IDENTITY_FIRST_FRAME_GRACE <= 1.0, winmod.IDENTITY_FIRST_FRAME_GRACE
615
+ assert 0 < winmod.IDENTITY_TIMEOUT <= 5.0, winmod.IDENTITY_TIMEOUT
616
+ print("identity probe order, isolation and concurrency OK")
617
+
577
618
  # --- host read acknowledgement ------------------------------------------------
578
619
  #
579
620
  # The plugin cannot see whether the host read a result, so the host says so with
@@ -838,10 +879,58 @@ with contextlib.redirect_stdout(out):
838
879
  "--client", "retail",
839
880
  "--wow-root", os.path.join(wow_root, "_retail_"),
840
881
  "--addon-dir", addon_install]) == 0
882
+ out = io.StringIO()
841
883
  with contextlib.redirect_stdout(out):
842
884
  assert cli.main(["--data-dir", profile_data, "sv", "find", "--profile", "direct"]) == 0
843
- assert expected_sv in out.getvalue()
885
+ assert out.getvalue().strip() == expected_sv, out.getvalue()
844
886
  assert cli.main(["--data-dir", profile_data, "sv", "find", "--profile", "missing"]) == 1
887
+
888
+ # WoW: Forever lives in a reused test folder on the test track, so a profile for
889
+ # it must resolve whichever accepted folder actually holds the account tree.
890
+ assert cli.CLIENT_FOLDERS["forever"] == ("_classic_beta_", "_forever_"), \
891
+ cli.CLIENT_FOLDERS["forever"]
892
+ forever_account = os.path.join(wow_root, "_classic_beta_", "WTF", "Account",
893
+ "TESTACCOUNT", "SavedVariables")
894
+ os.makedirs(forever_account, exist_ok=True)
895
+ forever_sv = os.path.join(forever_account, "Lychee Dev.lua")
896
+ with open(forever_sv, "wb") as handle:
897
+ handle.write(b"LycheeDevDB = {}\n")
898
+ assert cli.main(["--data-dir", profile_data, "profile", "set", "--name", "forever-main",
899
+ "--client", "forever", "--wow-root", wow_root,
900
+ "--addon-dir", addon_install]) == 0
901
+ out = io.StringIO()
902
+ with contextlib.redirect_stdout(out):
903
+ assert cli.main(["--data-dir", profile_data, "sv", "find",
904
+ "--profile", "forever-main"]) == 0
905
+ assert out.getvalue().strip() == forever_sv, out.getvalue()
906
+
907
+ # The same profile must still resolve after the client moves to its own folder,
908
+ # without rewriting the profile: the recorded folder is a hint, not the answer.
909
+ os.rename(os.path.join(wow_root, "_classic_beta_"), os.path.join(wow_root, "_forever_"))
910
+ out = io.StringIO()
911
+ with contextlib.redirect_stdout(out):
912
+ assert cli.main(["--data-dir", profile_data, "sv", "find",
913
+ "--profile", "forever-main"]) == 0
914
+ assert out.getvalue().strip() == os.path.join(
915
+ wow_root, "_forever_", "WTF", "Account", "TESTACCOUNT", "SavedVariables",
916
+ "Lychee Dev.lua"), out.getvalue()
917
+
918
+ # The old bug: a profile that recorded `_classic_arena_` (which does not exist)
919
+ # must still fall back to the client's real folders.
920
+ stale = os.path.join(profile_data, "profiles.json")
921
+ with open(stale, encoding="utf-8") as handle:
922
+ stored = json.load(handle)
923
+ stored["forever-main"]["clientFolder"] = "_classic_arena_"
924
+ stored["forever-main"]["clientFolders"] = ["_classic_arena_"]
925
+ with open(stale, "w", encoding="utf-8") as handle:
926
+ json.dump(stored, handle)
927
+ out = io.StringIO()
928
+ with contextlib.redirect_stdout(out):
929
+ assert cli.main(["--data-dir", profile_data, "sv", "find",
930
+ "--profile", "forever-main"]) == 0, out.getvalue()
931
+ assert out.getvalue().strip() == os.path.join(
932
+ wow_root, "_forever_", "WTF", "Account", "TESTACCOUNT", "SavedVariables",
933
+ "Lychee Dev.lua"), out.getvalue()
845
934
  print("profile set + sv find resolve the client folder OK")
846
935
 
847
936
  # --- send: host log first, reload dedup, explicit input failure ---------------