aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-11-18 16:43:16 +0100
committerDanilo M. <danix@danix.xyz>2026-11-18 16:43:16 +0100
commit0480dc62af2be80a17b98d88108cb04d7280a3bf (patch)
tree3c08e52e5cdd1a12f6bdd1cc62416f34b7b6cd4c
parent22bb2d5f5494c99acceb4eb9d055df9860fa2c0d (diff)
downloaddeck-it-0480dc62af2be80a17b98d88108cb04d7280a3bf.tar.gz
deck-it-0480dc62af2be80a17b98d88108cb04d7280a3bf.zip
feat(games): find the PC game and its name, cover and playtime
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--deckit/modules/games.py130
-rw-r--r--tests/test_games.py89
2 files changed, 219 insertions, 0 deletions
diff --git a/deckit/modules/games.py b/deckit/modules/games.py
index c14de2e..a68e161 100644
--- a/deckit/modules/games.py
+++ b/deckit/modules/games.py
@@ -20,7 +20,43 @@ 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:
@@ -80,3 +116,97 @@ def cache_serials(data: bytes) -> dict:
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)
diff --git a/tests/test_games.py b/tests/test_games.py
index 4c41367..a3ee50c 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -19,6 +19,8 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+import json
+import tempfile
import unittest
import deckit.modules.games as games
@@ -54,5 +56,92 @@ class Parsers(unittest.TestCase):
self.assertEqual(games.cache_serials(b"\xff" * 64), {})
+class Lookup(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def put(self, rel, data):
+ p = self.root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ (p.write_bytes if isinstance(data, bytes) else p.write_text)(data)
+ return p
+
+ def steam(self):
+ steam = self.root / "Steam"
+ other = self.root / "lib2"
+ self.put("Steam/steamapps/libraryfolders.vdf",
+ f'"libraryfolders"\n{{\n"0"\n{{\n"path" "{steam}"\n}}\n"1"\n{{\n"path" "{other}"\n}}\n}}\n')
+ self.put("lib2/steamapps/appmanifest_217200.acf", '"AppState"\n{\n"appid" "217200"\n"name" "Worms"\n}\n')
+ self.put("Steam/userdata/1/config/localconfig.vdf",
+ '"UserLocalConfigStore"\n{\n"Software"\n{\n"Valve"\n{\n"Steam"\n{\n"apps"\n{\n'
+ '"217200"\n{\n"Playtime" "125"\n}\n}\n}\n}\n}\n}\n')
+ self.put("Steam/appcache/librarycache/217200/library_600x900.jpg", b"JPG")
+ return steam
+
+ def test_steam_game(self):
+ g = games.steam_game(self.steam(), "217200")
+ self.assertEqual((g["platform"], g["name"], g["minutes"]), ("steam", "Worms", 125))
+ self.assertEqual(g["cover"].name, "library_600x900.jpg")
+
+ def test_steam_game_missing_files(self):
+ g = games.steam_game(self.root / "nope", "1")
+ self.assertEqual((g["name"], g["minutes"], g["cover"]), (None, None, None))
+
+ def emu(self):
+ emu = self.root / "duck"
+ self.put("duck/cache/gamelist.cache", cache(("/g/a.cue", "SCES-01615", "Cool Boarders 3 (Europe)")))
+ self.put("duck/playtime.dat", "SCES-01615 1006 1789987473\n")
+ self.put("duck/covers/SCES-01615.jpg", b"JPG")
+ return emu
+
+ def test_emu_game(self):
+ g = games.emu_game("ps1", self.emu(), "playtime.dat", "Cool Boarders 3 (Europe)")
+ self.assertEqual((g["platform"], g["name"], g["minutes"]), ("ps1", "Cool Boarders 3 (Europe)", 16))
+ self.assertEqual(g["cover"].name, "SCES-01615.jpg")
+
+ def test_emu_game_title_contains_cache_title(self):
+ g = games.emu_game("ps1", self.emu(), "playtime.dat", "Cool Boarders 3 (Europe) [SCES-01615]")
+ self.assertEqual(g["minutes"], 16)
+
+ def test_emu_game_unknown(self):
+ g = games.emu_game("ps1", self.emu(), "playtime.dat", "Other")
+ self.assertEqual((g["name"], g["minutes"], g["cover"]), ("Other", None, None))
+
+ def test_detect(self):
+ emu = {"duckstation": ("ps1", self.root, "p")}
+ d = lambda *cs: games.detect([{"class": c, "title": t} for c, t in cs], emu)
+ self.assertEqual(d(("kitty", "x"), ("steam_app_42", "Game")), ("steam", "42", "Game"))
+ self.assertEqual(d(("duckstation-qt", "Cool Boarders")), ("duckstation", "Cool Boarders", "Cool Boarders"))
+ self.assertIsNone(d(("duckstation-qt", "DuckStation 0.1-1234")))
+ self.assertIsNone(d(("steam", "Steam")))
+
+ def make(self, clients):
+ emu = {"duckstation": ("ps1", self.emu(), "playtime.dat")}
+ run = lambda cmd, timeout=2: json.dumps(clients[0])
+ return games.make({"run": run, "steam_root": self.steam(), "emulators": emu})
+
+ def test_state_and_cover(self):
+ clients = [[{"class": "steam_app_217200", "title": "Worms W.M.D"}]]
+ m = self.make(clients)
+ st = m.state()["playing"]
+ self.assertEqual((st["platform"], st["name"], st["minutes"]), ("steam", "Worms", 125))
+ self.assertIsInstance(st["session"], int)
+ key = st["cover"].rsplit("/", 1)[1]
+ self.assertEqual(m.image(key), (b"JPG", "image/jpeg"))
+ self.assertIsNone(m.image("other"))
+ self.assertEqual(m.state()["playing"]["session"], st["session"]) # same game, same session
+ clients[0] = []
+ self.assertEqual(m.state(), {"playing": None})
+ self.assertIsNone(m.image(key))
+
+ def test_state_hyprctl_fails(self):
+ m = self.make([""])
+ self.assertEqual(m.state(), {"playing": None})
+
+
if __name__ == "__main__":
unittest.main()