aboutsummarylogtreecommitdiffstats
path: root/minecraft-bedrock-steam-shortcut.py
blob: 33535791af04dce542d04151979d8a57d1b33c11 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#!/usr/bin/env python
"""Add, update, or remove the Minecraft Bedrock non-Steam shortcut."""

from __future__ import annotations

import argparse
import binascii
import os
from collections import OrderedDict
from datetime import datetime
from pathlib import Path
import shutil
import struct
import sys
from typing import Any


TYPE_OBJECT = 0
TYPE_STRING = 1
TYPE_INT32 = 2
TYPE_FLOAT32 = 3
TYPE_UINT64 = 7
TYPE_END = 8


class VdfError(RuntimeError):
    pass


class Int32(int):
    pass


class UInt64(int):
    pass


class Float32(float):
    pass


def read_cstring(data: bytes, offset: int) -> tuple[str, int]:
    end = data.find(b"\x00", offset)
    if end < 0:
        raise VdfError("unterminated string in shortcuts.vdf")
    return data[offset:end].decode("utf-8", errors="replace"), end + 1


def parse_object(data: bytes, offset: int = 0) -> tuple[OrderedDict[str, Any], int]:
    obj: OrderedDict[str, Any] = OrderedDict()

    while offset < len(data):
        value_type = data[offset]
        offset += 1

        if value_type == TYPE_END:
            return obj, offset

        key, offset = read_cstring(data, offset)

        if value_type == TYPE_OBJECT:
            value, offset = parse_object(data, offset)
        elif value_type == TYPE_STRING:
            value, offset = read_cstring(data, offset)
        elif value_type == TYPE_INT32:
            if offset + 4 > len(data):
                raise VdfError("truncated int32 in shortcuts.vdf")
            value = Int32(struct.unpack_from("<I", data, offset)[0])
            offset += 4
        elif value_type == TYPE_FLOAT32:
            if offset + 4 > len(data):
                raise VdfError("truncated float32 in shortcuts.vdf")
            value = Float32(struct.unpack_from("<f", data, offset)[0])
            offset += 4
        elif value_type == TYPE_UINT64:
            if offset + 8 > len(data):
                raise VdfError("truncated uint64 in shortcuts.vdf")
            value = UInt64(struct.unpack_from("<Q", data, offset)[0])
            offset += 8
        else:
            raise VdfError(f"unsupported binary VDF type {value_type} for key {key!r}")

        obj[key] = value

    raise VdfError("shortcuts.vdf ended before object terminator")


def write_cstring(output: bytearray, value: str) -> None:
    output.extend(value.encode("utf-8"))
    output.append(0)


def write_object(output: bytearray, obj: OrderedDict[str, Any] | dict[str, Any]) -> None:
    for key, value in obj.items():
        if isinstance(value, (OrderedDict, dict)):
            output.append(TYPE_OBJECT)
            write_cstring(output, key)
            write_object(output, value)
        elif isinstance(value, str):
            output.append(TYPE_STRING)
            write_cstring(output, key)
            write_cstring(output, value)
        elif isinstance(value, UInt64):
            output.append(TYPE_UINT64)
            write_cstring(output, key)
            output.extend(struct.pack("<Q", int(value) & 0xFFFFFFFFFFFFFFFF))
        elif isinstance(value, Float32):
            output.append(TYPE_FLOAT32)
            write_cstring(output, key)
            output.extend(struct.pack("<f", float(value)))
        elif isinstance(value, int):
            output.append(TYPE_INT32)
            write_cstring(output, key)
            output.extend(struct.pack("<I", int(value) & 0xFFFFFFFF))
        else:
            raise TypeError(f"cannot write {type(value).__name__} value for {key!r}")

    output.append(TYPE_END)


def load_vdf(path: Path) -> OrderedDict[str, Any]:
    if not path.exists() or path.stat().st_size == 0:
        return OrderedDict([("shortcuts", OrderedDict())])

    root, offset = parse_object(path.read_bytes())
    if offset != path.stat().st_size:
        trailing = path.stat().st_size - offset
        if trailing > 0:
            raise VdfError(f"shortcuts.vdf has {trailing} trailing bytes")

    shortcuts = root.get("shortcuts")
    if not isinstance(shortcuts, OrderedDict):
        root["shortcuts"] = OrderedDict()
    return root


def dump_vdf(root: OrderedDict[str, Any]) -> bytes:
    output = bytearray()
    write_object(output, root)
    return bytes(output)


def steam_quote(value: str | Path) -> str:
    text = str(value)
    if text.startswith('"') and text.endswith('"'):
        return text
    return f'"{text}"'


