deadlock-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- deadlock_mcp/__init__.py +3 -0
- deadlock_mcp/__main__.py +3 -0
- deadlock_mcp/assets.py +441 -0
- deadlock_mcp/bridge.py +365 -0
- deadlock_mcp/config.py +181 -0
- deadlock_mcp/consolelog.py +97 -0
- deadlock_mcp/css.py +279 -0
- deadlock_mcp/env.py +56 -0
- deadlock_mcp/errors.py +20 -0
- deadlock_mcp/game.py +184 -0
- deadlock_mcp/js/bridge_main.js +62 -0
- deadlock_mcp/js/core.js +408 -0
- deadlock_mcp/js/request_main.js +159 -0
- deadlock_mcp/layout.py +125 -0
- deadlock_mcp/resource.py +68 -0
- deadlock_mcp/server.py +675 -0
- deadlock_mcp/templates/inbox.vxml_c +0 -0
- deadlock_mcp/templates/script.vjs_c +0 -0
- deadlock_mcp/toolchain.py +220 -0
- deadlock_mcp/vpk.py +126 -0
- deadlock_mcp/watchdog.py +59 -0
- deadlock_mcp-0.1.0.dist-info/METADATA +146 -0
- deadlock_mcp-0.1.0.dist-info/RECORD +27 -0
- deadlock_mcp-0.1.0.dist-info/WHEEL +5 -0
- deadlock_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- deadlock_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
- deadlock_mcp-0.1.0.dist-info/top_level.txt +1 -0
deadlock_mcp/__init__.py
ADDED
deadlock_mcp/__main__.py
ADDED
deadlock_mcp/assets.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
"""Game asset access: list/decompile shipped Panorama files, compile sources via CSDK, mount the addon."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import fcntl
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shlex
|
|
10
|
+
import shutil
|
|
11
|
+
import stat
|
|
12
|
+
import struct
|
|
13
|
+
import tempfile
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from .config import Config
|
|
21
|
+
from .env import desktop_env
|
|
22
|
+
from .errors import AssetError
|
|
23
|
+
from .vpk import VPK, write_vpk
|
|
24
|
+
|
|
25
|
+
COMPILED_EXT = {".xml": ".vxml_c", ".css": ".vcss_c", ".js": ".vjs_c"}
|
|
26
|
+
SOURCE_EXT = {v: k for k, v in COMPILED_EXT.items()}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def winpath(p: Path) -> str:
|
|
30
|
+
return "Z:" + str(p.resolve()).replace("/", "\\")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def _run(cmd: list[str], timeout: float, cwd: Path | None = None, env: dict | None = None) -> tuple[int, str]:
|
|
34
|
+
"""Run a process, capturing output via a temp file and waiting on the process itself (a
|
|
35
|
+
persistent wineserver inherits pipes, so waiting for pipe EOF would hang)."""
|
|
36
|
+
with tempfile.TemporaryFile() as out:
|
|
37
|
+
proc = await asyncio.create_subprocess_exec(
|
|
38
|
+
*cmd, cwd=cwd, env=env, stdin=asyncio.subprocess.DEVNULL, stdout=out, stderr=out
|
|
39
|
+
)
|
|
40
|
+
try:
|
|
41
|
+
await asyncio.wait_for(proc.wait(), timeout)
|
|
42
|
+
except asyncio.TimeoutError:
|
|
43
|
+
proc.kill()
|
|
44
|
+
await proc.wait() # reap it, or it stays a zombie
|
|
45
|
+
raise AssetError(f"timed out after {timeout}s: {' '.join(cmd)}") from None
|
|
46
|
+
out.seek(0)
|
|
47
|
+
return proc.returncode or 0, out.read().decode("utf-8", "replace")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def safe_rel(path: str) -> str:
|
|
53
|
+
"""Validate a user-supplied path and return it as 'panorama/...' (case kept). Leading slashes are
|
|
54
|
+
dropped (paths are relative to the VPK root); anything that could leave the addon trees is rejected."""
|
|
55
|
+
p = path.strip().replace("\\", "/").lstrip("/")
|
|
56
|
+
head, _, rest = p.partition("/")
|
|
57
|
+
p = "panorama/" + rest if head.lower() == "panorama" and rest else "panorama/" + p
|
|
58
|
+
if "\0" in p or ":" in p or any(seg in ("", ".", "..") for seg in p.split("/")):
|
|
59
|
+
raise AssetError(f"invalid path {path!r}: must be a relative path under panorama/ without '..' or empty segments")
|
|
60
|
+
return p
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _open_vpk(path: Path) -> VPK:
|
|
64
|
+
try:
|
|
65
|
+
return VPK(path)
|
|
66
|
+
except (ValueError, struct.error, IndexError, OSError) as e:
|
|
67
|
+
raise AssetError(f"cannot read {path} (corrupt or truncated?): {e}") from None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _atomic_write(path: Path, data: bytes) -> None:
|
|
71
|
+
"""Replace path's contents without ever leaving a truncated file (keeps the file mode)."""
|
|
72
|
+
mode = stat.S_IMODE(path.stat().st_mode) if path.exists() else 0o644
|
|
73
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
|
|
74
|
+
try:
|
|
75
|
+
with os.fdopen(fd, "wb") as f:
|
|
76
|
+
f.write(data)
|
|
77
|
+
f.flush()
|
|
78
|
+
os.fsync(f.fileno())
|
|
79
|
+
os.chmod(tmp, mode)
|
|
80
|
+
os.replace(tmp, path)
|
|
81
|
+
except BaseException:
|
|
82
|
+
Path(tmp).unlink(missing_ok=True)
|
|
83
|
+
raise
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Assets:
|
|
87
|
+
def __init__(self, cfg: Config):
|
|
88
|
+
self.cfg = cfg
|
|
89
|
+
self._vpk: VPK | None = None
|
|
90
|
+
self._compile_lock = asyncio.Lock() # compile_many runs on the event loop; one compile/pack at a time
|
|
91
|
+
self._pack_lock = threading.Lock() # pack_addon is also reached from sync tools in worker threads
|
|
92
|
+
self._wineserver_started: float | None = None
|
|
93
|
+
|
|
94
|
+
# ------------------------------------------------------------------ shipped files
|
|
95
|
+
@property
|
|
96
|
+
def vpk(self) -> VPK:
|
|
97
|
+
"""The game's pak01_dir.vpk, reloaded when the file changes (a game update moves every offset)."""
|
|
98
|
+
path = self.cfg.pak_dir_vpk
|
|
99
|
+
if not path or not path.is_file():
|
|
100
|
+
raise AssetError("Deadlock pak01_dir.vpk not found; set DEADLOCK_DIR")
|
|
101
|
+
st = path.stat()
|
|
102
|
+
if self._vpk is None or self._vpk.stamp != (st.st_mtime_ns, st.st_size):
|
|
103
|
+
self._vpk = _open_vpk(path)
|
|
104
|
+
return self._vpk
|
|
105
|
+
|
|
106
|
+
def list_panorama(self, pattern: str | None = None, limit: int = 300) -> list[str]:
|
|
107
|
+
rx = re.compile(pattern, re.I) if pattern else None
|
|
108
|
+
names = sorted(
|
|
109
|
+
n for n in self.vpk.names()
|
|
110
|
+
if n.startswith("panorama/") and n.endswith((".vxml_c", ".vcss_c", ".vjs_c"))
|
|
111
|
+
)
|
|
112
|
+
if rx:
|
|
113
|
+
names = [n for n in names if rx.search(n)]
|
|
114
|
+
return names[:limit]
|
|
115
|
+
|
|
116
|
+
@staticmethod
|
|
117
|
+
def normalize(path: str) -> str:
|
|
118
|
+
"""Accept 'layout/foo', 'panorama/layout/foo.xml', 'panorama/styles/foo.vcss_c', ...; return VPK name."""
|
|
119
|
+
p = safe_rel(path).lower()
|
|
120
|
+
stem, ext = os.path.splitext(p)
|
|
121
|
+
if ext in COMPILED_EXT:
|
|
122
|
+
return stem + COMPILED_EXT[ext]
|
|
123
|
+
if ext in SOURCE_EXT:
|
|
124
|
+
return p
|
|
125
|
+
kind = p.split("/")[1] if p.count("/") >= 2 else ""
|
|
126
|
+
return p + {"layout": ".vxml_c", "styles": ".vcss_c", "scripts": ".vjs_c"}.get(kind, ".vxml_c")
|
|
127
|
+
|
|
128
|
+
def shipped_crc(self, path: str) -> int:
|
|
129
|
+
"""CRC32 of a shipped file, as recorded in pak01_dir.vpk (identifies the game build's version of it)."""
|
|
130
|
+
name = self.normalize(path)
|
|
131
|
+
vpk = self.vpk
|
|
132
|
+
if name not in vpk:
|
|
133
|
+
raise AssetError(f"{name} is not in pak01_dir.vpk")
|
|
134
|
+
return vpk.crc(name)
|
|
135
|
+
|
|
136
|
+
async def decompile(self, path: str, refresh: bool = False) -> str:
|
|
137
|
+
"""Return decompiled source text for a shipped Panorama file (via Source2Viewer-CLI)."""
|
|
138
|
+
name = self.normalize(path)
|
|
139
|
+
vpk = self.vpk
|
|
140
|
+
if name not in vpk:
|
|
141
|
+
raise AssetError(f"{name} is not in pak01_dir.vpk")
|
|
142
|
+
src_ext = SOURCE_EXT[os.path.splitext(name)[1]]
|
|
143
|
+
stem = os.path.splitext(name)[0]
|
|
144
|
+
# keyed on the shipped CRC, so a game update invalidates it (old un-keyed cache files are never read)
|
|
145
|
+
cache = self.cfg.cache_dir / "decompiled" / f"{stem}.{vpk.crc(name):08x}{src_ext}"
|
|
146
|
+
if cache.is_file() and not refresh:
|
|
147
|
+
return cache.read_text(encoding="utf-8", errors="replace")
|
|
148
|
+
|
|
149
|
+
cli = self.cfg.s2v_cli
|
|
150
|
+
if not cli or not cli.is_file():
|
|
151
|
+
raise AssetError(
|
|
152
|
+
"Source2Viewer-CLI not found. Download cli-linux-x64.zip from "
|
|
153
|
+
"https://github.com/ValveResourceFormat/ValveResourceFormat/releases into tools/s2v/ or set S2V_CLI."
|
|
154
|
+
)
|
|
155
|
+
try:
|
|
156
|
+
data = vpk.read(name)
|
|
157
|
+
except OSError as e:
|
|
158
|
+
raise AssetError(f"cannot read {name} from the game VPKs: {e}") from None
|
|
159
|
+
work = self.cfg.cache_dir / "work" / str(time.time_ns())
|
|
160
|
+
work.mkdir(parents=True)
|
|
161
|
+
try:
|
|
162
|
+
compiled = work / os.path.basename(name)
|
|
163
|
+
compiled.write_bytes(data)
|
|
164
|
+
out_dir = work / "out"
|
|
165
|
+
code, log = await _run([str(cli), "-i", str(compiled), "-o", str(out_dir), "-d"], timeout=120)
|
|
166
|
+
produced = [p for p in out_dir.rglob("*") if p.is_file()] if out_dir.exists() else []
|
|
167
|
+
if not produced and out_dir.is_file():
|
|
168
|
+
produced = [out_dir]
|
|
169
|
+
if code != 0 or not produced:
|
|
170
|
+
raise AssetError(f"Source2Viewer-CLI failed (exit {code}):\n{log[-2000:]}")
|
|
171
|
+
text = produced[0].read_text(encoding="utf-8", errors="replace")
|
|
172
|
+
finally:
|
|
173
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
174
|
+
cache.parent.mkdir(parents=True, exist_ok=True)
|
|
175
|
+
stale = re.compile(re.escape(os.path.basename(stem)) + r"(\.[0-9a-f]{8})?" + re.escape(src_ext))
|
|
176
|
+
for old in cache.parent.iterdir():
|
|
177
|
+
if old != cache and stale.fullmatch(old.name):
|
|
178
|
+
old.unlink(missing_ok=True)
|
|
179
|
+
_atomic_write(cache, text.encode("utf-8"))
|
|
180
|
+
return text
|
|
181
|
+
|
|
182
|
+
# ------------------------------------------------------------------ compiling (CSDK 13)
|
|
183
|
+
@property
|
|
184
|
+
def csdk_content_root(self) -> Path:
|
|
185
|
+
if not self.cfg.csdk_content_dir:
|
|
186
|
+
raise AssetError("CSDK_DIR is not set (path to your CSDK 13 install)")
|
|
187
|
+
return self.cfg.csdk_content_dir
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def csdk_game_root(self) -> Path:
|
|
191
|
+
if not self.cfg.csdk_game_dir:
|
|
192
|
+
raise AssetError("CSDK_DIR is not set (path to your CSDK 13 install)")
|
|
193
|
+
return self.cfg.csdk_game_dir
|
|
194
|
+
|
|
195
|
+
async def _ensure_wineserver(self, env: dict) -> None:
|
|
196
|
+
"""Keep a persistent wineserver so each compile skips Wine start-up (~2.5s → ~1s). Best effort:
|
|
197
|
+
if it fails, compiles still work, just slower."""
|
|
198
|
+
if not self.cfg.wine or (self._wineserver_started is not None
|
|
199
|
+
and time.monotonic() - self._wineserver_started < 500):
|
|
200
|
+
return
|
|
201
|
+
ws = self.cfg.wine.with_name("wineserver")
|
|
202
|
+
if not ws.is_file():
|
|
203
|
+
return
|
|
204
|
+
self._wineserver_started = time.monotonic() # also on failure, so we don't retry every compile
|
|
205
|
+
try:
|
|
206
|
+
await _run([str(ws), "-p", "600"], timeout=30, env=env)
|
|
207
|
+
except (AssetError, OSError):
|
|
208
|
+
pass
|
|
209
|
+
|
|
210
|
+
def _rc_command(self, rc: Path, src: Path) -> tuple[list[str], dict]:
|
|
211
|
+
# desktop_env: under Wine the compiler needs an X display (DISPLAY + XAUTHORITY), which a client that starts
|
|
212
|
+
# the server with a stripped environment doesn't pass on
|
|
213
|
+
env = dict(desktop_env(), WINEDEBUG="-all", WINEPREFIX=str(self.cfg.wineprefix))
|
|
214
|
+
if self.cfg.rc_cmd:
|
|
215
|
+
return shlex.split(self.cfg.rc_cmd.format(rc=rc, src=src, src_win=winpath(src))), env
|
|
216
|
+
if not self.cfg.wine or not self.cfg.wine.is_file():
|
|
217
|
+
raise AssetError("No Proton wine binary found; set DEADLOCK_WINE or DEADLOCK_RC_CMD")
|
|
218
|
+
if not (self.cfg.wineprefix / "system.reg").is_file():
|
|
219
|
+
raise AssetError(
|
|
220
|
+
f"Wine prefix {self.cfg.wineprefix} is not initialised; run setup (or set WINEPREFIX)"
|
|
221
|
+
)
|
|
222
|
+
return [str(self.cfg.wine), str(rc), "-f", "-i", winpath(src)], env
|
|
223
|
+
|
|
224
|
+
async def compile_many(self, files: dict[str, str], install: bool = True, roots: list[str] | None = None) -> dict:
|
|
225
|
+
"""Write Panorama sources ({'panorama/layout/foo.xml': text, ...}) into the CSDK content tree
|
|
226
|
+
and compile them; with install, repack the addon VPK.
|
|
227
|
+
|
|
228
|
+
roots: only invoke the compiler on these sources — resourcecompiler builds the files they
|
|
229
|
+
reference (stylesheets, scripts) itself, saving a ~1s compiler run per dependency."""
|
|
230
|
+
async with self._compile_lock: # concurrent calls would overwrite each other's sources and outputs
|
|
231
|
+
return await self._compile_many(files, install, roots)
|
|
232
|
+
|
|
233
|
+
async def _compile_many(self, files: dict[str, str], install: bool, roots: list[str] | None) -> dict:
|
|
234
|
+
rc = self.cfg.resourcecompiler
|
|
235
|
+
if not rc or not rc.is_file():
|
|
236
|
+
raise AssetError(f"resourcecompiler.exe not found (looked at {rc}); check CSDK_DIR")
|
|
237
|
+
prepared = [] # (source rel, source path, compiled output, output mtime before)
|
|
238
|
+
for rel_source, text in files.items():
|
|
239
|
+
rel = safe_rel(rel_source)
|
|
240
|
+
ext = os.path.splitext(rel)[1].lower()
|
|
241
|
+
if ext not in COMPILED_EXT:
|
|
242
|
+
raise AssetError(f"unsupported source type {ext!r} (use .xml, .css or .js)")
|
|
243
|
+
src = self.csdk_content_root / rel
|
|
244
|
+
out = self.csdk_game_root / (os.path.splitext(rel)[0] + COMPILED_EXT[ext])
|
|
245
|
+
before = out.stat().st_mtime_ns if out.exists() else 0
|
|
246
|
+
src.parent.mkdir(parents=True, exist_ok=True)
|
|
247
|
+
src.write_text(text, encoding="utf-8")
|
|
248
|
+
prepared.append((rel, src, out, before))
|
|
249
|
+
root_set = {safe_rel(r) for r in roots} if roots else None
|
|
250
|
+
if root_set and (unknown := root_set - {rel for rel, *_ in prepared}):
|
|
251
|
+
raise AssetError(f"roots not among the files: {', '.join(sorted(unknown))}")
|
|
252
|
+
results = []
|
|
253
|
+
for rel, src, out, before in prepared:
|
|
254
|
+
if root_set is not None and rel not in root_set:
|
|
255
|
+
continue
|
|
256
|
+
cmd, env = self._rc_command(rc, src)
|
|
257
|
+
await self._ensure_wineserver(env)
|
|
258
|
+
code, log = await _run(cmd, timeout=300, cwd=rc.parent, env=env)
|
|
259
|
+
log = "\n".join(
|
|
260
|
+
l for l in log.splitlines()
|
|
261
|
+
if l.strip() and not re.match(r"(ntsync|Creating render device|PIX|Disable asynchronous|Leaked KeyValues)", l)
|
|
262
|
+
)
|
|
263
|
+
m = re.search(r"(\d+) compiled, (\d+) failed", log)
|
|
264
|
+
ok = bool(m and int(m[1]) >= 1 and int(m[2]) == 0) and out.exists() and out.stat().st_mtime_ns > before
|
|
265
|
+
if not ok:
|
|
266
|
+
errs = [l.strip() for l in log.splitlines()
|
|
267
|
+
if ("COMPILE ERROR" in l or "error" in l.lower() and ":" in l)
|
|
268
|
+
and not l.strip().startswith(("Look for", "ERROR: 0 compiled"))]
|
|
269
|
+
errs = [re.sub(r"^Z:\\.*?\\citadel_addons\\[^\\]+\\", "", e).replace("\\", "/") for e in errs]
|
|
270
|
+
detail = "\n".join(dict.fromkeys(errs)) if errs else log[-4000:]
|
|
271
|
+
if "RenderDeviceMgr" in log:
|
|
272
|
+
raise AssetError(
|
|
273
|
+
f"compile failed for {rel}: resourcecompiler could not open a display. Under Wine it needs an "
|
|
274
|
+
f"X connection: DISPLAY={env.get('DISPLAY')!r}, XAUTHORITY={env.get('XAUTHORITY')!r}. Start the "
|
|
275
|
+
"MCP server from the desktop session, or set DISPLAY and XAUTHORITY (KDE keeps the cookie at "
|
|
276
|
+
f"$XDG_RUNTIME_DIR/xauth_*).\n{detail}")
|
|
277
|
+
raise AssetError(f"compile failed for {rel}:\n{detail}")
|
|
278
|
+
results.append({"source": rel, "compiled": str(out), "log": log[-1500:]})
|
|
279
|
+
# dependencies are built by the roots' compiler runs; a file no root references would silently stay stale
|
|
280
|
+
missing = [rel for rel, _, out, before in prepared if not (out.is_file() and out.stat().st_mtime_ns > before)]
|
|
281
|
+
if missing:
|
|
282
|
+
raise AssetError(f"no fresh compiled output for {', '.join(missing)} (is it referenced from a root?)")
|
|
283
|
+
if root_set is not None:
|
|
284
|
+
results += [{"source": rel, "compiled": str(out), "log": "(built as a dependency)"}
|
|
285
|
+
for rel, _, out, _ in prepared if rel not in root_set]
|
|
286
|
+
res: dict = {"files": results}
|
|
287
|
+
if install:
|
|
288
|
+
res["vpk"] = self.pack_addon()
|
|
289
|
+
return res
|
|
290
|
+
|
|
291
|
+
def addon_files(self) -> dict[str, Path]:
|
|
292
|
+
"""Compiled files in the CSDK addon output dir, keyed by game-relative path."""
|
|
293
|
+
root = self.csdk_game_root
|
|
294
|
+
if not root.is_dir():
|
|
295
|
+
return {}
|
|
296
|
+
return {
|
|
297
|
+
p.relative_to(root).as_posix(): p
|
|
298
|
+
for p in root.rglob("*_c")
|
|
299
|
+
if p.is_file()
|
|
300
|
+
and p.relative_to(root).parts[0] in ("panorama", "resource", "scripts", "materials")
|
|
301
|
+
and not p.name.startswith("mcp_inbox") # request template: never shipped
|
|
302
|
+
and "mcp_live" not in p.relative_to(root).parts # live layouts are loaded loose
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
def cleanup_live(self) -> int:
|
|
306
|
+
"""Delete live-loaded layouts/styles (only safe when the game is not running)."""
|
|
307
|
+
n = 0
|
|
308
|
+
roots = [r for r in (self.cfg.addons_dir, self.cfg.csdk_content_dir, self.cfg.csdk_game_dir) if r]
|
|
309
|
+
for r in roots:
|
|
310
|
+
for kind in ("layout", "styles", "scripts"):
|
|
311
|
+
d = r / "panorama" / kind / "mcp_live"
|
|
312
|
+
if d.is_dir():
|
|
313
|
+
n += sum(1 for _ in d.iterdir())
|
|
314
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
315
|
+
return n
|
|
316
|
+
|
|
317
|
+
def install_loose(self, rel_sources: list[str]) -> list[str]:
|
|
318
|
+
"""Copy compiled outputs for the given sources into the mounted addon dir as loose files
|
|
319
|
+
(for files with names the game's VPKs don't contain, e.g. live layouts)."""
|
|
320
|
+
if not self.cfg.addons_dir:
|
|
321
|
+
raise AssetError("Deadlock dir not found")
|
|
322
|
+
out = []
|
|
323
|
+
for rel in rel_sources:
|
|
324
|
+
rel = safe_rel(rel)
|
|
325
|
+
ext = os.path.splitext(rel)[1].lower()
|
|
326
|
+
if ext not in COMPILED_EXT:
|
|
327
|
+
raise AssetError(f"unsupported source type {ext!r} (use .xml, .css or .js)")
|
|
328
|
+
rel_c = os.path.splitext(rel)[0] + COMPILED_EXT[ext]
|
|
329
|
+
src = self.csdk_game_root / rel_c
|
|
330
|
+
if not src.is_file():
|
|
331
|
+
raise AssetError(f"compiled output {rel_c} not found in {self.csdk_game_root}; compile it first")
|
|
332
|
+
dest = self.cfg.addons_dir / rel_c
|
|
333
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
334
|
+
shutil.copy2(src, dest)
|
|
335
|
+
out.append(str(dest))
|
|
336
|
+
return out
|
|
337
|
+
|
|
338
|
+
def pack_addon(self) -> dict:
|
|
339
|
+
"""(Re)build <mount>/pak01_dir.vpk from all compiled addon files.
|
|
340
|
+
|
|
341
|
+
The engine searches every VPK before any loose directory, so overrides must ship as a VPK."""
|
|
342
|
+
if not self.cfg.addons_dir:
|
|
343
|
+
raise AssetError("Deadlock dir not found")
|
|
344
|
+
with self._pack_lock:
|
|
345
|
+
files = self.addon_files()
|
|
346
|
+
self.cfg.addons_dir.mkdir(parents=True, exist_ok=True)
|
|
347
|
+
dest = self.cfg.addons_dir / "pak01_dir.vpk"
|
|
348
|
+
write_vpk(dest, {rel: p.read_bytes() for rel, p in files.items()})
|
|
349
|
+
return {"vpk": str(dest), "files": sorted(files)}
|
|
350
|
+
|
|
351
|
+
def installed_names(self) -> set[str]:
|
|
352
|
+
"""File names inside the installed addon VPK (empty when there is none)."""
|
|
353
|
+
p = self.cfg.addons_dir / "pak01_dir.vpk" if self.cfg.addons_dir else None
|
|
354
|
+
if not p or not p.is_file():
|
|
355
|
+
return set()
|
|
356
|
+
return set(_open_vpk(p).names())
|
|
357
|
+
|
|
358
|
+
def uninstall_many(self, rel_compiled: Iterable[str]) -> list[str]:
|
|
359
|
+
"""Delete compiled addon files (e.g. 'panorama/styles/hud.vcss_c') and repack once; returns those removed."""
|
|
360
|
+
removed = []
|
|
361
|
+
for rel in [safe_rel(r) for r in rel_compiled]: # validate all before deleting any
|
|
362
|
+
p = self.csdk_game_root / rel
|
|
363
|
+
if p.is_file():
|
|
364
|
+
p.unlink()
|
|
365
|
+
removed.append(rel)
|
|
366
|
+
if removed:
|
|
367
|
+
self.pack_addon()
|
|
368
|
+
return removed
|
|
369
|
+
|
|
370
|
+
def uninstall(self, rel_compiled: str) -> bool:
|
|
371
|
+
return bool(self.uninstall_many([rel_compiled]))
|
|
372
|
+
|
|
373
|
+
# ------------------------------------------------------------------ gameinfo mounting
|
|
374
|
+
BEGIN, END = "// deadlock-mcp begin", "// deadlock-mcp end"
|
|
375
|
+
|
|
376
|
+
def _block_rx(self) -> re.Pattern:
|
|
377
|
+
return re.compile(r"^[ \t]*" + re.escape(self.BEGIN) + r".*?" + re.escape(self.END) + r"[ \t]*\r?\n", re.M | re.S)
|
|
378
|
+
|
|
379
|
+
@staticmethod
|
|
380
|
+
def _read_gameinfo(gi: Path) -> str:
|
|
381
|
+
# surrogateescape + no newline translation: writing it back reproduces every byte we didn't change
|
|
382
|
+
return gi.read_bytes().decode("utf-8", "surrogateescape")
|
|
383
|
+
|
|
384
|
+
@contextmanager
|
|
385
|
+
def _gameinfo_lock(self) -> Iterator[None]:
|
|
386
|
+
"""Inter-process lock: the server and the watchdog process both rewrite gameinfo.gi."""
|
|
387
|
+
self.cfg.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
388
|
+
with open(self.cfg.cache_dir / "gameinfo.lock", "a") as f:
|
|
389
|
+
fcntl.flock(f, fcntl.LOCK_EX)
|
|
390
|
+
try:
|
|
391
|
+
yield
|
|
392
|
+
finally:
|
|
393
|
+
fcntl.flock(f, fcntl.LOCK_UN)
|
|
394
|
+
|
|
395
|
+
def mount_status(self) -> bool:
|
|
396
|
+
gi = self.cfg.gameinfo
|
|
397
|
+
if not (gi and gi.is_file()):
|
|
398
|
+
return False
|
|
399
|
+
m = self._block_rx().search(self._read_gameinfo(gi))
|
|
400
|
+
# an outdated block (e.g. missing a newly configured extra mount) counts as not mounted
|
|
401
|
+
return bool(m and all(p in m[0] for p in [self.cfg.mount_path, *self.cfg.extra_mounts]))
|
|
402
|
+
|
|
403
|
+
def set_mount(self, enable: bool, only_if: Callable[[], bool] | None = None) -> str:
|
|
404
|
+
"""Insert our search path ahead of `Game citadel`. The first Game path normally also becomes
|
|
405
|
+
the MOD and DEFAULT_WRITE_PATH, so pin those back to citadel with explicit Mod/Write keys.
|
|
406
|
+
|
|
407
|
+
Disabling removes only the dev addon: the extra mounts (the standard mod folder) stay, so
|
|
408
|
+
installed mods keep loading in a normal Steam launch.
|
|
409
|
+
|
|
410
|
+
only_if: checked while holding the gameinfo lock; when it returns False nothing is changed
|
|
411
|
+
(lets the watchdog check its launch token and unmount atomically)."""
|
|
412
|
+
gi = self.cfg.gameinfo
|
|
413
|
+
if not gi or not gi.is_file():
|
|
414
|
+
raise AssetError("gameinfo.gi not found")
|
|
415
|
+
with self._gameinfo_lock():
|
|
416
|
+
if only_if is not None and not only_if():
|
|
417
|
+
return "skipped: condition no longer holds; gameinfo.gi left as is"
|
|
418
|
+
original = self._read_gameinfo(gi)
|
|
419
|
+
nl = "\r\n" if "\r\n" in original else "\n"
|
|
420
|
+
text = self._block_rx().sub("", original)
|
|
421
|
+
paths = [self.cfg.mount_path, *self.cfg.extra_mounts] if enable else list(self.cfg.extra_mounts)
|
|
422
|
+
if paths:
|
|
423
|
+
m = re.search(r"^([ \t]*)Game([ \t]+)citadel[ \t]*\r?$", text, re.M)
|
|
424
|
+
if not m:
|
|
425
|
+
raise AssetError("could not find the 'Game citadel' search path in gameinfo.gi")
|
|
426
|
+
ind, sep = m[1], m[2]
|
|
427
|
+
lines = [self.BEGIN, *(f"Game{sep}{p}" for p in paths), f"Mod{sep}citadel", f"Write{sep}citadel", self.END]
|
|
428
|
+
block = "".join(f"{ind}{line}{nl}" for line in lines)
|
|
429
|
+
text = text[: m.start()] + block + text[m.start() :]
|
|
430
|
+
if text == original:
|
|
431
|
+
return f"{self.cfg.mount_path} already {'mounted' if enable else 'unmounted'}"
|
|
432
|
+
backup = gi.with_name("gameinfo.gi.mcp-bak")
|
|
433
|
+
shutil.copy2(gi, backup)
|
|
434
|
+
if enable and self.cfg.addons_dir:
|
|
435
|
+
self.cfg.addons_dir.mkdir(parents=True, exist_ok=True)
|
|
436
|
+
_atomic_write(gi, text.encode("utf-8", "surrogateescape"))
|
|
437
|
+
kept = f"; kept {', '.join(self.cfg.extra_mounts)}" if not enable and self.cfg.extra_mounts else ""
|
|
438
|
+
return (
|
|
439
|
+
f"{'mounted' if enable else 'unmounted'} {self.cfg.mount_path} in gameinfo.gi{kept} "
|
|
440
|
+
f"(previous version saved as {backup.name}). Restart the game to apply."
|
|
441
|
+
)
|