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
Steam: follow a cold start too, and show Steam's window when it waits (#178)
Mikek50fc3936e62f
diff --git a/scripts/play.sh b/scripts/play.shindex 90f5ba7ae23..f97030667ed 100755--- a/scripts/play.sh+++ b/scripts/play.sh@@ -338,10 +338,16 @@ case "$MODE" in# Play on a game while Steam is open: Steam takes the request and may refuse it (no licence, offline) or wait# for an answer in its window, which may be hidden. Follow Steam's own log for that game and say so# (scripts/steam_launch.py); a start that goes through ends quietly. A cold start is Steam itself, so not here.- STEAM_WATCH=()+ # When Steam is not open yet, Steam starts in the background and the same watch follows the start, a+ # little longer, so a sign-in or a question in Steam's window is shown rather than waited on unseen.+ STEAM_WATCH=(); STEAM_COLD=0STEAM_APP=$(printf '%s\n' "${@:2}" | sed -n 's#^steam://rungameid/\([0-9][0-9]*\)$#\1#p' | head -1)- if [ -n "$STEAM_APP" ] && pgrep -f 'Steam.steam\.exe' >/dev/null 2>&1; then- STEAM_WATCH=(python3 "$(dirname "${BASH_SOURCE[0]}")/steam_launch.py" watch "$WINEPREFIX/drive_c/Program Files (x86)/Steam" "$STEAM_APP" --)+ if [ -n "$STEAM_APP" ]; then+ pgrep -f 'Steam.steam\.exe' >/dev/null 2>&1 || STEAM_COLD=1+ STEAM_WATCH=(python3 "$(dirname "${BASH_SOURCE[0]}")/steam_launch.py" watch "$WINEPREFIX/drive_c/Program Files (x86)/Steam" "$STEAM_APP")+ [ "$STEAM_COLD" = 0 ] || STEAM_WATCH+=(--seconds 150)+ STEAM_WATCH+=(--)+ export SOJU_STEAM_SHOW="/bin/bash"$'\x1f'"${BASH_SOURCE[0]}"$'\x1f'"steam"$'\x1f'"steam://open/main"fiif [ "${SOJU_STEAM_GPTK:-0}" = 1 ]; then# Steam with Apple GPTK: the CX engine plus the cross-process winemac@@ -374,6 +380,10 @@ case "$MODE" in{ [ -x "$REAPER" ] && ( "$REAPER" "$WINEPREFIX" "$ENGINE/bin/wineserver" steam >/dev/null 2>&1 & ); }STEAM_CMD=("C:\\Program Files (x86)\\Steam\\steam.exe" -no-cef-sandbox -cef-single-process)[ -f "$WINEPREFIX/drive_c/Program Files (x86)/Steam/steamui.dll" ] && STEAM_CMD+=(-noverifyfiles)+ if [ "$STEAM_COLD" = 1 ]; then+ ( "$ENGINE/bin/wine" "${STEAM_CMD[@]}" "${@:2}" & )+ exec "${STEAM_WATCH[@]}"+ fiexec ${STEAM_WATCH[@]+"${STEAM_WATCH[@]}"} "$ENGINE/bin/wine" "${STEAM_CMD[@]}" "${@:2}"fiWINESTABLE="$STEAM_WINE_ROOT/bin/wine"@@ -487,11 +497,16 @@ case "$MODE" in# rest of the bottle down so no Dock icon / winedevice lingers.pgrep -f "soju-reaper.sh $WINEPREFIX" >/dev/null 2>&1 || \{ [ -x "$REAPER" ] && ( "$REAPER" "$WINEPREFIX" "$WINESTABLE_SERVER" steam >/dev/null 2>&1 & ); }- exec ${STEAM_WATCH[@]+"${STEAM_WATCH[@]}"} "${STEAM_ENV[@]}" \- WINEDLLOVERRIDES="bcrypt=b;ncrypt=b;gameoverlayrenderer,gameoverlayrenderer64=d" \- WINE_NO_DOCK_ICON="steam.exe;steamservice.exe" \- WINE_DOCK_REOPEN_CMD="'$WINESTABLE' 'C:\\Program Files (x86)\\Steam\\steam.exe' steam://open/main" \- "$WINESTABLE" "${STEAM_CMD[@]}"+ STEAM_RUN=("${STEAM_ENV[@]}"+ WINEDLLOVERRIDES="bcrypt=b;ncrypt=b;gameoverlayrenderer,gameoverlayrenderer64=d"+ WINE_NO_DOCK_ICON="steam.exe;steamservice.exe"+ WINE_DOCK_REOPEN_CMD="'$WINESTABLE' 'C:\\Program Files (x86)\\Steam\\steam.exe' steam://open/main"+ "$WINESTABLE" "${STEAM_CMD[@]}")+ if [ "$STEAM_COLD" = 1 ]; then+ ( "${STEAM_RUN[@]}" & )+ exec "${STEAM_WATCH[@]}"+ fi+ exec ${STEAM_WATCH[@]+"${STEAM_WATCH[@]}"} "${STEAM_RUN[@]}";;controllers) # Game Controllers panel of the Battle.net bottle (Wine's joy.cpl):# shows what the bottle sees (DirectInput, XInput slots) and the SDL/hidrawdiff --git a/scripts/steam_launch.py b/scripts/steam_launch.pyindex 8f863da872a..c14de370014 100644--- a/scripts/steam_launch.py+++ b/scripts/steam_launch.py@@ -58,51 +58,106 @@ def message(kind, detail):number = detail.split("_")[-1]return "Steam could not start the game (" + detail + "). " + HINTS.get(number, "Open Steam to see why, then press Play again.")if kind == "waiting":- return "Steam is waiting for you before it starts the game (" + detail + "). Click Steam in the Dock to see its window and answer; the game starts after that."+ return "Steam is waiting for you before it starts the game (" + detail + "). Its window is open now: answer there and the game starts."if kind == "updating":return "Steam is updating the game first. It starts by itself when the download in Steam finishes."+ if kind == "signin":+ return "Steam is waiting for you to sign in. Its window is open now: sign in there and the game starts."return ""-def watch(steam_dir, appid, command, seconds=60, waiting_after=15, poll=1.0, clock=time.monotonic, sleep=time.sleep):- log = os.path.join(steam_dir, "logs", "console_log.txt")+def read_from(path, mark):+ """The log since mark (inode, size); all of it when Steam started a new log meanwhile."""+ try:+ st = os.stat(path)+ start = mark[1] if st.st_ino == mark[0] and st.st_size >= mark[1] else 0+ with open(path, "rb") as f:+ f.seek(start)+ return f.read().decode("utf-8", "replace")+ except OSError:+ return ""+++def signed_state(conn):+ """Steam's sign-in state from the last state tag in connection_log.txt: "Logged On", "Logged Off", ..."""try:- start = os.path.getsize(log)+ with open(conn, "rb") as f:+ f.seek(max(0, os.path.getsize(conn) - 20000))+ tail = f.read().decode("utf-8", "replace")except OSError:- start = 0+ return ""+ found = re.findall(r"\] \[(Logged On|Logged Off|Logging On|Logging Off|Connected|Connecting|Disconnected)[,\]]", tail)+ return found[-1] if found else ""+++def mark_of(path):+ try:+ st = os.stat(path)+ return (st.st_ino, st.st_size)+ except OSError:+ return (0, 0)+++def watch(steam_dir, appid, command, seconds=60, waiting_after=15, show=None, signin_after=40,+ poll=1.0, clock=time.monotonic, sleep=time.sleep):+ """Follow one start in Steam's log. Steam's window is brought forward when it waits for the player+ (a question, or its sign-in), since a closed Steam window sits in a tray macOS does not show."""+ log = os.path.join(steam_dir, "logs", "console_log.txt")+ conn = os.path.join(steam_dir, "logs", "connection_log.txt")+ marks = mark_of(log), mark_of(conn)code = subprocess.call(command) if command else 0if code != 0:return codebegun = clock()- since = None+ since, shown = None, False++ def bring():+ nonlocal shown+ if show and not shown:+ shown = True+ try:+ subprocess.call(show, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)+ except (OSError, subprocess.SubprocessError):+ pass+while clock() - begun < seconds:sleep(poll)- try:- with open(log, "rb") as f:- f.seek(start if os.path.getsize(log) >= start else 0)- text = f.read().decode("utf-8", "replace")- except OSError:- continue+ text = read_from(log, marks[0])kind, detail = outcome(text, appid)if kind == "ok":return 0if kind == "error":print("soju: " + message(kind, detail), flush=True)return 3- if kind in ("waiting", "updating"):+ if kind == "waiting":+ since = since or clock()+ if clock() - since >= 3:+ bring()+ if clock() - since >= waiting_after:+ print("soju: " + message(kind, detail), flush=True)+ return 4+ elif kind == "updating":since = since or clock()if clock() - since >= waiting_after:print("soju: " + message(kind, detail), flush=True)return 4else:since = None+ # Nothing for this game yet: Steam holds a start until it is signed in.+ if not kind and clock() - begun >= signin_after and signed_state(conn) not in ("", "Logged On"):+ bring()+ print("soju: " + message("signin", ""), flush=True)+ return 4return 0def main(argv):if len(argv) >= 3 and argv[0] == "watch":command = argv[argv.index("--") + 1:] if "--" in argv else []- return watch(argv[1], argv[2], command)+ 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_STEAM_SHOW")+ return watch(argv[1], argv[2], command, seconds=seconds, show=show.split("\x1f") if show else None)print("usage: steam_launch.py watch <Steam folder> <appid> -- <command>", file=sys.stderr)return 64diff --git a/tests/test_steam_launch.py b/tests/test_steam_launch.pyindex 3340561ce98..581093889eb 100644--- a/tests/test_steam_launch.py+++ b/tests/test_steam_launch.py@@ -47,10 +47,32 @@ class SteamLaunchTests(unittest.TestCase):clock, sleep = fake_time()self.assertEqual(sl.watch(d, "999", [sys.executable, "-c", "pass"], clock=clock, sleep=sleep), 0)+ def test_a_wait_brings_steams_window_forward_and_a_sign_in_is_named(self):+ with tempfile.TemporaryDirectory() as d:+ logs = Path(d) / "logs"+ logs.mkdir()+ (logs / "console_log.txt").write_text("")+ shown = Path(d) / "shown"+ show = [sys.executable, "-c", "open(%r,'w').write('x')" % str(shown)]+ cmd = [sys.executable, "-c", "open(%r,'a').write(%r)" % (str(logs / "console_log.txt"), ASK)]+ clock, sleep = fake_time()+ self.assertEqual(sl.watch(d, "70", cmd, show=show, clock=clock, sleep=sleep), 4)+ self.assertTrue(shown.exists())+ shown.unlink()+ (logs / "connection_log.txt").write_text("[t] [Logged Off, 4, 0] [U:1:1] LogOn() called\n")+ clock, sleep = fake_time()+ self.assertEqual(sl.watch(d, "71", [], show=show, seconds=150, clock=clock, sleep=sleep), 4)+ self.assertTrue(shown.exists())+ # Signed in and simply nothing yet: no message.+ (logs / "connection_log.txt").write_text("[t] [Logged On, 4, 7] [U:1:1] RecvMsgClientLogOnResponse() : processing complete\n")+ clock, sleep = fake_time()+ self.assertEqual(sl.watch(d, "72", [], seconds=150, clock=clock, sleep=sleep), 0)+def test_play_sh_follows_the_start_only_when_steam_is_open(self):text = (ROOT / "scripts/play.sh").read_text()self.assertIn('steam_launch.py" watch', text)self.assertEqual(text.count('${STEAM_WATCH[@]+"${STEAM_WATCH[@]}"}'), 2)+ self.assertEqual(text.count('exec "${STEAM_WATCH[@]}"'), 2) # a cold start, in both Steam modesif __name__ == "__main__":