lycheedev 1.0.1 → 1.0.3

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.
package/bin/lycheedev.js CHANGED
@@ -8,7 +8,13 @@ import { runDoctor } from '../src/doctor.js';
8
8
  import { runInstall } from '../src/install.js';
9
9
  import { loadConfig } from '../src/config.js';
10
10
  import { runAutomation } from '../src/python.js';
11
- import { scanClients } from '../src/wow.js';
11
+ import {
12
+ findInstances,
13
+ findSavedVariablesCandidates,
14
+ formatInstance,
15
+ resolveInstance,
16
+ scanClients,
17
+ } from '../src/wow.js';
12
18
  import { addonFolderName, exists } from '../src/paths.js';
13
19
 
14
20
  const HELP = `lycheedev - Lychee Dev installer and World of Warcraft automation driver
@@ -19,7 +25,8 @@ commands
19
25
  install install python dependencies, the skill and the addon
20
26
  update refresh dependencies, skill and addon to this version
21
27
  doctor report what is installed and what is missing
22
- clients list detected clients and their addon directories
28
+ clients list every detected build and its addon state
29
+ instances list running game clients (build, pid, window)
23
30
  send <text> type one slash command into the running game
24
31
  capture poll the game window and decode the completion notice
25
32
  run --task <id> deliver, decode, reload once and read the result ticket
@@ -32,8 +39,11 @@ commands
32
39
  recover show reload intents that were never confirmed
33
40
 
34
41
  options
35
- --wow-root <path> folder that contains _retail_/_classic_/_classic_arena_
42
+ --wow-root <path> folder that contains _retail_/_classic_/_classic_titan_
36
43
  --client <id> retail | classic | titan (default: the only configured one)
44
+ --instance <index> which running client to target when several are open
45
+ --hwnd <handle> target one window directly, skipping instance lookup
46
+ --pid <pid> expected process id for the target window
37
47
  --python <bin> python interpreter to use
38
48
  --force redo work that is already present
39
49
  --reset-registry install the addon with an empty task registry
@@ -41,6 +51,10 @@ options
41
51
  -h, --help show this help
42
52
  -v, --version show the version
43
53
 
54
+ Every non-retail client runs as WowClassic.exe, so a running client is matched
55
+ by its install path, not its process name. When several clients are open, run
56
+ "lycheedev instances" first and pass --instance <index> to choose one.
57
+
44
58
  The automation subcommands are thin wrappers over the bundled python helper, so
45
59
  the same arguments it accepts are forwarded unchanged.`;
46
60
 
@@ -121,15 +135,69 @@ function runClients(flags) {
121
135
  }
122
136
  console.log(root);
123
137
  for (const client of scanClients(root)) {
124
- const supported = ['retail', 'classic', 'titan'].includes(client.id);
125
- const installed = exists(path.join(client.addonsDir, addonFolderName));
126
- console.log(` ${client.id.padEnd(11)} ${client.folder.padEnd(16)} `
127
- + `${installed ? 'addon installed' : 'addon missing'}`.padEnd(18)
128
- + `${supported ? '' : '(not supported by the addon)'}`);
138
+ const version = client.version ? `v${client.version}` : 'unknown version';
139
+ const state = !client.toc
140
+ ? 'not served by the addon'
141
+ : (client.installed ? 'addon installed' : 'addon missing');
142
+ console.log(` ${client.id.padEnd(12)} ${client.folder.padEnd(18)} ${version.padEnd(18)} ${state}`);
143
+ }
144
+ return 0;
145
+ }
146
+
147
+ /** `lycheedev instances`: which game clients are running right now. */
148
+ function runInstances(flags) {
149
+ const instances = findInstances({ pythonBin: flags.python || null });
150
+ if (instances.length === 0) {
151
+ console.log('no World of Warcraft instance is running');
152
+ return 0;
153
+ }
154
+ console.log('running instances:');
155
+ instances.forEach((instance, index) => console.log(formatInstance(instance, index)));
156
+ const supported = instances.filter((item) => item.supported);
157
+ const sameBuild = supported.length > 1;
158
+ console.log('');
159
+ if (supported.length === 0) {
160
+ console.log('none of these builds are served by the addon');
161
+ } else if (sameBuild) {
162
+ console.log('several instances are running: target one with `--instance <index>`');
163
+ } else {
164
+ console.log('commands target this instance automatically');
129
165
  }
130
166
  return 0;
131
167
  }
132
168
 
