diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-07-03 20:40:58 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-07-03 20:40:58 +0300 |
| commit | e2ec4402a4d53dc08bd6773dc5b680e0eb283fb9 (patch) | |
| tree | 35a8a04c650e5c66816f5e2577bb5edfa088aac9 | |
| parent | 98219ca0720db057e434fd6e92852b6905ea34da (diff) | |
| download | fungus-launcher-e2ec4402a4d53dc08bd6773dc5b680e0eb283fb9.tar.gz fungus-launcher-e2ec4402a4d53dc08bd6773dc5b680e0eb283fb9.tar.xz | |
initial for split game storage in ini files instead of monolithic JSON
| -rw-r--r-- | fungus/constants.py | 1 | ||||
| -rw-r--r-- | fungus/game_model.py | 314 | ||||
| -rw-r--r-- | fungus/main_window.py | 90 | ||||
| -rw-r--r-- | fungus/run_manager.py | 39 |
4 files changed, 392 insertions, 52 deletions
diff --git a/fungus/constants.py b/fungus/constants.py index 333fc0e..6d94351 100644 --- a/fungus/constants.py +++ b/fungus/constants.py @@ -35,6 +35,7 @@ fungus_run = PathManager.find_binary('fungus-run') fungus_proton_manager = PathManager.find_binary('fungus-proton-manager') umu_run = PathManager.user_data('fungus-launcher/umu-run') +games_dir = PathManager.user_config('fungus-launcher/games') games_json = PathManager.user_config('fungus-launcher/games.json') prefixes_dir = PathManager.user_config('fungus-launcher/prefixes') fungus_launcher_share_dir = PathManager.user_data('fungus-launcher') diff --git a/fungus/game_model.py b/fungus/game_model.py index d12b239..b15c05c 100644 --- a/fungus/game_model.py +++ b/fungus/game_model.py @@ -1,10 +1,13 @@ #!/usr/bin/python3 +import configparser import json import os import shutil -from dataclasses import dataclass +import tempfile +from dataclasses import dataclass, field from datetime import datetime +from typing import TYPE_CHECKING # ── Game data model ───────────────────────────────────────────────────── @@ -165,3 +168,312 @@ def backup_games_file(source_path, backup_dir=None): while len(backups) > 20: oldest = backups.pop(0) os.remove(os.path.join(backup_dir, oldest)) + + +# ── Per-game INI storage ──────────────────────────────────────────────── + + +def _bool_to_ini(value: bool) -> str: + """Convert a boolean to an INI-compatible string.""" + return "true" if value else "false" + + +def _ini_to_bool(value: str) -> bool: + """Convert an INI string to a boolean.""" + return value.strip().lower() in ("true", "1", "yes") + + +GAME_INI_SECTION = "game" + +# Fields that require type coercion when reading from INI +_GAME_INT_FIELDS = {"playtime"} +_GAME_BOOL_FIELDS = {"hidden", "favorite"} + + +class GameLibrary: + """Manages per-game INI files in a directory. + + Each game is stored as ``{gameid}.ini`` under *games_dir*, with all fields + in a ``[game]`` section. Writes are atomic (write to temp file, then rename) + to prevent corruption on crash. + + Parameters + ---------- + games_dir : str, optional + Directory containing per-game ``.ini`` files. Defaults to + ``~/.config/fungus-launcher/games``. + """ + + def __init__(self, games_dir: str | None = None): + if games_dir is None: + from fungus.path_manager import PathManager + + games_dir = PathManager.user_config("fungus-launcher/games") + self.games_dir = games_dir + os.makedirs(self.games_dir, exist_ok=True) + + # ── File helpers ─────────────────────────────────────────────────── + + def _ini_path(self, gameid: str) -> str: + """Return the filesystem path for *gameid*.""" + return os.path.join(self.games_dir, f"{gameid}.ini") + + def _write_ini(self, gameid: str, data: dict) -> None: + """Write *data* to a ``{gameid}.ini`` file atomically. + + Writes to a temporary file in the same directory, then renames + into place. This guarantees that a crash mid-write never leaves + a partial or corrupt game file. + """ + ini_path = self._ini_path(gameid) + tmp_fd, tmp_path = tempfile.mkstemp( + suffix=".ini.tmp", dir=self.games_dir + ) + try: + with os.fdopen(tmp_fd, "w", encoding="utf-8") as fh: + config = configparser.ConfigParser() + config[GAME_INI_SECTION] = data + config.write(fh) + os.replace(tmp_path, ini_path) # atomic on POSIX + except BaseException: + # Clean up temp file on any failure + if os.path.exists(tmp_path): + os.unlink(tmp_path) + raise + + # ── Public API ───────────────────────────────────────────────────── + + def exists(self, gameid: str) -> bool: + """Return ``True`` if a game file for *gameid* exists on disk.""" + return os.path.isfile(self._ini_path(gameid)) + + def load(self, gameid: str) -> Game | None: + """Load a single game by ID. + + Returns ``None`` if the file does not exist or is invalid. + """ + ini_path = self._ini_path(gameid) + if not os.path.isfile(ini_path): + return None + + try: + config = configparser.ConfigParser() + config.read(ini_path, encoding="utf-8") + section = config[GAME_INI_SECTION] + except (configparser.Error, KeyError): + return None + + data: dict[str, str] = dict(section) + return Game( + gameid=data.get("gameid", ""), + title=data.get("title", ""), + path=data.get("path", ""), + prefix=data.get("prefix", ""), + launch_arguments=data.get("launch_arguments", ""), + game_arguments=data.get("game_arguments", ""), + protonfix=data.get("protonfix", ""), + runner=data.get("runner", ""), + playtime=int(data.get("playtime", 0)), + hidden=_ini_to_bool(data.get("hidden", "false")), + favorite=_ini_to_bool(data.get("favorite", "false")), + ) + + def load_all(self) -> list[Game]: + """Enumerate all ``.ini`` files in the games directory and load them. + + Returns a list of ``Game`` objects. If the same ``gameid`` appears + in multiple files, the first occurrence wins and a warning is logged. + """ + if TYPE_CHECKING: + from fungus.logger import get_logger + + log = get_logger(__name__) + else: + try: + from fungus.logger import get_logger + + log = get_logger(__name__) + except ImportError: + log = None # type: ignore[assignment] + + games: list[Game] = [] + seen: dict[str, str] = {} # gameid -> filename + + try: + entries = sorted(os.listdir(self.games_dir)) + except OSError: + return [] + + for fname in entries: + if not fname.endswith(".ini"): + continue + gameid_from_file = fname[:-4] # strip .ini + game = self.load(gameid_from_file) + if game is None: + continue + if game.gameid in seen: + if log: + log.warning( + "Duplicate gameid '%s' in %s and %s — skipping %s", + game.gameid, + seen[game.gameid], + fname, + fname, + ) + continue + seen[game.gameid] = fname + games.append(game) + + return games + + def save(self, game: Game) -> None: + """Persist a single ``Game`` to its ``.ini`` file atomically.""" + data: dict[str, str] = { + "gameid": game.gameid, + "title": game.title, + "path": game.path, + "prefix": game.prefix, + "launch_arguments": game.launch_arguments, + "game_arguments": game.game_arguments, + "protonfix": game.protonfix, + "runner": game.runner, + "playtime": str(game.playtime), + "hidden": _bool_to_ini(game.hidden), + "favorite": _bool_to_ini(game.favorite), + } + self._write_ini(game.gameid, data) + + def delete(self, gameid: str) -> bool: + """Remove a game's ``.ini`` file. + + Returns ``True`` if the file was deleted, ``False`` if it didn't exist. + """ + ini_path = self._ini_path(gameid) + if os.path.isfile(ini_path): + os.unlink(ini_path) + return True + return False + + def update_field(self, gameid: str, field: str, value) -> bool: + """Load one game, set a field, and save it back. + + Returns ``True`` if the game was found and updated, ``False`` if + the gameid does not exist. + """ + game = self.load(gameid) + if game is None: + return False + setattr(game, field, value) + self.save(game) + return True + + def add(self, game: Game) -> bool: + """Add a new game to the library. + + Returns ``True`` if the game was added, ``False`` if a game with + the same ``gameid`` already exists. + """ + if self.exists(game.gameid): + return False + self.save(game) + return True + + def save_all(self, games: list[Game]) -> None: + """Persist a list of games. Each game is written atomically. + + This is useful for batch operations (e.g. after a library scan). + Games are written individually — no single monolithic file is used. + """ + for game in games: + self.save(game) + + +# ── Migration: monolithic games.json → per-game INI files ─────────────── + + +@dataclass +class MigrationResult: + """Result of a migration operation.""" + + migrated: int = 0 + skipped_duplicate: int = 0 + skipped_error: int = 0 + errors: list[str] = field(default_factory=list) + + +def migrate_to_per_game( + games_json_path: str, games_dir: str, *, dry_run: bool = False +) -> MigrationResult: + """Migrate a monolithic ``games.json`` to per-game ``.ini`` files. + + Steps: + 1. Back up ``games.json`` to the backup directory + 2. Load all games from ``games.json`` + 3. Deduplicate by ``gameid`` (keep first occurrence) + 4. Write one ``.ini`` per game to ``games_dir/{gameid}.ini`` + 5. Rename ``games.json`` → ``games.json.migrated`` + + Parameters + ---------- + games_json_path : str + Path to the existing monolithic ``games.json``. + games_dir : str + Target directory for per-game ``.ini`` files. + dry_run : bool, default False + If ``True``, perform all steps except the final rename. + Useful for testing. + + Returns + ------- + MigrationResult + Summary of what was migrated, skipped, and any errors. + """ + result = MigrationResult() + + # Step 1: back up the monolithic file + try: + backup_games_file(games_json_path) + except Exception as exc: + result.errors.append(f"Backup failed: {exc}") + + # Step 2: load games from JSON + games = load_games_json(games_json_path) + if not games: + # Empty or missing file — nothing to migrate + return result + + # Step 3: deduplicate by gameid (keep first occurrence) + seen: dict[str, int] = {} # gameid -> index in games list + deduped: list[Game] = [] + for i, game in enumerate(games): + if game.gameid in seen: + result.skipped_duplicate += 1 + else: + seen[game.gameid] = i + deduped.append(game) + + # Step 4: write per-game INI files + library = GameLibrary(games_dir) + for game in deduped: + try: + library.save(game) + result.migrated += 1 + except Exception as exc: + result.skipped_error += 1 + result.errors.append(f"Failed to write {game.gameid}: {exc}") + + # Step 5: rename games.json → games.json.migrated (skip in dry-run) + if not dry_run: + migrated_path = games_json_path + ".migrated" + os.replace(games_json_path, migrated_path) + + return result + + +def needs_migration(games_json_path: str, games_dir: str) -> bool: + """Return ``True`` if a migration from monolithic JSON is needed. + + Migration is needed when the old ``games.json`` exists but the new + per-game directory has not yet been created. + """ + return os.path.isfile(games_json_path) and not os.path.isdir(games_dir) diff --git a/fungus/main_window.py b/fungus/main_window.py index 83ae2b1..989db27 100644 --- a/fungus/main_window.py +++ b/fungus/main_window.py @@ -15,17 +15,18 @@ from fungus.config_manager import ConfigManager from fungus.logger import get_logger from fungus.shortcuts import create_shortcut, remove_shortcut, set_image_shortcut_icon from fungus.constants import ( + app_dir, backup_dir, + desktop_dir, fungus_backup, - games_json, fungus_launcher_dir, fungus_png, fungus_run, + fungus_version, + games_dir, + games_json, icons_dir, umu_run, - fungus_version, - desktop_dir, - app_dir, ) from fungus.dialogs import ( GameDirectoriesNotConfiguredDialog, @@ -34,10 +35,8 @@ from fungus.dialogs import ( ) from fungus.game_model import ( Game, + GameLibrary, backup_games_file, - load_games_json, - save_games_json, - update_game_field, ) from fungus.settings_dialog import SettingsDialog from fungus.utils import format_title, is_safe_prefix_path @@ -239,6 +238,8 @@ class Main(Gtk.ApplicationWindow): self.flowbox.set_sort_func(sort_games, None) scroll_box.add(self.flowbox) + self._maybe_migrate() + self.library = GameLibrary() self.load_games() # Pack left and scrolled box into the top box @@ -321,7 +322,7 @@ class Main(Gtk.ApplicationWindow): self.menu_item_title.get_child().set_text(title) - games_data = load_games_json(games_json) + games_data = self.library.load_all() for game_data in games_data: if game_data.gameid == game.gameid: game.playtime = game_data.playtime @@ -379,12 +380,41 @@ class Main(Gtk.ApplicationWindow): self.context_menu.popup_at_pointer(event) + # ── Migration ──────────────────────────────────────────────────────── + + def _maybe_migrate(self): + """Migrate from monolithic games.json to per-game INI files, if needed. + + Runs silently on startup. If migration fails, logs the error and + returns False so that load_games can fall back to the old format. + """ + from fungus.game_model import migrate_to_per_game, needs_migration + + if not needs_migration(games_json, games_dir): + return True + + try: + result = migrate_to_per_game(games_json, games_dir) + log.info( + "Migrated %d games, skipped %d duplicates, %d errors", + result.migrated, + result.skipped_duplicate, + result.skipped_error, + ) + if result.errors: + for err in result.errors: + log.warning("Migration warning: %s", err) + except Exception: + log.exception("Migration failed; falling back to games.json") + return False + + return True + # ── Game List Rendering ────────────────────────────────────────────── def load_games(self): - """Load games from games.json, filter hidden ones, and render the flowbox.""" - from fungus.game_model import load_games_json - games_data = load_games_json(games_json) + """Load games from the library, filter hidden ones, and render the flowbox.""" + games_data = self.library.load_all() self.games.clear() for game in games_data: @@ -564,7 +594,7 @@ class Main(Gtk.ApplicationWindow): return game.hidden = not game.hidden - update_game_field(games_json, game.gameid, "hidden", game.hidden) + self.library.update_field(game.gameid, "hidden", game.hidden) self.update_list() self.select_first_child() @@ -580,7 +610,7 @@ class Main(Gtk.ApplicationWindow): return game.favorite = not game.favorite - update_game_field(games_json, game.gameid, "favorite", game.favorite) + self.library.update_field(game.gameid, "favorite", game.favorite) self.update_list() @@ -738,7 +768,9 @@ class Main(Gtk.ApplicationWindow): self.remove_shortcut(game, "both") self._deleted_gameid = game.gameid - save_games_json(games_json, self.games, deleted_gameid=self._deleted_gameid) + self.library.delete(game.gameid) + self.games = [g for g in self.games if g.gameid != game.gameid] + self.library.save_all(self.games) self.update_list() self.select_first_child() @@ -839,14 +871,12 @@ class Main(Gtk.ApplicationWindow): else: log.warning("Skipping prefix init for '%s' (GAMEID or runner missing)", title) - if os.path.exists(games_json): - existing = load_games_json(games_json) - if any(g.title == title for g in existing): - self.show_warning_dialog( - add_game_dialog, - "%s already exists." % title, - ) - return True + if self.library.exists(title_formatted): + self.show_warning_dialog( + add_game_dialog, + "%s already exists." % title, + ) + return True path = add_game_dialog.entry_path.get_text() launch_arguments = add_game_dialog.entry_launch_arguments.get_text() @@ -868,8 +898,7 @@ class Main(Gtk.ApplicationWindow): if os.path.isfile(icon_temp): shutil.copyfile(icon_temp, icon_final) - self.backup_games() - save_games_json(games_json, [*self.games, game]) + self.library.save(game) self.games.append(game) self.add_item_list(game) @@ -910,7 +939,7 @@ class Main(Gtk.ApplicationWindow): if os.path.isfile(icon_temp): shutil.copyfile(icon_temp, icon_final) - save_games_json(games_json, self.games) + self.library.save(game) self.update_list() self.select_game_by_title(game.title) else: @@ -972,9 +1001,9 @@ class Main(Gtk.ApplicationWindow): # ── Game Data Operations ───────────────────────────────────────────── def reload_playtimes(self): - """Reload playtime values from games.json onto the in-memory game objects.""" + """Reload playtime values from the library onto the in-memory game objects.""" try: - games_data = load_games_json(games_json) + games_data = self.library.load_all() except Exception: return @@ -989,11 +1018,12 @@ class Main(Gtk.ApplicationWindow): backup_games_file(games_json, backup_dir) def save_games(self): - """Persist the current in-memory game list to games.json.""" - deleted_id = getattr(self, "_deleted_gameid", None) - save_games_json(games_json, self.games, deleted_gameid=deleted_id) + """Persist the current in-memory game list to per-game INI files.""" + games_to_save = self.games if hasattr(self, "_deleted_gameid"): + games_to_save = [g for g in games_to_save if g.gameid != self._deleted_gameid] del self._deleted_gameid + self.library.save_all(games_to_save) # ── Shortcut & Icon Helpers ────────────────────────────────────────── diff --git a/fungus/run_manager.py b/fungus/run_manager.py index a485495..97dd790 100644 --- a/fungus/run_manager.py +++ b/fungus/run_manager.py @@ -25,11 +25,10 @@ from gi.repository import Gtk, GLib # type: ignore from fungus.config_manager import ConfigManager from fungus.constants import ( envar_dir, - games_json, share_dir, umu_run, ) -from fungus.game_model import Game, load_games_json, save_games_json +from fungus.game_model import Game, GameLibrary from fungus.path_manager import PathManager from fungus.utils import has_proton_installed, is_executable_in_whitelist from fungus.dialogs import SandboxWarningDialog @@ -314,7 +313,7 @@ class FungusRun: # ── Config files (read-only) ──────────────────────────────────── config_dir = Path(PathManager.user_config("fungus-launcher")) - for cfg_file in ("games.json", "config.ini"): + for cfg_file in ("games.json", "games.json.migrated", "config.ini"): cfg_path = config_dir / cfg_file if cfg_path.exists(): bwrap_args.extend(["--ro-bind", str(cfg_path), str(cfg_path)]) @@ -724,14 +723,13 @@ class FungusRun: game_id = os.environ.get("GAMEID") - if game_id and os.path.exists(games_json): + if game_id: try: - games = load_games_json(games_json) - for game in games: - if game.gameid == game_id: - game.playtime = int(game.playtime or 0) + runtime - break - save_games_json(games_json, games) + library = GameLibrary() + game = library.load(game_id) + if game: + game.playtime = int(game.playtime or 0) + runtime + library.save(game) except Exception: pass @@ -773,14 +771,13 @@ def run_winetricks(game: Game) -> None: runtime = int(time.time() - start_time) # ── Save playtime ──────────────────────────────────────────────── - if gameid and os.path.exists(games_json): + if gameid: try: - games = load_games_json(games_json) - for g in games: - if g.gameid == gameid: - g.playtime = int(g.playtime or 0) + runtime - break - save_games_json(games_json, games) + library = GameLibrary() + g = library.load(gameid) + if g: + g.playtime = int(g.playtime or 0) + runtime + library.save(g) except Exception: pass @@ -827,10 +824,10 @@ def handle_command(game: Game, cmd_override: str | None = None, igpu: bool = Fal def load_game_from_json(gameid): - """Load a ``Game`` object from games.json by its gameid.""" - for game in load_games_json(games_json): - if game.gameid == gameid: - return game + """Load a ``Game`` object from the library by its gameid.""" + library = GameLibrary() + if library.exists(gameid): + return library.load(gameid) return None |
