From 929c8cbca3cfe9971d99b66d495a344b1ed92bef Mon Sep 17 00:00:00 2001 From: Frotty Date: Tue, 17 Nov 2026 14:20:46 +0100 Subject: [PATCH 1/8] Renew the Warcraft III sign-in from Battle.net before grill run launches grill run starts Reforged clients with -launch -editor -loadfile, and such a client signs in with EDITOR_TOKEN, which it renews on each sign-in. Once the token lapses (overnight is enough) every run stops at the in-game login panel. Battle.net's own session never reaches a client started with -loadfile. Before launching, grill now has the Battle.net app start the game, closes that client before it spends the one-time WEB_TOKEN the app wrote for it, and stores that token as EDITOR_TOKEN. The map then launches as before, and grill waits until the client has replaced the token (about ten seconds) so the shared lock with WurstScript's Run Map and the wc3-e2e-harness covers it. wurst.wc3LaunchMode in .vscode/settings.json, as for Run Map: "auto" renews when Battle.net is open, "battlenet" refuses to launch without a renewal, "legacy" never renews. Only Windows and the Battle.net-managed install are affected. --- src/main/kotlin/config/WurstProjectConfig.kt | 8 +- src/main/kotlin/file/BattleNetSignIn.kt | 231 +++++++++++++++++++ src/main/kotlin/file/SetupApp.kt | 4 +- src/main/kotlin/file/Wc3MapRunner.kt | 70 +++++- src/test/kotlin/BattleNetSignInTests.kt | 66 ++++++ 5 files changed, 370 insertions(+), 9 deletions(-) create mode 100644 src/main/kotlin/file/BattleNetSignIn.kt create mode 100644 src/test/kotlin/BattleNetSignInTests.kt diff --git a/src/main/kotlin/config/WurstProjectConfig.kt b/src/main/kotlin/config/WurstProjectConfig.kt index 46cda17..caf53a3 100644 --- a/src/main/kotlin/config/WurstProjectConfig.kt +++ b/src/main/kotlin/config/WurstProjectConfig.kt @@ -156,7 +156,12 @@ object WurstProjectConfig { /** The VS Code extension's `wurst.customMapDataPath`, which the language server's hot reload also uses. */ fun configuredCustomMapDataPath(projectRoot: Path): Path? = configuredPath(projectRoot, "wurst.customMapDataPath") - private fun configuredPath(projectRoot: Path, setting: String): Path? { + /** The VS Code extension's `wurst.wc3LaunchMode` (auto, battlenet or legacy), which Run Map also follows. */ + fun configuredLaunchMode(projectRoot: Path): String = configuredString(projectRoot, "wurst.wc3LaunchMode") ?: "auto" + + private fun configuredPath(projectRoot: Path, setting: String): Path? = configuredString(projectRoot, setting)?.let(Paths::get) + + private fun configuredString(projectRoot: Path, setting: String): String? { val settings = projectRoot.resolve(".vscode").resolve("settings.json") if (!Files.isRegularFile(settings)) { return null @@ -166,7 +171,6 @@ object WurstProjectConfig { ?.get(setting) ?.asText() ?.takeIf(String::isNotBlank) - ?.let(Paths::get) } catch (_: Exception) { null } diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt new file mode 100644 index 0000000..22b2764 --- /dev/null +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -0,0 +1,231 @@ +package file + +import java.io.IOException +import java.net.BindException +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.nio.ByteBuffer +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import java.security.MessageDigest +import java.util.Locale +import java.util.concurrent.TimeUnit + +/** + * Renews the sign-in that Warcraft III 3.x uses for `-editor` launches, from the Battle.net desktop app. + * + * A client started with `-editor` (every `grill run` of a Reforged client) signs in with `EDITOR_TOKEN` + * (`HKCU\Software\Blizzard Entertainment\Warcraft III`) and replaces it with a fresh one each time it signs in. Once + * that token lapses (overnight is enough) every launch stops at the in-game login panel. The app's own session does + * not reach it: a client the app starts with `-loadfile` shows the login panel too. + * + * Just before the app starts the game it writes a one-time `WEB_TOKEN` (`...\Battle.net\Launch Options\W3`). Stored + * as `EDITOR_TOKEN`, that token signs the next `-editor` client in. [renew] asks the app to start the game, closes + * that client before it spends the token, and stores the token; the map is then launched as before. + * + * WurstScript's Run Map (`BattleNetSignIn`) and the wc3-e2e-harness (`docs/BattleNetSignIn.md`) do the same, and all + * hold the same localhost port as a lock from the renewal until the launched client has signed in. + */ +internal class BattleNetSignIn private constructor(private val config: Path, private val launcher: Path) { + + /** The lock, held until the launched client has signed in; see [awaitSignIn]. */ + class Renewal internal constructor(private val gate: ServerSocket, private val token: String) : AutoCloseable { + /** + * Blocks until the launched client replaces `EDITOR_TOKEN`, which it does as it signs in (about ten seconds after + * launch), or [SIGN_IN_TIMEOUT_SECONDS] pass, then releases the lock. Released earlier, another tool's renewal + * could replace the token before this client read it, leaving two clients one token. + */ + fun awaitSignIn(): Boolean { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SIGN_IN_TIMEOUT_SECONDS) + try { + while (System.nanoTime() < deadline) { + if (readBinary(GAME_KEY, "EDITOR_TOKEN") != token) return true + Thread.sleep(500) + } + return false + } finally { + close() + } + } + + override fun close() { + try { + gate.close() + } catch (_: IOException) { + } + } + } + + fun isRunning(): Boolean = ProcessHandle.allProcesses().anyMatch { named(command(it), LAUNCHER) } + + /** + * Stores a token from the app as `EDITOR_TOKEN` and returns the held lock. Throws, with a message for the user, + * when the app cannot provide one: it is closed, signed out, updating, or running a client of its own. + */ + fun renew(): Renewal { + val gate = acquireGate() + try { + return Renewal(gate, renewLocked()) + } catch (e: Throwable) { + gate.close() + throw e + } + } + + private fun renewLocked(): String { + if (!isRunning()) throw IOException("Battle.net is not running.") + val seen = HashSet() + for (game in games()) { + if (startedByLauncher(game)) { + throw IOException("Close the Warcraft III client started from Battle.net, then run the map again.") + } + seen.add(game.pid()) + } + val before = readBinary(LAUNCH_KEY, "WEB_TOKEN") + val start = System.nanoTime() + var askedAt = Long.MIN_VALUE + var token: String? = null + var tokenAt = 0L + var closed = 0 + while (System.nanoTime() - start < TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)) { + if (token == null && (askedAt == Long.MIN_VALUE + || System.nanoTime() - askedAt >= TimeUnit.SECONDS.toNanos(ASK_AGAIN_SECONDS))) { + askedAt = System.nanoTime() + // An app that is still starting ignores the command, so it is repeated while waiting. + ProcessBuilder(launcher.toString(), "--exec=launch W3") + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start() + } + for (game in games()) { + if (!seen.add(game.pid()) || !startedByLauncher(game)) continue + game.destroyForcibly() + closed++ + } + if (token == null) { + val now = readBinary(LAUNCH_KEY, "WEB_TOKEN") + if (now != null && now != before) { + token = now + tokenAt = System.nanoTime() + } + } + // The app writes the token, then starts the game: wait briefly for that game so it is closed. + if (token != null && (closed > 0 + || System.nanoTime() - tokenAt >= TimeUnit.SECONDS.toNanos(GAME_AFTER_TOKEN_SECONDS))) break + Thread.sleep(50) + } + if (token == null) { + throw IOException("Battle.net did not start Warcraft III. Check that it is signed in and the game is ready to play.") + } + writeBinary(GAME_KEY, "EDITOR_TOKEN", token) + return token + } + + private fun acquireGate(): ServerSocket { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30) + while (true) { + val socket = ServerSocket() + try { + // 127.0.0.1 exactly, as the harness binds it; the loopback name could resolve to ::1. + socket.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), gatePort(config))) + return socket + } catch (e: BindException) { + socket.close() + if (System.nanoTime() >= deadline) throw IOException("Another Warcraft III test is using Battle.net.", e) + Thread.sleep(250) + } catch (e: IOException) { + socket.close() + throw e + } + } + } + + companion object { + const val LAUNCH_KEY = "HKCU\\Software\\Blizzard Entertainment\\Battle.net\\Launch Options\\W3" + const val GAME_KEY = "HKCU\\Software\\Blizzard Entertainment\\Warcraft III" + private const val LAUNCHER = "Battle.net.exe" + private const val GAME = "Warcraft III.exe" + private const val TIMEOUT_SECONDS = 90L + private const val ASK_AGAIN_SECONDS = 25L + private const val GAME_AFTER_TOKEN_SECONDS = 10L + const val SIGN_IN_TIMEOUT_SECONDS = 120L + private val REG_BINARY = Regex("""^\s*(\S+)\s+REG_BINARY\s+([0-9A-Fa-f]*)\s*$""", RegexOption.MULTILINE) + + fun find(): BattleNetSignIn? { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) return null + val appData = System.getenv("APPDATA") ?: return null + val launcher = launcherExecutable() ?: return null + return BattleNetSignIn(Paths.get(appData, "Battle.net", "Battle.net.config"), launcher) + } + + private fun launcherExecutable(): Path? { + ProcessHandle.allProcesses().map { command(it) }.filter { named(it, LAUNCHER) }.findFirst().orElse(null) + ?.let { return it } + return listOfNotNull(System.getenv("ProgramFiles(x86)"), System.getenv("ProgramFiles")) + .map { Paths.get(it, "Battle.net", LAUNCHER) } + .firstOrNull(Files::isRegularFile) + } + + /** Whether [executable] belongs to the install Battle.net manages; the token only works there. */ + fun isRegisteredGame(executable: Path): Boolean { + val key = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Warcraft III" + for (view in listOf("/reg:32", "/reg:64")) { + for (line in readCommand("reg.exe", "query", key, "/v", "InstallLocation", view)) { + val fields = line.trim().split(Regex("\\s{2,}"), 3) + if (fields.size == 3 && fields[0].equals("InstallLocation", ignoreCase = true) + && executable.toAbsolutePath().normalize().startsWith(Paths.get(fields[2]).toAbsolutePath().normalize())) { + return true + } + } + } + return false + } + + fun parseBinary(regQueryOutput: List, value: String): String? = + REG_BINARY.findAll(regQueryOutput.joinToString("\n")) + .firstOrNull { it.groupValues[1].equals(value, ignoreCase = true) } + ?.groupValues?.get(2)?.uppercase(Locale.ROOT) + + /** The lock port the wc3-e2e-harness and WurstScript use for the same Battle.net profile. */ + fun gatePort(config: Path): Int { + val key = config.toAbsolutePath().normalize().toString().lowercase(Locale.ROOT) + val hash = MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8)) + return 33000 + Integer.remainderUnsigned(ByteBuffer.wrap(hash).int, 10000) + } + + private fun games(): List = + ProcessHandle.allProcesses().filter { named(command(it), GAME) }.toList() + + /** A client the app started; anything else is someone else's game and is left alone. */ + private fun startedByLauncher(game: ProcessHandle): Boolean = + game.parent().map { named(command(it), LAUNCHER) }.orElse(false) + + private fun command(process: ProcessHandle): Path? = process.info().command().map { Paths.get(it) }.orElse(null) + + private fun named(executable: Path?, image: String): Boolean = + executable?.fileName?.toString()?.equals(image, ignoreCase = true) == true + + private fun readBinary(key: String, value: String): String? = + parseBinary(readCommand("reg.exe", "query", key, "/v", value), value) + + private fun writeBinary(key: String, value: String, hex: String) { + val process = ProcessBuilder("reg.exe", "add", key, "/v", value, "/t", "REG_BINARY", "/d", hex, "/f") + .redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(ProcessBuilder.Redirect.DISCARD).start() + if (!process.waitFor(8, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly() + throw IOException("Could not store the Warcraft III sign-in.") + } + } + + private fun readCommand(vararg command: String): List { + val process = ProcessBuilder(*command).redirectError(ProcessBuilder.Redirect.DISCARD).start() + if (!process.waitFor(8, TimeUnit.SECONDS)) { + process.destroyForcibly() + throw IOException("Windows registry query timed out.") + } + return process.inputReader().use { it.readLines() } + } + } +} diff --git a/src/main/kotlin/file/SetupApp.kt b/src/main/kotlin/file/SetupApp.kt index 4625c0b..d2e520d 100644 --- a/src/main/kotlin/file/SetupApp.kt +++ b/src/main/kotlin/file/SetupApp.kt @@ -1202,7 +1202,9 @@ object SetupApp { private const val HOT_RELOAD_SESSION_CLASS = "de.peeeq.wurstio.languageserver.requests.LuaHotReloadSession" /** Starts Warcraft III with a built map; replaced in tests, which must never launch the game. */ - internal var launchMap: (Wc3ClientDetector.ClientInfo, Path) -> Unit = Wc3MapRunner::launch + internal var launchMap: (Wc3ClientDetector.ClientInfo, Path) -> Unit = { client, map -> + Wc3MapRunner.launch(client, map, WurstProjectConfig.configuredLaunchMode(setup.projectRoot), ::detail) + } /** What `run --hot` built with, so that `reload` builds the same script. */ private fun hotRunRecord(): Path = compilerOutputDir().resolve("hot-run.properties") diff --git a/src/main/kotlin/file/Wc3MapRunner.kt b/src/main/kotlin/file/Wc3MapRunner.kt index 77f95be..d5cb940 100644 --- a/src/main/kotlin/file/Wc3MapRunner.kt +++ b/src/main/kotlin/file/Wc3MapRunner.kt @@ -2,6 +2,7 @@ package file import config.WurstProjectConfig import config.WurstProjectConfigData +import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths @@ -89,12 +90,69 @@ internal object Wc3MapRunner { } } - fun launch(client: Wc3ClientDetector.ClientInfo, map: Path) { + /** + * Starts Warcraft III on [map]. A Reforged client managed by Battle.net first has its sign-in renewed from the app + * (see [BattleNetSignIn]), and this returns once that client has signed in, so the shared lock covers it. + */ + fun launch(client: Wc3ClientDetector.ClientInfo, map: Path, launchMode: String = "auto", report: (String) -> Unit = {}) { val launchMap = stageMap(client, map) - ProcessBuilder(launchCommand(client, launchMap)) - .directory(client.root.toFile()) - .redirectOutput(ProcessBuilder.Redirect.DISCARD) - .redirectError(ProcessBuilder.Redirect.DISCARD) - .start() + val command = launchCommand(client, launchMap) + val renewal = renewSignIn(client, command, launchMode, report) + try { + ProcessBuilder(command) + .directory(client.root.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start() + } catch (e: Exception) { + renewal?.close() + throw e + } + if (renewal != null) { + report("Waiting for Warcraft III to sign in...") + if (!renewal.awaitSignIn()) { + report("Warcraft III did not sign in within ${BattleNetSignIn.SIGN_IN_TIMEOUT_SECONDS} s.") + } + } + } + + /** + * `-editor` launches sign in with a stored token that lapses, after which the game asks for a login. + * [launchMode] is the VS Code setting `wurst.wc3LaunchMode`, as for the language server's Run Map: "auto" renews + * when Battle.net is open and otherwise launches on the stored token, "battlenet" fails the launch when it cannot + * renew, "legacy" never renews. + * + * @return the renewal holding the Battle.net lock, or null when there is none + */ + internal fun renewSignIn(client: Wc3ClientDetector.ClientInfo, command: List, launchMode: String, + report: (String) -> Unit, + find: () -> BattleNetSignIn? = BattleNetSignIn::find, + registered: (Path) -> Boolean = BattleNetSignIn::isRegisteredGame, + osName: String = System.getProperty("os.name")): BattleNetSignIn.Renewal? { + // The token lives in the Windows registry; other systems launch as before. + if (launchMode == "legacy" || "-editor" !in command || !osName.startsWith("Windows", ignoreCase = true)) return null + val battleNet = find() ?: return failOrNull(launchMode, "Battle.net was not found.", report) + val managed = try { + registered(client.executable) + } catch (e: IOException) { + false + } + if (!managed) return failOrNull(launchMode, "This Warcraft III install is not the one Battle.net manages.", report) + if (launchMode != "battlenet" && !battleNet.isRunning()) { + report("Battle.net is not running: launching with the stored sign-in, which may ask for a login.") + return null + } + report("Renewing the Warcraft III sign-in from Battle.net...") + return try { + battleNet.renew() + } catch (e: IOException) { + failOrNull(launchMode, "Could not renew the Warcraft III sign-in: ${e.message}", report) + } + } + + private fun failOrNull(launchMode: String, problem: String, report: (String) -> Unit): BattleNetSignIn.Renewal? { + if (launchMode == "battlenet") throw IllegalStateException("$problem (wurst.wc3LaunchMode is \"battlenet\")") + report("$problem Warcraft III may ask for a login.") + return null } } diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt new file mode 100644 index 0000000..ef4c02d --- /dev/null +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -0,0 +1,66 @@ +import file.BattleNetSignIn +import file.Wc3ClientDetector +import file.Wc3MapRunner +import org.testng.Assert +import org.testng.SkipException +import org.testng.annotations.Test +import java.nio.file.Files +import java.nio.file.Paths + +class BattleNetSignInTests { + private fun reforgedClient(): Wc3ClientDetector.ClientInfo { + val root = Files.createTempDirectory("grill-battlenet-client") + Files.writeString(Files.createDirectories(root.resolve("_retail_/x86_64")).resolve("Warcraft III.exe"), "") + return Wc3ClientDetector.inspectGameRoot(root)!! + } + + private val editorLaunch = listOf("Warcraft III.exe", "-launch", "-editor", "-windowmode", "windowed", "-loadfile", "map.w3x") + + @Test + fun readsOnlyTheRequestedBinaryValueFromRegQuery() { + val output = listOf( + "", + "HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Battle.net\\Launch Options\\W3", + " WEB_TOKEN REG_BINARY 01000000d08c9ddf", + " LOCALE REG_SZ enUS", + "") + Assert.assertEquals(BattleNetSignIn.parseBinary(output, "WEB_TOKEN"), "01000000D08C9DDF") + Assert.assertEquals(BattleNetSignIn.parseBinary(output, "web_token"), "01000000D08C9DDF") + Assert.assertNull(BattleNetSignIn.parseBinary(output, "LOCALE")) + Assert.assertNull(BattleNetSignIn.parseBinary( + listOf("ERROR: The system was unable to find the specified registry key or value."), "WEB_TOKEN")) + } + + @Test + fun takesTheSameLockAsTheE2eHarnessAndWurstScript() { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows paths") + // wc3-e2e-harness node/src/runner/battlenet.cjs: 33000 + sha256(lower-cased path) as uint32 BE % 10000 + Assert.assertEquals(BattleNetSignIn.gatePort(Paths.get("C:\\Users\\tester\\AppData\\Roaming\\Battle.net\\Battle.net.config")), 36941) + } + + @Test + fun legacyModeAndOtherSystemsNeverAskBattleNet() { + val client = reforgedClient() + val reports = mutableListOf() + val find: () -> BattleNetSignIn? = { throw AssertionError("Battle.net must not be asked") } + Assert.assertNull(Wc3MapRunner.renewSignIn(client, editorLaunch, "legacy", reports::add, find, { true }, "Windows 11")) + Assert.assertNull(Wc3MapRunner.renewSignIn(client, editorLaunch, "auto", reports::add, find, { true }, "Mac OS X")) + Assert.assertNull(Wc3MapRunner.renewSignIn(client, editorLaunch, "battlenet", reports::add, find, { true }, "Linux")) + Assert.assertNull(Wc3MapRunner.renewSignIn(client, listOf("war3.exe", "-window", "-loadfile", "map.w3x"), "auto", + reports::add, find, { true }, "Windows 11"), "a classic launch has no -editor sign-in to renew") + Assert.assertEquals(reports, emptyList()) + } + + @Test + fun autoModeLaunchesOnTheStoredSignInWhenBattleNetIsMissing() { + val reports = mutableListOf() + Assert.assertNull(Wc3MapRunner.renewSignIn(reforgedClient(), editorLaunch, "auto", reports::add, { null }, { true }, "Windows 11")) + Assert.assertEquals(reports.size, 1) + Assert.assertTrue(reports[0].contains("may ask for a login"), reports[0]) + } + + @Test(expectedExceptions = [IllegalStateException::class]) + fun battleNetModeRefusesToLaunchWithoutARenewal() { + Wc3MapRunner.renewSignIn(reforgedClient(), editorLaunch, "battlenet", {}, { null }, { true }, "Windows 11") + } +} From 2ae232e4182b55a106473e0d7c0730c5388a0730 Mon Sep 17 00:00:00 2001 From: Frotty Date: Tue, 17 Nov 2026 14:32:45 +0100 Subject: [PATCH 2/8] Keep the Battle.net window minimized and focus the map during grill run Asked to start Warcraft III for the sign-in renewal, the Battle.net app shows its window in front and, depending on its "when I launch a game" setting, leaves it there. Before asking, grill now starts battlenet-window.ps1 (a copy of the wc3-e2e-harness script) and waits until it is ready. For 30 s it minimizes every app window that appears or takes the foreground, without activating it, and brings the map's client to the front once it has a window, never a game that was already running. --- src/main/kotlin/file/BattleNetSignIn.kt | 48 ++++++++++++++++ src/main/resources/battlenet-window.ps1 | 75 +++++++++++++++++++++++++ src/test/kotlin/BattleNetSignInTests.kt | 12 ++++ 3 files changed, 135 insertions(+) create mode 100644 src/main/resources/battlenet-window.ps1 diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt index 22b2764..b1e02ff 100644 --- a/src/main/kotlin/file/BattleNetSignIn.kt +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -10,7 +10,9 @@ import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.security.MessageDigest +import java.util.Base64 import java.util.Locale +import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit /** @@ -84,6 +86,9 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri seen.add(game.pid()) } val before = readBinary(LAUNCH_KEY, "WEB_TOKEN") + // Asked to start the game, the app shows its window in front; the watcher minimizes it as soon as it appears + // and brings the map's client forward once that has a window. + watchLauncherWindow() val start = System.nanoTime() var askedAt = Long.MIN_VALUE var token: String? = null @@ -153,6 +158,49 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri const val SIGN_IN_TIMEOUT_SECONDS = 120L private val REG_BINARY = Regex("""^\s*(\S+)\s+REG_BINARY\s+([0-9A-Fa-f]*)\s*$""", RegexOption.MULTILINE) + /** A copy of the wc3-e2e-harness `node/src/runner/battlenet-window.ps1`; keep the two equal. */ + const val WINDOW_SCRIPT = "battlenet-window.ps1" + private const val WINDOW_WATCH_SECONDS = 30 + private const val WINDOW_READY_SECONDS = 3L + + /** The PowerShell command that runs [WINDOW_SCRIPT] with [arguments]; null if the script is missing. */ + fun windowWatcherCommand(arguments: String): List? { + val script = BattleNetSignIn::class.java.classLoader.getResourceAsStream(WINDOW_SCRIPT) + ?.use { it.readBytes().toString(Charsets.UTF_8) } ?: return null + val encoded = Base64.getEncoder().encodeToString("& {\n$script\n} $arguments".toByteArray(Charsets.UTF_16LE)) + return listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded) + } + + /** + * Starts the window watcher and waits until it has noted the windows already open (at most + * [WINDOW_READY_SECONDS]); it then runs on its own for [WINDOW_WATCH_SECONDS]. Best effort: a watcher that does + * not start only means the app's window may stay in front. + */ + private fun watchLauncherWindow() { + val command = windowWatcherCommand("-Seconds $WINDOW_WATCH_SECONDS -FocusGame") ?: return + val process = try { + ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start() + } catch (_: IOException) { + return + } + val ready = CountDownLatch(1) + Thread { + try { + // The watcher prints nothing after "ready", so its output can be let go then. + process.inputReader().use { reader -> + while (true) { + val line = reader.readLine() ?: break + if (line.trim() == "ready") break + } + } + } catch (_: IOException) { + } finally { + ready.countDown() + } + }.apply { isDaemon = true }.start() + ready.await(WINDOW_READY_SECONDS, TimeUnit.SECONDS) + } + fun find(): BattleNetSignIn? { if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) return null val appData = System.getenv("APPDATA") ?: return null diff --git a/src/main/resources/battlenet-window.ps1 b/src/main/resources/battlenet-window.ps1 new file mode 100644 index 0000000..f5808c5 --- /dev/null +++ b/src/main/resources/battlenet-window.ps1 @@ -0,0 +1,75 @@ +# Keeps the Battle.net app's window out of the way while a sign-in renewal asks it to start Warcraft III. +# +# Asked to start a game, the app shows its window in front, and depending on its "when I launch a game" setting +# leaves it there. Started just before the renewal, this minimizes every app window that appears or takes the +# foreground during the next seconds, without activating it, and leaves alone a window that was already open in the +# background. With -FocusGame it brings the Warcraft III client to the front once that client has a window. +# +# Prints "ready" once it has noted the windows already open, so the caller can ask the app only then; with -Log also +# one line per action. WurstSetup embeds a copy; keep it self-contained. +param([int]$Seconds = 20, [switch]$FocusGame, [switch]$Log) +$ErrorActionPreference = "Stop" +Add-Type @" +using System; using System.Collections.Generic; using System.Runtime.InteropServices; +public static class BattleNetWindow { + delegate bool EnumProc(IntPtr h, IntPtr p); + [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc f, IntPtr p); + [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h); + [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint cmd); + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr h, int cmd); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + // Visible, not minimized, unowned top-level windows of the given processes. + public static List Shown(HashSet pids) { + var found = new List(); + EnumWindows((h, p) => { + uint pid; GetWindowThreadProcessId(h, out pid); + if (pids.Contains(pid) && IsWindowVisible(h) && !IsIconic(h) && GetWindow(h, 4) == IntPtr.Zero) found.Add(h); + return true; + }, IntPtr.Zero); + return found; + } +} +"@ +function Pids([string]$name) { + $set = New-Object 'System.Collections.Generic.HashSet[uint32]' + Get-Process -Name $name -ErrorAction SilentlyContinue | ForEach-Object { [void]$set.Add([uint32]$_.Id) } + return ,$set +} +$backgroundWindows = @([BattleNetWindow]::Shown((Pids "Battle.net")) | Where-Object { $_ -ne [BattleNetWindow]::GetForegroundWindow() }) +# Games running already (the user's own) and those the app starts (the renewal's, closed at once) are never focused. +$notOurGame = Pids "Warcraft III" +function OurGame([uint32]$id) { + if ($notOurGame.Contains($id)) { return $false } + $parent = (Get-CimInstance Win32_Process -Filter "ProcessId=$id" -ErrorAction SilentlyContinue).ParentProcessId + if ($parent -and (Get-Process -Id $parent -ErrorAction SilentlyContinue).ProcessName -eq "Battle.net") { + [void]$notOurGame.Add($id) + return $false + } + return $true +} +$watch = [Diagnostics.Stopwatch]::StartNew() +"ready" +$focused = -not $FocusGame +while ($watch.Elapsed.TotalSeconds -lt $Seconds) { + $foreground = [BattleNetWindow]::GetForegroundWindow() + foreach ($window in [BattleNetWindow]::Shown((Pids "Battle.net"))) { + if ($backgroundWindows -contains $window -and $window -ne $foreground) { continue } + # 7 = SW_SHOWMINNOACTIVE; 6 = SW_MINIMIZE, which hands the foreground on, for the window that holds it. + [void][BattleNetWindow]::ShowWindowAsync($window, $(if ($window -eq $foreground) { 6 } else { 7 })) + if ($Log) { "minimized {0:N1}" -f $watch.Elapsed.TotalSeconds } + } + if (-not $focused) { + $ours = New-Object 'System.Collections.Generic.HashSet[uint32]' + foreach ($id in (Pids "Warcraft III")) { if (OurGame $id) { [void]$ours.Add($id) } } + $game = @([BattleNetWindow]::Shown($ours)) + if ($game.Count -gt 0) { + if ($game -notcontains $foreground) { [void][BattleNetWindow]::SetForegroundWindow($game[0]) } + $focused = $true + if ($Log) { "focused {0:N1}" -f $watch.Elapsed.TotalSeconds } + } + } + Start-Sleep -Milliseconds 50 +} diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt index ef4c02d..5036242 100644 --- a/src/test/kotlin/BattleNetSignInTests.kt +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -38,6 +38,18 @@ class BattleNetSignInTests { Assert.assertEquals(BattleNetSignIn.gatePort(Paths.get("C:\\Users\\tester\\AppData\\Roaming\\Battle.net\\Battle.net.config")), 36941) } + @Test + fun theWindowWatcherShipsAndRunsAsOneEncodedCommand() { + val command = BattleNetSignIn.windowWatcherCommand("-Seconds 30 -FocusGame")!! + Assert.assertEquals(command.subList(0, command.size - 1), + listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand")) + val script = String(java.util.Base64.getDecoder().decode(command.last()), Charsets.UTF_16LE) + Assert.assertTrue(script.startsWith("& {"), script.take(20)) + Assert.assertTrue(script.contains("param([int]\$Seconds = 20, [switch]\$FocusGame, [switch]\$Log)")) + Assert.assertTrue(script.contains("\"ready\""), "the caller waits for this line") + Assert.assertTrue(script.trimEnd().endsWith("} -Seconds 30 -FocusGame")) + } + @Test fun legacyModeAndOtherSystemsNeverAskBattleNet() { val client = reforgedClient() From c525d12ec4121e89a9df59ed2d6dd119d41b8426 Mon Sep 17 00:00:00 2001 From: Frotty Date: Tue, 17 Nov 2026 14:42:26 +0100 Subject: [PATCH 3/8] Wait out a busy sign-in lock instead of launching without it; keep invalid path settings optional grill gave up on the Battle.net lock after 30 s, and in auto mode then launched without it. Another grill, Run Map or harness run holds the lock through its renewal and its client's sign-in, up to about 3.5 minutes, so the unlocked launch could spend the token that client had not read yet. grill now waits up to 4 minutes, says it is waiting, and if the lock is still held refuses to launch in every mode. Reading a path setting from .vscode/settings.json converted it outside the error handler, so a path the system cannot represent aborted grill run where it used to be ignored. It is ignored again. --- src/main/kotlin/config/WurstProjectConfig.kt | 11 ++++- src/main/kotlin/file/BattleNetSignIn.kt | 42 ++++++++++++++++---- src/main/kotlin/file/Wc3MapRunner.kt | 7 +++- src/test/kotlin/BattleNetSignInTests.kt | 41 +++++++++++++++++++ 4 files changed, 91 insertions(+), 10 deletions(-) diff --git a/src/main/kotlin/config/WurstProjectConfig.kt b/src/main/kotlin/config/WurstProjectConfig.kt index caf53a3..012f15b 100644 --- a/src/main/kotlin/config/WurstProjectConfig.kt +++ b/src/main/kotlin/config/WurstProjectConfig.kt @@ -15,6 +15,7 @@ import logging.KotlinLogging import java.io.IOException import java.nio.file.Files import java.nio.file.Path +import java.nio.file.InvalidPathException import java.nio.file.Paths import java.nio.file.StandardOpenOption /** @@ -159,7 +160,15 @@ object WurstProjectConfig { /** The VS Code extension's `wurst.wc3LaunchMode` (auto, battlenet or legacy), which Run Map also follows. */ fun configuredLaunchMode(projectRoot: Path): String = configuredString(projectRoot, "wurst.wc3LaunchMode") ?: "auto" - private fun configuredPath(projectRoot: Path, setting: String): Path? = configuredString(projectRoot, setting)?.let(Paths::get) + /** An optional setting: a path the system cannot represent counts as unset, so callers fall back as before. */ + private fun configuredPath(projectRoot: Path, setting: String): Path? { + val value = configuredString(projectRoot, setting) ?: return null + return try { + Paths.get(value) + } catch (_: InvalidPathException) { + null + } + } private fun configuredString(projectRoot: Path, setting: String): String? { val settings = projectRoot.resolve(".vscode").resolve("settings.json") diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt index b1e02ff..f814be1 100644 --- a/src/main/kotlin/file/BattleNetSignIn.kt +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -30,7 +30,21 @@ import java.util.concurrent.TimeUnit * WurstScript's Run Map (`BattleNetSignIn`) and the wc3-e2e-harness (`docs/BattleNetSignIn.md`) do the same, and all * hold the same localhost port as a lock from the renewal until the launched client has signed in. */ -internal class BattleNetSignIn private constructor(private val config: Path, private val launcher: Path) { +/** What [Wc3MapRunner] needs from the Battle.net app; replaced in tests. */ +internal interface BattleNetApp { + fun isRunning(): Boolean + + /** @param onWait called once if another launch holds the lock and this one has to wait for it */ + fun renew(onWait: () -> Unit = {}): BattleNetSignIn.Renewal +} + +internal class BattleNetSignIn private constructor(private val config: Path, private val launcher: Path) : BattleNetApp { + + /** + * Another tool holds the renewal lock for longer than a renewal and a sign-in take. Not a reason to launch + * without it: that launch could spend the token the other tool's client has not read yet. + */ + class LockBusyException(message: String) : IOException(message) /** The lock, held until the launched client has signed in; see [awaitSignIn]. */ class Renewal internal constructor(private val gate: ServerSocket, private val token: String) : AutoCloseable { @@ -60,14 +74,16 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri } } - fun isRunning(): Boolean = ProcessHandle.allProcesses().anyMatch { named(command(it), LAUNCHER) } + override fun isRunning(): Boolean = ProcessHandle.allProcesses().anyMatch { named(command(it), LAUNCHER) } + + override fun renew(onWait: () -> Unit): Renewal = renew(GATE_WAIT_SECONDS, onWait) /** * Stores a token from the app as `EDITOR_TOKEN` and returns the held lock. Throws, with a message for the user, * when the app cannot provide one: it is closed, signed out, updating, or running a client of its own. */ - fun renew(): Renewal { - val gate = acquireGate() + fun renew(gateWaitSeconds: Long, onWait: () -> Unit = {}): Renewal { + val gate = acquireGate(gateWaitSeconds, onWait) try { return Renewal(gate, renewLocked()) } catch (e: Throwable) { @@ -128,8 +144,9 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri return token } - private fun acquireGate(): ServerSocket { - val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30) + private fun acquireGate(waitSeconds: Long, onWait: () -> Unit): ServerSocket { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(waitSeconds) + var waiting = false while (true) { val socket = ServerSocket() try { @@ -138,7 +155,13 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri return socket } catch (e: BindException) { socket.close() - if (System.nanoTime() >= deadline) throw IOException("Another Warcraft III test is using Battle.net.", e) + if (!waiting) { + waiting = true + onWait() + } + if (System.nanoTime() >= deadline) { + throw LockBusyException("Another Warcraft III launch has held the Battle.net sign-in for over $waitSeconds s.") + } Thread.sleep(250) } catch (e: IOException) { socket.close() @@ -156,6 +179,11 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri private const val ASK_AGAIN_SECONDS = 25L private const val GAME_AFTER_TOKEN_SECONDS = 10L const val SIGN_IN_TIMEOUT_SECONDS = 120L + /** Another holder renews (up to [TIMEOUT_SECONDS]) and waits for its client's sign-in; outwait both. */ + const val GATE_WAIT_SECONDS = TIMEOUT_SECONDS + SIGN_IN_TIMEOUT_SECONDS + 30 + + /** A renewal for [config] whose launcher is never started; for tests that only touch the lock. */ + internal fun forTest(config: Path): BattleNetSignIn = BattleNetSignIn(config, Paths.get(LAUNCHER)) private val REG_BINARY = Regex("""^\s*(\S+)\s+REG_BINARY\s+([0-9A-Fa-f]*)\s*$""", RegexOption.MULTILINE) /** A copy of the wc3-e2e-harness `node/src/runner/battlenet-window.ps1`; keep the two equal. */ diff --git a/src/main/kotlin/file/Wc3MapRunner.kt b/src/main/kotlin/file/Wc3MapRunner.kt index d5cb940..e9f228b 100644 --- a/src/main/kotlin/file/Wc3MapRunner.kt +++ b/src/main/kotlin/file/Wc3MapRunner.kt @@ -126,7 +126,7 @@ internal object Wc3MapRunner { */ internal fun renewSignIn(client: Wc3ClientDetector.ClientInfo, command: List, launchMode: String, report: (String) -> Unit, - find: () -> BattleNetSignIn? = BattleNetSignIn::find, + find: () -> BattleNetApp? = BattleNetSignIn::find, registered: (Path) -> Boolean = BattleNetSignIn::isRegisteredGame, osName: String = System.getProperty("os.name")): BattleNetSignIn.Renewal? { // The token lives in the Windows registry; other systems launch as before. @@ -144,7 +144,10 @@ internal object Wc3MapRunner { } report("Renewing the Warcraft III sign-in from Battle.net...") return try { - battleNet.renew() + battleNet.renew { report("Another Warcraft III launch is signing in; waiting until it has...") } + } catch (e: BattleNetSignIn.LockBusyException) { + // In every mode: launching without the lock could spend the other client's unread token. + throw IllegalStateException("${e.message} Run the map again once it has signed in.", e) } catch (e: IOException) { failOrNull(launchMode, "Could not renew the Warcraft III sign-in: ${e.message}", report) } diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt index 5036242..63ea815 100644 --- a/src/test/kotlin/BattleNetSignInTests.kt +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -1,4 +1,9 @@ +import config.WurstProjectConfig +import file.BattleNetApp import file.BattleNetSignIn +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket import file.Wc3ClientDetector import file.Wc3MapRunner import org.testng.Assert @@ -71,6 +76,42 @@ class BattleNetSignInTests { Assert.assertTrue(reports[0].contains("may ask for a login"), reports[0]) } + @Test + fun aRenewalLockHeldElsewhereIsReportedAsBusy() { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows only") + val config = Files.createTempDirectory("grill-battlenet-lock").resolve("Battle.net.config") + ServerSocket().use { holder -> + holder.bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), BattleNetSignIn.gatePort(config))) + var waited = false + try { + BattleNetSignIn.forTest(config).renew(gateWaitSeconds = 1, onWait = { waited = true }) + Assert.fail("the lock is held elsewhere") + } catch (e: BattleNetSignIn.LockBusyException) { + Assert.assertTrue(waited, "the user is told why the launch waits") + } + } + } + + @Test(expectedExceptions = [IllegalStateException::class]) + fun aBusyRenewalLockStopsTheLaunchEvenInAutoMode() { + // Launching without the lock could spend the token another tool's client has not read yet. + val busy = object : BattleNetApp { + override fun isRunning() = true + override fun renew(onWait: () -> Unit): BattleNetSignIn.Renewal = + throw BattleNetSignIn.LockBusyException("another launch is signing in") + } + Wc3MapRunner.renewSignIn(reforgedClient(), editorLaunch, "auto", {}, { busy }, { true }, "Windows 11") + } + + @Test + fun anInvalidConfiguredPathFallsBackToDetection() { + if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows path rules") + val project = Files.createTempDirectory("grill-bad-setting") + Files.writeString(Files.createDirectories(project.resolve(".vscode")).resolve("settings.json"), + """{ "wurst.wc3path": "C:\\Games\\War Date: Tue, 17 Nov 2026 14:51:30 +0100 Subject: [PATCH 4/8] Never fail a launch after the map started while waiting for its sign-in A registry query that timed out while grill waited for the launched client to sign in threw out of launchMap after the map was already running. grill run --hot treats that as a failed launch and rolls back to the previous hot reload session. The wait now reports such a failure and releases the lock instead of throwing. --- src/main/kotlin/file/BattleNetSignIn.kt | 11 +++++++--- src/main/kotlin/file/Wc3MapRunner.kt | 19 +++++++++++++++-- src/test/kotlin/BattleNetSignInTests.kt | 27 +++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt index f814be1..0e675c8 100644 --- a/src/main/kotlin/file/BattleNetSignIn.kt +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -47,7 +47,12 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri class LockBusyException(message: String) : IOException(message) /** The lock, held until the launched client has signed in; see [awaitSignIn]. */ - class Renewal internal constructor(private val gate: ServerSocket, private val token: String) : AutoCloseable { + class Renewal internal constructor( + private val gate: ServerSocket, + private val token: String, + private val currentToken: () -> String? = { readBinary(GAME_KEY, "EDITOR_TOKEN") }, + private val pollMillis: Long = 500, + ) : AutoCloseable { /** * Blocks until the launched client replaces `EDITOR_TOKEN`, which it does as it signs in (about ten seconds after * launch), or [SIGN_IN_TIMEOUT_SECONDS] pass, then releases the lock. Released earlier, another tool's renewal @@ -57,8 +62,8 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SIGN_IN_TIMEOUT_SECONDS) try { while (System.nanoTime() < deadline) { - if (readBinary(GAME_KEY, "EDITOR_TOKEN") != token) return true - Thread.sleep(500) + if (currentToken() != token) return true + Thread.sleep(pollMillis) } return false } finally { diff --git a/src/main/kotlin/file/Wc3MapRunner.kt b/src/main/kotlin/file/Wc3MapRunner.kt index e9f228b..5774e42 100644 --- a/src/main/kotlin/file/Wc3MapRunner.kt +++ b/src/main/kotlin/file/Wc3MapRunner.kt @@ -108,11 +108,26 @@ internal object Wc3MapRunner { renewal?.close() throw e } - if (renewal != null) { - report("Waiting for Warcraft III to sign in...") + if (renewal != null) awaitSignIn(renewal, report) + } + + /** + * Holds the Battle.net lock until the launched client has signed in. The map is running by now, so nothing here + * may throw: callers treat an exception from a launch as a failed launch and roll back, as `grill run --hot` does + * with its session. A sign-in that cannot be watched is reported and the lock released. + */ + internal fun awaitSignIn(renewal: BattleNetSignIn.Renewal, report: (String) -> Unit) { + report("Waiting for Warcraft III to sign in...") + try { if (!renewal.awaitSignIn()) { report("Warcraft III did not sign in within ${BattleNetSignIn.SIGN_IN_TIMEOUT_SECONDS} s.") } + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + } catch (e: Exception) { + report("Could not watch the Warcraft III sign-in (${e.message}); released the Battle.net lock.") + } finally { + renewal.close() } } diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt index 63ea815..408bb54 100644 --- a/src/test/kotlin/BattleNetSignInTests.kt +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -103,6 +103,33 @@ class BattleNetSignInTests { Wc3MapRunner.renewSignIn(reforgedClient(), editorLaunch, "auto", {}, { busy }, { true }, "Windows 11") } + @Test + fun aSignInThatCannotBeWatchedNeitherFailsTheLaunchNorKeepsTheLock() { + // The map runs by now: an exception would make `grill run --hot` roll back a session the new map uses. + val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } + val renewal = BattleNetSignIn.Renewal(gate, "TOKEN", { throw java.io.IOException("registry query timed out") }, 1) + val reports = mutableListOf() + + Wc3MapRunner.awaitSignIn(renewal, reports::add) + + Assert.assertTrue(gate.isClosed, "the lock is released") + Assert.assertTrue(reports.last().contains("registry query timed out"), reports.toString()) + } + + @Test + fun aSignInIsAwaitedUntilTheClientReplacesTheToken() { + val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } + val reads = mutableListOf("TOKEN", "TOKEN", "NEW") + val renewal = BattleNetSignIn.Renewal(gate, "TOKEN", { reads.removeAt(0) }, 1) + val reports = mutableListOf() + + Wc3MapRunner.awaitSignIn(renewal, reports::add) + + Assert.assertTrue(reads.isEmpty(), "polled until the token changed") + Assert.assertTrue(gate.isClosed) + Assert.assertEquals(reports, listOf("Waiting for Warcraft III to sign in...")) + } + @Test fun anInvalidConfiguredPathFallsBackToDetection() { if (!System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) throw SkipException("Windows path rules") From 35b209bdd3301a41e503ab9eba739847a8bad903 Mon Sep 17 00:00:00 2001 From: Frotty Date: Tue, 17 Nov 2026 14:56:30 +0100 Subject: [PATCH 5/8] Keep the launcher window watcher for the whole renewal and end it with the lock As in wc3-e2e-harness#61: the watcher ended after 30 s while a renewal keeps asking Battle.net every 25 s for up to 90 s. It now runs for the renewal timeout plus 15 s, and a successful renewal ends it together with the lock once the client has signed in, so it does not minimize a launcher the user opens later. --- src/main/kotlin/file/BattleNetSignIn.kt | 27 ++++++++++++++++--------- src/test/kotlin/BattleNetSignInTests.kt | 20 ++++++++++++++++++ 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt index 0e675c8..1911e2b 100644 --- a/src/main/kotlin/file/BattleNetSignIn.kt +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -52,6 +52,8 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri private val token: String, private val currentToken: () -> String? = { readBinary(GAME_KEY, "EDITOR_TOKEN") }, private val pollMillis: Long = 500, + /** The launcher window watcher, ended with the lock: the client is in front and signed in by then. */ + private val watcher: Process? = null, ) : AutoCloseable { /** * Blocks until the launched client replaces `EDITOR_TOKEN`, which it does as it signs in (about ten seconds after @@ -72,6 +74,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri } override fun close() { + watcher?.destroy() try { gate.close() } catch (_: IOException) { @@ -90,14 +93,16 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri fun renew(gateWaitSeconds: Long, onWait: () -> Unit = {}): Renewal { val gate = acquireGate(gateWaitSeconds, onWait) try { - return Renewal(gate, renewLocked()) + val (token, watcher) = renewLocked() + return Renewal(gate, token, watcher = watcher) } catch (e: Throwable) { gate.close() throw e } } - private fun renewLocked(): String { + /** @return the stored token, and the launcher window watcher (left to end on its own if this throws) */ + private fun renewLocked(): Pair { if (!isRunning()) throw IOException("Battle.net is not running.") val seen = HashSet() for (game in games()) { @@ -109,7 +114,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri val before = readBinary(LAUNCH_KEY, "WEB_TOKEN") // Asked to start the game, the app shows its window in front; the watcher minimizes it as soon as it appears // and brings the map's client forward once that has a window. - watchLauncherWindow() + val watcher = watchLauncherWindow() val start = System.nanoTime() var askedAt = Long.MIN_VALUE var token: String? = null @@ -146,7 +151,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri throw IOException("Battle.net did not start Warcraft III. Check that it is signed in and the game is ready to play.") } writeBinary(GAME_KEY, "EDITOR_TOKEN", token) - return token + return token to watcher } private fun acquireGate(waitSeconds: Long, onWait: () -> Unit): ServerSocket { @@ -193,7 +198,8 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri /** A copy of the wc3-e2e-harness `node/src/runner/battlenet-window.ps1`; keep the two equal. */ const val WINDOW_SCRIPT = "battlenet-window.ps1" - private const val WINDOW_WATCH_SECONDS = 30 + /** Covers every request the renewal may send (one every [ASK_AGAIN_SECONDS], up to [TIMEOUT_SECONDS]). */ + const val WINDOW_WATCH_SECONDS = TIMEOUT_SECONDS + 15 private const val WINDOW_READY_SECONDS = 3L /** The PowerShell command that runs [WINDOW_SCRIPT] with [arguments]; null if the script is missing. */ @@ -206,15 +212,15 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri /** * Starts the window watcher and waits until it has noted the windows already open (at most - * [WINDOW_READY_SECONDS]); it then runs on its own for [WINDOW_WATCH_SECONDS]. Best effort: a watcher that does - * not start only means the app's window may stay in front. + * [WINDOW_READY_SECONDS]); it then runs on its own for at most [WINDOW_WATCH_SECONDS], and a successful renewal + * ends it with the lock. Best effort: a watcher that does not start only means the app's window may stay in front. */ - private fun watchLauncherWindow() { - val command = windowWatcherCommand("-Seconds $WINDOW_WATCH_SECONDS -FocusGame") ?: return + private fun watchLauncherWindow(): Process? { + val command = windowWatcherCommand("-Seconds $WINDOW_WATCH_SECONDS -FocusGame") ?: return null val process = try { ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start() } catch (_: IOException) { - return + return null } val ready = CountDownLatch(1) Thread { @@ -232,6 +238,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri } }.apply { isDaemon = true }.start() ready.await(WINDOW_READY_SECONDS, TimeUnit.SECONDS) + return process } fun find(): BattleNetSignIn? { diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt index 408bb54..87ab608 100644 --- a/src/test/kotlin/BattleNetSignInTests.kt +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -116,6 +116,26 @@ class BattleNetSignInTests { Assert.assertTrue(reports.last().contains("registry query timed out"), reports.toString()) } + @Test + fun theLauncherWindowWatcherOutlivesEveryRequestOfASlowRenewal() { + // The renewal asks the app again every 25 s for up to 90 s; each request can bring its window back. + Assert.assertTrue(BattleNetSignIn.WINDOW_WATCH_SECONDS > 90, "${BattleNetSignIn.WINDOW_WATCH_SECONDS} s") + } + + @Test + fun releasingTheRenewalEndsTheLauncherWindowWatcher() { + // Otherwise it would go on minimizing a launcher the user opens after the map has started. + val windows = System.getProperty("os.name").startsWith("Windows", ignoreCase = true) + val watcher = (if (windows) ProcessBuilder("ping", "-n", "30", "127.0.0.1") else ProcessBuilder("sleep", "30")) + .redirectOutput(ProcessBuilder.Redirect.DISCARD).start() + val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } + + BattleNetSignIn.Renewal(gate, "TOKEN", { "NEW" }, 1, watcher).close() + + Assert.assertTrue(watcher.waitFor(5, java.util.concurrent.TimeUnit.SECONDS), "the watcher was ended") + Assert.assertTrue(gate.isClosed) + } + @Test fun aSignInIsAwaitedUntilTheClientReplacesTheToken() { val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } From f943a1c37f049c421a30dfcaa3dc5e0c2f7bed8f Mon Sep 17 00:00:00 2001 From: Frotty Date: Tue, 17 Nov 2026 15:19:43 +0100 Subject: [PATCH 6/8] Hide the Battle.net window as it is created during grill run Updates the copy of wc3-e2e-harness battlenet-window.ps1 (Frotty/wc3-e2e-harness#61): Battle.net creates a new window each time it is asked to start the game, so the watcher now hooks window creation, moves each new window off-screen before it shows and minimizes it there, instead of minimizing it after it flashed in front. The script is now run with -File from a content-named temp copy: passed with -EncodedCommand it came close to Windows' 32,767-character command line limit. --- src/main/kotlin/file/BattleNetSignIn.kt | 21 ++- src/main/resources/battlenet-window.ps1 | 218 +++++++++++++++++++----- src/test/kotlin/BattleNetSignInTests.kt | 19 ++- 3 files changed, 197 insertions(+), 61 deletions(-) diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt index 1911e2b..266aac3 100644 --- a/src/main/kotlin/file/BattleNetSignIn.kt +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -10,7 +10,6 @@ import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.security.MessageDigest -import java.util.Base64 import java.util.Locale import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @@ -203,11 +202,19 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri private const val WINDOW_READY_SECONDS = 3L /** The PowerShell command that runs [WINDOW_SCRIPT] with [arguments]; null if the script is missing. */ - fun windowWatcherCommand(arguments: String): List? { - val script = BattleNetSignIn::class.java.classLoader.getResourceAsStream(WINDOW_SCRIPT) - ?.use { it.readBytes().toString(Charsets.UTF_8) } ?: return null - val encoded = Base64.getEncoder().encodeToString("& {\n$script\n} $arguments".toByteArray(Charsets.UTF_16LE)) - return listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded) + fun windowWatcherCommand(arguments: List, dir: Path = Paths.get(System.getProperty("java.io.tmpdir"))): List? { + val script = BattleNetSignIn::class.java.classLoader.getResourceAsStream(WINDOW_SCRIPT)?.use { it.readBytes() } + ?: return null + // A file, not -EncodedCommand: encoded, the script is close to Windows' 32,767-character command line limit. + // Named by content, so a grill of another version never runs this one's copy. + val hash = MessageDigest.getInstance("SHA-256").digest(script).take(6).joinToString("") { "%02x".format(it) } + val file = dir.resolve("grill-battlenet-window-$hash.ps1") + try { + if (!Files.isRegularFile(file) || !Files.readAllBytes(file).contentEquals(script)) Files.write(file, script) + } catch (_: IOException) { + return null + } + return listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file.toString()) + arguments } /** @@ -216,7 +223,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri * ends it with the lock. Best effort: a watcher that does not start only means the app's window may stay in front. */ private fun watchLauncherWindow(): Process? { - val command = windowWatcherCommand("-Seconds $WINDOW_WATCH_SECONDS -FocusGame") ?: return null + val command = windowWatcherCommand(listOf("-Seconds", WINDOW_WATCH_SECONDS.toString(), "-FocusGame")) ?: return null val process = try { ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start() } catch (_: IOException) { diff --git a/src/main/resources/battlenet-window.ps1 b/src/main/resources/battlenet-window.ps1 index f5808c5..556b0ae 100644 --- a/src/main/resources/battlenet-window.ps1 +++ b/src/main/resources/battlenet-window.ps1 @@ -1,28 +1,89 @@ -# Keeps the Battle.net app's window out of the way while a sign-in renewal asks it to start Warcraft III. +# Keeps the Battle.net app's window out of sight while a sign-in renewal asks it to start Warcraft III. # -# Asked to start a game, the app shows its window in front, and depending on its "when I launch a game" setting -# leaves it there. Started just before the renewal, this minimizes every app window that appears or takes the -# foreground during the next seconds, without activating it, and leaves alone a window that was already open in the -# background. With -FocusGame it brings the Warcraft III client to the front once that client has a window. +# Asked to start a game, the app creates its window and shows it in front, and depending on its "when I launch a game" +# setting leaves it there. Started just before the renewal, this hooks window creation: each new top-level app window +# is moved off-screen as it is created, so it is shown out of sight, and then minimized without being activated. Its +# restore position is set back to where the app put it, so the user's own next Restore opens it normally. An app window +# that was already open is minimized too if it takes the foreground, and left alone otherwise. With -FocusGame it brings +# the map's Warcraft III client to the front once that has a window: a client that started after this script and not +# from the app, so never the user's own game or the renewal's short-lived one. # # Prints "ready" once it has noted the windows already open, so the caller can ask the app only then; with -Log also # one line per action. WurstSetup embeds a copy; keep it self-contained. param([int]$Seconds = 20, [switch]$FocusGame, [switch]$Log) $ErrorActionPreference = "Stop" Add-Type @" -using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; public static class BattleNetWindow { delegate bool EnumProc(IntPtr h, IntPtr p); + delegate void WinEventProc(IntPtr hook, uint ev, IntPtr hwnd, int idObject, int idChild, uint thread, uint time); [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc f, IntPtr p); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h); [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h); [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint cmd); - [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); - [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr h, int cmd); - [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint flags); + [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd); + [DllImport("user32.dll")] static extern bool ShowWindowAsync(IntPtr h, int cmd); + [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags); + [DllImport("user32.dll")] static extern bool GetWindowPlacement(IntPtr h, ref WINDOWPLACEMENT p); + [DllImport("user32.dll")] static extern bool SetWindowPlacement(IntPtr h, ref WINDOWPLACEMENT p); + [DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint min, uint max, IntPtr mod, WinEventProc proc, uint pid, uint tid, uint flags); + [DllImport("user32.dll")] static extern bool UnhookWinEvent(IntPtr hook); + [DllImport("user32.dll")] static extern uint MsgWaitForMultipleObjects(uint n, IntPtr[] h, bool all, uint ms, uint mask); + [DllImport("user32.dll")] static extern bool PeekMessage(out MSG m, IntPtr h, uint min, uint max, uint remove); + [DllImport("user32.dll")] static extern bool TranslateMessage(ref MSG m); + [DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref MSG m); + [DllImport("kernel32.dll")] static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint pid); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool Process32FirstW(IntPtr snap, ref PROCESSENTRY32 e); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool Process32NextW(IntPtr snap, ref PROCESSENTRY32 e); + [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h); + [StructLayout(LayoutKind.Sequential)] struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] struct POINT { public int X, Y; } + [StructLayout(LayoutKind.Sequential)] struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public POINT pt; } + [StructLayout(LayoutKind.Sequential)] struct WINDOWPLACEMENT { public int length, flags, showCmd; public POINT min, max; public RECT normal; } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct PROCESSENTRY32 { + public uint dwSize, cntUsage, th32ProcessID; public IntPtr th32DefaultHeapID; public uint th32ModuleID, cntThreads, + th32ParentProcessID; public int pcPriClassBase; public uint dwFlags; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExeFile; } + + const uint EVENT_CREATE = 0x8000, EVENT_SHOW = 0x8002, EVENT_LOCATION = 0x800B; + const uint SWP_MOVE_ONLY = 0x0001 | 0x0004 | 0x0010; // NOSIZE | NOZORDER | NOACTIVATE + const int OFF_SCREEN = -32000; + static readonly Stopwatch watch = new Stopwatch(); + static readonly Dictionary moved = new Dictionary(); + static readonly HashSet handled = new HashSet(); + static HashSet background = new HashSet(); + static HashSet appPids = new HashSet(); + static readonly HashSet notOurGame = new HashSet(); + static bool log; + static WinEventProc callback; + + static void Note(string s) { if (log) Console.WriteLine("{0} {1:N2}", s, watch.Elapsed.TotalSeconds); } + + static Dictionary Processes() { + var all = new Dictionary(); + IntPtr snap = CreateToolhelp32Snapshot(2, 0); + if (snap == new IntPtr(-1)) return all; + try { + var e = new PROCESSENTRY32(); e.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)); + for (bool ok = Process32FirstW(snap, ref e); ok; ok = Process32NextW(snap, ref e)) all[e.th32ProcessID] = e; + } finally { CloseHandle(snap); } + return all; + } + + static HashSet Pids(Dictionary all, string exe) { + var pids = new HashSet(); + foreach (var e in all.Values) if (string.Equals(e.szExeFile, exe, StringComparison.OrdinalIgnoreCase)) pids.Add(e.th32ProcessID); + return pids; + } + // Visible, not minimized, unowned top-level windows of the given processes. - public static List Shown(HashSet pids) { + static List Shown(HashSet pids) { var found = new List(); EnumWindows((h, p) => { uint pid; GetWindowThreadProcessId(h, out pid); @@ -31,45 +92,108 @@ public static class BattleNetWindow { }, IntPtr.Zero); return found; } -} -"@ -function Pids([string]$name) { - $set = New-Object 'System.Collections.Generic.HashSet[uint32]' - Get-Process -Name $name -ErrorAction SilentlyContinue | ForEach-Object { [void]$set.Add([uint32]$_.Id) } - return ,$set -} -$backgroundWindows = @([BattleNetWindow]::Shown((Pids "Battle.net")) | Where-Object { $_ -ne [BattleNetWindow]::GetForegroundWindow() }) -# Games running already (the user's own) and those the app starts (the renewal's, closed at once) are never focused. -$notOurGame = Pids "Warcraft III" -function OurGame([uint32]$id) { - if ($notOurGame.Contains($id)) { return $false } - $parent = (Get-CimInstance Win32_Process -Filter "ProcessId=$id" -ErrorAction SilentlyContinue).ParentProcessId - if ($parent -and (Get-Process -Id $parent -ErrorAction SilentlyContinue).ProcessName -eq "Battle.net") { - [void]$notOurGame.Add($id) - return $false + + static bool AppWindow(IntPtr h) { + uint pid; GetWindowThreadProcessId(h, out pid); + return appPids.Contains(pid) && GetAncestor(h, 2) == h && GetWindow(h, 4) == IntPtr.Zero; } - return $true -} -$watch = [Diagnostics.Stopwatch]::StartNew() -"ready" -$focused = -not $FocusGame -while ($watch.Elapsed.TotalSeconds -lt $Seconds) { - $foreground = [BattleNetWindow]::GetForegroundWindow() - foreach ($window in [BattleNetWindow]::Shown((Pids "Battle.net"))) { - if ($backgroundWindows -contains $window -and $window -ne $foreground) { continue } - # 7 = SW_SHOWMINNOACTIVE; 6 = SW_MINIMIZE, which hands the foreground on, for the window that holds it. - [void][BattleNetWindow]::ShowWindowAsync($window, $(if ($window -eq $foreground) { 6 } else { 7 })) - if ($Log) { "minimized {0:N1}" -f $watch.Elapsed.TotalSeconds } + + // Minimizes without activating; the window holding the foreground is minimized normally, which hands it on. + static void Minimize(IntPtr h, string why) { + bool foreground = GetForegroundWindow() == h; + ShowWindow(h, foreground ? 6 : 7); + handled.Add(h); + RECT original; + if (moved.TryGetValue(h, out original) && original.Right > original.Left) { + var p = new WINDOWPLACEMENT(); p.length = Marshal.SizeOf(p); + if (GetWindowPlacement(h, ref p)) { p.normal = original; p.showCmd = 7; SetWindowPlacement(h, ref p); } + } + Note("minimized " + why); + } + + static void OnEvent(IntPtr hook, uint ev, IntPtr h, int idObject, int idChild, uint thread, uint time) { + if (idObject != 0 || idChild != 0 || h == IntPtr.Zero || !AppWindow(h)) return; + if (ev == EVENT_CREATE && !moved.ContainsKey(h)) { + RECT r; GetWindowRect(h, out r); + moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } else if (ev == EVENT_LOCATION && moved.ContainsKey(h) && !handled.Contains(h)) { + // The app may put the window back where it last was; keep it off-screen, and remember that as its place. + RECT r; GetWindowRect(h, out r); + if (r.Left > OFF_SCREEN / 2) { + moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } + } else if (ev == EVENT_SHOW && moved.ContainsKey(h) && !handled.Contains(h)) { + RECT r; GetWindowRect(h, out r); + if (r.Left > OFF_SCREEN / 2) { + moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); + } + Minimize(h, "new window"); + } } - if (-not $focused) { - $ours = New-Object 'System.Collections.Generic.HashSet[uint32]' - foreach ($id in (Pids "Warcraft III")) { if (OurGame $id) { [void]$ours.Add($id) } } - $game = @([BattleNetWindow]::Shown($ours)) - if ($game.Count -gt 0) { - if ($game -notcontains $foreground) { [void][BattleNetWindow]::SetForegroundWindow($game[0]) } - $focused = $true - if ($Log) { "focused {0:N1}" -f $watch.Elapsed.TotalSeconds } + + public static void Prepare(bool logActions) { + log = logActions; + var all = Processes(); + appPids = Pids(all, "Battle.net.exe"); + foreach (uint pid in Pids(all, "Warcraft III.exe")) notOurGame.Add(pid); + IntPtr foreground = GetForegroundWindow(); + background = new HashSet(Shown(appPids)); + background.Remove(foreground); + } + + public static void Run(int seconds, bool focusGame) { + watch.Start(); + callback = OnEvent; + IntPtr hook = SetWinEventHook(EVENT_CREATE, EVENT_LOCATION, IntPtr.Zero, callback, 0, 0, 0); + bool focused = !focusGame; + long lastScan = -1000; + try { + while (watch.Elapsed.TotalSeconds < seconds) { + MsgWaitForMultipleObjects(0, null, false, 25, 0x04FF); + MSG m; + while (PeekMessage(out m, IntPtr.Zero, 0, 0, 1)) { TranslateMessage(ref m); DispatchMessage(ref m); } + if (watch.ElapsedMilliseconds - lastScan < 50) continue; + lastScan = watch.ElapsedMilliseconds; + var all = Processes(); + appPids = Pids(all, "Battle.net.exe"); + IntPtr foreground = GetForegroundWindow(); + // An app window that was open already, or one the hook missed: minimize it if it is in the way. + foreach (IntPtr h in Shown(appPids)) { + if (background.Contains(h) && h != foreground) continue; + Minimize(h, "shown window"); + } + if (!focused) { + var ours = new HashSet(); + foreach (uint pid in Pids(all, "Warcraft III.exe")) { + if (notOurGame.Contains(pid)) continue; + PROCESSENTRY32 e; PROCESSENTRY32 parent; + if (all.TryGetValue(pid, out e) && all.TryGetValue(e.th32ParentProcessID, out parent) + && string.Equals(parent.szExeFile, "Battle.net.exe", StringComparison.OrdinalIgnoreCase)) { notOurGame.Add(pid); continue; } + ours.Add(pid); + } + var game = Shown(ours); + if (game.Count > 0) { + if (!game.Contains(foreground)) SetForegroundWindow(game[0]); + focused = true; + Note("focused"); + } + } + } + } finally { + UnhookWinEvent(hook); + // Windows the app created but never showed go back where it put them. + foreach (var entry in moved) { + if (!handled.Contains(entry.Key) && IsWindow(entry.Key)) { + SetWindowPos(entry.Key, IntPtr.Zero, entry.Value.Left, entry.Value.Top, 0, 0, SWP_MOVE_ONLY); + } + } } } - Start-Sleep -Milliseconds 50 } +"@ +[BattleNetWindow]::Prepare([bool]$Log) +"ready" +[BattleNetWindow]::Run($Seconds, [bool]$FocusGame) diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt index 87ab608..d76159a 100644 --- a/src/test/kotlin/BattleNetSignInTests.kt +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -44,15 +44,20 @@ class BattleNetSignInTests { } @Test - fun theWindowWatcherShipsAndRunsAsOneEncodedCommand() { - val command = BattleNetSignIn.windowWatcherCommand("-Seconds 30 -FocusGame")!! - Assert.assertEquals(command.subList(0, command.size - 1), - listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand")) - val script = String(java.util.Base64.getDecoder().decode(command.last()), Charsets.UTF_16LE) - Assert.assertTrue(script.startsWith("& {"), script.take(20)) + fun theWindowWatcherShipsAndRunsFromAFileNamedByItsContent() { + val dir = Files.createTempDirectory("grill-window-watcher") + val command = BattleNetSignIn.windowWatcherCommand(listOf("-Seconds", "30", "-FocusGame"), dir)!! + Assert.assertEquals(command.subList(0, 6), + listOf("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File")) + Assert.assertEquals(command.subList(7, command.size), listOf("-Seconds", "30", "-FocusGame")) + val file = Paths.get(command[6]) + Assert.assertEquals(file.parent, dir) + val script = Files.readString(file) Assert.assertTrue(script.contains("param([int]\$Seconds = 20, [switch]\$FocusGame, [switch]\$Log)")) Assert.assertTrue(script.contains("\"ready\""), "the caller waits for this line") - Assert.assertTrue(script.trimEnd().endsWith("} -Seconds 30 -FocusGame")) + Assert.assertTrue(script.all { it.code < 128 }, "Windows PowerShell reads a .ps1 without BOM as ANSI") + // A second call reuses the same file. + Assert.assertEquals(BattleNetSignIn.windowWatcherCommand(listOf(), dir)!![6], command[6]) } @Test From bfa3f16f3625fcfb28f622028608ec665bdc0c93 Mon Sep 17 00:00:00 2001 From: Frotty Date: Tue, 17 Nov 2026 15:33:35 +0100 Subject: [PATCH 7/8] Keep the Battle.net window hidden through the client's sign-in during grill run Updates the copy of wc3-e2e-harness battlenet-window.ps1: Battle.net shows its window again as the launched client signs in, ten to twenty seconds after launch, so ending the watcher with the lock at that sign-in let it through. The watcher now ends itself a minute after the client appears (at most the renewal timeout plus 150 s), also hides a launcher window the app restores, and closes a crash reporter of the renewal's closed client. --- src/main/kotlin/file/BattleNetSignIn.kt | 29 +++++----- src/main/resources/battlenet-window.ps1 | 72 ++++++++++++++++--------- src/test/kotlin/BattleNetSignInTests.kt | 24 +++------ 3 files changed, 66 insertions(+), 59 deletions(-) diff --git a/src/main/kotlin/file/BattleNetSignIn.kt b/src/main/kotlin/file/BattleNetSignIn.kt index 266aac3..4e21ca8 100644 --- a/src/main/kotlin/file/BattleNetSignIn.kt +++ b/src/main/kotlin/file/BattleNetSignIn.kt @@ -51,8 +51,6 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri private val token: String, private val currentToken: () -> String? = { readBinary(GAME_KEY, "EDITOR_TOKEN") }, private val pollMillis: Long = 500, - /** The launcher window watcher, ended with the lock: the client is in front and signed in by then. */ - private val watcher: Process? = null, ) : AutoCloseable { /** * Blocks until the launched client replaces `EDITOR_TOKEN`, which it does as it signs in (about ten seconds after @@ -73,7 +71,6 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri } override fun close() { - watcher?.destroy() try { gate.close() } catch (_: IOException) { @@ -92,16 +89,14 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri fun renew(gateWaitSeconds: Long, onWait: () -> Unit = {}): Renewal { val gate = acquireGate(gateWaitSeconds, onWait) try { - val (token, watcher) = renewLocked() - return Renewal(gate, token, watcher = watcher) + return Renewal(gate, renewLocked()) } catch (e: Throwable) { gate.close() throw e } } - /** @return the stored token, and the launcher window watcher (left to end on its own if this throws) */ - private fun renewLocked(): Pair { + private fun renewLocked(): String { if (!isRunning()) throw IOException("Battle.net is not running.") val seen = HashSet() for (game in games()) { @@ -113,7 +108,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri val before = readBinary(LAUNCH_KEY, "WEB_TOKEN") // Asked to start the game, the app shows its window in front; the watcher minimizes it as soon as it appears // and brings the map's client forward once that has a window. - val watcher = watchLauncherWindow() + watchLauncherWindow() val start = System.nanoTime() var askedAt = Long.MIN_VALUE var token: String? = null @@ -150,7 +145,7 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri throw IOException("Battle.net did not start Warcraft III. Check that it is signed in and the game is ready to play.") } writeBinary(GAME_KEY, "EDITOR_TOKEN", token) - return token to watcher + return token } private fun acquireGate(waitSeconds: Long, onWait: () -> Unit): ServerSocket { @@ -197,8 +192,8 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri /** A copy of the wc3-e2e-harness `node/src/runner/battlenet-window.ps1`; keep the two equal. */ const val WINDOW_SCRIPT = "battlenet-window.ps1" - /** Covers every request the renewal may send (one every [ASK_AGAIN_SECONDS], up to [TIMEOUT_SECONDS]). */ - const val WINDOW_WATCH_SECONDS = TIMEOUT_SECONDS + 15 + /** The watcher's limit without a client: every request the renewal may send, then a launch and a slow sign-in. */ + const val WINDOW_WATCH_SECONDS = TIMEOUT_SECONDS + 150 private const val WINDOW_READY_SECONDS = 3L /** The PowerShell command that runs [WINDOW_SCRIPT] with [arguments]; null if the script is missing. */ @@ -219,15 +214,16 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri /** * Starts the window watcher and waits until it has noted the windows already open (at most - * [WINDOW_READY_SECONDS]); it then runs on its own for at most [WINDOW_WATCH_SECONDS], and a successful renewal - * ends it with the lock. Best effort: a watcher that does not start only means the app's window may stay in front. + * [WINDOW_READY_SECONDS]). It then runs on its own: the app shows its window again as the map's client signs in, + * so it ends a minute after that client appears, or after [WINDOW_WATCH_SECONDS]. Best effort: a watcher that does + * not start only means the app's window may show. */ - private fun watchLauncherWindow(): Process? { - val command = windowWatcherCommand(listOf("-Seconds", WINDOW_WATCH_SECONDS.toString(), "-FocusGame")) ?: return null + private fun watchLauncherWindow() { + val command = windowWatcherCommand(listOf("-Seconds", WINDOW_WATCH_SECONDS.toString(), "-FocusGame")) ?: return val process = try { ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start() } catch (_: IOException) { - return null + return } val ready = CountDownLatch(1) Thread { @@ -245,7 +241,6 @@ internal class BattleNetSignIn private constructor(private val config: Path, pri } }.apply { isDaemon = true }.start() ready.await(WINDOW_READY_SECONDS, TimeUnit.SECONDS) - return process } fun find(): BattleNetSignIn? { diff --git a/src/main/resources/battlenet-window.ps1 b/src/main/resources/battlenet-window.ps1 index 556b0ae..32dea8e 100644 --- a/src/main/resources/battlenet-window.ps1 +++ b/src/main/resources/battlenet-window.ps1 @@ -8,9 +8,13 @@ # the map's Warcraft III client to the front once that has a window: a client that started after this script and not # from the app, so never the user's own game or the renewal's short-lived one. # +# The app shows its window again as the map's client signs in, so the watcher ends $GameSeconds after that client +# (one that started after this script and not from the app) appears, or at $Seconds if none does. Until that client +# appears, a new crash reporter (BlizzardError.exe) can only belong to the renewal's closed client and is closed. +# # Prints "ready" once it has noted the windows already open, so the caller can ask the app only then; with -Log also # one line per action. WurstSetup embeds a copy; keep it self-contained. -param([int]$Seconds = 20, [switch]$FocusGame, [switch]$Log) +param([int]$Seconds = 20, [int]$GameSeconds = 60, [switch]$FocusGame, [switch]$Log) $ErrorActionPreference = "Stop" Add-Type @" using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; @@ -60,6 +64,7 @@ public static class BattleNetWindow { static HashSet background = new HashSet(); static HashSet appPids = new HashSet(); static readonly HashSet notOurGame = new HashSet(); + static readonly HashSet oldReporters = new HashSet(); static bool log; static WinEventProc callback; @@ -113,25 +118,32 @@ public static class BattleNetWindow { static void OnEvent(IntPtr hook, uint ev, IntPtr h, int idObject, int idChild, uint thread, uint time) { if (idObject != 0 || idChild != 0 || h == IntPtr.Zero || !AppWindow(h)) return; - if (ev == EVENT_CREATE && !moved.ContainsKey(h)) { - RECT r; GetWindowRect(h, out r); - moved[h] = r; - SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); - } else if (ev == EVENT_LOCATION && moved.ContainsKey(h) && !handled.Contains(h)) { - // The app may put the window back where it last was; keep it off-screen, and remember that as its place. - RECT r; GetWindowRect(h, out r); - if (r.Left > OFF_SCREEN / 2) { + RECT r; GetWindowRect(h, out r); + bool onScreen = r.Left > OFF_SCREEN / 2; + if (ev == EVENT_CREATE) { + if (!moved.ContainsKey(h)) { moved[h] = r; SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); } - } else if (ev == EVENT_SHOW && moved.ContainsKey(h) && !handled.Contains(h)) { - RECT r; GetWindowRect(h, out r); - if (r.Left > OFF_SCREEN / 2) { + return; + } + if (!IsWindowVisible(h)) { + // Not shown yet: the app may put it back where it last was; keep it off-screen and remember that as its place. + if (ev == EVENT_LOCATION && moved.ContainsKey(h) && !handled.Contains(h) && onScreen) { moved[h] = r; SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); } - Minimize(h, "new window"); + return; + } + if (IsIconic(h)) return; + // Shown, or restored, in the open: unless it is a window the user had open in the background, move it out of + // sight at once and minimize it. Its restore position stays the one the app first gave it. + if (background.Contains(h) && GetForegroundWindow() != h) return; + if (onScreen) { + if (!moved.ContainsKey(h)) moved[h] = r; + SetWindowPos(h, IntPtr.Zero, OFF_SCREEN, OFF_SCREEN, 0, 0, SWP_MOVE_ONLY); } + Minimize(h, ev == EVENT_SHOW ? "shown window" : "restored window"); } public static void Prepare(bool logActions) { @@ -139,19 +151,22 @@ public static class BattleNetWindow { var all = Processes(); appPids = Pids(all, "Battle.net.exe"); foreach (uint pid in Pids(all, "Warcraft III.exe")) notOurGame.Add(pid); + foreach (uint pid in Pids(all, "BlizzardError.exe")) oldReporters.Add(pid); IntPtr foreground = GetForegroundWindow(); background = new HashSet(Shown(appPids)); background.Remove(foreground); } - public static void Run(int seconds, bool focusGame) { + public static void Run(int seconds, int gameSeconds, bool focusGame) { watch.Start(); callback = OnEvent; IntPtr hook = SetWinEventHook(EVENT_CREATE, EVENT_LOCATION, IntPtr.Zero, callback, 0, 0, 0); bool focused = !focusGame; long lastScan = -1000; + double gameSeenAt = -1; try { - while (watch.Elapsed.TotalSeconds < seconds) { + // The app shows its window again as the map's client signs in, so watch until that client has run a while. + while (watch.Elapsed.TotalSeconds < seconds && (gameSeenAt < 0 || watch.Elapsed.TotalSeconds - gameSeenAt < gameSeconds)) { MsgWaitForMultipleObjects(0, null, false, 25, 0x04FF); MSG m; while (PeekMessage(out m, IntPtr.Zero, 0, 0, 1)) { TranslateMessage(ref m); DispatchMessage(ref m); } @@ -165,15 +180,24 @@ public static class BattleNetWindow { if (background.Contains(h) && h != foreground) continue; Minimize(h, "shown window"); } - if (!focused) { - var ours = new HashSet(); - foreach (uint pid in Pids(all, "Warcraft III.exe")) { - if (notOurGame.Contains(pid)) continue; - PROCESSENTRY32 e; PROCESSENTRY32 parent; - if (all.TryGetValue(pid, out e) && all.TryGetValue(e.th32ParentProcessID, out parent) - && string.Equals(parent.szExeFile, "Battle.net.exe", StringComparison.OrdinalIgnoreCase)) { notOurGame.Add(pid); continue; } - ours.Add(pid); + var ours = new HashSet(); + foreach (uint pid in Pids(all, "Warcraft III.exe")) { + if (notOurGame.Contains(pid)) continue; + PROCESSENTRY32 e; PROCESSENTRY32 parent; + if (all.TryGetValue(pid, out e) && all.TryGetValue(e.th32ParentProcessID, out parent) + && string.Equals(parent.szExeFile, "Battle.net.exe", StringComparison.OrdinalIgnoreCase)) { notOurGame.Add(pid); continue; } + ours.Add(pid); + } + if (ours.Count > 0 && gameSeenAt < 0) gameSeenAt = watch.Elapsed.TotalSeconds; + if (gameSeenAt < 0) { + // Until the map's client runs, a new crash reporter can only be the renewal's closed client's. + foreach (uint pid in Pids(all, "BlizzardError.exe")) { + if (oldReporters.Contains(pid)) continue; + oldReporters.Add(pid); + try { Process.GetProcessById((int)pid).Kill(); Note("closed crash reporter"); } catch (Exception) { } } + } + if (!focused) { var game = Shown(ours); if (game.Count > 0) { if (!game.Contains(foreground)) SetForegroundWindow(game[0]); @@ -196,4 +220,4 @@ public static class BattleNetWindow { "@ [BattleNetWindow]::Prepare([bool]$Log) "ready" -[BattleNetWindow]::Run($Seconds, [bool]$FocusGame) +[BattleNetWindow]::Run($Seconds, $GameSeconds, [bool]$FocusGame) diff --git a/src/test/kotlin/BattleNetSignInTests.kt b/src/test/kotlin/BattleNetSignInTests.kt index d76159a..151dab5 100644 --- a/src/test/kotlin/BattleNetSignInTests.kt +++ b/src/test/kotlin/BattleNetSignInTests.kt @@ -53,7 +53,7 @@ class BattleNetSignInTests { val file = Paths.get(command[6]) Assert.assertEquals(file.parent, dir) val script = Files.readString(file) - Assert.assertTrue(script.contains("param([int]\$Seconds = 20, [switch]\$FocusGame, [switch]\$Log)")) + Assert.assertTrue(script.contains("param([int]\$Seconds = 20, [int]\$GameSeconds = 60, [switch]\$FocusGame, [switch]\$Log)")) Assert.assertTrue(script.contains("\"ready\""), "the caller waits for this line") Assert.assertTrue(script.all { it.code < 128 }, "Windows PowerShell reads a .ps1 without BOM as ANSI") // A second call reuses the same file. @@ -122,23 +122,11 @@ class BattleNetSignInTests { } @Test - fun theLauncherWindowWatcherOutlivesEveryRequestOfASlowRenewal() { - // The renewal asks the app again every 25 s for up to 90 s; each request can bring its window back. - Assert.assertTrue(BattleNetSignIn.WINDOW_WATCH_SECONDS > 90, "${BattleNetSignIn.WINDOW_WATCH_SECONDS} s") - } - - @Test - fun releasingTheRenewalEndsTheLauncherWindowWatcher() { - // Otherwise it would go on minimizing a launcher the user opens after the map has started. - val windows = System.getProperty("os.name").startsWith("Windows", ignoreCase = true) - val watcher = (if (windows) ProcessBuilder("ping", "-n", "30", "127.0.0.1") else ProcessBuilder("sleep", "30")) - .redirectOutput(ProcessBuilder.Redirect.DISCARD).start() - val gate = ServerSocket().apply { bind(InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 0)) } - - BattleNetSignIn.Renewal(gate, "TOKEN", { "NEW" }, 1, watcher).close() - - Assert.assertTrue(watcher.waitFor(5, java.util.concurrent.TimeUnit.SECONDS), "the watcher was ended") - Assert.assertTrue(gate.isClosed) + fun theLauncherWindowWatcherOutlivesASlowRenewalAndTheSignInAfterIt() { + // The renewal asks the app again every 25 s for up to 90 s, and the app shows its window once more as the + // launched client signs in (up to 120 s); each can bring its window back. + Assert.assertTrue(BattleNetSignIn.WINDOW_WATCH_SECONDS >= 90 + BattleNetSignIn.SIGN_IN_TIMEOUT_SECONDS, + "${BattleNetSignIn.WINDOW_WATCH_SECONDS} s") } @Test From 076e4c44e2d79d359b8757cc2725b45469f9811b Mon Sep 17 00:00:00 2001 From: Frotty Date: Tue, 17 Nov 2026 15:45:41 +0100 Subject: [PATCH 8/8] Close only the renewal client's crash reporter (watcher copy) Updates the copy of wc3-e2e-harness battlenet-window.ps1. Until the run's client appeared, the watcher closed every new BlizzardError.exe, so a crash report from a game the user already had open was cut short too. It now closes a new reporter only when its parent is a renewal client it saw (started by Battle.net) or a process already gone that was not one of the games running before; every other reporter is left alone. --- src/main/resources/battlenet-window.ps1 | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/resources/battlenet-window.ps1 b/src/main/resources/battlenet-window.ps1 index 32dea8e..867886b 100644 --- a/src/main/resources/battlenet-window.ps1 +++ b/src/main/resources/battlenet-window.ps1 @@ -10,7 +10,7 @@ # # The app shows its window again as the map's client signs in, so the watcher ends $GameSeconds after that client # (one that started after this script and not from the app) appears, or at $Seconds if none does. Until that client -# appears, a new crash reporter (BlizzardError.exe) can only belong to the renewal's closed client and is closed. +# appears, a new crash reporter (BlizzardError.exe) of the renewal's closed client is closed; any other is left alone. # # Prints "ready" once it has noted the windows already open, so the caller can ask the app only then; with -Log also # one line per action. WurstSetup embeds a copy; keep it self-contained. @@ -65,6 +65,8 @@ public static class BattleNetWindow { static HashSet appPids = new HashSet(); static readonly HashSet notOurGame = new HashSet(); static readonly HashSet oldReporters = new HashSet(); + static readonly HashSet earlierGames = new HashSet(); + static readonly HashSet renewalClients = new HashSet(); static bool log; static WinEventProc callback; @@ -150,7 +152,7 @@ public static class BattleNetWindow { log = logActions; var all = Processes(); appPids = Pids(all, "Battle.net.exe"); - foreach (uint pid in Pids(all, "Warcraft III.exe")) notOurGame.Add(pid); + foreach (uint pid in Pids(all, "Warcraft III.exe")) { notOurGame.Add(pid); earlierGames.Add(pid); } foreach (uint pid in Pids(all, "BlizzardError.exe")) oldReporters.Add(pid); IntPtr foreground = GetForegroundWindow(); background = new HashSet(Shown(appPids)); @@ -185,15 +187,25 @@ public static class BattleNetWindow { if (notOurGame.Contains(pid)) continue; PROCESSENTRY32 e; PROCESSENTRY32 parent; if (all.TryGetValue(pid, out e) && all.TryGetValue(e.th32ParentProcessID, out parent) - && string.Equals(parent.szExeFile, "Battle.net.exe", StringComparison.OrdinalIgnoreCase)) { notOurGame.Add(pid); continue; } + && string.Equals(parent.szExeFile, "Battle.net.exe", StringComparison.OrdinalIgnoreCase)) { + notOurGame.Add(pid); + renewalClients.Add(pid); + continue; + } ours.Add(pid); } if (ours.Count > 0 && gameSeenAt < 0) gameSeenAt = watch.Elapsed.TotalSeconds; if (gameSeenAt < 0) { - // Until the map's client runs, a new crash reporter can only be the renewal's closed client's. + // A new crash reporter for the renewal's closed client: its parent is that client, or (seen too briefly to be + // noted) a process already gone that was not one of the games running before. Any other reporter is left alone. foreach (uint pid in Pids(all, "BlizzardError.exe")) { if (oldReporters.Contains(pid)) continue; oldReporters.Add(pid); + PROCESSENTRY32 reporter; + if (!all.TryGetValue(pid, out reporter)) continue; + uint parentPid = reporter.th32ParentProcessID; + bool renewals = renewalClients.Contains(parentPid) || (!all.ContainsKey(parentPid) && !earlierGames.Contains(parentPid)); + if (!renewals) continue; try { Process.GetProcessById((int)pid).Kill(); Note("closed crash reporter"); } catch (Exception) { } } }