169
+ /**
170
+ * Resolve the live game window a command should type into.
171
+ *
172
+ * The executable name cannot identify a build, so the running instance list is
173
+ * the source of truth: `--instance <index>` picks explicitly, `--client`
174
+ * filters by build, and a single match needs no flag at all. `--hwnd`/`--pid`
175
+ * still override for scripted use.
176
+ */
177
+ function resolveRuntime(flags) {
178
+ if (flags.hwnd || flags.pid) {
179
+ return { hwnd: flags.hwnd, pid: flags.pid };
180
+ }
181
+ const instances = findInstances({ pythonBin: flags.python || null });
182
+ const resolved = resolveInstance(instances, {
183
+ clientId: flags.client || null,
184
+ index: flags.instance !== undefined ? flags.instance : null,
185
+ });
186
+ if (resolved.error) {
187
+ console.error(`error: ${resolved.error}`);
188
+ if (resolved.candidates) {
189
+ resolved.candidates.forEach((item, index) => console.log(formatInstance(item, index)));
190
+ }
191
+ return { error: true };
192
+ }
193
+ const instance = resolved.instance;
194
+ return {
195
+ hwnd: instance.hwnd ? `0x${instance.hwnd.toString(16)}` : null,
196
+ pid: instance.pid ? String(instance.pid) : null,
197
+ instance,
198
+ };
199
+ }
200
+
133
201
  function main(argv) {
134
202
  const { flags, rest } = parse(argv);
135
203
  const command = rest.shift();
@@ -161,6 +229,8 @@ function main(argv) {
161
229
  return runDoctor({ flags });
162
230
  case 'clients':
163
231
  return runClients(flags);
232
+ case 'instances':
233
+ return runInstances(flags);
164
234
  case 'help':
165
235
  console.log(HELP);
166
236
  return 0;
@@ -178,6 +248,17 @@ function main(argv) {
178
248
  // AddOns folder that contains it.
179
249
  if (client.addonsDir) forwarded.push('--install-dir', path.join(client.addonsDir, addonFolderName));
180
250
 
251
+ // Commands that type into the game must target a live window, and the
252
+ // executable name cannot tell two instances apart, so resolve which running
253
+ // instance to use before forwarding.
254
+ const runtime = ['send', 'capture', 'run', 'bugs'].includes(command)
255
+ ? resolveRuntime(flags)
256
+ : null;
257
+ if (runtime && runtime.error) return 1;
258
+ const live = runtime && runtime.hwnd
259
+ ? { hwnd: runtime.hwnd, pid: runtime.pid }
260
+ : null;
261
+
181
262
  switch (command) {
182
263
  case 'send': {
183
264
  const text = rest.join(' ');
@@ -185,39 +266,47 @@ function main(argv) {
185
266
  console.error('error: send needs the command text, e.g. `lycheedev send "/dev auto status x"`');
186
267
  return 1;
187
268
  }
188
- return forward(['send', ...targetArgs(client), '--text', text, ...passthrough(flags)]);
269
+ if (!live) return 1;
270
+ return forward(['send', ...targetArgs(live), '--text', text, ...passthrough(flags)]);
189
271
  }
190
272
  case 'capture':
191
- return forward(['capture', ...targetArgs(client), ...passthrough(flags)]);
273
+ if (!live) return 1;
274
+ return forward(['capture', ...targetArgs(live), ...passthrough(flags)]);
192
275
  case 'run':
193
276
  if (!flags.task) {
194
277
  console.error('error: run needs --task <id>');
195
278
  return 1;
196
279
  }
280
+ if (!live) return 1;
197
281
  if (!client.svPath) {
198
282
  console.error('error: no SavedVariables path recorded for this client; re-run `lycheedev install`');
199
283
  return 1;
200
284
  }
201
- return forward(['run', ...targetArgs(client), '--task', flags.task, '--sv', client.svPath,
285
+ return forward(['run', ...targetArgs(live), '--task', flags.task, '--sv', client.svPath,
202
286
  ...passthrough(flags)]);
203
287
  case 'bugs':
204
288
  if (!flags.count) {
205
289
  console.error('error: bugs needs --count <1-100>');
206
290
  return 1;
207
291
  }
292
+ if (!live) return 1;
208
293
  if (!client.svPath) {
209
294
  console.error('error: no SavedVariables path recorded for this client; re-run `lycheedev install`');
210
295
  return 1;
211
296
  }
212
- return forward(['bugs', ...targetArgs(client), '--count', String(flags.count), '--sv', client.svPath,
297
+ return forward(['bugs', ...targetArgs(live), '--count', String(flags.count), '--sv', client.svPath,
213
298
  ...passthrough(flags)]);
214
- case 'ack':
299
+ case 'ack': {
215
300
  if (!flags.ticket || !flags.status) {
216
301
  console.error('error: ack needs --ticket <t> --status received|failed');
217
302
  return 1;
218
303
  }
219
- return forward(['ack', ...targetArgs(client), '--ticket', flags.ticket,
304
+ // An acknowledgement also has to reach a live window.
305
+ const ackTarget = resolveRuntime(flags);
306
+ if (ackTarget.error) return 1;
307
+ return forward(['ack', ...targetArgs(ackTarget), '--ticket', flags.ticket,
220
308
  '--status', flags.status, ...passthrough(flags)]);
309
+ }
221
310
  case 'task': {
222
311
  const sub = rest.shift();
223
312
  if (!sub) {
@@ -226,7 +315,42 @@ function main(argv) {
226
315
  }
227
316
  return forward(['task', sub, ...forwarded, ...passthrough(flags)]);
228
317
  }
229
- case 'sv':
318
+ case 'sv': {
319
+ const sub = rest.shift();
320
+ if (sub === 'find') {
321
+ // The wrapper already knows the plaintext install and can enumerate the
322
+ // account folders itself, so `sv find` needs no profile binding.
323
+ const config = loadConfig();
324
+ const root = flags['wow-root'] || config.wowRoot;
325
+ if (!root || !exists(root)) {
326
+ console.error('error: no World of Warcraft root; run `lycheedev install --wow-root <path>`');
327
+ return 1;
328
+ }
329
+ const candidates = findSavedVariablesCandidates(root, client.flavorFolder);
330
+ if (candidates.length === 0) {
331
+ console.error(`no account-level '${addonFolderName}.lua' found under ${root}`);
332
+ return 1;
333
+ }
334
+ for (const candidate of candidates) console.log(candidate.path);
335
+ return 0;
336
+ }
337
+ if (sub === 'read') {
338
+ if (!flags.ticket) {
339
+ console.error('error: sv read needs --ticket <t>');
340
+ return 1;
341
+ }
342
+ const svPath = flags.sv || client.svPath;
343
+ if (!svPath) {
344
+ console.error('error: no SavedVariables path known for this client; '
345
+ + 'run `lycheedev install`, or pass --sv <path>');
346
+ return 1;
347
+ }
348
+ return forward(['sv', 'read', '--sv', svPath, '--ticket', flags.ticket,
349
+ ...passthrough(flags)]);
350
+ }
351
+ console.error('error: sv needs a subcommand: find or read');
352
+ return 1;
353
+ }
230
354
  case 'profile':
231
355
  case 'status':
232
356
  case 'recover':
@@ -242,7 +366,7 @@ function main(argv) {
242
366
  // These are either handled by the wrapper itself or are global python
243
367
  // options that `forward()` places before the subcommand.
244
368
  const handled = ['wow-root', 'client', 'python', 'force', 'reset-registry', 'task', 'count',
245
- 'ticket', 'status', 'json', 'help', 'version', 'data-dir', 'installation'];
369
+ 'ticket', 'status', 'json', 'help', 'version', 'data-dir', 'installation', 'instance'];
246
370
  for (const [name, value] of Object.entries(all)) {
247
371
  if (handled.includes(name)) continue;
248
372
  if (value === true) out.push(`--${name}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lycheedev",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "lycheedev: install the World of Warcraft inspection addon, its in-game automation tooling, and drive it from the command line.",
5
5
  "keywords": [
6
6
  "wow",
package/src/addon.js CHANGED
@@ -25,12 +25,15 @@ export function payloadVersion() {
25
25
  }
26
26
  }
27
27
 
28
- /** Version of whatever is currently installed, if any. */
29
- export function installedVersion(addonsDir) {
28
+ /** Version of whatever is currently installed for one build's catalog. */
29
+ export function installedVersion(addonsDir, toc = null) {
30
30
  const target = addonTargetDir(addonsDir);
31
- for (const toc of [`${addonFolderName}_Mainline.toc`, `${addonFolderName}_Mists.toc`,
32
- `${addonFolderName}_Wrath.toc`]) {
33
- const file = path.join(target, toc);
31
+ const catalogs = toc
32
+ ? [toc]
33
+ : [`${addonFolderName}_Mainline.toc`, `${addonFolderName}_Mists.toc`,
34
+ `${addonFolderName}_Wrath.toc`];
35
+ for (const name of catalogs) {
36
+ const file = path.join(target, name);
34
37
  if (!exists(file)) continue;
35
38
  const match = fs.readFileSync(file, 'utf8').match(/^##\s*Version:\s*(.+)$/m);
36
39
  if (match) return match[1].trim();
@@ -55,11 +58,16 @@ export function countFiles(dir) {
55
58
  * cannot linger. `auto.lua` is local task data, so it is preserved when the
56
59
  * caller asks for it: the empty shipped registry must not wipe pending work.
57
60
  */
58
- export function installAddon(addonsDir, { preserveRegistry = true } = {}) {
61
+ export function installAddon(addonsDir, { preserveRegistry = true, toc = null } = {}) {
59
62
  const source = vendoredAddonRoot();
60
63
  if (!exists(source)) {
61
64
  return { ok: false, error: 'vendored addon payload is missing; reinstall the package' };
62
65
  }
66
+ // Refuse to write a build the addon has no catalog for: the game would load
67
+ // nothing and report only a silent "out of date" addon.
68
+ if (toc && !exists(path.join(source, toc))) {
69
+ return { ok: false, error: `the payload has no ${toc}` };
70
+ }
63
71
  const target = addonTargetDir(addonsDir);
64
72
 
65
73
  let savedRegistry = null;
package/src/doctor.js CHANGED
@@ -5,9 +5,9 @@ import path from 'node:path';
5
5
 
6
6
  import { installedVersion, payloadVersion } from './addon.js';
7
7
  import { loadConfig } from './config.js';
8
- import { addonFolderName, configPath, dataDir, exists, pythonDepsDir, skillTargetDir } from './paths.js';
8
+ import { configPath, dataDir, exists, pythonDepsDir, skillTargetDir } from './paths.js';
9
9
  import { automationScript, findPython, pythonEnv } from './python.js';
10
- import { findSavedVariablesCandidates, scanClients } from './wow.js';
10
+ import { findInstances, findSavedVariablesCandidates, scanClients } from './wow.js';
11
11
 
12
12
  const OK = 'ok ';
13
13
  const WARN = 'warn';
@@ -66,16 +66,22 @@ export function runDoctor({ flags }) {
66
66
  results.push(line(WARN, 'wow root', 'not configured; run `lycheedev install --wow-root <path>`'));
67
67
  } else {
68
68
  results.push(line(OK, 'wow root', roots[0]));
69
- for (const client of scanClients(roots[0])) {
70
- if (!['retail', 'classic', 'titan'].includes(client.id)) continue;
71
- const target = path.join(client.addonsDir, addonFolderName);
72
- if (!exists(target)) {
69
+ const clients = scanClients(roots[0]);
70
+ for (const client of clients) {
71
+ const version = client.version ? `v${client.version}` : 'unknown version';
72
+ if (!client.toc) {
73
+ // Present but intentionally not served: say so instead of hiding it.
74
+ results.push(line(OK, `build (${client.id})`, `${client.folder} ${version} - not served by the addon`));
75
+ continue;
76
+ }
77
+ const target = client.installedDir;
78
+ if (!client.installed) {
73
79
  results.push(line(WARN, `addon (${client.id})`, `not installed in ${client.addonsDir}`));
74
80
  continue;
75
81
  }
76
82
  const current = installedVersion(client.addonsDir);
77
83
  const shipped = payloadVersion();
78
- const detail = `${target} (installed ${current || '?'}, package ${shipped || '?'})`;
84
+ const detail = `${client.folder} ${version} (installed ${current || '?'}, package ${shipped || '?'})`;
79
85
  results.push(current && shipped && current !== shipped
80
86
  ? line(WARN, `addon (${client.id})`, `${detail} - run \`lycheedev update\``)
81
87
  : line(OK, `addon (${client.id})`, detail));
@@ -87,6 +93,25 @@ export function runDoctor({ flags }) {
87
93
  }
88
94
  }
89
95
 
96
+ // Which clients are running decides what `send`/`run` can target.
97
+ const instances = findInstances({ pythonBin: python ? python.bin : null });
98
+ const supportedRunning = instances.filter((item) => item.supported);
99
+ if (instances.length === 0) {
100
+ results.push(line(OK, 'running clients', 'none'));
101
+ } else {
102
+ for (const [index, instance] of instances.entries()) {
103
+ const label = instance.flavorLabel || instance.flavorFolder || 'unknown';
104
+ const detail = `${label} pid=${instance.pid}`
105
+ + `${instance.hwnd ? ` hwnd=0x${instance.hwnd.toString(16)}` : ''}`
106
+ + `${instance.supported ? '' : ' (not served by the addon)'}`;
107
+ results.push(line(instance.supported ? OK : WARN, `running [${index}]`, detail));
108
+ }
109
+ if (supportedRunning.length > 1) {
110
+ results.push(line(WARN, 'instance choice',
111
+ 'several clients are running; pass `--instance <index>` to target one'));
112
+ }
113
+ }
114
+
90
115
  console.log(`\nconfig: ${configPath()}`);
91
116
  console.log(`data : ${dataDir()}`);
92
117
  if (python) {
package/src/install.js CHANGED
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
 
5
5
  import { installAddon, installedVersion, payloadVersion } from './addon.js';
6
6
  import { loadConfig, setClient, updateConfig } from './config.js';
7
- import { addonFolderName, exists } from './paths.js';
7
+ import { exists } from './paths.js';
8
8
  import { depsInstalled, findPython, installDeps } from './python.js';
9
9
  import { installSkill } from './skill.js';
10
10
  import { detectWowRoots, findSavedVariablesCandidates, scanClients } from './wow.js';
@@ -82,8 +82,10 @@ export function runInstall({ flags }) {
82
82
  let defaultClient = config.defaultClient || null;
83
83
 
84
84
  for (const client of resolved.clients) {
85
- if (!['retail', 'classic', 'titan'].includes(client.id)) {
86
- console.log(`\n${client.label}: skipped (unsupported by the addon)`);
85
+ // A build without a catalog is reported, not silently dropped: the folder
86
+ // still exists and the user should know why nothing was installed there.
87
+ if (!client.toc) {
88
+ console.log(`\n${client.label} (${client.folder}): not served by the addon, skipped`);
87
89
  continue;
88
90
  }
89
91
  step(`${client.label}: installing addon into ${client.folder}`, () => {
@@ -92,12 +94,15 @@ export function runInstall({ flags }) {
92
94
  return { ok: false, skipped: true };
93
95
  }
94
96
  const before = installedVersion(client.addonsDir);
95
- const installed = installAddon(client.addonsDir, { preserveRegistry: !flags['reset-registry'] });
97
+ const installed = installAddon(client.addonsDir, {
98
+ preserveRegistry: !flags['reset-registry'],
99
+ toc: client.toc,
100
+ });
96
101
  if (!installed.ok) {
97
102
  console.log(` error: ${installed.error}`);
98
103
  return installed;
99
104
  }
100
- console.log(` ${addonFolderName} -> ${installed.target}`);
105
+ console.log(` ${client.toc} -> ${installed.target}`);
101
106
  console.log(` files: ${installed.files}, version: ${before ? `${before} -> ` : ''}${installed.version}`);
102
107
  if (installed.keptRegistry) console.log(' kept the existing task registry (local task data)');
103
108
  addonResults.push({ client: client.id, ...installed });
@@ -107,6 +112,7 @@ export function runInstall({ flags }) {
107
112
  const candidates = findSavedVariablesCandidates(resolved.root, client.folder);
108
113
  setClient(nextConfig, client.id, {
109
114
  flavorFolder: client.folder,
115
+ toc: client.toc,
110
116
  addonsDir: client.addonsDir,
111
117
  svPath: candidates[0] ? candidates[0].path : null,
112
118
  installedAt: new Date().toISOString(),
@@ -0,0 +1,120 @@
1
+ """List running World of Warcraft instances as JSON.
2
+
3
+ The executable name cannot identify a build: Blizzard ships every non-retail
4
+ client as ``WowClassic.exe``. The install path can, because each build lives in
5
+ a ``_flavor_`` directory. Visible top-level window handles are attached so the
6
+ caller can tell same-build instances apart.
7
+
8
+ Read-only: this opens no process, only enumerates windows and process metadata.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ctypes
14
+ import json
15
+ import os
16
+ import sys
17
+ from ctypes import wintypes
18
+
19
+ user32 = ctypes.windll.user32
20
+ kernel32 = ctypes.windll.kernel32
21
+
22
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
23
+ ERROR_INSUFFICIENT_BUFFER = 122
24
+
25
+ user32.EnumWindows.restype = wintypes.BOOL
26
+ user32.EnumWindows.argtypes = [ctypes.c_void_p, wintypes.LPARAM]
27
+ user32.IsWindowVisible.restype = wintypes.BOOL
28
+ user32.GetWindowTextLengthW.restype = ctypes.c_int
29
+ user32.GetWindowTextW.restype = ctypes.c_int
30
+ user32.GetWindowThreadProcessId.restype = wintypes.DWORD
31
+ user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
32
+
33
+ kernel32.OpenProcess.restype = wintypes.HANDLE
34
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
35
+ kernel32.QueryFullProcessImageNameW.restype = wintypes.BOOL
36
+ kernel32.QueryFullProcessImageNameW.argtypes = [
37
+ wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)]
38
+ kernel32.CloseHandle.restype = wintypes.BOOL
39
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
40
+
41
+ EnumWindowsProc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
42
+
43
+ FLAVOR_LABELS = {
44
+ "_retail_": ("retail", "Retail"),
45
+ "_classic_": ("classic", "Classic"),
46
+ "_classic_titan_": ("titan", "Classic Titan"),
47
+ "_classic_era_": ("classicEra", "Classic Era"),
48
+ "_anniversary_": ("anniversary", "Anniversary"),
49
+ "_beta_": ("beta", "Beta"),
50
+ }
51
+
52
+ SUPPORTED_EXE = {"wow.exe", "wowclassic.exe", "wowb.exe"}
53
+
54
+
55
+ def process_image(pid: int) -> str | None:
56
+ handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
57
+ if not handle:
58
+ return None
59
+ try:
60
+ size = wintypes.DWORD(32768)
61
+ buffer = ctypes.create_unicode_buffer(size.value)
62
+ if not kernel32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)):
63
+ return None
64
+ return buffer.value or None
65
+ finally:
66
+ kernel32.CloseHandle(handle)
67
+
68
+
69
+ def visible_windows() -> dict[int, dict]:
70
+ found: dict[int, dict] = {}
71
+
72
+ def callback(hwnd, _lparam):
73
+ if not user32.IsWindowVisible(hwnd):
74
+ return True
75
+ pid = wintypes.DWORD(0)
76
+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
77
+ length = user32.GetWindowTextLengthW(hwnd)
78
+ if length <= 0:
79
+ return True
80
+ buffer = ctypes.create_unicode_buffer(length + 1)
81
+ user32.GetWindowTextW(hwnd, buffer, length + 1)
82
+ found.setdefault(pid.value, {"hwnd": int(hwnd), "title": buffer.value})
83
+ return True
84
+
85
+ user32.EnumWindows(EnumWindowsProc(callback), 0)
86
+ return found
87
+
88
+
89
+ def main() -> int:
90
+ windows = visible_windows()
91
+ instances = []
92
+
93
+ for pid in windows:
94
+ image = process_image(pid)
95
+ if not image:
96
+ continue
97
+ base = os.path.basename(image).lower()
98
+ if base not in SUPPORTED_EXE:
99
+ continue
100
+ parts = image.replace("/", os.sep).split(os.sep)
101
+ folder = next((part for part in parts if part.startswith("_") and part.endswith("_")), None)
102
+ flavor_id, label = FLAVOR_LABELS.get(folder, (None, None))
103
+ instances.append({
104
+ "pid": pid,
105
+ "exe": os.path.basename(image),
106
+ "exePath": image,
107
+ "flavorFolder": folder,
108
+ "flavorId": flavor_id,
109
+ "flavorLabel": label,
110
+ "hwnd": windows[pid]["hwnd"],
111
+ "title": windows[pid]["title"],
112
+ })
113
+
114
+ instances.sort(key=lambda item: (item.get("flavorId") or "", item["pid"]))
115
+ print(json.dumps(instances, ensure_ascii=False))
116
+ return 0
117
+
118
+
119
+ if __name__ == "__main__":
120
+ sys.exit(main())
package/src/python.js CHANGED
@@ -61,6 +61,10 @@ export function pythonEnv() {
61
61
  ...process.env,
62
62
  PYTHONPATH: existing ? `${deps}${path.delimiter}${existing}` : deps,
63
63
  PYTHONDONTWRITEBYTECODE: '1',
64
+ // Player names, window titles and zone names are not ASCII; without this
65
+ // the helper's stdout is encoded with the console code page and comes back
66
+ // as mojibake.
67
+ PYTHONIOENCODING: 'utf-8',
64
68
  };
65
69
  }
66
70
 
package/src/wow.js CHANGED
@@ -1,21 +1,71 @@
1
- /** Locate World of Warcraft installations and their client flavors. */
1
+ /** Locate World of Warcraft installations, their builds, and running instances. */
2
2
 
3
+ import { execFileSync } from 'node:child_process';
3
4
  import fs from 'node:fs';
4
5
  import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
5
7
 
6
8
  import { addonFolderName, exists, isDir } from './paths.js';
7
9
 
10
+ const here = path.dirname(fileURLToPath(import.meta.url));
11
+ const instancesScript = path.join(here, 'py', 'instances.py');
12
+
13
+ /**
14
+ * Locate a Python 3 interpreter.
15
+ *
16
+ * This lives here instead of `python.js` on purpose: `python.js` only depends
17
+ * on `paths.js`, and importing it from here would create a cycle.
18
+ */
19
+ export function findPythonBin() {
20
+ if (process.env.LYCHEEDEV_PYTHON) return process.env.LYCHEEDEV_PYTHON;
21
+ const candidates = process.platform === 'win32'
22
+ ? ['python', 'python3', 'py']
23
+ : ['python3', 'python'];
24
+ for (const candidate of candidates) {
25
+ try {
26
+ const out = execFileSync(candidate, ['-c', 'import sys; print(sys.version_info[0])'], {
27
+ encoding: 'utf8', windowsHide: true, timeout: 15000,
28
+ });
29
+ if (out.trim().startsWith('3')) return candidate;
30
+ } catch {
31
+ // try the next candidate
32
+ }
33
+ }
34
+ return null;
35
+ }
36
+
8
37
  /**
9
- * Flavor folders the addon supports. `id` is the stable key used by the CLI and
10
- * by the Python automation profile; `folder` is what Blizzard names it.
38
+ * Every flavor folder Blizzard ships. `id` is the stable key used by the CLI;
39
+ * `folder` is what Blizzard names the directory; `toc` is the addon catalog
40
+ * that serves it, or null when the addon does not support that build.
41
+ *
42
+ * The Titan folder is `_classic_titan_`, which holds client 3.80.2 — the build
43
+ * the addon's Wrath TOC targets (Interface 38002). The previous value
44
+ * `_classic_arena_` does not exist, so an installed Titan client was silently
45
+ * skipped by both `install` and `doctor`.
11
46
  */
12
47
  export const CLIENT_FLAVORS = [
13
- { id: 'retail', folder: '_retail_', label: 'Retail (Midnight)' },
14
- { id: 'classic', folder: '_classic_', label: 'Classic (Mists)' },
15
- { id: 'titan', folder: '_classic_arena', label: 'Classic Titan (Wrath)' },
16
- { id: 'classicEra', folder: '_classic_era_', label: 'Classic Era' },
48
+ { id: 'retail', folder: '_retail_', label: 'Retail', exe: 'Wow.exe', toc: 'Lychee Dev_Mainline.toc' },
49
+ { id: 'classic', folder: '_classic_', label: 'Classic', exe: 'WowClassic.exe', toc: 'Lychee Dev_Mists.toc' },
50
+ { id: 'titan', folder: '_classic_titan_', label: 'Classic Titan', exe: 'WowClassic.exe', toc: 'Lychee Dev_Wrath.toc' },
51
+ { id: 'classicEra', folder: '_classic_era_', label: 'Classic Era', exe: 'WowClassic.exe', toc: null },
52
+ { id: 'anniversary', folder: '_anniversary_', label: 'Anniversary', exe: 'WowClassic.exe', toc: null },
53
+ { id: 'beta', folder: '_beta_', label: 'Beta', exe: 'WowB.exe', toc: null },
17
54
  ];
18
55
 
56
+ /** Flavors with an addon catalog, i.e. the builds the addon can install into. */
57
+ export function supportedFlavors() {
58
+ return CLIENT_FLAVORS.filter((flavor) => flavor.toc);
59
+ }
60
+
61
+ export function flavorById(id) {
62
+ return CLIENT_FLAVORS.find((flavor) => flavor.id === id) || null;
63
+ }
64
+
65
+ export function flavorByFolder(folder) {
66
+ return CLIENT_FLAVORS.find((flavor) => flavor.folder === folder) || null;
67
+ }
68
+
19
69
  const KNOWN_ROOTS = {
20
70
  win32: [
21
71
  'C:\\Program Files (x86)\\World of Warcraft',
@@ -34,7 +84,7 @@ function looksLikeWowRoot(dir) {
34
84
  return CLIENT_FLAVORS.some((flavor) => isDir(path.join(dir, flavor.folder)));
35
85
  }
36
86
 
37
- /** Directories that contain at least one known flavor folder. */
87
+ /** Roots on this machine that contain at least one known flavor folder. */
38
88
  export function detectWowRoots() {
39
89
  const candidates = [];
40
90
  const seen = new Set();
@@ -52,24 +102,41 @@ export function detectWowRoots() {
52
102
  return candidates;
53
103
  }
54
104
 
105
+ /** Client version, read from the executable's own file metadata. */
106
+ function exeVersion(exePath) {
107
+ try {
108
+ const out = execFileSync('powershell', [
109
+ '-NoProfile', '-Command',
110
+ `(Get-Item -LiteralPath '${exePath.replace(/'/g, "''")}').VersionInfo.FileVersion`,
111
+ ], { encoding: 'utf8', windowsHide: true, timeout: 20000 });
112
+ const value = out.replace(/^\uFEFF/, '').trim();
113
+ return value || null;
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
55
119
  /**
56
- * Describe the flavors present under a root. A given root may hold several
57
- * (retail + classic), and each gets its own AddOns directory.
120
+ * Describe every flavor present under a root, including builds the addon does
121
+ * not serve, so `doctor` can explain them instead of ignoring them silently.
58
122
  */
59
123
  export function scanClients(wowRoot) {
60
124
  const found = [];
61
125
  for (const flavor of CLIENT_FLAVORS) {
62
126
  const flavorDir = path.join(wowRoot, flavor.folder);
63
- const addonsDir = path.join(flavorDir, 'Interface', 'AddOns');
64
127
  if (!isDir(flavorDir)) continue;
128
+ const addonsDir = path.join(flavorDir, 'Interface', 'AddOns');
129
+ const exePath = path.join(flavorDir, flavor.exe);
130
+ const hasExe = exists(exePath);
65
131
  found.push({
66
132
  ...flavor,
67
133
  flavorDir,
68
134
  addonsDir,
69
135
  addonsDirExists: isDir(addonsDir),
70
- installed: exists(path.join(addonsDir, addonFolderName, `${addonFolderName}_Mainline.toc`))
71
- || exists(path.join(addonsDir, addonFolderName, `${addonFolderName}_Mists.toc`))
72
- || exists(path.join(addonsDir, addonFolderName, `${addonFolderName}_Wrath.toc`)),
136
+ exePath: hasExe ? exePath : null,
137
+ version: hasExe ? exeVersion(exePath) : null,
138
+ installedDir: path.join(addonsDir, addonFolderName),
139
+ installed: flavor.toc ? exists(path.join(addonsDir, addonFolderName, flavor.toc)) : false,
73
140
  });
74
141
  }
75
142
  return found;
@@ -95,16 +162,82 @@ export function findSavedVariablesCandidates(wowRoot, flavorFolder) {
95
162
  return results.sort((a, b) => b.mtime - a.mtime);
96
163
  }
97
164
 
98
- /** `Lychee Dev_Mainline.toc` style file for a flavor. */
99
- export function tocSuffixFor(flavorId) {
100
- switch (flavorId) {
101
- case 'retail':
102
- return 'Mainline';
103
- case 'classic':
104
- return 'Mists';
105
- case 'titan':
106
- return 'Wrath';
107
- default:
108
- return null;
165
+ /**
166
+ * Running game instances.
167
+ *
168
+ * Window handles need the Win32 enumeration API, which Node cannot call, so a
169
+ * small read-only helper does it: `src/py/instances.py` enumerates visible
170
+ * windows and reads process image paths without opening a process.
171
+ *
172
+ * Blizzard ships every non-retail client as `WowClassic.exe`, so the process
173
+ * name cannot identify a build; the executable path can, because each install
174
+ * lives under a `_flavor_` directory.
175
+ */
176
+ export function findInstances({ pythonBin = null } = {}) {
177
+ if (process.platform !== 'win32') return [];
178
+ const python = pythonBin || findPythonBin();
179
+ if (!python || !exists(instancesScript)) return [];
180
+
181
+ let rows = [];
182
+ try {
183
+ const out = execFileSync(python, ['-B', instancesScript], {
184
+ encoding: 'utf8',
185
+ windowsHide: true,
186
+ timeout: 30000,
187
+ env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
188
+ });
189
+ const parsed = JSON.parse(out.replace(/^\uFEFF/, '') || '[]');
190
+ rows = Array.isArray(parsed) ? parsed : [parsed];
191
+ } catch {
192
+ return [];
193
+ }
194
+
195
+ return rows
196
+ .map((row) => {
197
+ const flavor = flavorByFolder(row.flavorFolder);
198
+ return { ...row, supported: Boolean(flavor && flavor.toc) };
199
+ })
200
+ .sort((a, b) => (a.flavorId || '').localeCompare(b.flavorId || '') || a.pid - b.pid);
201
+ }
202
+
203
+ /**
204
+ * Choose which running instance a command targets.
205
+ *
206
+ * One instance needs no flag. Several instances of different builds are picked
207
+ * with `--client`. Several instances of the *same* build are genuinely
208
+ * ambiguous, so the caller must pass `--instance <index>` after seeing the
209
+ * table; guessing would type into the wrong game window.
210
+ */
211
+ export function resolveInstance(instances, { clientId = null, index = null } = {}) {
212
+ const supported = instances.filter((item) => item.supported);
213
+ if (supported.length === 0) {
214
+ return { error: 'no supported World of Warcraft instance is running' };
215
+ }
216
+ if (index !== null && index !== undefined) {
217
+ const chosen = supported[Number(index)];
218
+ if (!chosen) {
219
+ return { error: `--instance ${index} is out of range (0..${supported.length - 1})` };
220
+ }
221
+ return { instance: chosen };
222
+ }
223
+ const candidates = clientId ? supported.filter((item) => item.flavorId === clientId) : supported;
224
+ if (candidates.length === 0) {
225
+ return { error: `no running instance for client '${clientId}'` };
109
226
  }
227
+ if (candidates.length === 1) {
228
+ return { instance: candidates[0] };
229
+ }
230
+ return {
231
+ error: `${candidates.length} instances match; pass --instance <index>`,
232
+ candidates,
233
+ };
234
+ }
235
+
236
+ export function formatInstance(instance, index) {
237
+ const flavor = instance.flavorLabel || instance.flavorFolder || 'unknown';
238
+ const suffix = instance.supported ? '' : ' (the addon does not serve this build)';
239
+ const hwnd = instance.hwnd ? `0x${instance.hwnd.toString(16)}` : '-';
240
+ const title = instance.title ? ` "${instance.title}"` : '';
241
+ return ` [${index}] ${flavor.padEnd(14)} pid=${String(instance.pid).padEnd(8)} `
242
+ + `hwnd=${hwnd.padEnd(12)}${title}${suffix}`;
110
243
  }
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.0.1
9
+ ## Version: 1.0.3
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.0.1
9
+ ## Version: 1.0.3
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -6,7 +6,7 @@
6
6
  ## Notes-zhCN: 运行 Lua,检查对象与事件,追踪函数并查看错误。
7
7
  ## Notes-zhTW: 執行 Lua,檢查物件與事件,追蹤函式並檢視錯誤。
8
8
  ## Author: Follen
9
- ## Version: 1.0.1
9
+ ## Version: 1.0.3
10
10
  ## Dependencies: !BugGrabber
11
11
  ## SavedVariables: LycheeDevDB, DumperDB
12
12
  ## IconTexture: Interface\AddOns\Lychee Dev\Media\Logo.png
@@ -47,7 +47,7 @@ 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_arena"}
50
+ CLIENT_FOLDERS = {"retail": "_retail_", "classic": "_classic_", "titan": "_classic_titan_"}
51
51
  DEFAULT_TIMEOUT = 120.0
52
52
  DEFAULT_INTERVAL = 0.1
53
53
  SV_READ_RETRIES = 3