diff --git a/docs/coop.md b/docs/coop.md index aba2febc..ad0c2134 100644 --- a/docs/coop.md +++ b/docs/coop.md @@ -16,9 +16,12 @@ and the time of day are each game's own. the test app Valve gives every account. While co-op is on, Steam shows you as playing Spacewar. Nobody forwards a port on a router and nobody runs a server: the room is a Steam lobby and the games talk through Steam's own network, which finds a direct path between them or relays for them. -- **Steam's library file, `steam_api64.dll`, beside `ocarina.exe`.** NX2navi may not ship that file. Every Steam game - has one in its folder: copy one from a recent game (2021 or later) into the folder of `ocarina.exe`. The Co-op tab - says when the file is missing or too old. The game loads it from that one place only. +- **At least one Steam game from 2021 or later installed** (Windows). Co-op uses Steam's library file, + `steam_api64.dll`, which NX2navi may not ship; every Steam game has one in its folder. The launcher fetches it for + you: each time it starts the game and the file is not beside `ocarina.exe`, it looks through your Steam libraries + for the newest one that Valve signed and that has the calls co-op uses, and copies it there (a second or two, once; + `launcher/steamlib.py`). You can also copy one there yourself. The Co-op tab says when the file is missing or too + old; the game loads it from that one place only. - **The same NX2navi version and game version (1.1.1)** as the others. A game of another version is told so and does not get into the room. diff --git a/docs/launcher.md b/docs/launcher.md index 944e2969..18523dd8 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -65,6 +65,11 @@ Customize Launcher (on the home screen) makes the look the player's own: it is silent until the player's game has been read. Moving the cursor makes no sound. They are played from memory (PlaySound on Windows; `pw-play`, `paplay` or `aplay` elsewhere). +- Steam's library file for co-op (Windows, `launcher/steamlib.py`, [coop.md](coop.md)): before Play and before a start + from the Steam shortcut, when `steam_api64.dll` is not beside the game, the launcher copies one there: one a release + ships in its `bin` folder if it has one, else the newest one in the games of the player's Steam libraries that Valve + signed (WinVerifyTrust and the signer's name) and that has every call `runtime/steam.c` uses. Nothing is downloaded. + With no Steam or no suitable file the game starts as before and co-op says what is missing. - Add to Steam (Windows): the game in the player's Steam library as *The Legend of Zelda Ocarina of Time*, started from there without the launcher's window (`launcher/steam.py`). Its pictures are made from the player's game when the row is selected (`launcher/gameart.py`): Navi as the game's HUD draws her for the icon, the title screen's logo, diff --git a/docs/releases/v0.9.3.md b/docs/releases/v0.9.3.md index 934dcf77..e680af09 100644 --- a/docs/releases/v0.9.3.md +++ b/docs/releases/v0.9.3.md @@ -28,8 +28,9 @@ shows you as playing Spacewar. In a room you see the other players' names where their Link stands (with DLSS, FSR or TAA on), you can chat, and progress is shared: story, chests, doors, items and songs count for everyone, while small keys, rupees, ammunition and hearts stay each player's own. Your save is copied to `coop-backup` in the - profile folder before anything of a room reaches it. It needs Steam running and Steam's library file - `steam_api64.dll` beside `ocarina.exe` (copy one from any recent Steam game's folder; NX2navi may not ship it). Not + profile folder before anything of a room reaches it. It needs Steam running and one Steam game from 2021 or later + installed: co-op uses Steam's library file, `steam_api64.dll`, which NX2navi may not ship, so the launcher copies + it beside the game from your own Steam library when it starts the game. Not yet: the other players as a Link model, shared enemies, and invites that start the game for a friend who has it closed. Everyone needs the same NX2navi version. `docs/coop.md` has the details and how to go back to a save. diff --git a/launcher/steamlib.py b/launcher/steamlib.py new file mode 100644 index 00000000..c18e0b95 --- /dev/null +++ b/launcher/steamlib.py @@ -0,0 +1,231 @@ +"""Steam's library file for co-op, put beside the game so that no player has to fetch it. + +Co-op (runtime/steam.c, docs/coop.md) loads steam_api64.dll from beside ocarina.exe. NX2navi's repository may not hold +that file, so the launcher supplies it on the player's PC: before the game starts, when the file is not there, it takes +one a release shipped in its bin folder, else the newest suitable one of the player's own Steam library (every Steam +game has one in its folder), checks that Valve signed it and that it has the calls the game uses, and copies it. + +"Suitable" is steam.c's list: the manual dispatch calls, the networking messages interface and the lobby calls, which +libraries since 2020 have. The names an exe can import are stored in the file as plain text, so the check is a search +for them. A file that is not signed by Valve (a replacement that makes a game run without Steam) is never taken. + +Windows only: elsewhere ensure() does nothing and co-op says that the file is missing. +""" +import ctypes +import os +import re +import shutil +from pathlib import Path + +NAME = 'steam_api64.dll' +MAX_BYTES = 8 << 20 # the real file is under half a megabyte +SEARCH_DEPTH = 5 # folders below a game's own: Unity keeps the file in _Data/Plugins/x86_64 +MAX_FOLDERS = 60000 # of all libraries together: a search that would take minutes ends without a file + +NEEDS = ( + b'SteamAPI_ManualDispatch_Init', b'SteamAPI_ManualDispatch_RunFrame', b'SteamAPI_ManualDispatch_GetNextCallback', + b'SteamAPI_ManualDispatch_FreeLastCallback', b'SteamAPI_ManualDispatch_GetAPICallResult', b'SteamAPI_GetHSteamPipe', + b'SteamAPI_Shutdown', b'SteamAPI_SteamMatchmaking_v009', b'SteamAPI_SteamNetworkingMessages_SteamAPI_v002', + b'SteamAPI_ISteamNetworkingMessages_SendMessageToUser', b'SteamAPI_ISteamNetworkingMessages_ReceiveMessagesOnChannel', + b'SteamAPI_ISteamMatchmaking_CreateLobby', b'SteamAPI_ISteamMatchmaking_InviteUserToLobby', + b'SteamAPI_ISteamFriends_HasFriend', b'SteamAPI_SteamNetworkingIdentity_SetSteamID64', +) +ONE_OF = ( + (b'SteamAPI_InitFlat', b'SteamAPI_InitSafe', b'SteamAPI_Init'), + (b'SteamAPI_SteamUser_v023', b'SteamAPI_SteamUser_v022', b'SteamAPI_SteamUser_v021', b'SteamAPI_SteamUser_v020'), + (b'SteamAPI_SteamFriends_v018', b'SteamAPI_SteamFriends_v017'), + (b'SteamAPI_SteamUtils_v010', b'SteamAPI_SteamUtils_v009'), +) + + +def suitable(path): + """True when the file is a library with every call runtime/steam.c needs (its NEED list and interface versions).""" + try: + path = Path(path) + if not path.is_file() or path.stat().st_size > MAX_BYTES: + return False + data = path.read_bytes() + except OSError: + return False + if data[:2] != b'MZ': + return False + + def has(name): + return b'\0' + name + b'\0' in data + + return all(has(n) for n in NEEDS) and all(any(has(n) for n in group) for group in ONE_OF) + + +def signed_by_valve(path): + """True when Windows finds the file's signature valid and its signer is Valve.""" + if os.name != 'nt': + return False + try: + return _trusted(str(path)) and 'valve' in _signer(str(path)).lower() + except (OSError, ValueError, AttributeError): + return False + + +def _trusted(path): + from ctypes import wintypes + + class Guid(ctypes.Structure): + _fields_ = [('a', wintypes.DWORD), ('b', wintypes.WORD), ('c', wintypes.WORD), ('d', ctypes.c_ubyte * 8)] + + class FileInfo(ctypes.Structure): + _fields_ = [('size', wintypes.DWORD), ('path', wintypes.LPCWSTR), ('file', wintypes.HANDLE), ('subject', ctypes.c_void_p)] + + class Data(ctypes.Structure): + _fields_ = [('size', wintypes.DWORD), ('policy', ctypes.c_void_p), ('sip', ctypes.c_void_p), ('ui', wintypes.DWORD), + ('revocation', wintypes.DWORD), ('union', wintypes.DWORD), ('info', ctypes.POINTER(FileInfo)), + ('action', wintypes.DWORD), ('state', wintypes.HANDLE), ('url', wintypes.LPCWSTR), + ('flags', wintypes.DWORD), ('context', wintypes.DWORD), ('settings', ctypes.c_void_p)] + + # WINTRUST_ACTION_GENERIC_VERIFY_V2 + action = Guid(0x00AAC56B, 0xCD44, 0x11D0, (ctypes.c_ubyte * 8)(0x8C, 0xC2, 0x00, 0xC0, 0x4F, 0xC2, 0x95, 0xEE)) + info = FileInfo(ctypes.sizeof(FileInfo), path, None, None) + # no window (ui 2), the whole chain's revocation is not asked from the network (0), a file (1), verify (1), and + # the cache only for revocation (flags 0x1000): a start of the game never waits for the internet + data = Data(ctypes.sizeof(Data), None, None, 2, 0, 1, ctypes.pointer(info), 1, None, None, 0x1000, 0, None) + verify = ctypes.windll.wintrust.WinVerifyTrust + verify.argtypes = [wintypes.HWND, ctypes.POINTER(Guid), ctypes.POINTER(Data)] + verify.restype = ctypes.c_long + ok = verify(None, ctypes.byref(action), ctypes.byref(data)) == 0 + data.action = 2 # close: frees what the verification kept + verify(None, ctypes.byref(action), ctypes.byref(data)) + return ok + + +def _signer(path): + """The name on the certificate that signed the file, '' when it has none.""" + from ctypes import wintypes + crypt = ctypes.windll.crypt32 + store, msg = wintypes.HANDLE(), wintypes.HANDLE() + crypt.CryptQueryObject.argtypes = [wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(wintypes.HANDLE), + ctypes.POINTER(wintypes.HANDLE), ctypes.c_void_p] + crypt.CryptQueryObject.restype = wintypes.BOOL + name = ctypes.create_unicode_buffer(path) + # a file (1), a signature embedded in it (1 << 10), binary (1 << 1) + if not crypt.CryptQueryObject(1, name, 1 << 10, 1 << 1, 0, None, None, None, ctypes.byref(store), ctypes.byref(msg), None): + return '' + try: + crypt.CryptMsgGetParam.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + ctypes.POINTER(wintypes.DWORD)] + crypt.CryptMsgGetParam.restype = wintypes.BOOL + size = wintypes.DWORD(0) + if not crypt.CryptMsgGetParam(msg, 7, 0, None, ctypes.byref(size)): # CMSG_SIGNER_CERT_INFO_PARAM + return '' + info = ctypes.create_string_buffer(size.value) + if not crypt.CryptMsgGetParam(msg, 7, 0, info, ctypes.byref(size)): + return '' + crypt.CertFindCertificateInStore.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, + ctypes.c_void_p, ctypes.c_void_p] + crypt.CertFindCertificateInStore.restype = ctypes.c_void_p + # X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, CERT_FIND_SUBJECT_CERT + cert = crypt.CertFindCertificateInStore(store, 0x10001, 0, 11 << 16, info, None) + if not cert: + return '' + try: + crypt.CertGetNameStringW.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.LPWSTR, wintypes.DWORD] + crypt.CertGetNameStringW.restype = wintypes.DWORD + out = ctypes.create_unicode_buffer(256) + crypt.CertGetNameStringW(cert, 4, 0, None, out, 256) # CERT_NAME_SIMPLE_DISPLAY_TYPE + return out.value + finally: + crypt.CertFreeCertificateContext.argtypes = [ctypes.c_void_p] + crypt.CertFreeCertificateContext(cert) + finally: + crypt.CryptMsgClose.argtypes = [wintypes.HANDLE] + crypt.CryptMsgClose(msg) + crypt.CertCloseStore.argtypes = [wintypes.HANDLE, wintypes.DWORD] + crypt.CertCloseStore(store, 0) + + +def libraries(steam_folder): + """The steamapps folders of the player's Steam libraries: Steam's own and those libraryfolders.vdf lists.""" + steam_folder = Path(steam_folder) + out = [steam_folder / 'steamapps'] + try: + text = (steam_folder / 'steamapps' / 'libraryfolders.vdf').read_text(encoding='utf-8', errors='replace') + for raw in re.findall(r'"path"\s+"([^"]+)"', text): + out.append(Path(raw.replace('\\\\', '\\')) / 'steamapps') + except OSError: + pass + seen, unique = set(), [] + for p in out: + key = os.path.normcase(os.path.abspath(str(p))) + if key not in seen and p.is_dir(): + seen.add(key) + unique.append(p) + return unique + + +def candidates(steam_folder): + """Every steam_api64.dll in the games of the player's libraries, the newest file first.""" + found, budget = [], [MAX_FOLDERS] + + def walk(folder, depth): + if budget[0] <= 0: + return + budget[0] -= 1 + try: + entries = list(os.scandir(folder)) + except OSError: + return + for e in entries: + try: + if e.is_file(follow_symlinks=False): + if e.name.lower() == NAME: + found.append((e.stat().st_mtime, e.path)) + elif depth < SEARCH_DEPTH and e.is_dir(follow_symlinks=False): + walk(e.path, depth + 1) + except OSError: + continue + + for lib in libraries(steam_folder): + walk(lib / 'common', 0) + return [Path(p) for _, p in sorted(found, reverse=True)] + + +def find(steam_folder, signed=signed_by_valve): + """The newest suitable library of the player's Steam games that Valve signed; None when there is none.""" + for path in candidates(steam_folder): + if suitable(path) and signed(path): + return path + return None + + +_none = set() # game folders for which this run of the launcher found no library: not searched again at each Play + + +def ensure(game_dir, kit_bin=None, steam_folder=None, log=print, signed=signed_by_valve): + """Puts the library beside the game when it is not there. 'there', 'copied' or 'none' (no Steam, or no game of + the player's library has a suitable one). Never raises: co-op then says that the file is missing. The search of + the Steam library takes a second or two, once: a folder that got none is not searched again by this process.""" + try: + dst = Path(game_dir) / NAME + if suitable(dst): + return 'there' + if str(dst) in _none: + return 'none' + shipped = Path(kit_bin) / NAME if kit_bin else None + src = shipped if shipped is not None and suitable(shipped) and signed(shipped) else None + if src is None and os.name == 'nt': + if steam_folder is None: + from . import steam + at = steam.find_steam() + steam_folder = at[0] if at else None + src = find(steam_folder, signed) if steam_folder else None + if src is None: + log("co-op: no suitable steam_api64.dll (Steam's library file) was found for the game: co-op needs Steam " + 'installed with at least one game from 2021 or later') + _none.add(str(dst)) + return 'none' + shutil.copyfile(src, dst) + log(f"co-op: Steam's library file was copied beside the game from {src.parent}") + return 'copied' + except OSError as e: + log(f"co-op: Steam's library file could not be put beside the game: {e}") + return 'none' diff --git a/launcher/ui/app.py b/launcher/ui/app.py index 87bad706..f04cba67 100644 --- a/launcher/ui/app.py +++ b/launcher/ui/app.py @@ -37,7 +37,7 @@ import tkinter.font as tkfont from pathlib import Path from tkinter import filedialog -from .. import NAME, build, feed, gameini, gamefiles, jobs, mods, saves, steam, versions, winsys +from .. import NAME, build, feed, gameini, gamefiles, jobs, mods, saves, steam, steamlib, versions, winsys from ..context import Context from . import art, picture, sound @@ -1862,6 +1862,7 @@ class App: return if waiting: self.ctx.log(f'play: without the code of {", ".join(waiting)}, whose build did not finish') + steamlib.ensure(gd, self.ctx.layout.app / 'bin', log=self.ctx.log) # co-op's Steam library file, beside the game try: self.game_proc = winsys.start_game(exe) except OSError as e: @@ -2718,6 +2719,7 @@ def play_only(ctx): if waiting: # the window builds the mods' code in, then starts the game (App.start with --play) ctx.log(f'play from Steam: the game is built again first for the code of {", ".join(waiting)}') return None + steamlib.ensure(gd, ctx.layout.app / 'bin', log=ctx.log) # co-op's Steam library file, beside the game try: proc = winsys.start_game(exe) except OSError as e: diff --git a/nx2navi.ini.example b/nx2navi.ini.example index 9f393cef..3c703aca 100644 --- a/nx2navi.ini.example +++ b/nx2navi.ini.example @@ -640,7 +640,8 @@ [coop] # Co-op, experimental: play with friends over Steam, each in their own game and save (docs/coop.md). The game signs in # to Steam as its test app, so Steam shows you as playing Spacewar; it needs Steam running and Steam's library file -# steam_api64.dll beside ocarina.exe. Rooms are made and joined in the menu's Co-op tab, never from this file. +# steam_api64.dll beside ocarina.exe, which the launcher copies there from a Steam game you have installed. Rooms are +# made and joined in the menu's Co-op tab, never from this file. # 0 = off, the game uses no network. Takes effect at once. # coop = 0 # In a room, share progress, items and songs with the other players; your save is copied to coop-backup in the profile diff --git a/runtime/steam.h b/runtime/steam.h index fdca12d1..44bc4661 100644 --- a/runtime/steam.h +++ b/runtime/steam.h @@ -4,8 +4,9 @@ // playing that app. // // The Steamworks library is not part of NX2navi and is never in its repository. steam.c declares the functions it -// calls itself and loads steam_api64.dll from beside the game at run time; without the file, or without a running -// Steam client that is signed in, steam_start fails and says why. +// calls itself and loads steam_api64.dll from beside the game at run time (the launcher copies one there from a +// Steam game the player has, launcher/steamlib.py); without the file, or without a running Steam client that is +// signed in, steam_start fails and says why. // // Every function here is called from one thread (the co-op thread, coop.c): the library is used single-threaded. #pragma once diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 0389e73c..14b0ccd6 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -648,9 +648,12 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_COOP_ON] = "Co-op (experimental)", [UI_MENU_COOP_ON_DESC] = "Play with friends over Steam, each in their own game and save. Nobody sets up a router: rooms " "and invites go through Steam, which shows you as playing Spacewar, its test app. Needs Steam " - "running and its library file steam_api64.dll beside the game. Off: the game uses no network.", - [UI_MENU_COOP_NO_LIBRARY] = "Steam's library file, steam_api64.dll, is not beside the game. Copy one from any Steam game's " - "folder into the folder of ocarina.exe, then choose Look for Steam again.", + "running; the launcher takes Steam's library file from a Steam game you have installed. Off: the " + "game uses no network.", + [UI_MENU_COOP_NO_LIBRARY] = "Steam's library file, steam_api64.dll, is not beside the game. The launcher puts it there when " + "it starts the game, from a Steam game you have installed: start the game from the launcher, with " + "Steam and at least one game from 2021 or later installed. You can also copy the file yourself " + "from a Steam game's folder into the folder of ocarina.exe.", [UI_MENU_COOP_OLD_LIBRARY] = "The steam_api64.dll beside the game is too old for co-op. Replace it with one from a newer Steam " "game.", [UI_MENU_COOP_NO_CLIENT] = "Steam did not answer. Start Steam and sign in, then choose Look for Steam again.", @@ -1292,10 +1295,12 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_COOP_ON] = "Кооператив (эксперимент)", [UI_MENU_COOP_ON_DESC] = "Играйте с друзьями через Steam, каждый в своей игре и со своим сохранением. Настраивать роутер " "не нужно: комнаты и приглашения идут через Steam, который показывает, что вы играете в Spacewar, " - "его тестовое приложение. Нужны запущенный Steam и файл его библиотеки steam_api64.dll рядом с " - "игрой. Выкл.: игра не использует сеть.", - [UI_MENU_COOP_NO_LIBRARY] = "Файла библиотеки Steam, steam_api64.dll, нет рядом с игрой. Скопируйте его из папки любой игры " - "Steam в папку с ocarina.exe и выберите «Искать Steam снова».", + "его тестовое приложение. Нужен запущенный Steam; файл его библиотеки лаунчер берёт из " + "установленной у вас игры Steam. Выкл.: игра не использует сеть.", + [UI_MENU_COOP_NO_LIBRARY] = "Файла библиотеки Steam, steam_api64.dll, нет рядом с игрой. Лаунчер кладёт его туда при запуске " + "игры, из установленной у вас игры Steam: запустите игру из лаунчера при установленном Steam и " + "хотя бы одной игре 2021 года или новее. Можно и самому скопировать файл из папки любой игры " + "Steam в папку с ocarina.exe.", [UI_MENU_COOP_OLD_LIBRARY] = "Файл steam_api64.dll рядом с игрой слишком старый для кооператива. Замените его файлом из более " "новой игры Steam.", [UI_MENU_COOP_NO_CLIENT] = "Steam не ответил. Запустите Steam, войдите в аккаунт и выберите «Искать Steam снова».", @@ -1922,10 +1927,12 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_COOP_ON] = "Co-op (experimental)", [UI_MENU_COOP_ON_DESC] = "Jogue com amigos pela Steam, cada um no seu jogo e no seu save. Ninguém configura roteador: " "salas e convites passam pela Steam, que mostra você jogando Spacewar, o app de teste dela. " - "Precisa da Steam aberta e do arquivo steam_api64.dll ao lado do jogo. Desligado: o jogo não usa " - "a rede.", - [UI_MENU_COOP_NO_LIBRARY] = "O arquivo da biblioteca da Steam, steam_api64.dll, não está ao lado do jogo. Copie um da pasta " - "de qualquer jogo da Steam para a pasta do ocarina.exe e escolha Procurar a Steam de novo.", + "Precisa da Steam aberta; o launcher pega o arquivo da biblioteca da Steam de um jogo da Steam " + "que você tem instalado. Desligado: o jogo não usa a rede.", + [UI_MENU_COOP_NO_LIBRARY] = "O arquivo da biblioteca da Steam, steam_api64.dll, não está ao lado do jogo. O launcher o coloca " + "lá ao iniciar o jogo, a partir de um jogo da Steam que você tem instalado: inicie o jogo pelo " + "launcher, com a Steam e pelo menos um jogo de 2021 ou mais novo instalados. Você também pode " + "copiar o arquivo da pasta de um jogo da Steam para a pasta do ocarina.exe.", [UI_MENU_COOP_OLD_LIBRARY] = "O steam_api64.dll ao lado do jogo é antigo demais para o co-op. Troque por um de um jogo mais " "novo da Steam.", [UI_MENU_COOP_NO_CLIENT] = "A Steam não respondeu. Abra a Steam, entre na sua conta e escolha Procurar a Steam de novo.", @@ -2641,8 +2648,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_TAB_COOP] = "合作", [UI_MENU_COOP_ON] = "合作(实验性)", [UI_MENU_COOP_ON_DESC] = "通过 Steam 与朋友一起玩,各自运行自己的游戏和存档。无需设置路由器:房间和邀请都经由 Steam,Steam 会显示你正在玩它的测试应用 Spacewar。需要 Steam " - "正在运行,并且游戏旁边有它的库文件 steam_api64.dll。关闭:游戏不使用网络。", - [UI_MENU_COOP_NO_LIBRARY] = "游戏旁边没有 Steam 的库文件 steam_api64.dll。从任意 Steam 游戏的文件夹里复制一个到 ocarina.exe 所在的文件夹,然后选择“重新查找 Steam”。", + "正在运行;启动器会从你已安装的 Steam 游戏里取得 Steam 的库文件。关闭:游戏不使用网络。", + [UI_MENU_COOP_NO_LIBRARY] = "游戏旁边没有 Steam 的库文件 steam_api64.dll。启动器在启动游戏时会从你已安装的 Steam 游戏里把它放到那里:请在安装了 Steam 和至少一款 2021 " + "年或更新的游戏的情况下,从启动器启动游戏。你也可以自己从某个 Steam 游戏的文件夹里把这个文件复制到 ocarina.exe 所在的文件夹。", [UI_MENU_COOP_OLD_LIBRARY] = "游戏旁边的 steam_api64.dll 对合作模式来说太旧。请换成较新的 Steam 游戏里的那个文件。", [UI_MENU_COOP_NO_CLIENT] = "Steam 没有响应。请启动 Steam 并登录,然后选择“重新查找 Steam”。", [UI_MENU_COOP_RETRY] = "重新查找 Steam", diff --git a/tests/launcher_test.py b/tests/launcher_test.py index 18060972..36d43ca4 100644 --- a/tests/launcher_test.py +++ b/tests/launcher_test.py @@ -49,7 +49,7 @@ ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / 'tools')) -from launcher import build, feed, gameini, gamefiles, jobs, net, saves, settings, toolchain, updater, versions, winsys # noqa: E402 +from launcher import build, feed, gameini, gamefiles, jobs, net, saves, settings, steamlib, toolchain, updater, versions, winsys # noqa: E402 from launcher.context import Context # noqa: E402 from launcher.paths import Layout # noqa: E402 @@ -4502,6 +4502,92 @@ def have_display(): @unittest.skipUnless(have_display(), 'needs tkinter, numpy and a display') +class SteamLibTest(Tmp): + """launcher/steamlib.py: Steam's library file for co-op, found in the player's Steam library and put beside the + game. The files here are made up: the bytes a library's exported names leave in it, no code.""" + + def lib(self, path, old=False, mtime=None): + names = list(steamlib.NEEDS) + [group[-1] for group in steamlib.ONE_OF] + if old: # a library from before the networking messages interface + names = [n for n in names if b'NetworkingMessages' not in n] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'MZ' + bytes(64) + b'\x00'.join(names) + b'\x00') + if mtime: + os.utime(path, (mtime, mtime)) + return path + + def steam(self): + """A Steam folder with a second library elsewhere, as libraryfolders.vdf lists it (backslashes doubled).""" + steam = self.tmp / 'Steam' + other = self.tmp / 'Games Drive' / 'SteamLibrary' + (steam / 'steamapps' / 'common').mkdir(parents=True) + (other / 'steamapps' / 'common').mkdir(parents=True) + one = chr(92) + rows = ''.join('\t"%d"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n' % (i, str(p).replace(one, one + one)) + for i, p in enumerate((steam, other))) + (steam / 'steamapps' / 'libraryfolders.vdf').write_text('"libraryfolders"\n{\n' + rows + '}\n', encoding='utf-8') + return steam, other + + def test_a_library_is_suitable_only_with_every_call_co_op_uses(self): + self.assertTrue(steamlib.suitable(self.lib(self.tmp / 'a' / steamlib.NAME))) + self.assertFalse(steamlib.suitable(self.lib(self.tmp / 'b' / steamlib.NAME, old=True))) + (self.tmp / 'c').mkdir() + (self.tmp / 'c' / steamlib.NAME).write_bytes(b'not a library at all') + self.assertFalse(steamlib.suitable(self.tmp / 'c' / steamlib.NAME)) + self.assertFalse(steamlib.suitable(self.tmp / 'missing' / steamlib.NAME)) + + def test_the_newest_suitable_signed_library_of_any_steam_library_is_found(self): + steam, other = self.steam() + now = time.time() + self.lib(steam / 'steamapps' / 'common' / 'Old Game' / steamlib.NAME, old=True, mtime=now) + mid = self.lib(steam / 'steamapps' / 'common' / 'Mid Game' / 'bin' / steamlib.NAME, mtime=now - 5000) + new = self.lib(other / 'steamapps' / 'common' / 'Unity Game' / 'Game_Data' / 'Plugins' / 'x86_64' / steamlib.NAME, + mtime=now - 100) + unsigned = self.lib(other / 'steamapps' / 'common' / 'Replaced' / steamlib.NAME, mtime=now - 10) + self.lib(other / 'steamapps' / 'common' / 'Deep' / 'a' / 'b' / 'c' / 'd' / 'e' / 'f' / steamlib.NAME, mtime=now) + self.assertEqual([p.parent.name for p in steamlib.libraries(steam)], ['Steam', 'SteamLibrary']) + self.assertEqual(steamlib.find(steam, lambda p: Path(p) != unsigned), new) # not the old, unsigned or too deep one + self.assertEqual(steamlib.find(steam, lambda p: Path(p) == mid), mid) + self.assertIsNone(steamlib.find(steam, lambda p: False)) + self.assertIsNone(steamlib.find(self.tmp / 'no steam here', lambda p: True)) + + def test_the_library_is_put_beside_the_game_once(self): + steam, other = self.steam() + src = self.lib(other / 'steamapps' / 'common' / 'Some Game' / steamlib.NAME) + game = self.tmp / 'game' + game.mkdir() + lines = [] + self.assertEqual(steamlib.ensure(game, None, steam, lines.append, lambda p: True), 'copied') + self.assertEqual((game / steamlib.NAME).read_bytes(), src.read_bytes()) + self.assertIn('Some Game', lines[-1]) + self.assertEqual(steamlib.ensure(game, None, self.tmp / 'gone', lines.append, lambda p: False), 'there') + # a file beside the game that is not a library co-op can use is replaced + (game / steamlib.NAME).write_bytes(b'MZ old') + self.assertEqual(steamlib.ensure(game, None, steam, lines.append, lambda p: True), 'copied') + self.assertTrue(steamlib.suitable(game / steamlib.NAME)) + + def test_a_library_the_release_ships_comes_first_and_none_is_said_once(self): + steam, other = self.steam() + kit_bin = self.tmp / 'kit' / 'bin' + shipped = self.lib(kit_bin / steamlib.NAME) + shipped.write_bytes(shipped.read_bytes() + b'shipped') + self.lib(other / 'steamapps' / 'common' / 'Some Game' / steamlib.NAME) + game = self.tmp / 'game' + game.mkdir() + self.assertEqual(steamlib.ensure(game, kit_bin, steam, lambda line: None, lambda p: True), 'copied') + self.assertTrue((game / steamlib.NAME).read_bytes().endswith(b'shipped')) + # nothing suitable anywhere: said in the log once, and not searched again by this process + empty = self.tmp / 'empty game' + empty.mkdir() + lines = [] + nothing = self.tmp / 'Steam without games' + (nothing / 'steamapps' / 'common').mkdir(parents=True) + self.assertEqual(steamlib.ensure(empty, None, nothing, lines.append, lambda p: True), 'none') + self.assertEqual(steamlib.ensure(empty, None, steam, lines.append, lambda p: True), 'none') + self.assertEqual(len(lines), 1) + self.assertFalse((empty / steamlib.NAME).exists()) + + class SteamTest(Tmp): """launcher/steam.py on made-up Steam files: the binary shortcuts file read and written back unchanged, our shortcut added beside another and updated in place, its id as Steam computes it, the accounts that signed in."""