@team-antioch/sc2-adjutant-host-windows 0.0.0-stage → 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TeamAntioch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # @team-antioch/sc2-adjutant-host-windows
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Windows **Host Adapter** for [sc2-adjutant](https://github.com/TeamAntioch/sc2-adjutant). It is the Plugin that does what a Windows PC can do with StarCraft II, so the co-design tools can open, test and look at your maps for you. Without it, those tools hand you the steps to follow in the Editor yourself.
4
+
5
+ ## What it does
6
+
7
+ | Capability | How |
8
+ |---|---|
9
+ | `editor.open`, `editor.checkClosed` | Opens a Map Package in the Galaxy Editor, and tells whether the Editor has it open. |
10
+ | `editor.testDocument`, `editor.save` | Runs File > Test Document, and saves a throwaway copy of a map, through the Editor's menu. |
11
+ | `game.banksDir` | The folder the game keeps its banks in; test_mission snapshots it around a test game. |
12
+ | `editor.captureTour`, `editor.closeCaptureCopies` | Plays a capture map and screenshots each camera stop, then closes it unsaved. |
13
+ | `game.launch` | Starts the game on a Map Package without the Editor. |
14
+ | `game.logsFolder` | `<Documents>\StarCraft II\GameLogs`, Documents as the shell has it. |
15
+ | `game.running`, `game.list`, `game.quit` | Tells whether a game runs, lists the running games with their start times, and quits one recorded game gracefully (close the window, then Yes), ending it only after a timeout. |
16
+ | `screen.capture` | Captures the game's window, even when other windows cover it. |
17
+ | `tts.speak` | Speaks placeholder voice lines with Windows' built-in voices. |
18
+ | `model.render`, `model.rendererKey`, `model.export`, `model.exportGltf` | Renders game and mod models to turntable thumbnails, and exports them as `.m3` or glTF, with the WhiteoutFlakes model viewer on D3D11. It falls back to WARP, Windows' software rasterizer, when the GPU can't run the viewer. |
19
+
20
+ The Editor, window capture and speech are driven by small C# helpers that the adapter compiles on first use, with the `csc.exe` that comes with Windows. Nothing is installed, and no binary ships.
21
+
22
+ ## Install
23
+
24
+ `npx @team-antioch/sc2-adjutant init` installs it in a new Workspace on Windows, and names it in your machine config. To add it to an existing Workspace:
25
+
26
+ ```sh
27
+ npm install @team-antioch/sc2-adjutant-host-windows
28
+ ```
29
+
30
+ Then name it in your machine config (below): it loads only when it's named. It needs sc2-adjutant core (`@team-antioch/sc2-adjutant`) installed beside it, which is a peer dependency.
31
+
32
+ ## What it needs
33
+
34
+ Set these in `%APPDATA%\sc2-adjutant\machine.json`:
35
+
36
+ ```json
37
+ {
38
+ "hostAdapter": "bundled:host-windows",
39
+ "editorPath": "C:\\Program Files (x86)\\StarCraft II\\Support\\SC2Editor.exe",
40
+ "sc2Path": "C:\\Program Files (x86)\\StarCraft II",
41
+ "cacheDir": "~/AppData/Local/sc2-adjutant",
42
+ "modelViewerPath": "~/AppData/Local/sc2-adjutant/whiteoutflakes/stage-arm64/WhiteoutFlakes.exe"
43
+ }
44
+ ```
45
+
46
+ - **`editorPath`**: the 32-bit Editor, `Support\SC2Editor.exe`.
47
+ - **`sc2Path`**: the install folder, for `game.launch`.
48
+ - **`cacheDir`**: a folder outside the Workspace for the compiled helpers and the model viewer's working copies.
49
+ - **For models, `modelViewerPath`**: the WhiteoutFlakes viewer, which `scripts\build-whiteoutflakes.ps1` builds (`powershell -ExecutionPolicy Bypass -File scripts\build-whiteoutflakes.ps1 [-Dir <dir>] [-Arch x64|ARM64]`) into `stage-<arch>\`: `stage-x64` on most PCs, `stage-arm64` on an ARM PC as in the example above. It needs Git, Visual Studio 2022 (or its Build Tools) with the C++ workload (and the ARM64 tools for an ARM64 build), CMake, and the LunarG Vulkan SDK 1.4.341.0 with VMA. The first build takes 20 minutes or more.
50
+
51
+ Every path comes from the machine config. Nothing about your machine is built in, so a capability that needs a missing setting fails with the setting to add. The rest of the machine config is in [core's README](https://github.com/TeamAntioch/sc2-adjutant/tree/main/packages/core#the-machine-config).
52
+
53
+ ## More
54
+
55
+ - [`docs/windows-host.md`](https://github.com/TeamAntioch/sc2-adjutant/blob/main/packages/plugin-host-windows/docs/windows-host.md): setup in detail, the Editor and game behaviour this adapter relies on, and how to do each step by hand.
56
+ - [The plugin API](https://github.com/TeamAntioch/sc2-adjutant/blob/main/docs/plugin-api.md#host-adapter-kinds): what every Host Adapter capability takes and returns.
57
+
58
+ MIT licensed.
package/dist/.built ADDED
File without changes
@@ -0,0 +1,95 @@
1
+ // The capture tour's logic on Windows, apart from the Editor and the game: the bank the map saves,
2
+ // the frames and stops.txt it writes, the watch from the game's start to the tour's end, and which
3
+ // documents are capture copies. Pure, or driven through a TourWorld, so it's tested without SC2.
4
+ // The watch is the macOS adapter's (plugin-host-macos/capture-tour.ts), as the Exemplar and
5
+ // cinematic-set captures expect it.
6
+ import path from "node:path";
7
+ import { elidedMatches } from "./editor-windows.js";
8
+ /** A bank file's int or fixed value for a key, as the game writes it (`<Key name="..."><Value int="..."/>`). */
9
+ export function bankValue(bank, key, kind) {
10
+ const match = new RegExp(`name="${key}"[^\\n]*\\n[^\\n]*${kind}="([-0-9.]*)"`).exec(bank);
11
+ return match?.[1];
12
+ }
13
+ /** Where the game saves a bank: `<Documents>\StarCraft II\Banks\<bank>.SC2Bank`, Documents being wherever the shell says. */
14
+ export const bankFile = (documents, bank) => path.join(documents, "StarCraft II", "Banks", `${bank}.SC2Bank`);
15
+ /** A stop's frame: `<stop>.jpg`, zero-padded to `digits`. */
16
+ export const frameName = (stop, digits) => `${stop.padStart(digits, "0")}.jpg`;
17
+ /** A stop's line in stops.txt: the stop, then each key's fixed value (empty when the bank lacks it). */
18
+ export const stopsLine = (stop, bank, keys) => `${[stop, ...keys.map((key) => bankValue(bank, key, "fixed") ?? "")].join(" ")}\n`;
19
+ /** How often the watch reads the bank, in seconds. */
20
+ const POLL_SECONDS = 0.5;
21
+ /** How often Space is pressed while no stop comes, once pressSpaceAfterSeconds have passed, in seconds. */
22
+ const SPACE_EVERY_SECONDS = 10;
23
+ /**
24
+ * Watches a running game until its tour ends: reads the bank every half second, captures each new
25
+ * stop, and records it in stops.txt when `recordKeys` are given. Ends "done" at stop -1, "game
26
+ * exited" when the game quits first, and "never started" with no stop within `startSeconds`, having
27
+ * pressed Space every 10 s after `pressSpaceAfterSeconds`, for a loading screen that waits for it.
28
+ */
29
+ export async function watchTour(watch, world) {
30
+ // When the watch began, until the first stop comes; then undefined.
31
+ let waiting = world.now();
32
+ let leftover = watch.leftover;
33
+ let last = 0;
34
+ let frames = 0;
35
+ let lastSpace;
36
+ for (;;) {
37
+ await world.wait(POLL_SECONDS);
38
+ if (!(await world.gameRunning())) {
39
+ world.log(`game exited at stop ${last}`);
40
+ return { frames, end: "game exited" };
41
+ }
42
+ const bank = await world.readBank();
43
+ if (leftover !== undefined && bank !== leftover)
44
+ leftover = undefined;
45
+ const stop = leftover === undefined ? bankValue(bank, "stop", "int") : undefined;
46
+ if (stop === undefined) {
47
+ // Once the tour has started, a bank caught mid-write is just read again.
48
+ if (waiting === undefined)
49
+ continue;
50
+ const waited = (world.now() - waiting) / 1000;
51
+ if (waited >= watch.pressSpaceAfterSeconds && (lastSpace === undefined || waited - lastSpace >= SPACE_EVERY_SECONDS)) {
52
+ lastSpace = waited;
53
+ world.log("no stop yet; pressing Space in the game (takes focus)");
54
+ await world.pressSpace();
55
+ }
56
+ if (waited > watch.startSeconds) {
57
+ world.log("the tour never started");
58
+ return { frames, end: "never started" };
59
+ }
60
+ continue;
61
+ }
62
+ waiting = undefined;
63
+ if (stop === "-1") {
64
+ world.log(`tour done (${frames} stops)`);
65
+ return { frames, end: "done" };
66
+ }
67
+ if (Number(stop) === last)
68
+ continue;
69
+ if (!(await world.capture(path.join(watch.outputDir, frameName(stop, watch.frameDigits)))))
70
+ continue;
71
+ last = Number(stop);
72
+ frames++;
73
+ world.log(`stop ${stop}`);
74
+ if (watch.recordKeys)
75
+ await world.record(stopsLine(stop, bank, watch.recordKeys));
76
+ }
77
+ }
78
+ /**
79
+ * The Map Packages in this cache's capture folder (`maps`) that the Editor has open. A document
80
+ * counts when the path it shows can stand for `<maps>\<its name>`, and either shows that path
81
+ * whole or the copy is on disk: an elided path (`C:/.../capture/maps/X.SC2Map`) could be another
82
+ * cache's copy, which isn't this machine's to close.
83
+ */
84
+ export function captureCopies(state, maps, exists) {
85
+ const copies = new Set();
86
+ for (const document of state.documents) {
87
+ const copy = path.join(maps, path.posix.basename(document.path));
88
+ if (!/\.SC2Map$/i.test(copy) || !elidedMatches(document.path, copy))
89
+ continue;
90
+ if (document.path.includes("...") && !exists(copy))
91
+ continue;
92
+ copies.add(copy);
93
+ }
94
+ return [...copies];
95
+ }
@@ -0,0 +1,299 @@
1
+ // editor.captureTour and editor.closeCaptureCopies on Windows: camera-tour captures driven through
2
+ // the Galaxy Editor, as on the Mac (plugin-host-macos/capture-tour.ts). Opens the capture map in the
3
+ // Editor, runs File > Test Document, captures the game's window each time the map announces a new
4
+ // stop in its bank, then quits the game and closes the map without saving. Only documents under
5
+ // <cacheDir>/capture/maps/ are ever closed or discarded. The watch itself is capture-tour-windows.ts.
6
+ //
7
+ // Windows facts it relies on (docs/windows-host.md has more):
8
+ // - The Editor's menu commands are posted to its main window (editor.ts), so nothing comes forward
9
+ // and nobody's typing gets in the way, unlike on the Mac.
10
+ // - The game saves banks to <Documents>\StarCraft II\Banks\, and Documents may be redirected, so
11
+ // the shell says where it is.
12
+ // - Windows.Graphics.Capture gets the game's frames while other windows cover it, but not while it's
13
+ // minimized, so a minimized game is restored (behind whatever covers it). The display is kept awake
14
+ // for the tour, since a sleeping display stops the game drawing.
15
+ // - A loading screen may wait for Space; pressing it brings the game forward, so only after a long wait.
16
+ import { spawn } from "node:child_process";
17
+ import { existsSync } from "node:fs";
18
+ import { appendFile, mkdir, readFile, rm } from "node:fs/promises";
19
+ import path from "node:path";
20
+ import { CAPTURE_MAPS_FOLDER, ownedGame, quitOwnedGame, refuseForeignGame } from "@team-antioch/sc2-adjutant/plugin-sdk";
21
+ import { bankFile, captureCopies, watchTour } from "./capture-tour-windows.js";
22
+ import { documentsOf } from "./editor-windows.js";
23
+ import { activate, choose, closeDocument, editorExe, editorHelper, launch, promptText, readEditor } from "./editor.js";
24
+ import { firstAnswer, gamePids, tolerantCheck, topWindows, wasMinimized, windowsSystem } from "./game.js";
25
+ import { gameWindows } from "./game-windows.js";
26
+ import { deadline, helper, runHelper, sleep } from "./helpers.js";
27
+ /** How long the Editor may take to open and load the capture map, in seconds: a cold Editor took a minute. */
28
+ const MAP_LOAD_SECONDS = 300;
29
+ /** How long the game may take to start once Test Document runs, in seconds. */
30
+ const GAME_START_SECONDS = 60;
31
+ const documentsFolders = new Map();
32
+ /** The Documents folder, as the shell has it, once a process. */
33
+ function documentsFolder(editor) {
34
+ let folder = documentsFolders.get(editor.exe);
35
+ if (!folder) {
36
+ folder = runHelper(editor.exe, ["documents"]).then((stdout) => {
37
+ const found = stdout.trim();
38
+ if (!found)
39
+ throw new Error("the shell has no Documents folder, where the game saves its banks");
40
+ return found;
41
+ });
42
+ documentsFolders.set(editor.exe, folder);
43
+ folder.catch(() => documentsFolders.delete(editor.exe));
44
+ }
45
+ return folder;
46
+ }
47
+ /** The folder the game saves its banks in (`game.banksDir`): `<Documents>\StarCraft II\Banks`. */
48
+ export async function banksDir(_request, context) {
49
+ return path.join(await documentsFolder(await editorHelper(context)), "StarCraft II", "Banks");
50
+ }
51
+ /** game.logsFolder: `<Documents>\StarCraft II\GameLogs`, Documents as the shell has it (it may be redirected). */
52
+ export async function gameLogsFolder(_request, context) {
53
+ return path.join(await documentsFolder(await editorHelper(context)), "StarCraft II", "GameLogs");
54
+ }
55
+ const isOpen = async (editor, mapPath) => documentsOf(await readEditor(editor), mapPath).length > 0;
56
+ /**
57
+ * Opens the map, makes it the active document and runs File > Test Document, then waits for a new
58
+ * game. Fails with the Editor's prompt when one comes up instead, such as script errors.
59
+ */
60
+ async function startTest(mapPath, context, editor, log) {
61
+ await launch(mapPath, MAP_LOAD_SECONDS, context, editor);
62
+ const window = await activate(mapPath, editor);
63
+ const state = await readEditor(editor);
64
+ const earlier = new Set(state.prompts.map((prompt) => prompt.hwnd));
65
+ const pids = tolerantCheck(() => gamePids(editor.exe));
66
+ const before = await firstAnswer(pids);
67
+ await choose(editor, window, "testDocument");
68
+ log("Test Document run");
69
+ const late = deadline(GAME_START_SECONDS);
70
+ for (;;) {
71
+ await sleep(1);
72
+ if ((await pids())?.some((pid) => !before.includes(pid)))
73
+ return;
74
+ const prompts = (await readEditor(editor)).prompts.filter((prompt) => !earlier.has(prompt.hwnd));
75
+ if (prompts.length > 0)
76
+ throw new Error(`ran File > Test Document on ${path.basename(mapPath)}, but the Editor is asking: ${await promptText(editor, prompts)}`);
77
+ if (late())
78
+ throw new Error("the game never started");
79
+ }
80
+ }
81
+ /**
82
+ * Closes the map without saving, if the Editor has it open; says so when it couldn't. Leaves it
83
+ * open while the Editor is asking something (script errors, say): a Close posted under the prompt
84
+ * could stack a save prompt behind it.
85
+ */
86
+ async function closeMap(mapPath, editor, log, earlier = new Set()) {
87
+ try {
88
+ const state = await readEditor(editor);
89
+ if (documentsOf(state, mapPath).length === 0)
90
+ return;
91
+ // Dialogs the author had open before the run aren't the map's, and don't keep it open.
92
+ const prompts = state.prompts.filter((prompt) => !earlier.has(prompt.hwnd));
93
+ if (prompts.length > 0) {
94
+ log(`couldn't close ${path.basename(mapPath)}: the Editor is asking: ${await promptText(editor, prompts)}; answer it there, then close the map without saving`);
95
+ return;
96
+ }
97
+ await closeDocument(mapPath, editor);
98
+ }
99
+ catch (error) {
100
+ log(`couldn't close ${path.basename(mapPath)}: ${error.message}`);
101
+ }
102
+ }
103
+ /** Reads the bank as it is when a watch attaches, trying again for a moment while the game writes it; undefined when there's none. */
104
+ async function bankNow(bank) {
105
+ for (let attempt = 0;; attempt++) {
106
+ if (!existsSync(bank))
107
+ return undefined;
108
+ try {
109
+ return await readFile(bank, "utf8");
110
+ }
111
+ catch (error) {
112
+ if (attempt >= 5)
113
+ throw error;
114
+ await sleep(0.2);
115
+ }
116
+ }
117
+ }
118
+ /**
119
+ * How many game checks in a row may fail during a watch before the tour gives up: at its poll of
120
+ * twice a second, a few seconds of a helper that won't run.
121
+ */
122
+ export const WATCH_FAILED_CHECKS = 10;
123
+ /** The watch's world: the game's processes, the bank on disk, and the capture helper on the game's window. */
124
+ export function gameWorld(request, editor, capture, bank, leftover, log,
125
+ /** Whether the game this capture started runs; without it, whether any game does (attaching). */
126
+ gameUp) {
127
+ let warned = "";
128
+ /** A capture problem, logged once until another comes up. */
129
+ const warn = (line) => {
130
+ if (line !== warned)
131
+ log(line);
132
+ warned = line;
133
+ };
134
+ // The game's window, found once and again only after a capture fails, so a capture costs one
135
+ // helper run: a stop the bank moves past during a slow capture is missed.
136
+ let window;
137
+ let running = true;
138
+ let failedChecks = 0;
139
+ let lastBank = leftover ?? "";
140
+ const gameWindow = async () => (window ??= gameWindows(await topWindows(editor.exe))[0]?.hwnd);
141
+ return {
142
+ // A helper run or a read that fails says nothing: the game is taken as still running, and the
143
+ // bank as it was last read, so a moment's failure neither ends the tour nor clears the leftover.
144
+ // Checks that keep failing end the tour, rather than watch a game that may be gone.
145
+ gameRunning: async () => {
146
+ try {
147
+ running = gameUp ? await gameUp() : (await gamePids(editor.exe)).length > 0;
148
+ failedChecks = 0;
149
+ }
150
+ catch (error) {
151
+ const message = `couldn't tell whether the game is still running: ${error.message}`;
152
+ if (++failedChecks >= WATCH_FAILED_CHECKS)
153
+ throw new Error(`${message} (${failedChecks} checks in a row)`, { cause: error });
154
+ warn(message);
155
+ }
156
+ return running;
157
+ },
158
+ readBank: async () => {
159
+ if (!existsSync(bank))
160
+ return (lastBank = "");
161
+ try {
162
+ lastBank = await readFile(bank, "utf8");
163
+ }
164
+ catch (error) {
165
+ warn(`couldn't read the bank: ${error.message}`);
166
+ }
167
+ return lastBank;
168
+ },
169
+ capture: async (frame) => {
170
+ const game = await gameWindow();
171
+ if (!game) {
172
+ warn(`${path.basename(frame)}: no game window to capture`);
173
+ return false;
174
+ }
175
+ const shoot = () => runHelper(capture, ["frame", game, frame, String(request.quality), String(request.width)]);
176
+ try {
177
+ await shoot().catch(async (error) => {
178
+ if (!wasMinimized(error))
179
+ throw error;
180
+ // A minimized window gives no frames: shown again, behind whatever covers it.
181
+ await runHelper(editor.exe, ["restore", game]);
182
+ log("restored the minimized game window to capture it (it can sit behind other windows, but not minimized)");
183
+ await sleep(0.5);
184
+ await shoot();
185
+ });
186
+ return true;
187
+ }
188
+ catch (error) {
189
+ window = undefined;
190
+ warn(`${path.basename(frame)}: ${error.message}`);
191
+ return false;
192
+ }
193
+ },
194
+ pressSpace: async () => {
195
+ const game = await gameWindow();
196
+ if (game)
197
+ await runHelper(editor.exe, ["space", game]).catch((error) => log(`couldn't press Space: ${error.message}`));
198
+ },
199
+ record: (line) => appendFile(path.join(request.outputDir, "stops.txt"), line),
200
+ wait: async (seconds) => {
201
+ await sleep(seconds);
202
+ },
203
+ now: Date.now,
204
+ log,
205
+ };
206
+ }
207
+ export async function captureTour(request, context) {
208
+ const log = request.log ?? (() => undefined);
209
+ const maps = path.join(context.requirePath("cacheDir"), CAPTURE_MAPS_FOLDER);
210
+ const mapPath = path.resolve(request.mapPath);
211
+ if (!request.attach && path.dirname(mapPath).toLowerCase() !== maps.toLowerCase()) {
212
+ throw new Error(`editor.captureTour closes its map without saving, so it only takes maps in ${maps}; ${mapPath} isn't there`);
213
+ }
214
+ if (!request.attach)
215
+ editorExe(context);
216
+ const editor = await editorHelper(context);
217
+ const capture = await helper(context, "capture");
218
+ const bank = bankFile(await documentsFolder(editor), request.bank);
219
+ await mkdir(request.outputDir, { recursive: true });
220
+ // Keep the display awake for the whole run, as caffeinate does on the Mac: a sleeping display
221
+ // stops the game drawing. The helper ends with this process if it isn't stopped first.
222
+ const awake = spawn(editor.exe, ["awake", String(process.pid)], { stdio: "ignore", windowsHide: true });
223
+ awake.on("error", (error) => log(`couldn't keep the display awake: ${error.message}`));
224
+ // Set once this run may have opened the map or started the game; whatever ends the run then
225
+ // quits the game and closes the map.
226
+ let touchedEditor = false;
227
+ // The game this capture starts, once it appears: the only one it watches or quits. Attaching, the author's game is watched and left alone.
228
+ const system = windowsSystem(editor.exe);
229
+ const own = ownedGame(system, request.onGameStarted);
230
+ // Attached to a game already running, the bank may still hold an earlier run's last stop (-1);
231
+ // that content is ignored until the game saves the bank again.
232
+ let leftover;
233
+ // The Editor's dialogs open before the run, which closing the map at its end ignores.
234
+ let earlier = new Set();
235
+ try {
236
+ if (request.attach) {
237
+ if ((await firstAnswer(tolerantCheck(() => gamePids(editor.exe)))).length === 0)
238
+ throw new Error("no game is running to watch");
239
+ leftover = await bankNow(bank);
240
+ }
241
+ else {
242
+ await rm(bank, { force: true });
243
+ // Nothing is quit here: a game already running isn't this capture's.
244
+ await refuseForeignGame(system);
245
+ // A copy left open by an earlier run would be tested as it was: opening only brings it forward.
246
+ if (await isOpen(editor, mapPath)) {
247
+ log("closing a stale copy");
248
+ await closeMap(mapPath, editor, log);
249
+ if (await isOpen(editor, mapPath))
250
+ throw new Error(`a stale copy of ${path.basename(mapPath)} is still open in the Editor`);
251
+ }
252
+ await request.writeMap?.();
253
+ earlier = new Set((await readEditor(editor)).prompts.map((prompt) => prompt.hwnd));
254
+ touchedEditor = true;
255
+ await startTest(mapPath, context, editor, log);
256
+ }
257
+ log("game started; it can sit behind other windows now (don't minimize it)");
258
+ return await watchTour({ ...request, ...(leftover !== undefined ? { leftover } : {}) }, gameWorld(request, editor, capture, bank, leftover, log, request.attach ? undefined : () => own.running()));
259
+ }
260
+ finally {
261
+ try {
262
+ if (touchedEditor) {
263
+ // A game that appeared since the last look is this capture's too.
264
+ await own.running().catch(() => false);
265
+ const game = own.game();
266
+ if (game)
267
+ await quitOwnedGame(game, system, log).catch((error) => log(`couldn't quit the game: ${error.message}`));
268
+ await closeMap(mapPath, editor, log, earlier);
269
+ }
270
+ }
271
+ finally {
272
+ awake.kill();
273
+ }
274
+ }
275
+ }
276
+ /**
277
+ * Closes, without saving, every capture copy the Editor has open (any document under
278
+ * <cacheDir>/capture/maps/), after quitting the games it is given: the capture's own, which the
279
+ * broker recorded. Another game is left running. The Editor Broker runs this as it starts and after a failed tour.
280
+ */
281
+ export async function closeCaptureCopies(request, context) {
282
+ const log = request.log ?? (() => undefined);
283
+ const maps = path.join(context.requirePath("cacheDir"), CAPTURE_MAPS_FOLDER);
284
+ const editor = await editorHelper(context);
285
+ // Only the games the broker recorded as a capture's; one it didn't is the author's to quit.
286
+ const system = windowsSystem(editor.exe);
287
+ for (const game of request.games ?? [])
288
+ await quitOwnedGame(game, system, log).catch((error) => log(`couldn't quit game ${game.pid}: ${error.message}`));
289
+ const copies = captureCopies(await readEditor(editor), maps, existsSync);
290
+ if (copies.length === 0)
291
+ return;
292
+ for (const copy of copies) {
293
+ log(`closing ${path.basename(copy)}`);
294
+ await closeMap(copy, editor, log);
295
+ }
296
+ const left = captureCopies(await readEditor(editor), maps, existsSync);
297
+ if (left.length > 0)
298
+ log(`WARNING: ${left.map((copy) => path.basename(copy)).join(", ")} still open in the Editor`);
299
+ }
@@ -0,0 +1,136 @@
1
+ // Reading the StarCraft II Editor's windows on Windows, from what the editor helper prints
2
+ // (helpers/editor.cs). Pure, so it's tested without the Editor.
3
+ //
4
+ // What the 32-bit Editor (build 98310) shows, seen 2026-11-18 (docs/windows-host.md has more):
5
+ // - One main window, a top-level `#32770` with the native menu bar, holds every open document. Its
6
+ // title names the active one by an elided path, `Terrain - [C:/.../output/Spike.SC2Map/] -
7
+ // StarCraft II Editor` (the module first; `/*` after the path when it has unsaved changes), and
8
+ // just `Terrain - StarCraft II Editor` with none open.
9
+ // - The Window menu lists every open document, `&1 C:/.../output/Spike.SC2Map/`, elided further;
10
+ // choosing its item (posting its command id) makes that document the active one.
11
+ // - Menu command ids change between Editor sessions, so File > Test Document, Save and Close are
12
+ // found by their labels (English) in the main window's menu each time.
13
+ // - While a map loads, an `Activity - StarCraft II Editor` window is open.
14
+ // - Prompts are `#32770` dialogs with no menu, such as "Warning", whose text names the whole path:
15
+ // `Save changes to 'C:/Users/.../Spike.SC2Map/'?` with &Yes, &No and Cancel.
16
+ const COMMAND_LABELS = { testDocument: "Test Document", save: "Save", close: "Close" };
17
+ /** A menu label without its access-key ampersands (`&Test Document` is "Test Document"). */
18
+ const plainLabel = (label) => label.replace(/&(.)/g, "$1");
19
+ /** The ids of File > Test Document, Save and Close in a window's menus. */
20
+ export function menuCommands(items) {
21
+ const file = items.filter((item) => plainLabel(item.menu) === "File");
22
+ const id = (label) => file.find((item) => plainLabel(item.label) === label)?.id;
23
+ return Object.fromEntries(Object.entries(COMMAND_LABELS).flatMap(([command, label]) => {
24
+ const found = id(label);
25
+ return found === undefined ? [] : [[command, found]];
26
+ }));
27
+ }
28
+ const lines = (stdout) => stdout.split(/\r?\n/).filter((line) => line.length > 0);
29
+ export function parseWindows(stdout) {
30
+ return lines(stdout).flatMap((line) => {
31
+ const [hwnd, owner, pid, process, className, visible, hasMenu, ...title] = line.split("\t");
32
+ if (hwnd === undefined || hasMenu === undefined)
33
+ return [];
34
+ return [{ hwnd, owner: owner, pid: Number(pid), process: process, className: className, visible: visible === "1", hasMenu: hasMenu === "1", title: title.join("\t") }];
35
+ });
36
+ }
37
+ export function parseMenu(stdout) {
38
+ return lines(stdout).flatMap((line) => {
39
+ const [menu, id, checked, label, shortcut] = line.split("\t");
40
+ if (menu === undefined || label === undefined)
41
+ return [];
42
+ return [{ menu, id: Number(id), checked: checked === "1", label, shortcut: shortcut ?? "" }];
43
+ });
44
+ }
45
+ export function parseButtons(stdout) {
46
+ const buttons = [];
47
+ const text = [];
48
+ for (const line of lines(stdout)) {
49
+ const [first, second, ...rest] = line.split("\t");
50
+ if (first === "text")
51
+ text.push([second, ...rest].join("\t"));
52
+ else if (first !== undefined && second !== undefined)
53
+ buttons.push({ hwnd: first, enabled: second === "1", text: rest.join("\t") });
54
+ }
55
+ return { buttons, text };
56
+ }
57
+ /** The game's process names, 32- and 64-bit (`Versions\Base<build>\SC2.exe`, `SC2_x64.exe`). */
58
+ export const GAME_PROCESSES = ["SC2", "SC2_x64"];
59
+ /** The Editor's processes: `SC2Editor`, or `SC2Editor_x64` for the 64-bit build. */
60
+ export const isEditorProcess = (name) => /^SC2Editor(_x64)?$/i.test(name);
61
+ /** An elided document path as the Editor shows it, without the unsaved mark or trailing slash. */
62
+ const cleanPath = (shown) => shown.replace(/\*$/, "").replace(/\/$/, "");
63
+ /** The active document's elided path in a main window's title; undefined with none open. */
64
+ export function titleDocument(title) {
65
+ // The module's name comes first and has no bracket; the path may.
66
+ const match = /^[^[]* - \[(.+)\] - StarCraft II Editor$/.exec(title);
67
+ return match ? cleanPath(match[1]) : undefined;
68
+ }
69
+ /**
70
+ * A document a Window menu item names (`&1 C:/.../Spike.SC2Map/`); undefined for its other items.
71
+ * A menu label writes a literal `&` as `&&`.
72
+ */
73
+ function menuDocument(text) {
74
+ const match = /^&?\d+&?\d* (.+)$/.exec(text);
75
+ return match && /[/\\]/.test(match[1]) ? cleanPath(match[1].replaceAll("&&", "&")) : undefined;
76
+ }
77
+ /** A path as the Editor writes it, for comparing: forward slashes, no trailing slash, lower case. */
78
+ const comparable = (file) => file.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase();
79
+ /**
80
+ * Whether the Editor's elided path (`C:/.../output/Spike.SC2Map`) can stand for this whole path.
81
+ * Each `...` stands for one or more whole folders; the rest must match, ignoring case.
82
+ */
83
+ export function elidedMatches(elided, mapPath) {
84
+ const parts = comparable(elided).split("/");
85
+ const target = comparable(mapPath).split("/");
86
+ const matchFrom = (part, at) => {
87
+ if (part === parts.length)
88
+ return at === target.length;
89
+ if (parts[part] === "...") {
90
+ for (let next = at + 1; next <= target.length; next++)
91
+ if (matchFrom(part + 1, next))
92
+ return true;
93
+ return false;
94
+ }
95
+ return at < target.length && parts[part] === target[at] && matchFrom(part + 1, at + 1);
96
+ };
97
+ return matchFrom(0, 0);
98
+ }
99
+ /** The Editor's Messages window, which has a menu bar but holds no documents. */
100
+ const MESSAGES_WINDOW = /^Messages - StarCraft II Editor$/;
101
+ const PROGRESS_WINDOWS = /^(Activity - StarCraft II Editor|Welcome to the StarCraft II Editor|Downloading Data)$/;
102
+ /** What the Editor has open, from its windows and the menus of those with a menu bar (by hwnd). */
103
+ export function editorState(windows, menus) {
104
+ const editor = windows.filter((window) => isEditorProcess(window.process));
105
+ const visible = editor.filter((window) => window.visible);
106
+ const mainWindows = visible.filter((window) => window.hasMenu && menuCommands(menus.get(window.hwnd) ?? []).testDocument !== undefined);
107
+ const documents = mainWindows.flatMap((window) => {
108
+ const active = titleDocument(window.title);
109
+ const listed = (menus.get(window.hwnd) ?? []).flatMap((item) => {
110
+ const shown = plainLabel(item.menu) === "Window" ? menuDocument(item.label) : undefined;
111
+ return shown ? [{ window: window.hwnd, path: shown, active: false, menuId: item.id }] : [];
112
+ });
113
+ return [...(active ? [{ window: window.hwnd, path: active, active: true }] : []), ...listed];
114
+ });
115
+ return {
116
+ running: editor.length > 0,
117
+ loading: visible.some((window) => window.title.startsWith("Activity - ")),
118
+ mainWindows: mainWindows.map((window) => ({ hwnd: window.hwnd, commands: menuCommands(menus.get(window.hwnd) ?? []) })),
119
+ unreadable: mainWindows.length === 0 && visible.some((window) => window.hasMenu && !MESSAGES_WINDOW.test(window.title)),
120
+ documents,
121
+ prompts: visible.filter((window) => window.className === "#32770" && !window.hasMenu && !PROGRESS_WINDOWS.test(window.title)),
122
+ };
123
+ }
124
+ /** The open documents that may be this Map Package: each one whose elided path can stand for it. */
125
+ export const documentsOf = (state, mapPath) => state.documents.filter((document) => elidedMatches(document.path, mapPath));
126
+ /** The Yes and No buttons of a prompt asking to save this map's changes, when it is one. */
127
+ export function savePromptFor(prompt, mapPath) {
128
+ const asks = prompt.text.some((text) => {
129
+ const match = /^Save changes to '(.+)'\?$/.exec(text);
130
+ return match !== null && comparable(match[1]) === comparable(mapPath);
131
+ });
132
+ const button = (label) => prompt.buttons.find((candidate) => plainLabel(candidate.text) === label)?.hwnd;
133
+ const yes = button("Yes");
134
+ const no = button("No");
135
+ return asks && yes && no ? { yes, no } : undefined;
136
+ }