Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.
HTML apple-siliconbattle-netcrossover-alternatived3dmetaldiablo-ii-resurrecteddxmtea-appepic-gamesgame-porting-toolkitgogmac-gamingmacosmacos-gamingrockstar-gamessteamubisoft-connectwhisky-alternativewindows-gameswinewine-wrapper
Battle.net: say why a game did not start (#180)
Mikek6846ae0197d3
diff --git a/scripts/battlenet_launch.py b/scripts/battlenet_launch.pynew file mode 100644index 00000000000..bad1e2121a7--- /dev/null+++ b/scripts/battlenet_launch.py@@ -0,0 +1,129 @@+#!/usr/bin/env python3+"""What Battle.net did with a request to start a game, read from Battle.net's own logs.++Battle.net writes a new battle.net-<time>.log each time it starts (in the bottle, under+users/<name>/AppData/Local/Battle.net/Logs), with lines like:+ I 2026-11-22 17:53:23.851176 [GameLaunchController] {Main} LaunchBinary: uid=osi selectedRegion=KR binaryType=game+ I 2026-11-22 17:57:17.832215 [BNLogin] {Main} Logged into Battle.net successfully. ...+ I ... [ProductState] {Main} InstallState (osi): currentOperation=Update ...+Times are UTC.++ battlenet_launch.py watch <bottle> <game uid> [--seconds N] [-- <command that hands --exec="launch X" over>]+ Runs the command, then follows the logs. A start that goes through ends quietly; one that waits for the+ player's sign-in or for an update ends with a "soju: ..." line the app shows, and a non-zero status.+ ("Pre-existing game session detected" is not a sign of trouble: Battle.net writes it right after+ every start it performs, seen 2026-11-23.)++Also used by scripts/play-stats.py: reason(bottle, uid, since) gives the word sent with a start that did not run.+"""+import glob+import os+import re+import subprocess+import sys+import time++LOGS = "drive_c/users/*/AppData/Local/Battle.net/Logs/battle.net-*.log"+STAMP = re.compile(r"^[A-Z] (\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)")+++def text_since(bottle, since):+ """Log lines written since `since` (epoch seconds), from the logs touched since then."""+ stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(since))+ out = []+ for path in glob.glob(os.path.join(str(bottle), LOGS)):+ try:+ if os.path.getmtime(path) < since - 5:+ continue+ with open(path, "r", encoding="utf-8", errors="replace") as f:+ for line in f:+ m = STAMP.match(line)+ if m and m.group(1) >= stamp:+ out.append(line)+ except OSError:+ pass+ return "".join(out)+++def signed_in(bottle):+ """Whether the Battle.net running now (its newest log) says it signed in."""+ logs = glob.glob(os.path.join(str(bottle), LOGS))+ if not logs:+ return False+ try:+ newest = max(logs, key=os.path.getmtime)+ with open(newest, "r", encoding="utf-8", errors="replace") as f:+ return "Logged into Battle.net successfully" in f.read()+ except OSError:+ return False+++def outcome(text, uid):+ """"ok" (Battle.net started the game or it is running), "updating", or ""."""+ uid = re.escape(uid.lower())+ if re.search(r"LaunchBinary: uid=%s\b" % uid, text) or re.search(r"Game is running: %s\b" % uid, text):+ return "ok"+ if re.search(r"InstallState \(%s\): currentOperation=Update\b" % uid, text) or re.search(r"Update started: %s\b" % uid, text):+ return "updating"+ return ""+++def reason(bottle, uid, since):+ """The word for a start that did not run: bnet_launched when Battle.net did start it (so the game closed+ or was not seen), bnet_updating, bnet_signin, or ""."""+ kind = outcome(text_since(bottle, since), uid)+ if kind == "ok":+ return "bnet_launched"+ if kind:+ return "bnet_" + kind+ return "" if signed_in(bottle) else "bnet_signin"+++MESSAGES = {+ "updating": "Battle.net is updating the game first. It starts by itself when the update in Battle.net finishes.",+ "signin": "Battle.net is waiting for you to sign in. Its window is open now: sign in there and the game starts by itself.",+}+++def watch(bottle, uid, command, seconds=60, waiting_after=15, signin_after=60, show=None,+ poll=1.0, clock=time.monotonic, sleep=time.sleep, now=time.time):+ since = now() - 2+ code = subprocess.call(command) if command else 0+ if code != 0:+ return code+ begun = clock()+ first = {}+ while clock() - begun < seconds:+ sleep(poll)+ kind = outcome(text_since(bottle, since), uid)+ if kind == "ok":+ return 0+ if kind:+ first.setdefault(kind, clock())+ if clock() - first[kind] >= waiting_after:+ print("soju: " + MESSAGES[kind], flush=True)+ return 4+ elif clock() - begun >= signin_after and not signed_in(bottle):+ if show:+ try:+ subprocess.call(show, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)+ except (OSError, subprocess.SubprocessError):+ pass+ print("soju: " + MESSAGES["signin"], flush=True)+ return 4+ return 0+++def main(argv):+ if len(argv) >= 3 and argv[0] == "watch":+ command = argv[argv.index("--") + 1:] if "--" in argv else []+ head = argv[:argv.index("--")] if "--" in argv else argv+ seconds = int(head[head.index("--seconds") + 1]) if "--seconds" in head else 60+ show = os.environ.get("SOJU_BNET_SHOW")+ return watch(argv[1], argv[2], command, seconds=seconds, show=show.split("\x1f") if show else None)+ print("usage: battlenet_launch.py watch <bottle> <uid> [--seconds N] [-- <command>]", file=sys.stderr)+ return 64+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/scripts/play-stats.py b/scripts/play-stats.pyindex 7ec7601378e..d2827220a29 100755--- a/scripts/play-stats.py+++ b/scripts/play-stats.py@@ -178,13 +178,14 @@ def log_marks(game, launcher):out[str(path)] = (st.st_ino, st.st_size)except OSError:out[str(path)] = (0, 0)+ out["_t"] = time.time()return outdef log_since(marks, limit=400_000):"""What the launch logs gained since log_marks (all of a log that was started again meanwhile)."""text = []- for name, (inode, size) in (marks or {}).items():+ for name, (inode, size) in ((k, v) for k, v in (marks or {}).items() if not k.startswith("_")):try:st = os.stat(name)start = size if st.st_ino == inode and st.st_size >= size else 0@@ -251,6 +252,15 @@ def reason(started, minutes, marks, found, path, launcher="", game=""):word, name = "steam_" + kind, SAFE.sub("", step)[:40]except Exception:pass+ if not word and launcher == "battlenet" and ":" in game and isinstance(marks, dict) and marks.get("_t"):+ try:+ import battlenet_launch+ word = battlenet_launch.reason(BASE / "bottle", game.split(":", 1)[1], marks["_t"])+ except Exception:+ word = ""+ # Battle.net started it and the game was never seen: what Wine said, if anything, goes along.+ if word == "bnet_launched":+ name = "_".join(x for x in why(text, found) if x)[:40]if not word:word, name = why(text, found)if not word and not started:diff --git a/scripts/play.sh b/scripts/play.shindex f97030667ed..129316e28eb 100755--- a/scripts/play.sh+++ b/scripts/play.sh@@ -207,7 +207,9 @@ case "$MODE" in# "What's New?" on top, no LaunchBinary in its log). So after a cold start the same request is sent again once# Battle.net's log says it is signed in, until the log shows the game being launched. Someone who has to type# a password first gets the game right after signing in, without pressing Play again.- if [[ " ${*:2} " == *" --exec="* ]] && ! pgrep -f 'Battle\.net\.exe' >/dev/null 2>&1; then+ BN_COLD=0+ pgrep -f 'Battle\.net\.exe' >/dev/null 2>&1 || BN_COLD=1+ if [[ " ${*:2} " == *" --exec="* ]] && [ "$BN_COLD" = 1 ]; thenBN_MARK="$WINEPREFIX/.soju-launch-mark"; : > "$BN_MARK"(sent=0; last=0@@ -225,6 +227,18 @@ case "$MODE" indone) >/dev/null 2>&1 &fi+ # Then follow the start in Battle.net's own log (scripts/battlenet_launch.py): quiet when the game starts;+ # a sign-in, an update first, or a game Battle.net thinks is still running is shown and said.+ BN_UID=$(printf '%s\n' "${@:2}" | sed -n 's/^--exec=launch \(.*\)$/\1/p' | head -1)+ if [ -n "$BN_UID" ]; then+ export SOJU_BNET_SHOW="/bin/bash"$'\x1f'"${BASH_SOURCE[0]}"$'\x1f'"battlenet"+ BN_WATCH=(python3 "$(dirname "${BASH_SOURCE[0]}")/battlenet_launch.py" watch "$WINEPREFIX" "$BN_UID")+ if [ "$BN_COLD" = 1 ]; then+ ( "$ENGINE/bin/wine" "$BN_EXE" $BN_ARGS "${@:2}" & )+ exec "${BN_WATCH[@]}" --seconds 150+ fi+ exec "${BN_WATCH[@]}" -- "$ENGINE/bin/wine" "$BN_EXE" $BN_ARGS "${@:2}"+ fiexec "$ENGINE/bin/wine" "$BN_EXE" $BN_ARGS "${@:2}";;d2r) # Launch the game directly (offline / previous session)diff --git a/site-worker/stats.js b/site-worker/stats.jsindex 8dbc1b4549a..e6536c1b205 100644--- a/site-worker/stats.js+++ b/site-worker/stats.js@@ -22,7 +22,7 @@ const SCHEMA = [];const RESULTS = new Set(["ran", "quick_exit", "no_start"]);// Why a start did not run, as the Mac read it from its own launch log: one word, one name, and the game's anti-cheat.-const WHY = new Set(["crash", "missing_dll", "graphics", "memory", "dotnet", "launcher_open", "launcher_closed", "steam_error", "steam_waiting", "steam_updating"]);+const WHY = new Set(["crash", "missing_dll", "graphics", "memory", "dotnet", "launcher_open", "launcher_closed", "steam_error", "steam_waiting", "steam_updating", "bnet_launched", "bnet_session", "bnet_updating", "bnet_signin"]);const AC = new Set(["eac", "battleye", "vanguard", "gameguard", "xigncode", "punkbuster"]);const name = (v) => { const s = text(v, 40); return /^[A-Za-z0-9._+-]*$/.test(s) ? s : ""; };const HOW = new Set(["soju", "steam"]);diff --git a/tests/test_battlenet_launch.py b/tests/test_battlenet_launch.pynew file mode 100644index 00000000000..a16e5d06efa--- /dev/null+++ b/tests/test_battlenet_launch.py@@ -0,0 +1,74 @@+import os+import sys+import tempfile+import time+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "scripts"))+import battlenet_launch as bl # noqa: E402+++def stamp(t):+ return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(t)) + ".100000"+++class BattleNetLaunchTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.bottle = Path(self.tmp.name)+ self.logs = self.bottle / "drive_c/users/crossover/AppData/Local/Battle.net/Logs"+ self.logs.mkdir(parents=True)++ def tearDown(self):+ self.tmp.cleanup()++ def log(self, name, lines):+ with open(self.logs / name, "a") as f:+ for t, text in lines:+ f.write("I %s [Main] {Main} %s\r\n" % (stamp(t), text))++ def test_reads_how_a_start_went_and_only_since_it_began(self):+ t = time.time()+ self.log("battle.net-1.log", [(t - 600, "LaunchBinary: uid=osi selectedRegion=KR binaryType=game"),+ (t - 590, "Logged into Battle.net successfully. |bnet=1")])+ self.assertEqual(bl.outcome(bl.text_since(self.bottle, t - 10), "OSI"), "") # the old start is not this one+ self.assertEqual(bl.reason(self.bottle, "osi", t - 10), "") # signed in, nothing more known+ self.log("battle.net-1.log", [(t, "InstallState (osi): currentOperation=Update currentOperationStatus=New")])+ self.assertEqual(bl.reason(self.bottle, "osi", t - 10), "bnet_updating")+ self.log("battle.net-1.log", [(t + 1, "LaunchBinary: uid=osi selectedRegion=KR binaryType=game")])+ self.assertEqual(bl.reason(self.bottle, "osi", t - 10), "bnet_launched")+ # Written right after every start Battle.net performs: not a sign of trouble.+ self.assertEqual(bl.outcome("Pre-existing game session detected without a pending launch.", "osi"), "")++ def test_a_battle_net_that_never_signed_in_is_named(self):+ t = time.time()+ self.log("battle.net-2.log", [(t, "Command line arguments: {[0]=--exec=launch OSI}")])+ self.assertEqual(bl.reason(self.bottle, "osi", t - 10), "bnet_signin")++ def test_watch_is_quiet_when_the_game_starts_and_says_why_when_not(self):+ clockv = [0.0]+ def clock(): return clockv[0]+ def sleep(s): clockv[0] += s+ t = time.time()+ cmd = [sys.executable, "-c", "import time;open(%r,'a').write('I %s [x] {Main} LaunchBinary: uid=osi x\\r\\n')"+ % (str(self.logs / "battle.net-3.log"), stamp(t + 1))]+ self.assertEqual(bl.watch(self.bottle, "OSI", cmd, clock=clock, sleep=sleep), 0)+ clockv[0] = 0.0+ self.log("battle.net-4.log", [(t + 2, "Logged into Battle.net successfully.")])+ cmd = [sys.executable, "-c", "open(%r,'a').write('I %s [x] {Main} InstallState (s1): currentOperation=Update currentOperationStatus=New\\r\\n')"+ % (str(self.logs / "battle.net-4.log"), stamp(t + 3))]+ self.assertEqual(bl.watch(self.bottle, "s1", cmd, clock=clock, sleep=sleep), 4)+ # Signed in, nothing about the game for the whole minute: no message.+ clockv[0] = 0.0+ self.assertEqual(bl.watch(self.bottle, "fenris", [], clock=clock, sleep=sleep, now=lambda: t + 10), 0)++ def test_play_sh_follows_battle_net_starts(self):+ text = (ROOT / "scripts/play.sh").read_text()+ self.assertIn('battlenet_launch.py" watch', text)+ self.assertIn('exec "${BN_WATCH[@]}" --seconds 150', text)+++if __name__ == "__main__":+ unittest.main()