def steam_unquote(value: Any) -> str:
    if not isinstance(value, str):
        return ""
    return value.strip('"')


def shortcut_appid(exe: str, app_name: str) -> Int32:
    checksum = binascii.crc32((exe + app_name).encode("utf-8"))
    return Int32((checksum | 0x80000000) & 0xFFFFFFFF)


def normalize_path(value: str) -> str:
    return os.path.normcase(os.path.normpath(value))


def shortcut_tags(tags: list[str]) -> OrderedDict[str, str]:
    deduped = list(dict.fromkeys(tag for tag in tags if tag))
    return OrderedDict((str(index), tag) for index, tag in enumerate(deduped))


def build_shortcut(args: argparse.Namespace) -> OrderedDict[str, Any]:
    exe = steam_quote(Path(args.exe).expanduser().resolve())
    start_dir = steam_quote(Path(args.start_dir).expanduser().resolve())
    icon = str(Path(args.icon).expanduser().resolve()) if args.icon else ""

    return OrderedDict(
        [
            ("appid", shortcut_appid(exe, args.name)),
            ("AppName", args.name),
            ("Exe", exe),
            ("StartDir", start_dir),
            ("icon", icon),
            ("ShortcutPath", ""),
            ("LaunchOptions", args.launch_options),
            ("IsHidden", Int32(0)),
            ("AllowDesktopConfig", Int32(1)),
            ("AllowOverlay", Int32(1)),
            ("OpenVR", Int32(0)),
            ("Devkit", Int32(0)),
            ("DevkitGameID", ""),
            ("DevkitOverrideAppID", Int32(0)),
            ("LastPlayTime", Int32(0)),
            ("FlatpakAppID", ""),
            ("tags", shortcut_tags(args.tag)),
        ]
    )


def find_steam_root(explicit: str | None) -> Path:
    candidates: list[Path] = []
    if explicit:
        candidates.append(Path(explicit))
    for env_name in ("STEAM_COMPAT_CLIENT_INSTALL_PATH", "STEAM_ROOT"):
        env_value = os.environ.get(env_name)
        if env_value:
            candidates.append(Path(env_value))
    candidates.extend(
        [
            Path.home() / ".steam/root",
            Path.home() / ".local/share/Steam",
            Path.home() / ".var/app/com.valvesoftware.Steam/.local/share/Steam",
        ]
    )

    for candidate in candidates:
        root = candidate.expanduser().resolve()
        if (root / "userdata").is_dir() or (root / "steamapps").is_dir():
            return root

    raise SystemExit("Steam root not found")


def select_userdata(steam_root: Path, user_id: str | None) -> Path:
    userdata_root = steam_root / "userdata"
    if user_id:
        selected = userdata_root / user_id
        if not selected.is_dir():
            raise SystemExit(f"Steam userdata id not found: {user_id}")
        return selected

    users = sorted(path for path in userdata_root.iterdir() if path.is_dir() and path.name.isdigit())
    if not users:
        raise SystemExit(f"No Steam userdata directories found in {userdata_root}")
    if len(users) == 1:
        return users[0]

    def recency(path: Path) -> float:
        config = path / "config/localconfig.vdf"
        try:
            return config.stat().st_mtime
        except FileNotFoundError:
            return path.stat().st_mtime

    selected = max(users, key=recency)
    print(
        f"warning: multiple Steam users found; selected {selected.name}. "
        "Set MINECRAFT_BEDROCK_STEAM_USER_ID or pass --user-id to override.",
        file=sys.stderr,
    )
    return selected


def steam_running() -> bool:
    proc = Path("/proc")
    if not proc.is_dir():
        return False

    for path in proc.iterdir():
        if not path.name.isdigit():
            continue
        try:
            comm = (path / "comm").read_text(encoding="utf-8").strip()
        except OSError:
            continue
        if comm in {"steam", "steamwebhelper"}:
            return True
    return False


def ordered_shortcuts(shortcuts_obj: OrderedDict[str, Any]) -> list[OrderedDict[str, Any]]:
    def key_index(item: tuple[str, Any]) -> int:
        key, _value = item
        return int(key) if key.isdigit() else 999999

    shortcuts: list[OrderedDict[str, Any]] = []
    for _key, value in sorted(shortcuts_obj.items(), key=key_index):
        if isinstance(value, OrderedDict):
            shortcuts.append(value)
    return shortcuts


