# deck-it - games module # Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Now playing for PC games: Steam, PCSX2 and DuckStation. The game is the first Hyprland window that is one. Its name, cover and total playtime come from the launcher's own files, so no account is needed. """ import hashlib import json import re import subprocess import time from pathlib import Path from ..module import Module HOME = Path.home() STEAM = HOME / ".local/share/Steam" # window class substring -> (platform, data dir, playtime.dat in it) EMULATORS = { "pcsx2": ("ps2", HOME / ".config/PCSX2", "inis/playtime.dat"), "duckstation": ("ps1", HOME / ".local/share/duckstation", "playtime.dat"), } def _run(cmd, timeout=2): try: return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout.strip() except (OSError, subprocess.TimeoutExpired): return "" def _read(p: Path) -> str: try: return p.read_text(errors="replace") except OSError: return "" def _int(v): try: return int(v) except (TypeError, ValueError): return None def vdf(text: str) -> dict: """Valve's KeyValues text: "key" "value" pairs and "key" { ... } blocks.""" root, stack, key = {}, [], None cur = root for m in re.finditer(r'"((?:[^"\\]|\\.)*)"|([{}])', text): s, brace = m.groups() if brace == "{": new = {} cur[key] = new stack.append(cur) cur, key = new, None elif brace == "}": cur, key = (stack.pop() if stack else cur), None elif key is None: key = s else: cur[key], key = s, None return root def _get(d, *keys): """d[k1][k2]..., keys matched without case (KeyValues ignores it).""" for k in keys: if not isinstance(d, dict): return None d = next((v for kk, v in d.items() if kk.lower() == k.lower()), None) return d def _lstr(data: bytes, i: int): """The length-prefixed string at i and the offset after it, or (None, i).""" if i + 4 > len(data): return None, i n = int.from_bytes(data[i:i + 4], "little") if not 0 < n <= 4096 or i + 4 + n > len(data): return None, i try: return data[i + 4:i + 4 + n].decode(), i + 4 + n except UnicodeDecodeError: return None, i def cache_serials(data: bytes) -> dict: """title -> serial from an emulator's cache/gamelist.cache, whose entries (PCSX2 and DuckStation alike) start with path, serial and title strings.""" out = {} for i in range(len(data) - 5): if data[i + 4] != 0x2F: # an entry's path starts with "/" continue path, j = _lstr(data, i) if not path: continue serial, j = _lstr(data, j) title, _ = _lstr(data, j) if serial and title: out.setdefault(title, serial) return out def _first_file(paths): return next((p for p in paths if p.is_file()), None) def steam_game(root: Path, appid: str) -> dict: libs = _get(vdf(_read(root / "steamapps/libraryfolders.vdf")), "libraryfolders") or {} dirs = [root] + [Path(v["path"]) for v in libs.values() if isinstance(v, dict) and v.get("path")] name = next((_get(vdf(acf), "AppState", "name") for acf in (_read(d / f"steamapps/appmanifest_{appid}.acf") for d in dirs) if acf), None) minutes = next((m for m in (_int(_get(vdf(_read(f)), "UserLocalConfigStore", "Software", "Valve", "Steam", "apps", appid, "Playtime")) for f in sorted(root.glob("userdata/*/config/localconfig.vdf"))) if m is not None), None) art = root / "appcache/librarycache" / appid return {"platform": "steam", "name": name, "minutes": minutes, "cover": _first_file([art / "library_600x900.jpg", art / "header.jpg"])} def emu_game(platform: str, root: Path, playtime: str, title: str) -> dict: try: serials = cache_serials((root / "cache/gamelist.cache").read_bytes()) except OSError: serials = {} # ponytail: the window title names the game; a title that only contains a # cache title (an emulator adding the serial or a version) takes the longest. serial = serials.get(title) or next( (serials[t] for t in sorted(serials, key=len, reverse=True) if t in title), None) minutes = None if serial: for line in _read(root / playtime).splitlines(): f = line.split() if len(f) >= 2 and f[0] == serial and f[1].isdigit(): minutes = int(f[1]) // 60 covers = [root / "covers" / f"{stem}{ext}" for stem in filter(None, (serial, title)) for ext in (".jpg", ".png")] return {"platform": platform, "name": title, "minutes": minutes, "cover": _first_file(covers)} def detect(clients: list, emulators: dict): """(kind, arg, title) for the first window that is a game: kind "steam" with the app id, or an emulator key with the window title.""" for c in clients: cls, title = c.get("class") or "", c.get("title") or "" m = re.fullmatch(r"steam_app_(\d+)", cls) if m: return "steam", m[1], title for k in emulators: # the idle game list's title is the emulator's own name if k in cls.lower() and title and not title.lower().startswith(k): return k, title, title return None def make(cfg: dict) -> Module: run = cfg.get("run", _run) steam = Path(cfg.get("steam_root", STEAM)) emulators = cfg.get("emulators", EMULATORS) cur = {"id": None, "game": None, "session": None, "key": None} def state(): try: clients = json.loads(run(["hyprctl", "clients", "-j"]) or "[]") except ValueError: clients = [] found = detect(clients if isinstance(clients, list) else [], emulators) if found != cur["id"]: # ponytail: the session starts when deck-it first sees the game, as on the Xbox. game, key = None, None if found: kind, arg, title = found game = steam_game(steam, arg) if kind == "steam" else emu_game(*emulators[kind], title) game["name"] = game["name"] or title if game["cover"]: key = hashlib.sha1(str(game["cover"]).encode()).hexdigest()[:16] cur.update(id=found, game=game, key=key, session=int(time.time()) if found else None) g = cur["game"] if not g: return {"playing": None} return {"playing": {"platform": g["platform"], "name": g["name"], "minutes": g["minutes"], "cover": f"/api/games/image/{cur['key']}" if cur["key"] else None, "session": cur["session"]}} def image(key): g = cur["game"] if not g or not cur["key"] or key != cur["key"]: return None try: data = g["cover"].read_bytes() except OSError: return None return data, "image/png" if g["cover"].suffix == ".png" else "image/jpeg" return Module(name="games", title="Games", state=state, image=image)