def add_shortcut(args: argparse.Namespace) -> None:
    steam_root = find_steam_root(args.steam_root)
    userdata = select_userdata(steam_root, args.user_id)
    shortcuts_path = userdata / "config/shortcuts.vdf"
    root = load_vdf(shortcuts_path)
    existing_shortcuts = ordered_shortcuts(root["shortcuts"])
    new_shortcut = build_shortcut(args)
    target_exe = normalize_path(str(Path(args.exe).expanduser().resolve()))

    replaced = False
    for index, shortcut in enumerate(existing_shortcuts):
        current_name = shortcut.get("AppName")
        current_exe = normalize_path(steam_unquote(shortcut.get("Exe")))
        if current_name == args.name or current_exe == target_exe:
            existing_shortcuts[index] = new_shortcut
            replaced = True
            break

    if not replaced:
        existing_shortcuts.append(new_shortcut)

    root["shortcuts"] = OrderedDict(
        (str(index), shortcut) for index, shortcut in enumerate(existing_shortcuts)
    )

    new_data = dump_vdf(root)
    old_data = shortcuts_path.read_bytes() if shortcuts_path.exists() else b""
    if new_data == old_data:
        print(f"Steam shortcut already up to date: {args.name}")
        return

    shortcuts_path.parent.mkdir(parents=True, exist_ok=True)
    if shortcuts_path.exists():
        stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
        backup = shortcuts_path.with_name(f"{shortcuts_path.name}.bak.{stamp}")
        shutil.copy2(shortcuts_path, backup)
        print(f"Backed up {shortcuts_path} to {backup}")

    if steam_running():
        print(
            "warning: Steam appears to be running; restart Steam after this command "
            "and avoid exiting Steam before it reloads shortcuts.",
            file=sys.stderr,
        )

    tmp_path = shortcuts_path.with_name(f".{shortcuts_path.name}.tmp")
    tmp_path.write_bytes(new_data)
    os.replace(tmp_path, shortcuts_path)

    action = "Updated" if replaced else "Added"
    print(f"{action} Steam shortcut for {args.name} in userdata {userdata.name}")


def remove_shortcut(args: argparse.Namespace) -> None:
    steam_root = find_steam_root(args.steam_root)
    userdata = select_userdata(steam_root, args.user_id)
    shortcuts_path = userdata / "config/shortcuts.vdf"
    if not shortcuts_path.exists():
        print(f"No Steam shortcuts file found in userdata {userdata.name}")
        return

    root = load_vdf(shortcuts_path)
    existing_shortcuts = ordered_shortcuts(root["shortcuts"])
    target_exe = normalize_path(str(Path(args.exe).expanduser().resolve())) if args.exe else ""
    remaining_shortcuts: list[OrderedDict[str, Any]] = []
    removed = 0

    for shortcut in existing_shortcuts:
        current_name = shortcut.get("AppName")
        current_exe = normalize_path(steam_unquote(shortcut.get("Exe")))
        if current_name == args.name or (target_exe and current_exe == target_exe):
            removed += 1
            continue
        remaining_shortcuts.append(shortcut)

    if removed == 0:
        print(f"No Steam shortcut found for {args.name}")
        return

    root["shortcuts"] = OrderedDict(
        (str(index), shortcut) for index, shortcut in enumerate(remaining_shortcuts)
    )

    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    backup = shortcuts_path.with_name(f"{shortcuts_path.name}.bak.{stamp}")
    shutil.copy2(shortcuts_path, backup)
    print(f"Backed up {shortcuts_path} to {backup}")

    if steam_running():
        print(
            "warning: Steam appears to be running; restart Steam after this command "
            "and avoid exiting Steam before it reloads shortcuts.",
            file=sys.stderr,
        )

    tmp_path = shortcuts_path.with_name(f".{shortcuts_path.name}.tmp")
    tmp_path.write_bytes(dump_vdf(root))
    os.replace(tmp_path, shortcuts_path)
    print(f"Removed {removed} Steam shortcut(s) for {args.name} from userdata {userdata.name}")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    subparsers = parser.add_subparsers(dest="command", required=True)

    add = subparsers.add_parser("add", help="add or update a shortcut")
    add.add_argument("--steam-root")
    add.add_argument("--user-id")
    add.add_argument("--name", required=True)
    add.add_argument("--exe", required=True)
    add.add_argument("--start-dir", required=True)
    add.add_argument("--launch-options", default="")
    add.add_argument("--icon", default="")
    add.add_argument("--tag", action="append", default=[])
    add.set_defaults(func=add_shortcut)

    remove = subparsers.add_parser("remove", help="remove a shortcut")
    remove.add_argument("--steam-root")
    remove.add_argument("--user-id")
    remove.add_argument("--name", required=True)
    remove.add_argument("--exe")
    remove.set_defaults(func=remove_shortcut)

    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        args.func(args)
    except VdfError as error:
        print(f"error: {error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())