diff --git a/autotester/automodpack_autotester/harness.py b/autotester/automodpack_autotester/harness.py index a28f6ada1..0dd4f300c 100644 --- a/autotester/automodpack_autotester/harness.py +++ b/autotester/automodpack_autotester/harness.py @@ -2,8 +2,10 @@ from __future__ import annotations import json +import re import secrets import time +import tomllib from contextlib import contextmanager from copy import deepcopy from dataclasses import dataclass, field @@ -103,19 +105,23 @@ def client(self, name: str = "default") -> ClientProcess: return self._clients[name] def configure_server(self, *, connection_mode: str = "HOLEPUNCH", overrides: dict[str, Any] | None = None) -> Path: - """Write automodpack-server.json into the server dir before starting.""" + """Write automodpack/server.toml into the server dir before starting.""" cfg = deepcopy((self.settings.get("automodpack") or {}).get("config") or {}) - cfg["connectionMode"] = connection_mode.upper() - if connection_mode.upper() in ("HTTP", "HTTPS"): - cfg["bindAddress"] = "0.0.0.0" - cfg["bindPort"] = self.server.endpoint_port - cfg["advertisedEndpointHost"] = self.server.host - cfg["advertisedEndpointPort"] = self.server.endpoint_port + network = cfg.setdefault("network", {}) + mode = connection_mode.upper() + network["connection-mode"] = mode + if mode in ("HTTP", "HTTPS"): + network["bind-address"] = "0.0.0.0" + network["bind-port"] = self.server.endpoint_port + network["advertised-host"] = self.server.host + network["advertised-port"] = self.server.endpoint_port if overrides: - cfg.update(overrides) - cfg_path = self.server.server_dir / "automodpack" / "automodpack-server.json" + _deep_merge(cfg, overrides) + rendered = _dump_toml(cfg) + tomllib.loads(rendered) + cfg_path = self.server.server_dir / "automodpack" / "server.toml" cfg_path.parent.mkdir(parents=True, exist_ok=True) - cfg_path.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8") + cfg_path.write_text(rendered, encoding="utf-8") return cfg_path def stage_server_file(self, rel_path: str, content: str | bytes) -> Path: @@ -163,6 +169,54 @@ def close(self, *, passed: bool) -> None: prune_passed_case(self.case_dir) +_BARE_KEY_RE = re.compile(r"^[A-Za-z0-9_-]+$") + + +def _deep_merge(base: dict[str, Any], patch: dict[str, Any]) -> None: + for key, val in patch.items(): + if isinstance(val, dict) and isinstance(base.get(key), dict): + _deep_merge(base[key], val) + else: + base[key] = deepcopy(val) + + +def _format_key(key: str) -> str: + return key if _BARE_KEY_RE.match(key) else json.dumps(key) + + +def _format_value(value: Any) -> str: + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, int): + return str(value) + if isinstance(value, float): + return repr(value) + if isinstance(value, str): + return json.dumps(value) + if isinstance(value, (list, tuple)): + return "[" + ", ".join(_format_value(v) for v in value) + "]" + raise TypeError(f"Unsupported TOML value: {value!r}") + + +def _emit_table(lines: list[str], data: dict[str, Any], prefix: tuple[str, ...]) -> None: + scalars = [(k, v) for k, v in data.items() if not isinstance(v, dict)] + tables = [(k, v) for k, v in data.items() if isinstance(v, dict)] + if prefix and (scalars or not tables): + if lines: + lines.append("") + lines.append("[" + ".".join(_format_key(p) for p in prefix) + "]") + for k, v in scalars: + lines.append(f"{_format_key(k)} = {_format_value(v)}") + for k, v in tables: + _emit_table(lines, v, (*prefix, k)) + + +def _dump_toml(data: dict[str, Any]) -> str: + lines: list[str] = [] + _emit_table(lines, data, ()) + return "\n".join(lines) + ("\n" if lines else "") + + def run_scenario_fn( fn: Callable[[TestCase], None], *, diff --git a/autotester/automodpack_autotester/hmc.py b/autotester/automodpack_autotester/hmc.py index 76344ed9a..f0f48e351 100644 --- a/autotester/automodpack_autotester/hmc.py +++ b/autotester/automodpack_autotester/hmc.py @@ -104,7 +104,16 @@ def target_hmc_cache(target: Target) -> Path: return shared_cache_root() / "hmc" / target.id -def write_hmc_config(config_root: Path, mc_cache: Path, game_dir: Path, java_home: Path, *, username: str | None = None, user_uuid: str | None = None) -> None: +def write_hmc_config( + config_root: Path, + mc_cache: Path, + game_dir: Path, + java_home: Path, + *, + username: str | None = None, + user_uuid: str | None = None, + xvfb_check: bool = False, +) -> None: cfg_dir = config_root / "headlessmc" cfg_dir.mkdir(parents=True, exist_ok=True) props = { @@ -115,7 +124,7 @@ def write_hmc_config(config_root: Path, mc_cache: Path, game_dir: Path, java_hom "hmc.java.versions": java_home.as_posix(), "hmc.launcher.crash-report-watcher": "true", "hmc.jline.enabled": "false", - "hmc.xvfb.check": "false", + "hmc.xvfb.check": "true" if xvfb_check else "false", } if username: props["hmc.offline.username"] = username diff --git a/autotester/automodpack_autotester/provider.py b/autotester/automodpack_autotester/provider.py index 8d37ac8d3..bedbe6a24 100644 --- a/autotester/automodpack_autotester/provider.py +++ b/autotester/automodpack_autotester/provider.py @@ -51,7 +51,7 @@ class ClientProcess(Protocol): token: str bridge: BridgeClient | None - def start(self, *, fast_timers: bool = True, render: bool = False, extra_jvm_args: list[str] | None = None) -> None: ... + def start(self, *, fast_timers: bool = True, render: bool = False, extra_jvm_args: list[str] | None = None, resolution: tuple[int, int] | None = None) -> None: ... def stop(self, *, force: bool = True) -> None: ... def wait_ready(self, timeout: float = 180.0) -> BridgeClient: ... def wait_exit(self, timeout: float = 60.0) -> int: ... @@ -95,10 +95,7 @@ def _prepare_dir(self) -> None: mods_dir.mkdir(parents=True, exist_ok=True) dest_jar = mods_dir / self.artifact.name if not dest_jar.exists(): - try: - os.link(self.artifact, dest_jar) - except OSError: - shutil.copy2(self.artifact, dest_jar) + shutil.copy2(self.artifact, dest_jar) self._materialized = True write_server_properties( self.server_dir, @@ -156,6 +153,17 @@ def logs(self, tail: int = 120) -> str: return self._proc.tailer.tail(tail) if self._proc is not None else (self.log_path.read_text(encoding="utf-8", errors="replace") if self.log_path.is_file() else "") +def linux_render_wrapper(width: int = 1280, height: int = 720) -> list[str] | None: + """Return a virtual display command prefix on Linux (`xvfb-run` first, then `gamescope` headless).""" + xvfb = shutil.which("xvfb-run") + if xvfb: + return [xvfb, "-a", "-s", f"-screen 0 {width}x{height}x24"] + gamescope = shutil.which("gamescope") + if gamescope: + return [gamescope, "--backend", "headless", "-W", str(width), "-H", str(height), "--"] + return None + + class LocalClient: """Native HeadlessMC 3 Minecraft client running directly on the host OS (no Docker).""" @@ -171,8 +179,9 @@ def __init__(self, name: str, target: Target, settings: dict, client_root: Path, self._proc: ManagedProcess | None = None self.log_path = client_root / f"client-{name}.log" self._prepared = False + self._render = False - def _prepare(self) -> tuple[Path, Path, Path]: + def _prepare(self, *, xvfb_check: bool = False, gui_scale: int | None = None) -> tuple[Path, Path, Path]: home = java_home(self.settings, self.target.java) mc_cache = ensure_profile_prepared(self.target, self.settings, home) self.game_dir.mkdir(parents=True, exist_ok=True) @@ -180,24 +189,26 @@ def _prepare(self) -> tuple[Path, Path, Path]: mods_dir.mkdir(parents=True, exist_ok=True) dest_jar = mods_dir / self.artifact.name if not dest_jar.exists(): - try: - os.link(self.artifact, dest_jar) - except OSError: - shutil.copy2(self.artifact, dest_jar) + shutil.copy2(self.artifact, dest_jar) seed_fml_toml(self.game_dir, self.target) options_txt = self.game_dir / "options.txt" if not options_txt.is_file(): - options_txt.write_text("onboardAccessibility:false\nskipMultiplayerWarning:true\n", encoding="utf-8") + extra = f"guiScale:{gui_scale}\n" if gui_scale is not None else "" + options_txt.write_text(f"onboardAccessibility:false\nskipMultiplayerWarning:true\n{extra}", encoding="utf-8") + elif gui_scale is not None: + lines = [line for line in options_txt.read_text(encoding="utf-8").splitlines() if not line.startswith("guiScale:")] + lines.append(f"guiScale:{gui_scale}") + options_txt.write_text("\n".join(lines) + "\n", encoding="utf-8") import uuid player_name = f"amp_{self.name}"[:16] player_uuid = str(uuid.uuid3(uuid.NAMESPACE_DNS, f"OfflinePlayer:{player_name}")) cfg_root = self.client_root / "hmc-config" - write_hmc_config(cfg_root, mc_cache, self.game_dir, home, username=player_name, user_uuid=player_uuid) + write_hmc_config(cfg_root, mc_cache, self.game_dir, home, username=player_name, user_uuid=player_uuid, xvfb_check=xvfb_check) self._prepared = True return mc_cache, home, cfg_root - def start(self, *, fast_timers: bool = True, render: bool = False, extra_jvm_args: list[str] | None = None) -> None: + def start(self, *, fast_timers: bool = True, render: bool = False, extra_jvm_args: list[str] | None = None, resolution: tuple[int, int] | None = None) -> None: if self.bridge is not None: self.bridge.close() self.bridge = None @@ -205,7 +216,9 @@ def start(self, *, fast_timers: bool = True, render: bool = False, extra_jvm_arg state_file = self.game_dir / "automodpack" / "autotest" / "bridge-state.json" state_file.unlink(missing_ok=True) - mc_cache, home, cfg_root = self._prepare() + self._render = render + width, height = resolution or ((1280, 720) if render else (854, 480)) + mc_cache, home, cfg_root = self._prepare(xvfb_check=render, gui_scale=2 if render else None) hmc_bin = ensure_hmc_binary(self.settings) memory = str((self.settings.get("jvm") or {}).get("clientMemory", "1G")) jvm_args = [ @@ -228,16 +241,14 @@ def start(self, *, fast_timers: bool = True, render: bool = False, extra_jvm_arg *([] if render else ["-lwjgl"]), "--jvm", " ".join(jvm_args), - "--game", - "--width 854 --height 480", "--resolution", - "854x480", + f"{width}x{height}", ] if render and not sys.platform.startswith("win"): - xvfb = shutil.which("xvfb-run") - if not xvfb: - raise RuntimeError("render=True requires xvfb-run on Linux") - argv = [xvfb, "-a", *argv] + wrapper = linux_render_wrapper(width, height) + if not wrapper: + raise RuntimeError("render=True requires xvfb-run or gamescope on Linux") + argv = [*wrapper, *argv] env = hmc_env(mc_cache, home, cfg_root) self._proc = ManagedProcess(argv, cwd=self.game_dir, env=env, log_path=self.log_path) self._proc.start() @@ -254,10 +265,20 @@ def wait_ready(self, timeout: float = 180.0) -> BridgeClient: if client is not None: try: client.ping() - self.bridge = client - return client except Exception: client.close() + time.sleep(0.05) + continue + if self._render and "forcing headless mode" in self.logs(200).lower(): + client.close() + self.stop(force=True) + raise RuntimeError( + "HeadlessMC forced stub-LWJGL headless mode despite render=True. " + "Offline rendered UI requires Xvfb (xvfb-run) on Linux with hmc.xvfb.check=true, " + "or a logged-in Microsoft account." + ) + self.bridge = client + return client time.sleep(0.05) raise TimeoutError(f"Client {self.name!r} bridge did not become ready within {timeout:.0f}s\n--- log tail ---\n{self.logs(60)}") @@ -321,7 +342,7 @@ def __init__(self): name="local", os_family=os_family, native_windows_ntfs=(os_family == "windows"), - rendered_ui=bool(os_family == "windows" or shutil.which("xvfb-run")), + rendered_ui=bool(os_family == "linux" and shutil.which("xvfb-run")), ) def prerequisites(self, settings: dict, targets: list[Target]) -> list[tuple[str, bool, str]]: @@ -337,6 +358,16 @@ def prerequisites(self, settings: dict, targets: list[Target]) -> list[tuple[str except Exception as e: checks.append((f"java-{t.java}", False, str(e))) checks.append(("provider", True, f"local ({self.capabilities.os_family}, zero-docker)")) + if self.capabilities.os_family == "linux": + if shutil.which("xvfb-run"): + render_backend = "xvfb-run" + elif shutil.which("gamescope"): + render_backend = "gamescope (offline rendering requires xvfb-run or Microsoft account)" + else: + render_backend = "none" + else: + render_backend = "native" + checks.append(("renderedUi", True, render_backend)) return checks def create_server(self, target: Target, settings: dict, server_dir: Path, artifact: Path) -> ServerProcess: diff --git a/autotester/automodpack_autotester/scenarios/__init__.py b/autotester/automodpack_autotester/scenarios/__init__.py index 65dc9c7aa..532a152ea 100644 --- a/autotester/automodpack_autotester/scenarios/__init__.py +++ b/autotester/automodpack_autotester/scenarios/__init__.py @@ -93,7 +93,7 @@ def list_scenarios() -> list[ScenarioSpec]: def _load_all() -> None: - from . import compat, edge, faults, gate, offline, release, transport # noqa: F401 + from . import compat, edge, faults, gate, groups, offline, release, transport # noqa: F401 # --- Shared AutoModpack UI / sync flow helpers --- diff --git a/autotester/automodpack_autotester/scenarios/groups.py b/autotester/automodpack_autotester/scenarios/groups.py new file mode 100644 index 000000000..d50c0f6b5 --- /dev/null +++ b/autotester/automodpack_autotester/scenarios/groups.py @@ -0,0 +1,221 @@ +"""Group selection UI and category/platform/dependency scenario.""" +from __future__ import annotations + +import time +from pathlib import Path + +from ..bridge import BridgeClient, Selector, select_elements +from ..harness import TestCase +from . import scenario, wait_for_tls_fingerprint + + +def _stage_group_file(server_dir: Path, group_id: str, text: str) -> None: + path = server_dir / "automodpack" / "host-modpack" / group_id / "config" / f"{group_id}.txt" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def _row_texts(gui: dict) -> list[str]: + return [str(e.get("text") or "") for e in (gui.get("other") or ())] + + +def _row_checked(gui: dict, title: str) -> bool | None: + for e in gui.get("other") or (): + text = str(e.get("text") or "") + if text.lower().startswith(title.lower()): + return e.get("checked") + return None + + +def _viewport_bounds(gui: dict) -> tuple[int, int]: + lists = [e for e in (gui.get("other") or ()) if e.get("type") == "GroupSelectionList"] + if lists: + el = lists[0] + top = int(el["y"]) + return top, top + int(el["height"]) + return 74, int(gui["screenHeight"]) - 40 + + +def _scroll_row_into_view(bridge: BridgeClient, needle: str, *, max_steps: int = 12) -> dict: + for _ in range(max_steps + 1): + gui = bridge.gui() + view_top, view_bottom = _viewport_bounds(gui) + matches = [e for e in (gui.get("other") or ()) if needle.lower() in str(e.get("text") or "").lower()] + if matches: + el = matches[0] + if int(el["y"]) >= view_top and int(el["y"]) + int(el["height"]) <= view_bottom: + return el + bridge.call("scroll", x=int(gui["screenWidth"]) // 2, y=int(gui["screenHeight"]) // 2, dx=0.0, dy=-3.0) + time.sleep(0.1) + raise AssertionError(f"Row containing {needle!r} never scrolled cleanly into view; gui={bridge.gui()}") + + +@scenario( + "groups-ui", + description="Verify category pick modes, dependency badges, platform dropdown visibility, and optional UI screenshots", + groups=("ui", "groups"), +) +def groups_ui(case: TestCase) -> None: + rich_overrides = { + "modpack": {"name": "Skyward SMP", "auto-exclude-server-side-mods": "METADATA"}, + "categories": { + "shaders": {"name": "Shaders", "description": "Pick one shader pack or leave disabled", "pick": "AT_MOST_ONE"}, + "lighting": {"name": "Lighting Style", "pick": "EXACTLY_ONE"}, + "extras": {"name": "Visual & QoL Extras", "description": "Optional client-side enhancements", "pick": "ANY"}, + }, + "groups": { + "main": {"name": "Core", "description": "Core modpack files", "selection": "REQUIRED", "from-server": []}, + "iris": {"name": "Iris Shaders Engine", "selection": "AUTOMATIC"}, + "complementary": { + "name": "Complementary Reimagined", + "description": "Balanced lighting and reflections", + "category": "shaders", + "selection": "RECOMMENDED", + "requires": ["iris"], + }, + "bsl": { + "name": "BSL Shaders", + "description": "Warm stylized shaders", + "category": "shaders", + "selection": "OPTIONAL", + "requires": ["iris"], + }, + "warm": {"name": "Warm Torchlight", "description": "Cozy golden torches", "category": "lighting", "selection": "RECOMMENDED"}, + "crisp": {"name": "Crisp Daylight", "description": "Neutral daylight palette", "category": "lighting", "selection": "OPTIONAL"}, + "minimap": {"name": "Xaero's Minimap", "description": "HUD map and waypoints", "category": "extras", "selection": "RECOMMENDED"}, + "zoom": {"name": "Zoomify", "description": "Smooth spyglass zoom", "category": "extras", "selection": "OPTIONAL"}, + "waypoints": { + "name": "Shared Waypoints", + "description": "Sync waypoints with teammates", + "category": "extras", + "selection": "OPTIONAL", + "requires": ["minimap"], + }, + "audio": {"name": "Ambient Sounds", "description": "Biome soundscape overhaul", "selection": "OPTIONAL", "conflicts": ["zoom"]}, + }, + } + + with case.step("stage multi-category server.toml"): + case.configure_server(connection_mode="HOLEPUNCH", overrides=rich_overrides) + for gid in ("main", "iris", "complementary", "bsl", "warm", "crisp", "minimap", "zoom", "waypoints", "audio"): + _stage_group_file(case.server.server_dir, gid, f"{gid}-content\n") + + render = case.provider.capabilities.rendered_ui + client = case.client("default") + with case.step("boot server and client and open GroupSelectionScreen"): + case.server.start() + client.start(fast_timers=case.fast_timers, render=render) + case.server.wait_ready(timeout=float(case.settings["timeouts"]["serverStartSeconds"])) + fp = wait_for_tls_fingerprint(case, timeout=60.0) + bridge = client.wait_ready(timeout=float(case.settings["timeouts"]["clientStartSeconds"])) + bridge.connect(f"{case.server.host}:{case.server.game_port}#amp1={fp}") + bridge.wait_screen("PackConfirmScreen", timeout=60.0) + bridge.assert_layout_clean() + bridge.click(Selector(role="button", key="automodpack.confirm.customize", enabled=True), timeout=15.0) + bridge.wait_screen("GroupSelectionScreen", timeout=30.0) + bridge.assert_layout_clean() + + with case.step("verify included-automatically section, hidden OS dropdown, dependency badges, and pairwise conflict"): + gui = bridge.gui() + texts = "\n".join(_row_texts(gui)) + assert "Included automatically" in texts, f"REQUIRED/AUTOMATIC groups must surface under their own section: {texts}" + assert "Core" in texts, "REQUIRED group must be listed under Included automatically" + assert "Iris Shaders Engine" in texts, "AUTOMATIC group required by the default shader must be listed as included" + assert "Required by: Complementary Reimagined" in texts, "active AUTOMATIC group must name its dependents" + assert any(t.startswith("Core") and t.endswith("Required") for t in _row_texts(gui)), "REQUIRED group must say it is required" + assert "Complementary Reimagined" in texts + assert not select_elements(gui, Selector(key="automodpack.selection.platformButton")), "OS dropdown must hide when no platforms are declared" + assert any("None" in t for t in _row_texts(gui)), "AT_MOST_ONE category must expose None radio option" + if render: + time.sleep(0.25) + bridge.screenshot("group_selection_top") + + bridge.click(Selector(role="other", text="None"), timeout=10.0) + bridge.wait_until( + lambda g: "Iris Shaders Engine" not in "\n".join(_row_texts(g)), + timeout=10.0, + desc="AUTOMATIC group hidden once nothing requires it", + ) + bridge.click(Selector(role="other", text="Complementary Reimagined"), timeout=10.0) + bridge.wait_until( + lambda g: any(t.startswith("Iris Shaders Engine") for t in _row_texts(g)), + timeout=10.0, + desc="AUTOMATIC group back once its dependent is selected again", + ) + + _scroll_row_into_view(bridge, "Zoomify") + bridge.click(Selector(role="other", text="Zoomify"), timeout=10.0) + bridge.wait_until(lambda g: _row_checked(g, "Zoomify") is True, timeout=10.0, desc="Zoomify selected") + + _scroll_row_into_view(bridge, "Ambient Sounds") + bridge.click(Selector(role="other", text="Ambient Sounds"), timeout=10.0) + bridge.wait_until( + lambda g: _row_checked(g, "Ambient Sounds") is True and _row_checked(g, "Zoomify") is False, + timeout=10.0, + desc="declared conflict turns the other selected group off", + ) + + _scroll_row_into_view(bridge, "Shared Waypoints") + bridge.click(Selector(role="other", text="Shared Waypoints"), timeout=10.0) + bridge.wait_until( + lambda g: any("Required by: Shared Waypoints" in t for t in _row_texts(g)), + timeout=10.0, + desc="dependency badge after selecting Shared Waypoints", + ) + + _scroll_row_into_view(bridge, "Included automatically") + _scroll_row_into_view(bridge, "Iris Shaders Engine") + bridge.assert_layout_clean() + if render: + time.sleep(0.25) + bridge.screenshot("group_selection_bottom") + + with case.step("reload with platform-restricted group and verify OS dropdown + unavailability"): + bridge.disconnect() + bridge.wait_screen("TitleScreen", timeout=20.0) + rich_overrides["groups"]["win_only"] = { + "name": "Windows Audio Bridge", + "description": "Windows-only spatial audio integration", + "category": "extras", + "selection": "OPTIONAL", + "compatible-platforms": ["windows"], + } + rich_overrides["groups"]["win_core"] = { + "name": "Windows Runtime", + "description": "Required only on Windows", + "selection": "REQUIRED", + "compatible-platforms": ["windows"], + } + case.configure_server(connection_mode="HOLEPUNCH", overrides=rich_overrides) + _stage_group_file(case.server.server_dir, "win_only", "win-only\n") + _stage_group_file(case.server.server_dir, "win_core", "win-core\n") + assert case.server.rcon("automodpack config reload").returncode == 0 + assert case.server.rcon("automodpack generate").returncode == 0 + # Generation runs off the command thread and refuses connections while it runs, so wait for its report. + case.server.wait_for_log(r"\[Rcon: (PUBLISHED|NO_CHANGES|FAILED)", timeout=120.0) + + bridge.connect(f"{case.server.host}:{case.server.game_port}#amp1={fp}") + bridge.wait_screen("PackConfirmScreen", timeout=60.0) + bridge.click(Selector(role="button", key="automodpack.confirm.customize", enabled=True), timeout=15.0) + bridge.wait_screen("GroupSelectionScreen", timeout=30.0) + gui_plat = bridge.gui() + assert select_elements(gui_plat, Selector(text="OS:")), "OS dropdown must appear once compatible-platforms are declared" + plat_texts = "\n".join(_row_texts(gui_plat)) + if case.provider.capabilities.os_family == "windows": + assert "Windows Runtime" in plat_texts, "OS-scoped REQUIRED group must be included on its own platform" + else: + assert "Windows Runtime" not in plat_texts, "OS-scoped REQUIRED group must stay out of Included automatically on another OS" + bridge.assert_layout_clean() + if render: + time.sleep(0.25) + bridge.screenshot("group_selection_platforms") + + row = _scroll_row_into_view(bridge, "Windows Audio Bridge") + if case.provider.capabilities.os_family != "windows": + assert "Not available on" in str(row.get("text") or ""), f"Expected platform incompatibility badge on row: {row}" + assert row.get("enabled") is False + bridge.assert_layout_clean() + if render: + time.sleep(0.25) + bridge.screenshot("group_selection_platforms_row") + client.stop(force=False) diff --git a/autotester/automodpack_autotester/scenarios/release.py b/autotester/automodpack_autotester/scenarios/release.py index 1492be235..3cabb4399 100644 --- a/autotester/automodpack_autotester/scenarios/release.py +++ b/autotester/automodpack_autotester/scenarios/release.py @@ -54,14 +54,11 @@ def no_modpack_server(case: TestCase) -> None: case.configure_server( connection_mode="HOLEPUNCH", overrides={ - "modpack": { - "General": { - "main": { - "required": True, - "default-selected": True, - "from-server": ["config/excluded-only.txt"], - "exclude": ["config/excluded-only.txt"], - } + "groups": { + "main": { + "selection": "REQUIRED", + "from-server": ["config/excluded-only.txt"], + "exclude": ["config/excluded-only.txt"], } } }, diff --git a/autotester/automodpack_autotester/server_seed.py b/autotester/automodpack_autotester/server_seed.py index b89bb613c..7c9d2fb93 100644 --- a/autotester/automodpack_autotester/server_seed.py +++ b/autotester/automodpack_autotester/server_seed.py @@ -24,22 +24,28 @@ _NEOFORGE_MAVEN = "https://maven.neoforged.net/releases/net/neoforged/neoforge" _FORGE_MAVEN = "https://maven.minecraftforge.net/net/minecraftforge/forge" _SEED_SKIP_ON_COPY = frozenset({"logs", "crash-reports", "mods", "automodpack", _SEED_MARKER}) +_USER_AGENT = "automodpack-autotester" def server_cache_dir(target: Target) -> Path: return shared_cache_root() / "servers" / target.id +def _urlopen(url: str, *, timeout: float): + req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT}) + return urllib.request.urlopen(req, timeout=timeout) + + def _download(url: str, dest: Path, timeout: float = 180.0) -> None: dest.parent.mkdir(parents=True, exist_ok=True) tmp = dest.with_suffix(".tmp") - with urllib.request.urlopen(url, timeout=timeout) as resp, tmp.open("wb") as out: + with _urlopen(url, timeout=timeout) as resp, tmp.open("wb") as out: shutil.copyfileobj(resp, out) tmp.replace(dest) def _latest_fabric_installer() -> str: - with urllib.request.urlopen(f"{_FABRIC_META}/versions/installer", timeout=30) as resp: + with _urlopen(f"{_FABRIC_META}/versions/installer", timeout=30) as resp: items = json.loads(resp.read().decode("utf-8")) stable = [i["version"] for i in items if i.get("stable")] return stable[0] if stable else items[0]["version"] diff --git a/autotester/settings.yaml b/autotester/settings.yaml index 1f681efcd..17bf2fd76 100644 --- a/autotester/settings.yaml +++ b/autotester/settings.yaml @@ -47,39 +47,41 @@ server: automodpack: config: - modpackHost: true - generateModpackOnStart: true + modpack-host: true + generate-modpack-on-start: true + require-modpack: true + self-updater: false + nag: + enabled: false + network: + connection-mode: HOLEPUNCH + bind-address: "" + bind-port: -1 + advertised-host: "" + advertised-port: -1 + disable-internal-tls: false + bandwidth-limit: 0 + secrets: + validate: true + lifetime-hours: 336 modpack: - General: - main: - required: true - default-selected: true - from-server: - - "mods/*.jar" - - "config/**" - - "kubejs/**" - - "!kubejs/server_scripts/**" - - "emotes/*" - exclude: - - "**/.*" - - "**/.*/**" - - "**/*.{tmp,disabled,bak}" - - "kubejs/server_scripts/**" - editable: - - "config/**" - autoExcludeServerSideMods: true - requireModpack: true - nagUnModdedClients: false - bindAddress: "" - bindPort: -1 - advertisedEndpointHost: "" - advertisedEndpointPort: -1 - disableInternalTLS: false - connectionMode: HOLEPUNCH - bandwidthLimit: 0 - validateSecrets: true - secretLifetime: 336 - selfUpdater: false + auto-exclude-server-side-mods: METADATA + groups: + main: + selection: REQUIRED + from-server: + - "mods/*.jar" + - "config/**" + - "kubejs/**" + - "!kubejs/server_scripts/**" + - "emotes/*" + exclude: + - "**/.*" + - "**/.*/**" + - "**/*.{tmp,disabled,bak}" + - "kubejs/server_scripts/**" + editable: + - "config/**" windowsVm: # Default location for the KVM/QEMU golden image and live snapshot. diff --git a/autotester/tests/test_core.py b/autotester/tests/test_core.py index 7310b9e2f..166cccbc2 100644 --- a/autotester/tests/test_core.py +++ b/autotester/tests/test_core.py @@ -11,10 +11,13 @@ from automodpack_autotester.bridge import BridgeClient, Selector, select_elements from automodpack_autotester.cache import deduplicate_tree, materialize_tree, prune_passed_case -from automodpack_autotester.hmc import hmc_asset_name +from automodpack_autotester.harness import _deep_merge, _dump_toml +from automodpack_autotester.hmc import hmc_asset_name, write_hmc_config from automodpack_autotester.mod_fixtures import assert_valid_mod_fixture, valid_mod_jar_bytes from automodpack_autotester.process import LogTailer, PortReservation +from automodpack_autotester.provider import linux_render_wrapper from automodpack_autotester.proxy import FaultProxy +from automodpack_autotester.server_seed import _download from automodpack_autotester.static_server import StaticHttpsHost @@ -175,3 +178,62 @@ def test_hmc_asset_names_and_mod_fixture(): assert hmc_asset_name("darwin", "arm64") == "headlessmc-launcher-macos-arm64" fx = {"modId": "test_mod", "version": "1.2.3", "marker": "ok"} assert_valid_mod_fixture(valid_mod_jar_bytes(fx, "26.2"), fx, "26.2") + + +def test_toml_emitter_round_trips_server_config_and_deep_merges(): + import tomllib + + base = { + "modpack-host": True, + "network": {"connection-mode": "HOLEPUNCH", "bind-port": -1}, + "groups": {"main": {"selection": "REQUIRED", "from-server": ["mods/*.jar"]}}, + } + _deep_merge(base, {"modpack": {"name": "Pack"}, "groups": {"main": {"exclude": ["**/.*"]}}}) + parsed = tomllib.loads(_dump_toml(base)) + assert parsed["modpack-host"] is True + assert parsed["network"]["bind-port"] == -1 + assert parsed["modpack"]["name"] == "Pack" + assert parsed["groups"]["main"]["from-server"] == ["mods/*.jar"] + assert parsed["groups"]["main"]["exclude"] == ["**/.*"] + + +def test_render_wrapper_priority_and_hmc_xvfb_flag(tmp_path: Path, monkeypatch): + import shutil + + monkeypatch.setattr(shutil, "which", lambda cmd: f"/usr/bin/{cmd}" if cmd in ("xvfb-run", "gamescope") else None) + assert linux_render_wrapper(1280, 720) == ["/usr/bin/xvfb-run", "-a", "-s", "-screen 0 1280x720x24"] + monkeypatch.setattr(shutil, "which", lambda cmd: "/usr/bin/gamescope" if cmd == "gamescope" else None) + assert linux_render_wrapper(1280, 720) == ["/usr/bin/gamescope", "--backend", "headless", "-W", "1280", "-H", "720", "--"] + monkeypatch.setattr(shutil, "which", lambda _cmd: None) + assert linux_render_wrapper(1280, 720) is None + + write_hmc_config(tmp_path, tmp_path / "mc", tmp_path / "game", tmp_path / "jdk", xvfb_check=True) + cfg = (tmp_path / "headlessmc" / "config.properties").read_text(encoding="utf-8") + assert "hmc.xvfb.check=true" in cfg + + +def test_server_seed_download_sets_non_urllib_user_agent(tmp_path: Path, monkeypatch): + seen_ua: list[str] = [] + + class FakeResp: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def read(self, n=-1): + if getattr(self, "_done", False): + return b"" + self._done = True + return b"installer-bytes" + + def fake_urlopen(req, timeout=None): + seen_ua.append(req.get_header("User-agent") or "") + return FakeResp() + + monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) + out = tmp_path / "inst.jar" + _download("https://example.invalid/forge.jar", out) + assert seen_ua == ["automodpack-autotester"] + assert out.read_bytes() == b"installer-bytes" diff --git a/core/src/main/java/pl/skidam/automodpack_core/change/ChangeBrowserProjection.java b/core/src/main/java/pl/skidam/automodpack_core/change/ChangeBrowserProjection.java index d78ee6d51..ff78c111a 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/change/ChangeBrowserProjection.java +++ b/core/src/main/java/pl/skidam/automodpack_core/change/ChangeBrowserProjection.java @@ -63,7 +63,7 @@ private static List visibleEffects(ChangeSet changes, Filter filter) if (!filter.contentKinds().isEmpty() || !filter.featureIds().isEmpty()) return List.of(); List visible = new ArrayList<>(); for (ChangeSet.Effect effect : changes.effects()) { - if (!effect.category().startsWith("pack.") && !effect.category().startsWith("group.")) continue; + if (!effect.category().startsWith("pack.") && !effect.category().startsWith("category.") && !effect.category().startsWith("group.")) continue; if (!filter.search().isBlank() && !Filter.contains(filter.search(), effect.category()) && !Filter.contains(filter.search(), effect.value())) continue; visible.add(new EffectRow("metadata/" + visible.size(), 0, effect)); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/client/ClientLaunch.java b/core/src/main/java/pl/skidam/automodpack_core/client/ClientLaunch.java index 4af543378..e38e16abe 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/client/ClientLaunch.java +++ b/core/src/main/java/pl/skidam/automodpack_core/client/ClientLaunch.java @@ -116,9 +116,10 @@ private void syncFromServer(ConnectionJsons.ConnectionInfo connectionInfo, Secre try { String modpackId = ModpackId.requireValid(manifestResult.content().policy.modpackId); SelectionIntent desired = new ClientSelectionStore(storage.selectionFile()).get(modpackId).orElse(null); + ClientPlatform platform = ClientPlatform.effective(desired); selectedTarget = desired == null - ? SelectedModpackTarget.prepareDefault(manifestResult.content(), ClientPlatform.current()) - : SelectedModpackTarget.prepare(manifestResult.content(), new ClientGenerationStore(storage).appliedSelection(modpackId).orElse(null), desired, ClientPlatform.current()); + ? SelectedModpackTarget.prepareDefault(manifestResult.content(), platform) + : SelectedModpackTarget.prepare(manifestResult.content(), new ClientGenerationStore(storage).appliedSelection(modpackId).orElse(null), desired, platform); } catch (RuntimeException e) { LOGGER.error("Failed to resolve the downloaded modpack catalogue and group selection", e); transport.close(); diff --git a/core/src/main/java/pl/skidam/automodpack_core/client/ModpackUpdater.java b/core/src/main/java/pl/skidam/automodpack_core/client/ModpackUpdater.java index c9bf3d871..1eaeaf3af 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/client/ModpackUpdater.java +++ b/core/src/main/java/pl/skidam/automodpack_core/client/ModpackUpdater.java @@ -135,7 +135,7 @@ ModpackJsons.ModpackContentFields storedTarget() throws IOException { void reselectTarget(SelectionIntent intent) { Objects.requireNonNull(intent, "intent"); SelectedModpackTarget current = getSelectedTarget(); - SelectedModpackTarget replacement = SelectedModpackTarget.prepare(current.document(), current.expectedPriorIntent(), intent, current.platform()); + SelectedModpackTarget replacement = SelectedModpackTarget.prepare(current.document(), current.expectedPriorIntent(), intent, ClientPlatform.effective(intent)); selectedTarget = replacement; serverModpackContent = replacement.flatTarget(); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/client/RemovalAttempt.java b/core/src/main/java/pl/skidam/automodpack_core/client/RemovalAttempt.java index 4ef380cb8..6c913f859 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/client/RemovalAttempt.java +++ b/core/src/main/java/pl/skidam/automodpack_core/client/RemovalAttempt.java @@ -117,7 +117,7 @@ private static ResolvedSelection removalSelection(ClientUpdatePlanBuilder.Remova SelectionIntent intent = preparation.expectedPriorIntent(); if (intent == null) return null; Set selected = preparation.installed().selectedGroups == null ? Set.of() : preparation.installed().selectedGroups; - Set stale = new TreeSet<>(intent.requestedGroups()); + Set stale = new TreeSet<>(intent.enabled()); stale.removeAll(selected); return new ResolvedSelection(intent, new TreeSet<>(selected), new TreeSet<>(stale)); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/client/SwitchFlow.java b/core/src/main/java/pl/skidam/automodpack_core/client/SwitchFlow.java index e593fed57..a9b2ad66f 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/client/SwitchFlow.java +++ b/core/src/main/java/pl/skidam/automodpack_core/client/SwitchFlow.java @@ -8,7 +8,6 @@ import pl.skidam.automodpack_core.modpack.generation.PackDocument; import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; -import pl.skidam.automodpack_core.modpack.group.GroupSelectionResolver; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.screen.FailureCategory; @@ -57,7 +56,7 @@ public static void rollback(ClientStorage storage, String modpackId, JournalEntr PackDocument record = new ClientGenerationStore(storage).document(modpackId, entry); SelectionIntent appliedSelection = new ClientGenerationStore(storage).appliedSelection(modpackId).orElse(null); SelectionIntent desiredSelection = new ClientSelectionStore(storage.selectionFile()).get(modpackId).orElse(null); - SelectionIntent targetSelection = desiredSelection == null ? GroupSelectionResolver.defaultIntent(record.manifest()) : desiredSelection; + SelectionIntent targetSelection = desiredSelection == null ? SelectionIntent.DEFAULTS : desiredSelection; SelectedModpackTarget target = SelectedModpackTarget.prepare(record, appliedSelection, targetSelection, ClientPlatform.effective(targetSelection)); updater = new ModpackUpdater(target, null, null, storage, modpackLoader); if (updater.requiresSelectedTargetDownload()) diff --git a/core/src/main/java/pl/skidam/automodpack_core/client/UpdateSession.java b/core/src/main/java/pl/skidam/automodpack_core/client/UpdateSession.java index fcdb7c187..75ef6c488 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/client/UpdateSession.java +++ b/core/src/main/java/pl/skidam/automodpack_core/client/UpdateSession.java @@ -8,6 +8,8 @@ import java.util.Comparator; import java.util.List; import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -26,6 +28,7 @@ import pl.skidam.automodpack_core.modpack.generation.JournalEntry; import pl.skidam.automodpack_core.modpack.generation.PackDocument; import pl.skidam.automodpack_core.modpack.generation.PackTarget; +import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.ModpackPathPolicy; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; @@ -215,10 +218,21 @@ private UpdatePreview previewFor(ClientUpdatePlanBuilder.PreparedPlan prepared, // so nothing of the target is still uncached wire bytes here. long remaining = 0; return UpdatePreview.forUpdate(prepared.plan(), target.selection(), journal, tokenRule.installedToken(storage, target.manifest().modpackId())) - .withFeatureManifest(target.manifest()).withUnownedLocalMods(prepared.unownedLocalMods().keySet().stream().sorted().toList()) + .withFeatureManifest(target.manifest()).withNewGroups(newlyAddedChoosableGroups()).withUnownedLocalMods(prepared.unownedLocalMods().keySet().stream().sorted().toList()) .withRemainingWireBytes(remaining); } + private Set newlyAddedChoosableGroups() throws IOException { + PackDocument installed = newest(new ClientGenerationStore(storage), target.manifest().modpackId()); + if (installed == null) return Set.of(); + Set known = installed.manifest().groups().keySet(); + Set added = new TreeSet<>(); + target.manifest().groups().forEach((id, group) -> { + if (group.selection().choosable() && !known.contains(id)) added.add(id); + }); + return added; + } + /** * The one commit of the reviewed plan: changelogs, then the transactional commit with its restart decision. The * confirm is the consent moment, so the commit begins by recording the desire it was approved under; an executing @@ -403,10 +417,11 @@ record = newest(generations, followId); ClientSelectionStore selections = new ClientSelectionStore(storage.selectionFile()); SelectionIntent desired = selections.get(record.manifest().modpackId()).orElse(null); SelectionIntent applied = new ClientGenerationStore(storage).appliedSelection(record.manifest().modpackId()).orElse(null); - if (record.manifest().modpackId().equals(pending.plan().modpackId()) && Objects.equals(desired, pending.targetIntent())) + ClientPlatform effective = desired != null && desired.platform() != null ? desired.platform() : pending.platform(); + if (record.manifest().modpackId().equals(pending.plan().modpackId()) && Objects.equals(desired, pending.targetIntent()) && Objects.equals(effective, pending.platform())) return SelectedModpackTarget.prepare(record, applied, pending.targetIntent(), pending.platform()); - if (desired == null) return SelectedModpackTarget.prepareDefault(record, pending.platform()); - return SelectedModpackTarget.prepare(record, applied, desired, pending.platform()); + if (desired == null) return SelectedModpackTarget.prepareDefault(record, effective); + return SelectedModpackTarget.prepare(record, applied, desired, effective); } private static PackDocument newest(ClientGenerationStore generations, String modpackId) throws IOException { diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/CategoryIds.java b/core/src/main/java/pl/skidam/automodpack_core/config/CategoryIds.java new file mode 100644 index 000000000..eaade9bd8 --- /dev/null +++ b/core/src/main/java/pl/skidam/automodpack_core/config/CategoryIds.java @@ -0,0 +1,30 @@ +package pl.skidam.automodpack_core.config; + +import java.util.Locale; +import java.util.Set; + +import pl.skidam.automodpack_core.utils.OsPaths; + +/** Slugs rc.7 category display names into category IDs that are unique within a document. */ +final class CategoryIds { + /** Same cap as the group ID and category name limits in {@code GroupManifestValidator}. */ + private static final int MAX_LENGTH = 64; + + private CategoryIds() {} + + static String slugify(String rawName, Set usedIds) { + String lower = rawName.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9_-]+", "-").replaceAll("^[-_]+|[-_]+$", ""); + String base = lower.isEmpty() ? "category" : lower; + if (!Character.isLetterOrDigit(base.charAt(0))) base = "c-" + base; + if (OsPaths.isReservedWindowsDeviceName(base)) base = "c-" + base; + if (base.length() > MAX_LENGTH) base = base.substring(0, MAX_LENGTH); + String candidate = base; + for (int suffix = 2; usedIds.contains(candidate) || OsPaths.isReservedWindowsDeviceName(candidate); suffix++) { + String tag = "-" + suffix; + int maxBase = Math.max(1, MAX_LENGTH - tag.length()); + candidate = (base.length() > maxBase ? base.substring(0, maxBase) : base) + tag; + } + usedIds.add(candidate); + return candidate; + } +} diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/ClientStorageJsons.java b/core/src/main/java/pl/skidam/automodpack_core/config/ClientStorageJsons.java index c59c0fe6d..b93b931e8 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/ClientStorageJsons.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/ClientStorageJsons.java @@ -44,15 +44,8 @@ public static class ClientGenerationStateFields { * corruption of unique state and fails the boot in place instead of passing for absent. */ public String createdAt = ""; - /** - * The group selection this pointer was committed under: the applied answer to "what is installed". Null lists - * mean a pointer written before the selection was recorded; readers fall back to the selection store, which - * was the applied record before the store became the player's desired state. - */ - public List selectedGroups = null; - public List selectedCategories = null; - public List excludedGroups = null; - public String selectedPlatform = null; + /** The selection this pointer was committed under; null on pointers written before it was recorded, where readers use the selection store. */ + public SelectionJsons.SelectionFields selection = null; /** * Local sovereignty of the active pack. Exactly two transition kinds exist, both explicit: declared true by * declining a reviewed update, rolling back to an older generation, or the details screen's stop-syncing @@ -78,9 +71,7 @@ public static class InstanceTreeFields { public String activeModpackId = ""; public String contentToken = ""; public boolean detached; - public List requestedGroups = List.of(); - public List requestedCategories = List.of(); - public List excludedGroups = List.of(); + public SelectionJsons.SelectionFields selection = null; public List tombstones = List.of(); public List files = List.of(); @@ -99,7 +90,7 @@ public static class FileFields { } public static class RelayConsentFields { - public int DO_NOT_CHANGE_IT = 1; // file version + public int schemaVersion = 1; public Set modpackIds = new TreeSet<>(); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/ConfigTools.java b/core/src/main/java/pl/skidam/automodpack_core/config/ConfigTools.java index 4bd9356fa..9e2a52b51 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/ConfigTools.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/ConfigTools.java @@ -19,6 +19,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -45,8 +46,7 @@ public final class ConfigTools { /** The custom JSON shapes registered on {@link #GSON}; the same set defines which types key-reflection may not inspect. */ private static final Map, Object> CUSTOM_JSON_ADAPTERS = Map.of(InetSocketAddress.class, new InetSocketAddressTypeAdapter(), ConnectionJsons.ConnectionInfo.class, - new ConnectionInfoTypeAdapter(), ConnectionJsons.CertificateTrustEntry.class, new CertificateTrustEntryTypeAdapter(), ServerConfigJsons.ModpackFields.class, - new ServerConfigJsons.ModpackFields.Adapter()); + new ConnectionInfoTypeAdapter(), ConnectionJsons.CertificateTrustEntry.class, new CertificateTrustEntryTypeAdapter()); /** * Stream-reader strictness for the integral types, registered because Gson 2.8.9 deserializing from a parsed tree @@ -88,13 +88,32 @@ public static GsonBuilder strictEnums(GsonBuilder builder) { public static Optional read(Path path, Class type) { if (!Files.isRegularFile(path)) return Optional.empty(); + return Optional.of(deserialize(readTree(path, type), type, GSON)); + } + + /** + * Reads like {@link #read}, letting the document's reader rewrite an older persisted shape on the parsed tree + * before binding - the seam for shapes whose bytes can never converge on disk, because a mirror keeps the served + * bytes verbatim behind its etag and a content-addressed object's hash is its address. + */ + public static Optional read(Path path, Class type, Consumer legacyShapes) { + if (!Files.isRegularFile(path)) return Optional.empty(); + return Optional.of(deserialize(legacyShapes(readTree(path, type), legacyShapes), type, GSON)); + } + + private static JsonElement readTree(Path path, Class type) { String json; try { json = Files.readString(path, StandardCharsets.UTF_8); } catch (IOException e) { throw new ConfigException("Failed to read configuration " + path.toAbsolutePath().normalize(), e); } - return Optional.of(deserialize(parseTree(json, type), type, GSON)); + return parseTree(json, type); + } + + private static JsonElement legacyShapes(JsonElement tree, Consumer legacyShapes) { + if (tree.isJsonObject()) legacyShapes.accept(tree.getAsJsonObject()); + return tree; } public static T readOrCreate(Path path, Class type, Supplier defaults) { @@ -186,6 +205,16 @@ public static T parse(String json, Class type) { return deserialize(parseTree(json, type), type, GSON); } + /** Binds an already parsed tree, for a reader that inspected the document itself before deciding which shape to bind. */ + public static T parse(JsonElement tree, Class type) { + return deserialize(tree, type, GSON); + } + + /** Parses like {@link #parse}, with the same reader-supplied rewrite of older persisted shapes as {@link #read(Path, Class, Consumer)}. */ + public static T parse(String json, Class type, Consumer legacyShapes) { + return deserialize(legacyShapes(parseTree(json, type), legacyShapes), type, GSON); + } + /** Human {@code .conf} JSON: enum names match without regard to case, unknown names still fail. */ public static T parseHuman(String json, Class type) { return deserialize(parseTree(json, type), type, HUMAN); diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/ConfigUtils.java b/core/src/main/java/pl/skidam/automodpack_core/config/ConfigUtils.java index 1400b8b8d..e447b6425 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/ConfigUtils.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/ConfigUtils.java @@ -10,6 +10,7 @@ import org.apache.logging.log4j.Logger; import pl.skidam.automodpack_core.Environment; +import pl.skidam.automodpack_core.modpack.group.ServerSideModExclusion; import pl.skidam.automodpack_core.protocol.ModpackConnectionMode; public class ConfigUtils { @@ -61,19 +62,21 @@ public static void normalizeServerConfig(ServerConfigJsons.ServerConfigFieldsV3 public static void normalizeServerConfig(ServerConfigJsons.ServerConfigFieldsV3 config) { if (config.connectionMode == null) config.connectionMode = ModpackConnectionMode.HOLEPUNCH; + if (config.modpack == null) return; + if (config.modpack.autoExcludeServerSideMods == null) config.modpack.autoExcludeServerSideMods = ServerSideModExclusion.METADATA; + config.modpack.exclude = normalizeRuleSet(config.modpack.exclude, "modpack.exclude", "", null, false); + config.modpack.editable = normalizeRuleSet(config.modpack.editable, "modpack.editable", "", null, false); - // Rules are group-directory-relative: no leading slash, no '/automodpack/host-modpack/' prefix (slash optional). for (var categoryEntry : config.modpack.categories.entrySet()) { - var category = categoryEntry.getValue(); - if (category == null) throw new ConfigTools.ConfigParseException("Category '" + categoryEntry.getKey() + "' is null; declare its groups or remove the category"); - for (var groupEntry : category.entrySet()) { - var group = groupEntry.getValue(); - if (group == null) throw new ConfigTools.ConfigParseException("Group '" + groupEntry.getKey() + "' in category '" + categoryEntry.getKey() + "' is null; declare it or remove the entry"); - Pattern ownGroupPrefix = Pattern.compile("^/?automodpack/host-modpack/" + Pattern.quote(groupEntry.getKey()) + "(?:/|$)"); - group.fromServer = normalizeRuleSet(group.fromServer, "from-server", groupEntry.getKey(), ownGroupPrefix, true); - group.exclude = normalizeRuleSet(group.exclude, "exclude", groupEntry.getKey(), ownGroupPrefix, false); - group.editable = normalizeRuleSet(group.editable, "editable", groupEntry.getKey(), ownGroupPrefix, false); - } + if (categoryEntry.getValue() == null) throw new ConfigTools.ConfigParseException("Category '" + categoryEntry.getKey() + "' is null; declare it or remove the entry"); + } + for (var groupEntry : config.modpack.groups.entrySet()) { + var group = groupEntry.getValue(); + if (group == null) throw new ConfigTools.ConfigParseException("Group '" + groupEntry.getKey() + "' is null; declare it or remove the entry"); + Pattern ownGroupPrefix = Pattern.compile("^/?automodpack/host-modpack/" + Pattern.quote(groupEntry.getKey()) + "(?:/|$)"); + group.fromServer = normalizeRuleSet(group.fromServer, "from-server", groupEntry.getKey(), ownGroupPrefix, true); + group.exclude = normalizeRuleSet(group.exclude, "exclude", groupEntry.getKey(), ownGroupPrefix, false); + group.editable = normalizeRuleSet(group.editable, "editable", groupEntry.getKey(), ownGroupPrefix, false); } } @@ -93,7 +96,7 @@ private static Set normalizeRuleSet(Set ruleSet, String configKe String body = negated ? path.substring(1) : path; while (body.startsWith("/")) body = body.substring(1); if (body.startsWith("automodpack/host-modpack/")) { - if (ownGroupPrefix.matcher(body).find()) { + if (ownGroupPrefix != null && ownGroupPrefix.matcher(body).find()) { if (dropOwnGroupPaths) LOGGER.info("Removed redundant {} entry '{}': the group directory under '/automodpack/host-modpack/' is included in full.", configKey, rule); else { String remainder = ownGroupPrefix.matcher(body).replaceFirst(""); @@ -107,7 +110,8 @@ private static Set normalizeRuleSet(Set ruleSet, String configKe } else { // Another group's directory cannot be spelled in this group's relative space; stripping it would // silently rebind the rule to this group's files. Keep it verbatim and tell the server owner. - LOGGER.warn("Kept {} entry '{}' verbatim: host-modpack rules must name their own group '{}'.", configKey, rule, groupId); + String target = groupId.isEmpty() ? "pack-level rules must stay group-relative" : "host-modpack rules must name their own group '" + groupId + "'"; + LOGGER.warn("Kept {} entry '{}' verbatim: {}.", configKey, rule, target); normalized.add((negated ? "!" : "") + body); } continue; diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/GroupSelectionMigration.java b/core/src/main/java/pl/skidam/automodpack_core/config/GroupSelectionMigration.java index a424e0a50..0e5b3aa4d 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/GroupSelectionMigration.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/GroupSelectionMigration.java @@ -22,8 +22,8 @@ private GroupSelectionMigration() {} static GroupSelectionMode fromLegacyPair(JsonObject declaration, String context) { boolean required = ConfigTools.strictBoolean(declaration, "required", context); boolean defaultSelected = strictBoolean(declaration, LEGACY_DEFAULT_SELECTED, context); - GroupSelectionMode mode = GroupSelectionMode.of(required, defaultSelected); - if (GroupSelectionMode.collapsed(required, defaultSelected)) LOGGER.info("{} wrote required with default-selected false, which the selection modes cannot express; it became {}", context, mode); + GroupSelectionMode mode = required ? GroupSelectionMode.REQUIRED : defaultSelected ? GroupSelectionMode.RECOMMENDED : GroupSelectionMode.OPTIONAL; + if (required && !defaultSelected) LOGGER.info("{} wrote required with default-selected false, which the selection modes cannot express; it became {}", context, mode); return mode; } diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/HumanConfigMigration.java b/core/src/main/java/pl/skidam/automodpack_core/config/HumanConfigMigration.java index 790624121..6c0e66413 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/HumanConfigMigration.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/HumanConfigMigration.java @@ -1,6 +1,7 @@ package pl.skidam.automodpack_core.config; import java.util.ArrayList; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -20,20 +21,31 @@ import pl.skidam.automodpack_core.modpack.group.ServerSideModExclusion; import pl.skidam.automodpack_core.protocol.ModpackConnectionMode; -/** One-shot JSON → current human model. Used only when the canonical {@code .conf} is missing. */ +/** Imports v4 JSON and rc {@code .conf} configs when the {@code .toml} is missing. */ public final class HumanConfigMigration { private static final Logger LOGGER = LogManager.getLogger(HumanConfigMigration.class); + private static final String DEFAULT_LEGACY_CATEGORY = "General"; private HumanConfigMigration() {} private static final List DROPPED_SERVER = List.of("forceCopyFilesToStandardLocation", "nonModpackFilesToDelete", "updateIpsOnEveryStart", "autoExcludeUnnecessaryFiles"); private static final List DROPPED_CLIENT = List.of("selectedModpack", "installedModpacks", "allowRemoteNonModpackDeletions"); + public static ServerConfigJsons.ServerConfigFieldsV3 mapServer(JsonObject json) { ServerConfigJsons.ServerConfigFieldsV3 config = isV4Server(json) ? mapV4Server(json) : mapV5Server(json); - ServerSideExclusionMigration.applyToMapped(config, json); + applyTopLevelExclusion(config, json); return config; } + private static void applyTopLevelExclusion(ServerConfigJsons.ServerConfigFieldsV3 config, JsonObject json) { + JsonElement element = first(json, "auto-exclude-server-side-mods", "autoExcludeServerSideMods"); + if (element == null) return; + if (!element.isJsonPrimitive()) throw new ConfigTools.ConfigParseException("auto-exclude-server-side-mods must be a boolean or mode name, got " + element); + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isBoolean()) config.modpack.autoExcludeServerSideMods = primitive.getAsBoolean() ? ServerSideModExclusion.METADATA : ServerSideModExclusion.DISABLED; + else config.modpack.autoExcludeServerSideMods = ConfigTools.enumConstant(ServerSideModExclusion.class, primitive.getAsString()); + } + public static MappedClient mapClient(JsonObject json) { ClientConfigJsons.ClientConfigFieldsV3 config = new ClientConfigJsons.ClientConfigFieldsV3(); copyBoolean(json, config, "updateSelectedModpackOnLaunch", "update-selected-modpack-on-launch"); @@ -67,13 +79,14 @@ private static ServerConfigJsons.ServerConfigFieldsV3 mapV4Server(JsonObject jso if (address != null) config.advertisedEndpointHost = address; if (json.has("portToSend") && json.get("portToSend").isJsonPrimitive()) config.advertisedEndpointPort = json.get("portToSend").getAsInt(); config.connectionMode = mapV4ConnectionMode(json, config.bindPort); - ServerConfigJsons.GroupDeclaration main = mainGroup(config); + ServerConfigJsons.GroupDeclaration main = config.modpack.groups.computeIfAbsent("main", ignored -> new ServerConfigJsons.GroupDeclaration()); + main.selection = GroupSelectionMode.REQUIRED; List synced = stringList(json.get("syncedFiles")); if (synced != null) main.fromServer = stripLeadingSlashes(synced); List editable = stringList(json.get("allowEditsInFiles")); - if (editable != null) main.editable = stripLeadingSlashes(editable); + if (editable != null) config.modpack.editable = stripLeadingSlashes(editable); boolean skipJunk = json.has("autoExcludeUnnecessaryFiles") && !json.get("autoExcludeUnnecessaryFiles").getAsBoolean(); - main.exclude = skipJunk ? new LinkedHashSet<>() : new LinkedHashSet<>(ServerConfigJsons.FACTORY_JUNK_EXCLUDE); + config.modpack.exclude = skipJunk ? new LinkedHashSet<>() : new LinkedHashSet<>(ServerConfigJsons.FACTORY_JUNK_EXCLUDE); logDropped(json, DROPPED_SERVER); return config; } @@ -98,7 +111,13 @@ private static ServerConfigJsons.ServerConfigFieldsV3 mapV5Server(JsonObject jso if (leftover != null) config.modpack.name = leftover; } JsonElement modpack = json.get("modpack"); - if (modpack != null && modpack.isJsonObject()) config.modpack = mapModpack(modpack.getAsJsonObject(), config.modpack.name); + if (modpack != null && modpack.isJsonObject()) { + config.modpack = mapModpack(modpack.getAsJsonObject(), config.modpack.name); + } else { + // rc groups did not inherit the pack-wide exclude/editable lists. + config.modpack.exclude = Set.of(); + config.modpack.editable = Set.of(); + } ModpackConnectionMode mode = connectionMode(json); if (mode != null) config.connectionMode = mode; logDropped(json, DROPPED_SERVER); @@ -138,31 +157,55 @@ private static void copySameNameServer(JsonObject json, ServerConfigJsons.Server private static ServerConfigJsons.ModpackFields mapModpack(JsonObject json, String existingName) { ServerConfigJsons.ModpackFields fields = new ServerConfigJsons.ModpackFields(); + fields.exclude = Set.of(); + fields.editable = Set.of(); String name = string(json.get("name")); fields.name = name != null ? name : existingName; - Map> categories = new LinkedHashMap<>(); - Map flat = new LinkedHashMap<>(); + + Map> legacyCategories = new LinkedHashMap<>(); + Map uncategorized = new LinkedHashMap<>(); for (var entry : json.entrySet()) { if (entry.getKey().equals("name") || !entry.getValue().isJsonObject()) continue; JsonObject object = entry.getValue().getAsJsonObject(); - if (looksLikeGroup(object)) flat.put(entry.getKey(), mapGroup(object, entry.getKey())); - else { + if (looksLikeGroup(object)) { + uncategorized.put(entry.getKey(), mapGroup(object, entry.getKey())); + } else { Map groups = new LinkedHashMap<>(); - for (var group : object.entrySet()) if (group.getValue().isJsonObject()) groups.put(group.getKey(), mapGroup(group.getValue().getAsJsonObject(), group.getKey())); - if (!groups.isEmpty()) categories.put(entry.getKey(), groups); + for (var group : object.entrySet()) { + if (group.getValue().isJsonObject()) groups.put(group.getKey(), mapGroup(group.getValue().getAsJsonObject(), group.getKey())); + } + if (!groups.isEmpty()) legacyCategories.put(entry.getKey(), groups); } } - if (!flat.isEmpty()) categories.put("General", merge(categories.get("General"), flat)); - if (categories.isEmpty()) categories.put("General", new LinkedHashMap<>(Map.of("main", new ServerConfigJsons.GroupDeclaration()))); - fields.categories = categories; - return fields; - } - private static Map merge(Map first, Map second) { - LinkedHashMap out = new LinkedHashMap<>(); - if (first != null) out.putAll(first); - out.putAll(second); - return out; + boolean hasCustomCategory = legacyCategories.keySet().stream().anyMatch(cat -> !cat.equals(DEFAULT_LEGACY_CATEGORY)); + Set usedCategoryIds = new HashSet<>(); + for (var catEntry : legacyCategories.entrySet()) { + String rawCategory = catEntry.getKey(); + Map groups = catEntry.getValue(); + // A category of nothing but REQUIRED groups is flattened away: every one of them is always installed, so the legacy section had no pick to offer and the groups belong under Included automatically. + boolean flatten = (rawCategory.equals(DEFAULT_LEGACY_CATEGORY) && !hasCustomCategory) + || groups.values().stream().noneMatch(g -> g.selection != GroupSelectionMode.REQUIRED); + String categoryId = ""; + if (!flatten) { + categoryId = CategoryIds.slugify(rawCategory, usedCategoryIds); + ServerConfigJsons.CategoryDeclaration cat = new ServerConfigJsons.CategoryDeclaration(); + cat.name = rawCategory; + fields.categories.put(categoryId, cat); + } + for (var grpEntry : groups.entrySet()) { + ServerConfigJsons.GroupDeclaration g = grpEntry.getValue(); + if (!categoryId.isEmpty() && g.selection != GroupSelectionMode.REQUIRED) g.category = categoryId; + if (fields.groups.containsKey(grpEntry.getKey())) LOGGER.warn("Duplicate group ID '{}' in legacy category '{}'; the later definition wins", grpEntry.getKey(), rawCategory); + fields.groups.put(grpEntry.getKey(), g); + } + } + fields.groups.putAll(uncategorized); + + if (fields.groups.isEmpty()) { + fields.groups.put("main", new ServerConfigJsons.GroupDeclaration()); + } + return fields; } private static boolean looksLikeGroup(JsonObject object) { @@ -175,17 +218,16 @@ private static boolean looksLikeGroup(JsonObject object) { private static ServerConfigJsons.GroupDeclaration mapGroup(JsonObject json, String groupId) { ServerConfigJsons.GroupDeclaration group = new ServerConfigJsons.GroupDeclaration(); - String displayName = string(first(json, "displayName", "display-name")); - if (displayName != null) group.displayName = displayName; + String displayName = string(first(json, "displayName", "display-name", "name")); + if (displayName != null) group.name = displayName; String description = string(json.get("description")); if (description != null) group.description = description; - // The selection key wins; the flag pair it replaced is read by the same rule the reconf repair applies. if (json.has("selection")) group.selection = selectionEnum(json.get("selection")); else if (json.has("required") || json.has("defaultSelected") || json.has("default-selected")) group.selection = GroupSelectionMigration.fromLegacyPair(json, "Group '" + groupId + "'"); JsonElement exclusion = first(json, "auto-exclude-server-side-mods", "autoExcludeServerSideMods"); if (exclusion != null) group.autoExcludeServerSideMods = exclusionEnum(exclusion); - List breaksWith = stringList(first(json, "breaksWith", "breaks-with")); - if (breaksWith != null) group.breaksWith = new LinkedHashSet<>(breaksWith); + List conflicts = stringList(first(json, "breaksWith", "breaks-with")); + if (conflicts != null) group.conflicts = new LinkedHashSet<>(conflicts); List requires = stringList(json.get("requires")); if (requires != null) group.requires = new LinkedHashSet<>(requires); List platforms = stringList(first(json, "compatiblePlatforms", "compatible-platforms")); @@ -210,15 +252,6 @@ private static ServerSideModExclusion exclusionEnum(JsonElement element) { return ConfigTools.enumConstant(ServerSideModExclusion.class, element.getAsString()); } - private static ServerConfigJsons.GroupDeclaration mainGroup(ServerConfigJsons.ServerConfigFieldsV3 config) { - ServerConfigJsons.GroupDeclaration main = config.modpack.categories.computeIfAbsent("General", ignored -> new LinkedHashMap<>()).computeIfAbsent("main", ignored -> new ServerConfigJsons.GroupDeclaration()); - // v4 had no groups, so the migrated core group takes the factory declaration's required flags: a - // deselectable main group would let players join a migrated server with none of its content. - main.description = "Core modpack files"; - main.selection = GroupSelectionMode.REQUIRED; - return main; - } - private static Set stripLeadingSlashes(List rules) { LinkedHashSet out = new LinkedHashSet<>(); for (String rule : rules) { diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/ModpackJsons.java b/core/src/main/java/pl/skidam/automodpack_core/config/ModpackJsons.java index 3f042f460..7e892f13f 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/ModpackJsons.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/ModpackJsons.java @@ -5,9 +5,12 @@ import java.util.Objects; import java.util.Set; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; + public class ModpackJsons { - /** The immutable policy document of one generation: pack metadata and every group's files and rules. */ + /** The immutable policy document of one generation. */ public static class CompleteModpackContentFields { public String modpackId = ""; public String modpackName = ""; @@ -15,16 +18,22 @@ public static class CompleteModpackContentFields { public String loader = ""; public String loaderVersion = ""; public String mcVersion = ""; - // Category name -> group id -> group fields. The group id is referenced by requires/breaksWith and by the client's saved selection; the category name is the player-facing section label. - public Map> categories = Map.of(); + public Map categories = Map.of(); + public Map groups = Map.of(); + + public static class CategoryFields { + public String name = ""; + public String description = ""; + public CategoryPickMode pick = CategoryPickMode.ANY; + } public static class ModpackGroupFields { - public String displayName = ""; + public String name = ""; public String description = ""; - public Boolean required; - public Boolean defaultSelected; - public Set breaksWith = Set.of(); + public String category = ""; + public GroupSelectionMode selection; public Set requires = Set.of(); + public Set conflicts = Set.of(); public Set compatiblePlatforms = Set.of(); public Map files = Map.of(); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/Rc7ClientSelectionMigration.java b/core/src/main/java/pl/skidam/automodpack_core/config/Rc7ClientSelectionMigration.java new file mode 100644 index 000000000..7aa04dee6 --- /dev/null +++ b/core/src/main/java/pl/skidam/automodpack_core/config/Rc7ClientSelectionMigration.java @@ -0,0 +1,271 @@ +package pl.skidam.automodpack_core.config; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import pl.skidam.automodpack_core.modpack.ModpackId; +import pl.skidam.automodpack_core.modpack.group.ClientPlatform; +import pl.skidam.automodpack_core.modpack.group.GroupManifest; +import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; + +public final class Rc7ClientSelectionMigration { + public interface PolicyLookup { + GroupManifest generation(String modpackId, String contentToken) throws IOException; + + GroupManifest latest(String modpackId) throws IOException; + } + + private static final Logger LOGGER = LogManager.getLogger(Rc7ClientSelectionMigration.class); + private static final List LEGACY_SELECTED_GROUPS = List.of("selectedGroups", "requestedGroups"); + private static final List LEGACY_EXCLUDED_GROUPS = List.of("excludedGroups"); + private static final List LEGACY_SELECTED_CATEGORIES = List.of("selectedCategories", "requestedCategories"); + private static final String LEGACY_SELECTED_PLATFORM = "selectedPlatform"; + + private Rc7ClientSelectionMigration() {} + + /** Keeps the source file intact when a category pick cannot be resolved. */ + public static void migrateActiveState(Path file, PolicyLookup policies) throws IOException { + JsonObject document = readObject(file); + if (document == null || !activeState(document, policies)) return; + ConfigTools.writeAtomic(file, document); + LOGGER.info("Migrated legacy rc.7 client active state to the current shape: {}", file); + } + + /** Caller must hold ClientStorageMutation while migrating the desired-selection store. */ + public static void migrateClientSelections(Path file, PolicyLookup policies) throws IOException { + JsonObject document = readObject(file); + if (document == null) return; + JsonElement version = document.get("DO_NOT_CHANGE_IT"); + if (version == null) return; + if (!version.isJsonPrimitive() || !version.getAsJsonPrimitive().isNumber() || version.getAsInt() != 1) + throw new IOException("Unsupported legacy client group selection version in " + file); + SelectionJsons.ClientSelectionStoreFields migrated = new SelectionJsons.ClientSelectionStoreFields(); + JsonElement selections = document.get("selections"); + if (selections != null && !selections.isJsonNull()) { + if (!selections.isJsonObject()) throw new IOException("Legacy client group selection 'selections' must be an object"); + for (var entry : selections.getAsJsonObject().entrySet()) { + String modpackId = ModpackId.requireValid(entry.getKey()); + if (!entry.getValue().isJsonObject()) throw new IOException("Legacy client group selection for " + modpackId + " must be an object"); + JsonObject legacy = entry.getValue().getAsJsonObject(); + List categories = values(strings(legacy, List.of("requestedCategories"))); + ClientPlatform platform = platform(legacy, "platform"); + List enabled = values(strings(legacy, List.of("requestedGroups"))); + if (!categories.isEmpty()) { + GroupManifest manifest = policies.latest(modpackId); + platform = effectivePlatform(platform, manifest, categories); + enabled = union(enabled, categoryMembers(manifest, categories, platform)); + } + List disabled = sortedDistinct(values(strings(legacy, List.of("excludedGroups")))); + enabled = sortedDistinct(enabled); + disabled.removeAll(enabled); + migrated.selections.put(modpackId, new SelectionJsons.SelectionFields(enabled, disabled, platform == null ? null : platform.id())); + } + } + migrated.selections = new LinkedHashMap<>(new TreeMap<>(migrated.selections)); + ConfigTools.writeAtomic(file, migrated); + LOGGER.info("Migrated legacy rc.7 client group selections: {}", file); + } + + /** + * Converts one legacy instance tree document in memory. The tree's owner proves its stored hash first, because the + * migrated shape can never replace the file: the file is named by the hash of the bytes rc.7 wrote. + * + *

+ * A tree no generation catalogue can answer records no selection instead of failing the read: snapshots outlive the + * generations they ran, and one unresolvable rc.7 category pick must not fail every boot. No selection is the shape + * written before the selection became part of the identity, whose applied answer falls back to the stored desire. + */ + public static void instanceTree(JsonObject document, PolicyLookup policies) { + if (document.has("selection") || !hasLegacySelection(document)) return; + // rc.7 recorded a selection only for the tree that ran a pack; one without a pack records none at all. + if (!hasActivePack(document)) { + removeLegacySelection(document); + return; + } + String modpackId = document.get("activeModpackId").getAsString(); + try { + List categories = values(strings(document, LEGACY_SELECTED_CATEGORIES)); + GroupManifest catalogue = categories.isEmpty() ? null : policies.generation(modpackId, string(document, "contentToken")); + activePointer(document, catalogue, null); + } catch (IOException unresolved) { + LOGGER.warn("The instance tree of {} records no applied selection, its rc.7 selection cannot be resolved: {}", modpackId, unresolved.getMessage()); + removeLegacySelection(document); + } + } + + private static boolean activeState(JsonObject document, PolicyLookup policies) throws IOException { + JsonElement manifestElement = document.get("manifest"); + boolean converted = manifestElement != null && manifestElement.isJsonObject() && Rc7PolicyMigration.policyDocument(manifestElement.getAsJsonObject()); + List selectedCategories = strings(document, LEGACY_SELECTED_CATEGORIES); + if (selectedCategories != null && !selectedCategories.isEmpty()) { + GroupManifest catalogue; + if (manifestElement != null && manifestElement.isJsonObject()) catalogue = currentManifest(manifestElement.getAsJsonObject()); + else catalogue = policies.generation(string(document, "modpackId"), string(document, "contentToken")); + ClientPlatform platform = effectivePlatform(platform(document, LEGACY_SELECTED_PLATFORM), catalogue, selectedCategories); + converted |= activePointer(document, catalogue, platform); + } else { + converted |= activePointer(document, null, platform(document, LEGACY_SELECTED_PLATFORM)); + } + return converted; + } + + private static JsonObject readObject(Path file) throws IOException { + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) return null; + try { + JsonElement tree = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)); + return tree.isJsonObject() ? tree.getAsJsonObject() : null; + } catch (RuntimeException invalid) { + return null; + } + } + + private static GroupManifest currentManifest(JsonObject manifest) { + return GroupManifestValidator.validate(ConfigTools.parse(manifest.toString(), ModpackJsons.CompleteModpackContentFields.class)); + } + + private static boolean activePointer(JsonObject document, GroupManifest catalogue, ClientPlatform platform) throws IOException { + if (document.has("selection")) return false; + List selectedGroups = strings(document, LEGACY_SELECTED_GROUPS); + List excludedGroups = strings(document, LEGACY_EXCLUDED_GROUPS); + List selectedCategories = strings(document, LEGACY_SELECTED_CATEGORIES); + if (selectedGroups == null && excludedGroups == null && selectedCategories == null && !document.has(LEGACY_SELECTED_PLATFORM)) return false; + + List expandedCategories = selectedCategories == null || selectedCategories.isEmpty() ? List.of() : categoryMembers(catalogue, selectedCategories, platform); + List enabled = sortedDistinct(union(selectedGroups, expandedCategories)); + List disabled = sortedDistinct(excludedGroups); + disabled.removeAll(enabled); + + JsonObject selection = new JsonObject(); + selection.add("enabled", array(enabled)); + selection.add("disabled", array(disabled)); + if (platform != null) selection.addProperty("platform", platform.id()); + + document.remove(LEGACY_SELECTED_PLATFORM); + removeLegacySelection(document); + document.add("selection", selection); + return true; + } + + private static boolean hasActivePack(JsonObject document) { + JsonElement active = document.get("activeModpackId"); + return active != null && active.isJsonPrimitive() && active.getAsJsonPrimitive().isString() && !active.getAsString().isBlank(); + } + + private static boolean hasLegacySelection(JsonObject document) { + for (String key : LEGACY_SELECTED_GROUPS) if (document.has(key)) return true; + for (String key : LEGACY_EXCLUDED_GROUPS) if (document.has(key)) return true; + for (String key : LEGACY_SELECTED_CATEGORIES) if (document.has(key)) return true; + return false; + } + + private static void removeLegacySelection(JsonObject document) { + for (String key : LEGACY_SELECTED_GROUPS) document.remove(key); + for (String key : LEGACY_EXCLUDED_GROUPS) document.remove(key); + for (String key : LEGACY_SELECTED_CATEGORIES) document.remove(key); + } + + private static List categoryMembers(GroupManifest manifest, List selectedCategories, ClientPlatform platform) throws IOException { + List members = new ArrayList<>(); + for (String category : selectedCategories) { + for (String groupId : manifest.groupsOf(categoryId(manifest, category))) { + GroupManifest.Group group = manifest.groups().get(groupId); + if (group.selection().choosable() && group.supports(platform)) members.add(groupId); + } + } + return sortedDistinct(members); + } + + private static String categoryId(GroupManifest manifest, String category) throws IOException { + return manifest.categories().entrySet().stream() + .filter(entry -> entry.getKey().equals(category) || entry.getValue().name().equals(category)) + .map(Map.Entry::getKey).findFirst() + .orElseThrow(() -> new IOException("Legacy category selection '" + category + "' cannot be mapped in modpack " + manifest.modpackId())); + } + + private static ClientPlatform effectivePlatform(ClientPlatform stored, GroupManifest manifest, List categories) throws IOException { + if (stored != null) return stored; + ClientPlatform current = ClientPlatform.current(); + if (current != null) return current; + for (String category : categories) { + String categoryId = categoryId(manifest, category); + for (String groupId : manifest.groupsOf(categoryId)) { + if (!manifest.groups().get(groupId).compatiblePlatforms().isEmpty()) + throw new IOException("Legacy category selection for " + manifest.modpackId() + " has no recorded platform"); + } + } + return null; + } + + private static ClientPlatform platform(JsonObject document, String key) { + JsonElement value = document.get(key); + return value == null || value.isJsonNull() ? null : platform(value, key); + } + + private static ClientPlatform platform(JsonElement value, String key) { + if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) + throw new ConfigTools.ConfigParseException("A rc.7 selection has a non-string '" + key + "'"); + String raw = value.getAsString().strip(); + return raw.isEmpty() ? null : ClientPlatform.parse(raw); + } + + private static String string(JsonObject document, String key) throws IOException { + JsonElement value = document.get(key); + if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString() || value.getAsString().isBlank()) + throw new IOException("Legacy active state is missing its " + key); + return value.getAsString(); + } + + private static List union(List first, List second) { + List joined = new ArrayList<>(); + if (first != null) joined.addAll(first); + if (second != null) joined.addAll(second); + return joined; + } + + private static List values(List values) { + return values == null ? List.of() : values; + } + + private static JsonArray array(List values) { + JsonArray array = new JsonArray(); + for (String value : values) array.add(value); + return array; + } + + private static List strings(JsonObject document, List keys) { + for (String key : keys) { + JsonElement element = document.get(key); + if (element == null || element.isJsonNull()) continue; + if (!element.isJsonArray()) throw new ConfigTools.ConfigParseException("A rc.7 selection has a non-array '" + key + "'"); + List values = new ArrayList<>(); + for (JsonElement item : element.getAsJsonArray()) { + if (!item.isJsonPrimitive() || !item.getAsJsonPrimitive().isString()) + throw new ConfigTools.ConfigParseException("A rc.7 selection has a non-string entry in '" + key + "'"); + values.add(item.getAsString()); + } + return values; + } + return null; + } + + private static List sortedDistinct(List values) { + if (values == null) return new ArrayList<>(); + return new ArrayList<>(values.stream().filter(value -> !value.isBlank()).distinct().sorted().toList()); + } +} diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/Rc7PolicyMigration.java b/core/src/main/java/pl/skidam/automodpack_core/config/Rc7PolicyMigration.java new file mode 100644 index 000000000..0fbdd5e75 --- /dev/null +++ b/core/src/main/java/pl/skidam/automodpack_core/config/Rc7PolicyMigration.java @@ -0,0 +1,109 @@ +package pl.skidam.automodpack_core.config; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.function.Predicate; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; + +public final class Rc7PolicyMigration { + private static final Logger LOGGER = LogManager.getLogger(Rc7PolicyMigration.class); + + private Rc7PolicyMigration() {} + + public static boolean headDocument(JsonObject document) { + JsonElement policy = document.get("policy"); + return policy != null && policy.isJsonObject() && policyDocument(policy.getAsJsonObject()); + } + + /** Policy objects are content-addressed, so this conversion never rewrites their bytes. */ + public static boolean policyDocument(JsonObject document) { + JsonElement categories = document.get("categories"); + if (document.has("groups") || categories == null || !categories.isJsonObject()) return false; + JsonObject groups = new JsonObject(); + JsonObject migratedCategories = new JsonObject(); + Set usedCategoryIds = new LinkedHashSet<>(); + for (var categoryEntry : categories.getAsJsonObject().entrySet()) { + if (!categoryEntry.getValue().isJsonObject()) + throw new ConfigTools.ConfigParseException("A rc.7 manifest category must map group IDs to declarations: " + categoryEntry.getKey()); + JsonObject categoryGroups = categoryEntry.getValue().getAsJsonObject(); + if (categoryGroups.isEmpty()) continue; + String rawName = categoryEntry.getKey(); + String categoryId = rawName.isBlank() ? "" : CategoryIds.slugify(rawName, usedCategoryIds); + if (!categoryId.isEmpty()) migratedCategories.add(categoryId, category(rawName)); + for (var groupEntry : categoryGroups.entrySet()) { + if (groups.has(groupEntry.getKey())) throw new ConfigTools.ConfigParseException("A rc.7 manifest declares group '" + groupEntry.getKey() + "' more than once"); + groups.add(groupEntry.getKey(), group(groupEntry.getKey(), groupEntry.getValue(), categoryId)); + } + } + document.add("categories", migratedCategories); + document.add("groups", groups); + return true; + } + + public static void migrateProjection(Path file) throws IOException { + JsonObject migrated = migrateFile(file, Rc7PolicyMigration::headDocument); + if (migrated == null) return; + ConfigTools.writeAtomicCompact(file, migrated); + LOGGER.info("Migrated legacy rc.7 server generation projection to the current shape: {}", file); + } + + private static JsonObject migrateFile(Path file, Predicate shapes) throws IOException { + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) return null; + JsonElement tree; + try { + tree = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)); + } catch (IOException | RuntimeException unreadable) { + return null; + } + if (!tree.isJsonObject()) return null; + JsonObject document = tree.getAsJsonObject(); + try { + return shapes.test(document) ? document : null; + } catch (RuntimeException invalid) { + return null; + } + } + + private static JsonObject category(String rawName) { + JsonObject category = new JsonObject(); + category.addProperty("name", rawName); + category.addProperty("description", ""); + category.addProperty("pick", CategoryPickMode.ANY.name()); + return category; + } + + private static JsonObject group(String id, JsonElement declaration, String categoryId) { + if (!declaration.isJsonObject()) throw new ConfigTools.ConfigParseException("A rc.7 manifest group must be an object: " + id); + JsonObject legacy = declaration.getAsJsonObject(); + if (!legacy.has("required") || !legacy.has("defaultSelected")) + throw new ConfigTools.ConfigParseException("A rc.7 manifest group without its selection flags cannot be read: " + id); + JsonObject group = new JsonObject(); + copy(legacy, "displayName", group, "name"); + copy(legacy, "description", group, "description"); + if (!categoryId.isEmpty()) group.addProperty("category", categoryId); + group.addProperty("selection", GroupSelectionMigration.fromLegacyPair(legacy, "Group '" + id + "'").name()); + copy(legacy, "requires", group, "requires"); + copy(legacy, "breaksWith", group, "conflicts"); + copy(legacy, "compatiblePlatforms", group, "compatiblePlatforms"); + copy(legacy, "files", group, "files"); + return group; + } + + private static void copy(JsonObject source, String sourceKey, JsonObject target, String targetKey) { + JsonElement value = source.get(sourceKey); + if (value != null && !value.isJsonNull()) target.add(targetKey, value); + } +} diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/SelectionJsons.java b/core/src/main/java/pl/skidam/automodpack_core/config/SelectionJsons.java index 847f29c11..b02d1d9cf 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/SelectionJsons.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/SelectionJsons.java @@ -1,33 +1,69 @@ package pl.skidam.automodpack_core.config; +import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; +import java.util.List; import java.util.Map; -import java.util.Set; import com.google.gson.annotations.SerializedName; +import pl.skidam.automodpack_core.modpack.group.ClientPlatform; +import pl.skidam.automodpack_core.modpack.group.SelectionIntent; + public class SelectionJsons { public static class ClientSelectionStoreFields { - public int DO_NOT_CHANGE_IT = 1; // file version - public Map selections = new HashMap<>(); - - public static class ModpackSelection { - public Set requestedGroups = new HashSet<>(); - public Set requestedCategories = new HashSet<>(); - public Set excludedGroups = new HashSet<>(); - @SerializedName("platform") - public String platform; - - public ModpackSelection() {} - - public ModpackSelection(Set requestedGroups, Set requestedCategories, Set excludedGroups, String platform) { - this.requestedGroups = requestedGroups; - this.requestedCategories = requestedCategories; - this.excludedGroups = excludedGroups; - this.platform = platform; + public int schemaVersion = 2; + public Map selections = new HashMap<>(); + } + + /** Persisted selection shared by the client store, active pointer, instance tree and update transactions. */ + public static class SelectionFields { + public List enabled = new ArrayList<>(); + public List disabled = new ArrayList<>(); + @SerializedName("platform") + public String platform; + + public SelectionFields() {} + + public SelectionFields(List enabled, List disabled, String platform) { + this.enabled = enabled; + this.disabled = disabled; + this.platform = platform; + } + + public static SelectionFields from(SelectionIntent intent) { + if (intent == null) return null; + return new SelectionFields(new ArrayList<>(intent.enabled()), new ArrayList<>(intent.disabled()), + intent.platform() == null ? null : intent.platform().id()); + } + + public SelectionIntent toIntent() { + ClientPlatform parsed = platform == null || platform.isBlank() ? null : ClientPlatform.parse(platform); + return new SelectionIntent(enabled == null ? List.of() : enabled, disabled == null ? List.of() : disabled, parsed); + } + + public SelectionFields copy() { + return new SelectionFields(enabled == null ? null : new ArrayList<>(enabled), disabled == null ? null : new ArrayList<>(disabled), platform); + } + + public boolean isCanonical() { + if (!isCanonicalList(enabled) || !isCanonicalList(disabled)) return false; + for (String id : enabled) if (disabled.contains(id)) return false; + if (platform != null) { + try { + if (!ClientPlatform.parse(platform).id().equals(platform)) return false; + } catch (RuntimeException e) { + return false; + } } + return true; + } + + private static boolean isCanonicalList(List values) { + if (values == null) return false; + for (String value : values) if (value == null || value.isBlank()) return false; + return values.equals(values.stream().distinct().sorted().toList()); } } } diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/ServerConfigJsons.java b/core/src/main/java/pl/skidam/automodpack_core/config/ServerConfigJsons.java index 49c7f8d97..5a3dcae17 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/ServerConfigJsons.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/ServerConfigJsons.java @@ -1,6 +1,5 @@ package pl.skidam.automodpack_core.config; -import java.lang.reflect.Type; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -8,37 +7,14 @@ import java.util.Map; import java.util.Set; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; import com.google.gson.annotations.SerializedName; -import com.google.gson.reflect.TypeToken; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.ServerSideModExclusion; import pl.skidam.automodpack_core.protocol.ModpackConnectionMode; public class ServerConfigJsons { - static final String PACK_SECTION = "modpack"; - private static final String PACK_NAME_KEY = "name"; - - /** Every group declaration under {@code modpack}; {@code name} is the pack's display name, not a category. */ - static void forEachGroup(JsonObject document, GroupVisitor visitor) { - if (!(document.get(PACK_SECTION) instanceof JsonObject modpack)) return; - for (var category : modpack.entrySet()) { - if (category.getKey().equals(PACK_NAME_KEY) || !(category.getValue() instanceof JsonObject categoryObject)) continue; - for (var group : categoryObject.entrySet()) if (group.getValue() instanceof JsonObject groupObject) visitor.visit(category.getKey(), group.getKey(), groupObject); - } - } - - @FunctionalInterface - interface GroupVisitor { - void visit(String category, String group, JsonObject declaration); - } public static class ServerConfigFieldsV3 { @SerializedName("modpack-host") @@ -106,94 +82,55 @@ public static ServerConfigFieldsV3 standalone() { private static GroupDeclaration mainGroupDeclaration() { GroupDeclaration declaration = new GroupDeclaration(); - declaration.description = "Core modpack files"; declaration.selection = GroupSelectionMode.REQUIRED; declaration.fromServer = new LinkedHashSet<>(FACTORY_FROM_SERVER); - declaration.exclude = new LinkedHashSet<>(FACTORY_EXCLUDE); - declaration.editable = new LinkedHashSet<>(FACTORY_EDITABLE); return declaration; } /** - * The pack section: the reserved {@code name} key is the pack's display name, every other member is a category of - * groups. The reserved key is what makes this a typed object instead of a bare map - a {@code name} member that is - * not a string fails the parse with a clear message instead of being silently swallowed as an unread category. + * The field initializers are the single table of defaults: every read starts here and overlays only what the document declares, so an omitted key takes its documented default. Only the bootstrap writes that a + * fresh config needs add the {@code main} group via {@link #withMainGroup()}; a document without groups stays without groups and generation refuses it. */ public static class ModpackFields { public String name = ""; - public Map> categories = new LinkedHashMap<>(); - - private static final Type GROUPS_TYPE = new TypeToken>() { - }.getType(); + @SerializedName("auto-exclude-server-side-mods") + public ServerSideModExclusion autoExcludeServerSideMods = ServerSideModExclusion.METADATA; + public Set exclude = new LinkedHashSet<>(FACTORY_EXCLUDE); + public Set editable = new LinkedHashSet<>(FACTORY_EDITABLE); + public Map categories = new LinkedHashMap<>(); + public Map groups = new LinkedHashMap<>(); + /** The fresh host bootstrap: defaults plus the {@code main} group. Never a parse default. */ public static ModpackFields withMainGroup() { ModpackFields fields = new ModpackFields(); - fields.categories = new LinkedHashMap<>(Map.of("General", new LinkedHashMap<>(Map.of("main", mainGroupDeclaration())))); + fields.groups = new LinkedHashMap<>(Map.of("main", mainGroupDeclaration())); return fields; } public static ModpackFields withStandaloneMain() { ModpackFields fields = withMainGroup(); - fields.categories.get("General").get("main").fromServer = Set.of(); + fields.groups.get("main").fromServer = Set.of(); return fields; } + } - /** Serializes {@code name} plus every category into one flat object and reads the same shape back. */ - public static final class Adapter implements JsonSerializer, JsonDeserializer, ConfigTools.UnknownKeyScanner { - @Override - public JsonElement serialize(ModpackFields src, Type type, JsonSerializationContext context) { - JsonObject object = new JsonObject(); - object.addProperty(PACK_NAME_KEY, src.name); - for (var entry : src.categories.entrySet()) object.add(entry.getKey(), context.serialize(entry.getValue())); - return object; - } - - @Override - public ModpackFields deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { - if (json == null || !json.isJsonObject()) throw new JsonParseException("modpack must hold the pack name and its categories: modpack { name: \"\", { { ... } } }"); - ModpackFields fields = new ModpackFields(); - for (var entry : json.getAsJsonObject().entrySet()) { - if (entry.getKey().equals(PACK_NAME_KEY)) { - if (entry.getValue() == null || !entry.getValue().isJsonPrimitive() || !entry.getValue().getAsJsonPrimitive().isString()) - throw new JsonParseException("modpack.name must be a string; the name key is reserved and cannot be a category"); - fields.name = entry.getValue().getAsString(); - } else { - fields.categories.put(entry.getKey(), context.deserialize(entry.getValue(), GROUPS_TYPE)); - } - } - return fields; - } - - @Override - public void collectUnknownKeys(JsonElement element, String prefix, List unknown) { - for (var entry : element.getAsJsonObject().entrySet()) { - if (entry.getKey().equals(PACK_NAME_KEY)) continue; - String categoryPath = prefix.isEmpty() ? entry.getKey() : prefix + "." + entry.getKey(); - ConfigTools.collectUnknownKeys(entry.getValue(), GROUPS_TYPE, categoryPath, unknown); - } - } - } + public static class CategoryDeclaration { + public String name = ""; + public String description = ""; + public CategoryPickMode pick = CategoryPickMode.ANY; } public static class GroupDeclaration { - @SerializedName("display-name") - public String displayName = ""; + public String name = ""; public String description = ""; + public String category = ""; public GroupSelectionMode selection = GroupSelectionMode.OPTIONAL; @SerializedName("auto-exclude-server-side-mods") - public ServerSideModExclusion autoExcludeServerSideMods = ServerSideModExclusion.METADATA; - - @SerializedName("breaks-with") - public Set breaksWith = Set.of(); + public ServerSideModExclusion autoExcludeServerSideMods; public Set requires = Set.of(); + public Set conflicts = Set.of(); @SerializedName("compatible-platforms") public Set compatiblePlatforms = Set.of(); - - /** - * File rules scoped to this group. Two postures: the group's directory under host-modpack is included in full - * and {@code exclude} is the only way to leave content out of it, while nothing is synced from the server - * directory unless a {@code from-server} rule includes it - exclude carves exceptions out of either. - */ @SerializedName("from-server") public Set fromServer = Set.of(); public Set exclude = Set.of(); diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/ServerSideExclusionMigration.java b/core/src/main/java/pl/skidam/automodpack_core/config/ServerSideExclusionMigration.java deleted file mode 100644 index efd5dbe29..000000000 --- a/core/src/main/java/pl/skidam/automodpack_core/config/ServerSideExclusionMigration.java +++ /dev/null @@ -1,51 +0,0 @@ -package pl.skidam.automodpack_core.config; - -import java.util.HashSet; -import java.util.Set; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import pl.skidam.automodpack_core.modpack.group.ServerSideModExclusion; - -/** - * Translates the legacy pack-level {@code auto-exclude-server-side-mods} boolean onto each group's - * {@link ServerSideModExclusion} enum during migration from v4 JSON and v5-rc {@code .conf}. - */ -final class ServerSideExclusionMigration { - static final String KEY = "auto-exclude-server-side-mods"; - private static final String LEGACY_CAMEL = "autoExcludeServerSideMods"; - - private ServerSideExclusionMigration() {} - - /** Pack-level boolean when the file still has one; null when the key is already gone. */ - static Boolean packLevelEnabled(JsonObject document) { - JsonElement element = first(document, KEY, LEGACY_CAMEL); - if (element == null) return null; - if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isBoolean()) - throw new ConfigTools.ConfigParseException("auto-exclude-server-side-mods must be a boolean, got " + element); - return element.getAsBoolean(); - } - - /** Stamps {@code DISABLED} onto migrated groups that omitted the key when pack-level exclusion was false. */ - static void applyToMapped(ServerConfigJsons.ServerConfigFieldsV3 config, JsonObject original) { - Boolean enabled = packLevelEnabled(original); - if (enabled == null || enabled) return; - Set explicit = new HashSet<>(); - ServerConfigJsons.forEachGroup(original, (category, group, declaration) -> { - if (declaration.has(KEY) || declaration.has(LEGACY_CAMEL)) explicit.add(category + "/" + group); - }); - for (var category : config.modpack.categories.entrySet()) { - if (category.getValue() == null) continue; - for (var group : category.getValue().entrySet()) { - if (group.getValue() == null || explicit.contains(category.getKey() + "/" + group.getKey())) continue; - group.getValue().autoExcludeServerSideMods = ServerSideModExclusion.DISABLED; - } - } - } - - private static JsonElement first(JsonObject json, String... names) { - for (String name : names) if (json.has(name)) return json.get(name); - return null; - } -} diff --git a/core/src/main/java/pl/skidam/automodpack_core/config/TomlConfigs.java b/core/src/main/java/pl/skidam/automodpack_core/config/TomlConfigs.java index d1912fc78..bb2105c33 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/config/TomlConfigs.java +++ b/core/src/main/java/pl/skidam/automodpack_core/config/TomlConfigs.java @@ -15,7 +15,6 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -30,15 +29,16 @@ import com.google.gson.JsonSyntaxException; import pl.skidam.automodpack_core.config.ClientConfigJsons.ClientConfigFieldsV3; +import pl.skidam.automodpack_core.config.ServerConfigJsons.CategoryDeclaration; import pl.skidam.automodpack_core.config.ServerConfigJsons.GroupDeclaration; import pl.skidam.automodpack_core.config.ServerConfigJsons.ModpackFields; import pl.skidam.automodpack_core.config.ServerConfigJsons.ServerConfigFieldsV3; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.ServerSideModExclusion; import pl.skidam.automodpack_core.protocol.ModpackConnectionMode; import pl.skidam.automodpack_core.utils.DurableFiles; import pl.skidam.automodpack_core.utils.OsPaths; -import pl.skidam.tomledit.Comments; import pl.skidam.tomledit.ConfigPath; import pl.skidam.tomledit.Document; import pl.skidam.tomledit.ParseError; @@ -46,8 +46,8 @@ import pl.skidam.tomledit.ReconcilePolicy; import pl.skidam.tomledit.TableReader; import pl.skidam.tomledit.TomlEdit; +import pl.skidam.tomledit.TomlException; import pl.skidam.tomledit.TomlSchema; -import pl.skidam.tomledit.TomlValidationException; import pl.skidam.tomledit.TomlValue; /** @@ -71,6 +71,16 @@ public final class TomlConfigs { .field(ConfigPath.of("self-updater"), TomlValue.bool(false)) .field(ConfigPath.of("accepted-loaders"), TomlValue.array(), "extra loaders allowed to join; this server's loader is always accepted") .field(ConfigPath.of("advertise-versions-to-sync"), TomlValue.bool(true), "tell clients the pack Minecraft and loader versions") + .comment(ConfigPath.of("modpack"), + "host-modpack// is included in full. from-server pulls extra files from the server root. exclude and editable apply to every group; groups can extend or negate (!) them.") + .field(ConfigPath.of("modpack", "name"), TomlValue.str("")) + .field(ConfigPath.of("modpack", "auto-exclude-server-side-mods"), TomlValue.str(ServerSideModExclusion.METADATA.name()), + "DISABLED ships every jar. METADATA and PLATFORMS drop dedicated-server jars on a best-effort basis.") + .field(ConfigPath.of("modpack", "exclude"), stringArray(ServerConfigJsons.FACTORY_EXCLUDE)) + .field(ConfigPath.of("modpack", "editable"), stringArray(ServerConfigJsons.FACTORY_EDITABLE)) + .dynamicTable(ConfigPath.of("categories")) + .comment(ConfigPath.of("groups"), "Each group maps 1:1 to host-modpack//. selection: REQUIRED, RECOMMENDED, OPTIONAL, AUTOMATIC.") + .dynamicTable(ConfigPath.of("groups")) .field(ConfigPath.of("network", "connection-mode"), TomlValue.str(ModpackConnectionMode.HOLEPUNCH.name()), "HOLEPUNCH uses the Minecraft port. MAGIC can share it or use bind-port. HTTP uses bind-port.") .field(ConfigPath.of("network", "bind-address"), TomlValue.str("")) @@ -88,24 +98,6 @@ public final class TomlConfigs { .field(ConfigPath.of("nag", "clickable-link"), TomlValue.str("https://modrinth.com/project/automodpack")) .field(ConfigPath.of("export-http", "directory"), TomlValue.str("")) .field(ConfigPath.of("export-http", "include-all"), TomlValue.bool(false)) - .comment(ConfigPath.of("modpack"), - "host-modpack// is included in full. from-server pulls extra files from the server root. exclude and editable apply after that; they do not add files.") - .field(ConfigPath.of("modpack", "name"), TomlValue.str("")) - .build(); - - private static final TomlSchema GROUP_SCHEMA = TomlSchema.builder() - .field(ConfigPath.of("display-name"), TomlValue.str("")) - .field(ConfigPath.of("description"), TomlValue.str("")) - .field(ConfigPath.of("selection"), TomlValue.str(GroupSelectionMode.OPTIONAL.name()), - "REQUIRED is always installed. RECOMMENDED is pre-selected, players can opt out. OPTIONAL starts unchecked.") - .field(ConfigPath.of("auto-exclude-server-side-mods"), TomlValue.str(ServerSideModExclusion.METADATA.name()), - "DISABLED ships every jar. METADATA and PLATFORMS drop dedicated-server jars on a best-effort basis. Use exclude for anything else.") - .field(ConfigPath.of("breaks-with"), TomlValue.array()) - .field(ConfigPath.of("requires"), TomlValue.array()) - .field(ConfigPath.of("compatible-platforms"), TomlValue.array()) - .field(ConfigPath.of("from-server"), TomlValue.array(), "extra paths from the server root") - .field(ConfigPath.of("exclude"), TomlValue.array(), "drop these from the pack; they do not add files") - .field(ConfigPath.of("editable"), TomlValue.array(), "pack files players may change; listing a path here does not add it to the pack") .build(); private static final TomlSchema CLIENT_SCHEMA = TomlSchema.builder() @@ -135,9 +127,7 @@ public static Optional read(Path path, Class type) { return Optional.empty(); } - /** - * Reads or generates one human config; a fresh file is generated canonically with declared comments. - */ + /** Reads a human config, generating it when missing. */ public static T readOrCreate(Path path, Class type, Supplier defaults) { Optional existing = read(path, type); if (existing.isPresent()) return existing.get(); @@ -152,15 +142,38 @@ public static T readOrCreate(Path path, Class type, Supplier defaults) * comments, and the result is written atomically. A corrupt existing file fails loudly. */ public static void save(Path path, T model, Class type, Supplier defaults) throws IOException { - Document document = prepareSaveDocument(path, model, type); + byte[] bytes = prepareSaveBytes(path, model, type); OsPaths.requirePublishableConfig(path); - DurableFiles.writeAtomic(path, document.text()); + DurableFiles.writeAtomic(path, bytes); } - private static Document prepareSaveDocument(Path path, T model, Class type) throws IOException { - if (!Files.isRegularFile(path)) { - return freshDocument(model, type); + /** Appends new {@code [groups.]} tables, leaving existing entries and comments untouched. */ + public static void insertImportedGroups(Path path, Map imported) throws IOException { + if (imported == null || imported.isEmpty()) return; + byte[] bytes; + if (Files.isRegularFile(path)) { + Document document = parseExistingForEdit(path); + try { + document.atomic(d -> { + for (var entry : imported.entrySet()) { + if (entry.getValue() == null) continue; + d.ensure(ConfigPath.of("groups", entry.getKey()), groupToTable(entry.getValue(), null), null); + } + }); + } catch (TomlException e) { + throw new ConfigTools.ConfigParseException("Cannot update " + path.getFileName() + ": " + e.getMessage(), e); + } + bytes = document.text(); + } else { + ServerConfigFieldsV3 config = new ServerConfigFieldsV3(); + config.modpack.groups.putAll(imported); + bytes = canonicalBytes(config, ServerConfigFieldsV3.class); } + OsPaths.requirePublishableConfig(path); + DurableFiles.writeAtomic(path, bytes); + } + + private static Document parseExistingForEdit(Path path) throws IOException { byte[] bytes = Files.readAllBytes(path); ParseResult result = TomlEdit.parse(bytes); if (!result.isOk()) { @@ -168,30 +181,28 @@ private static Document prepareSaveDocument(Path path, T model, Class typ throw new ConfigTools.ConfigParseException("Cannot save " + path.getFileName() + ": the file is corrupt at line " + error.line() + ":" + error.column() + " (" + error.kind() + "): " + error.message() + "; fix or remove the file and retry"); } - Document document = result.document(); - if (type == ServerConfigFieldsV3.class) { - ServerConfigFieldsV3 server = (ServerConfigFieldsV3) model; - SERVER_SCHEMA.apply(document, serverToTable(server), ReconcilePolicy.SYNC); - ensureGroupDefaults(document, server); - } else if (type == ClientConfigFieldsV3.class) { - ClientConfigFieldsV3 client = (ClientConfigFieldsV3) model; - CLIENT_SCHEMA.apply(document, clientToTable(client), ReconcilePolicy.SYNC); - } else { - throw new ConfigTools.ConfigException("Unsupported TOML config type: " + type.getSimpleName()); - } - return document; + return result.document(); } - private static void ensureGroupDefaults(Document document, ServerConfigFieldsV3 server) { - if (server.modpack == null || server.modpack.categories == null) return; - for (var category : server.modpack.categories.entrySet()) { - if (category.getValue() == null) continue; - for (var group : category.getValue().entrySet()) { - if (group.getValue() == null) continue; - ConfigPath groupPath = ConfigPath.of("modpack", "groups", category.getKey(), group.getKey()); - GROUP_SCHEMA.ensureDefaults(document, groupPath); + private static byte[] prepareSaveBytes(Path path, T model, Class type) throws IOException { + if (!Files.isRegularFile(path)) { + return canonicalBytes(model, type); + } + Document document = parseExistingForEdit(path); + try { + if (type == ServerConfigFieldsV3.class) { + ServerConfigFieldsV3 server = (ServerConfigFieldsV3) model; + SERVER_SCHEMA.apply(document, serverToTable(server, document.tree()), ReconcilePolicy.SYNC); + } else if (type == ClientConfigFieldsV3.class) { + ClientConfigFieldsV3 client = (ClientConfigFieldsV3) model; + CLIENT_SCHEMA.apply(document, clientToTable(client), ReconcilePolicy.SYNC); + } else { + throw new ConfigTools.ConfigException("Unsupported TOML config type: " + type.getSimpleName()); } + } catch (TomlException e) { + throw new ConfigTools.ConfigParseException("Cannot save " + path.getFileName() + ": " + e.getMessage(), e); } + return document.text(); } // ------------------------------------------------------------------ TOML read / write @@ -206,17 +217,16 @@ private static T readToml(Path path, Class type) { } Document document = parseDocument(path, bytes); try { - if (type == ServerConfigFieldsV3.class) return (T) readServerTable(document.tree(), path); - if (type == ClientConfigFieldsV3.class) return (T) readClientTable(document.tree(), path); + if (type == ServerConfigFieldsV3.class) return (T) readServerTable(document.reader(), path); + if (type == ClientConfigFieldsV3.class) return (T) readClientTable(document.reader(), path); throw new ConfigTools.ConfigException("Unsupported TOML config type: " + type.getSimpleName()); - } catch (TomlValidationException e) { + } catch (TomlException e) { throw new ConfigTools.ConfigParseException("Invalid configuration " + path.getFileName() + ": " + e.getMessage(), e); } } - private static ServerConfigFieldsV3 readServerTable(TomlValue.Table tree, Path path) { + private static ServerConfigFieldsV3 readServerTable(TableReader root, Path path) { ServerConfigFieldsV3 config = new ServerConfigFieldsV3(); - TableReader root = TableReader.of(tree); config.modpackHost = root.bool("modpack-host", config.modpackHost); config.generateModpackOnStart = root.bool("generate-modpack-on-start", config.generateModpackOnStart); @@ -250,42 +260,42 @@ private static ServerConfigFieldsV3 readServerTable(TomlValue.Table tree, Path p config.exportHttpIncludeAll = exportHttp.bool("include-all", config.exportHttpIncludeAll); Optional modpackOpt = root.table("modpack"); + Optional> categoriesOpt = root.tableMap("categories"); + Optional> groupsOpt = root.tableMap("groups"); + // The document is authoritative: a table it does not declare stays at the field defaults, and groups it does not declare do not exist. + ModpackFields fields = new ModpackFields(); if (modpackOpt.isPresent()) { TableReader modpack = modpackOpt.get(); - ModpackFields fields = new ModpackFields(); - fields.name = modpack.string("name", ""); - Optional groupsOpt = modpack.table("groups"); - if (groupsOpt.isPresent()) { - TableReader groupsTable = groupsOpt.get(); - Map> categories = new LinkedHashMap<>(); - for (String categoryName : groupsTable.keys()) { - TableReader catReader = groupsTable.table(categoryName).orElseThrow(); - Map catGroups = new LinkedHashMap<>(); - for (String groupId : catReader.keys()) { - TableReader groupReader = catReader.table(groupId).orElseThrow(); - catGroups.put(groupId, readGroup(groupReader)); - } - categories.put(categoryName, catGroups); - } - fields.categories = categories; - } else { - fields.categories = ModpackFields.withMainGroup().categories; - } - config.modpack = fields; + fields.name = modpack.string("name", fields.name); + fields.autoExcludeServerSideMods = modpack.enumVal("auto-exclude-server-side-mods", ServerSideModExclusion.class, fields.autoExcludeServerSideMods); + fields.exclude = modpack.stringSet("exclude", fields.exclude); + fields.editable = modpack.stringSet("editable", fields.editable); } + categoriesOpt.ifPresent(map -> map.forEach((categoryId, catReader) -> fields.categories.put(categoryId, readCategory(catReader)))); + groupsOpt.ifPresent(map -> map.forEach((groupId, groupReader) -> fields.groups.put(groupId, readGroup(groupReader)))); + config.modpack = fields; warnUnknownKeys(root, path); return config; } + private static CategoryDeclaration readCategory(TableReader r) { + CategoryDeclaration c = new CategoryDeclaration(); + c.name = r.string("name", c.name); + c.description = r.string("description", c.description); + c.pick = r.enumVal("pick", CategoryPickMode.class, c.pick); + return c; + } + private static GroupDeclaration readGroup(TableReader r) { GroupDeclaration g = new GroupDeclaration(); - g.displayName = r.string("display-name", g.displayName); + g.name = r.string("name", g.name); g.description = r.string("description", g.description); + g.category = r.string("category", g.category); g.selection = r.enumVal("selection", GroupSelectionMode.class, g.selection); - g.autoExcludeServerSideMods = r.enumVal("auto-exclude-server-side-mods", ServerSideModExclusion.class, g.autoExcludeServerSideMods); - g.breaksWith = r.stringSet("breaks-with", g.breaksWith); + g.autoExcludeServerSideMods = r.enumVal("auto-exclude-server-side-mods", ServerSideModExclusion.class).orElse(null); g.requires = r.stringSet("requires", g.requires); + g.conflicts = r.stringSet("conflicts", g.conflicts); g.compatiblePlatforms = r.stringSet("compatible-platforms", g.compatiblePlatforms); g.fromServer = r.stringSet("from-server", g.fromServer); g.exclude = r.stringSet("exclude", g.exclude); @@ -293,9 +303,8 @@ private static GroupDeclaration readGroup(TableReader r) { return g; } - private static ClientConfigFieldsV3 readClientTable(TomlValue.Table tree, Path path) { + private static ClientConfigFieldsV3 readClientTable(TableReader root, Path path) { ClientConfigFieldsV3 config = new ClientConfigFieldsV3(); - TableReader root = TableReader.of(tree); config.updateSelectedModpackOnLaunch = root.bool("update-selected-modpack-on-launch", config.updateSelectedModpackOnLaunch); config.selfUpdater = root.bool("self-updater", config.selfUpdater); @@ -317,7 +326,7 @@ private static void warnUnknownKeys(TableReader root, Path path) { LOGGER.warn("{}: unknown keys ignored: {}", path.getFileName(), String.join(", ", names)); } - private static TomlValue.Table serverToTable(ServerConfigFieldsV3 c) { + private static TomlValue.Table serverToTable(ServerConfigFieldsV3 c, TomlValue.Table existingTree) { TomlValue.Table root = TomlValue.table(); root.put("modpack-host", TomlValue.bool(c.modpackHost)); root.put("generate-modpack-on-start", TomlValue.bool(c.generateModpackOnStart)); @@ -326,6 +335,34 @@ private static TomlValue.Table serverToTable(ServerConfigFieldsV3 c) { root.put("accepted-loaders", stringArray(c.acceptedLoaders)); root.put("advertise-versions-to-sync", TomlValue.bool(c.advertiseVersionsToSync)); + ModpackFields mp = c.modpack != null ? c.modpack : new ModpackFields(); + ServerSideModExclusion packExclusion = mp.autoExcludeServerSideMods != null ? mp.autoExcludeServerSideMods : ServerSideModExclusion.METADATA; + root.put("modpack", TomlValue.table() + .put("name", TomlValue.str(nonNull(mp.name))) + .put("auto-exclude-server-side-mods", TomlValue.str(packExclusion.name())) + .put("exclude", stringArray(mp.exclude)) + .put("editable", stringArray(mp.editable))); + + TomlValue.Table existingCategories = childTable(existingTree, "categories"); + if (mp.categories != null && !mp.categories.isEmpty()) { + TomlValue.Table categoriesTable = TomlValue.table(); + for (var entry : mp.categories.entrySet()) { + if (entry.getValue() == null) continue; + categoriesTable.put(entry.getKey(), categoryToTable(entry.getValue(), childTable(existingCategories, entry.getKey()))); + } + if (!categoriesTable.members().isEmpty() || existingCategories != null) root.put("categories", categoriesTable); + } + + TomlValue.Table existingGroups = childTable(existingTree, "groups"); + if (mp.groups != null && !mp.groups.isEmpty()) { + TomlValue.Table groupsTable = TomlValue.table(); + for (var entry : mp.groups.entrySet()) { + if (entry.getValue() == null) continue; + groupsTable.put(entry.getKey(), groupToTable(entry.getValue(), childTable(existingGroups, entry.getKey()))); + } + if (!groupsTable.members().isEmpty() || existingGroups != null) root.put("groups", groupsTable); + } + ModpackConnectionMode mode = c.connectionMode != null ? c.connectionMode : ModpackConnectionMode.HOLEPUNCH; root.put("network", TomlValue.table() .put("connection-mode", TomlValue.str(mode.name())) @@ -350,40 +387,46 @@ private static TomlValue.Table serverToTable(ServerConfigFieldsV3 c) { root.put("export-http", TomlValue.table() .put("directory", TomlValue.str(nonNull(c.exportHttpDirectory))) .put("include-all", TomlValue.bool(c.exportHttpIncludeAll))); - - ModpackFields mp = c.modpack != null ? c.modpack : ModpackFields.withMainGroup(); - TomlValue.Table modpackTable = TomlValue.table().put("name", TomlValue.str(nonNull(mp.name))); - TomlValue.Table groupsTable = TomlValue.table(); - if (mp.categories != null) { - for (var catEntry : mp.categories.entrySet()) { - if (catEntry.getValue() == null) continue; - TomlValue.Table catTable = TomlValue.table(); - for (var grpEntry : catEntry.getValue().entrySet()) { - if (grpEntry.getValue() == null) continue; - catTable.put(grpEntry.getKey(), groupToTable(grpEntry.getValue())); - } - groupsTable.put(catEntry.getKey(), catTable); - } - } - modpackTable.put("groups", groupsTable); - root.put("modpack", modpackTable); return root; } - private static TomlValue.Table groupToTable(GroupDeclaration g) { + private static TomlValue.Table categoryToTable(CategoryDeclaration cat, TomlValue.Table existing) { + TomlValue.Table t = TomlValue.table(); + CategoryPickMode pick = cat.pick != null ? cat.pick : CategoryPickMode.ANY; + if (hasKey(existing, "name") || !nonNull(cat.name).isEmpty()) t.put("name", TomlValue.str(nonNull(cat.name))); + if (hasKey(existing, "description") || !nonNull(cat.description).isEmpty()) t.put("description", TomlValue.str(nonNull(cat.description))); + if (hasKey(existing, "pick") || pick != CategoryPickMode.ANY || t.members().isEmpty()) t.put("pick", TomlValue.str(pick.name())); + return t; + } + + private static TomlValue.Table groupToTable(GroupDeclaration g, TomlValue.Table existing) { + TomlValue.Table t = TomlValue.table(); GroupSelectionMode selection = g.selection != null ? g.selection : GroupSelectionMode.OPTIONAL; - ServerSideModExclusion exclusion = g.autoExcludeServerSideMods != null ? g.autoExcludeServerSideMods : ServerSideModExclusion.METADATA; - return TomlValue.table() - .put("display-name", TomlValue.str(nonNull(g.displayName))) - .put("description", TomlValue.str(nonNull(g.description))) - .put("selection", TomlValue.str(selection.name())) - .put("auto-exclude-server-side-mods", TomlValue.str(exclusion.name())) - .put("breaks-with", stringArray(g.breaksWith)) - .put("requires", stringArray(g.requires)) - .put("compatible-platforms", stringArray(g.compatiblePlatforms)) - .put("from-server", stringArray(g.fromServer)) - .put("exclude", stringArray(g.exclude)) - .put("editable", stringArray(g.editable)); + if (hasKey(existing, "name") || !nonNull(g.name).isEmpty()) t.put("name", TomlValue.str(nonNull(g.name))); + if (hasKey(existing, "description") || !nonNull(g.description).isEmpty()) t.put("description", TomlValue.str(nonNull(g.description))); + if (hasKey(existing, "category") || !nonNull(g.category).isEmpty()) t.put("category", TomlValue.str(nonNull(g.category))); + if (g.autoExcludeServerSideMods != null) t.put("auto-exclude-server-side-mods", TomlValue.str(g.autoExcludeServerSideMods.name())); + if (hasKey(existing, "requires") || !isEmpty(g.requires)) t.put("requires", stringArray(g.requires)); + if (hasKey(existing, "conflicts") || !isEmpty(g.conflicts)) t.put("conflicts", stringArray(g.conflicts)); + if (hasKey(existing, "compatible-platforms") || !isEmpty(g.compatiblePlatforms)) t.put("compatible-platforms", stringArray(g.compatiblePlatforms)); + if (hasKey(existing, "from-server") || !isEmpty(g.fromServer)) t.put("from-server", stringArray(g.fromServer)); + if (hasKey(existing, "exclude") || !isEmpty(g.exclude)) t.put("exclude", stringArray(g.exclude)); + if (hasKey(existing, "editable") || !isEmpty(g.editable)) t.put("editable", stringArray(g.editable)); + if (hasKey(existing, "selection") || selection != GroupSelectionMode.OPTIONAL || t.members().isEmpty()) t.put("selection", TomlValue.str(selection.name())); + return t; + } + + private static TomlValue.Table childTable(TomlValue.Table parent, String key) { + if (parent == null) return null; + return parent.get(key) instanceof TomlValue.Table child ? child : null; + } + + private static boolean hasKey(TomlValue.Table table, String key) { + return table != null && table.get(key) != null; + } + + private static boolean isEmpty(Collection values) { + return values == null || values.isEmpty(); } private static TomlValue.Table clientToTable(ClientConfigFieldsV3 c) { @@ -411,34 +454,16 @@ private static String nonNull(String s) { return s == null ? "" : s; } - private static Document freshDocument(T model, Class type) { - byte[] bytes; - if (type == ServerConfigFieldsV3.class) { - ServerConfigFieldsV3 server = (ServerConfigFieldsV3) model; - Comments.Builder comments = Comments.builder().banner(BANNER); - SERVER_SCHEMA.addCommentsTo(comments, ConfigPath.root()); - if (server.modpack != null && server.modpack.categories != null) { - for (var cat : server.modpack.categories.entrySet()) { - if (cat.getValue() == null) continue; - for (var grp : cat.getValue().entrySet()) { - if (grp.getValue() == null) continue; - GROUP_SCHEMA.addCommentsTo(comments, ConfigPath.of("modpack", "groups", cat.getKey(), grp.getKey())); - } - } - } - bytes = TomlEdit.canonical(serverToTable(server), comments.build()); - } else if (type == ClientConfigFieldsV3.class) { - bytes = CLIENT_SCHEMA.canonical(clientToTable((ClientConfigFieldsV3) model)); - } else { - throw new ConfigTools.ConfigException("Unsupported TOML config type: " + type.getSimpleName()); - } - return TomlEdit.parse(bytes).document(); + private static byte[] canonicalBytes(T model, Class type) { + if (type == ServerConfigFieldsV3.class) return SERVER_SCHEMA.canonical(serverToTable((ServerConfigFieldsV3) model, null)); + if (type == ClientConfigFieldsV3.class) return CLIENT_SCHEMA.canonical(clientToTable((ClientConfigFieldsV3) model)); + throw new ConfigTools.ConfigException("Unsupported TOML config type: " + type.getSimpleName()); } private static void writeFresh(Path path, T model, Class type) { try { OsPaths.requirePublishableConfig(path); - DurableFiles.writeAtomic(path, freshDocument(model, type).text()); + DurableFiles.writeAtomic(path, canonicalBytes(model, type)); } catch (IOException e) { throw new ConfigTools.ConfigException("Failed to create configuration " + path.toAbsolutePath().normalize(), e); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/GroupInspector.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/GroupInspector.java index 6d629249e..e589a50d5 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/GroupInspector.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/GroupInspector.java @@ -1,67 +1,94 @@ package pl.skidam.automodpack_core.modpack; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; +import java.util.stream.Stream; import pl.skidam.automodpack_core.config.ServerConfigJsons; +import pl.skidam.automodpack_core.config.TomlConfigs; import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.GroupManifest; +import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.ModpackContentType; import pl.skidam.automodpack_core.utils.ByteFormat; +import pl.skidam.automodpack_core.utils.FileTrees; -/** Operator-facing text views of the group model: the config declarations plus whatever generation is published. */ +/** Operator views and folder import for groups. */ public final class GroupInspector { private GroupInspector() {} - /** One line per group under its category heading; {@code published} may be null when nothing was generated yet. */ - public static List overview(Map> modpack, GroupManifest published) { + public record ImportResult(List imported, List skipped, List warnings) {} + + /** One line per group, grouped by category; {@code published} may be null. */ + public static List overview(ServerConfigJsons.ModpackFields modpack, GroupManifest published) { Map publishedGroups = publishedGroups(published); + Map groups = modpack == null || modpack.groups == null ? Map.of() : modpack.groups; + Map categories = modpack == null || modpack.categories == null ? Map.of() : modpack.categories; List lines = new ArrayList<>(); - int groupCount = 0; - for (var category : modpack.entrySet()) { - lines.add(category.getKey() + ":"); - for (var group : category.getValue().entrySet()) { - groupCount++; - lines.add(" " + summaryLine(group.getKey(), group.getValue(), publishedGroups.get(group.getKey()))); - } + lines.add("Modpack groups: " + groups.size() + " groups" + (categories.isEmpty() ? "" : ", " + categories.size() + " categories")); + + Map>> byCategory = new LinkedHashMap<>(); + for (var entry : groups.entrySet()) { + String cat = entry.getValue() == null || entry.getValue().category == null ? "" : entry.getValue().category; + byCategory.computeIfAbsent(cat, ignored -> new ArrayList<>()).add(entry); + } + + List> uncategorized = byCategory.getOrDefault("", List.of()); + if (!uncategorized.isEmpty()) { + String indent = categories.isEmpty() ? " " : " "; + if (!categories.isEmpty()) lines.add(" (uncategorized):"); + for (var group : uncategorized) lines.add(indent + summaryLine(group.getKey(), group.getValue(), publishedGroups.get(group.getKey()))); + } + for (var catEntry : categories.entrySet()) { + String catId = catEntry.getKey(); + ServerConfigJsons.CategoryDeclaration cat = catEntry.getValue(); + String label = cat != null && cat.name != null && !cat.name.isBlank() ? cat.name + " (" + catId + ")" : catId; + String pickSuffix = cat != null && cat.pick != null && cat.pick.isExclusive() ? " [" + cat.pick.name().toLowerCase(Locale.ROOT) + "]" : ""; + lines.add(" " + label + pickSuffix + ":"); + for (var group : byCategory.getOrDefault(catId, List.of())) lines.add(" " + summaryLine(group.getKey(), group.getValue(), publishedGroups.get(group.getKey()))); } - lines.add(0, "Modpack groups: " + modpack.size() + " categories, " + groupCount + " groups"); return lines; } /** The detail view of one group, or empty when neither the config nor the published manifest knows the id. */ - public static Optional> detail(Map> modpack, String groupId, GroupManifest published) { - Map.Entry declared = declaredGroup(modpack, groupId); + public static Optional> detail(ServerConfigJsons.ModpackFields modpack, String groupId, GroupManifest published) { + ServerConfigJsons.GroupDeclaration declaration = modpack != null && modpack.groups != null ? modpack.groups.get(groupId) : null; GroupManifest.Group publishedGroup = publishedGroups(published).get(groupId); - if (declared == null && publishedGroup == null) return Optional.empty(); + if (declaration == null && publishedGroup == null) return Optional.empty(); List lines = new ArrayList<>(); - if (declared == null) { - // Removed from the config but still served from the older generation; report the manifest side instead of "unknown". + if (declaration == null) { lines.add("Group " + groupId + " is published but missing from the server config"); addField(lines, "Category", publishedGroup.category()); - addField(lines, "Display name", publishedGroup.displayName()); + addField(lines, "Name", publishedGroup.name()); addField(lines, "Description", publishedGroup.description()); - lines.add("Flags: " + flags(publishedGroup.selection())); + lines.add("Selection: " + selectionLabel(publishedGroup.selection())); addJoined(lines, "Platforms", platforms(publishedGroup)); addJoined(lines, "Requires", publishedGroup.requires()); - addJoined(lines, "Breaks with", publishedGroup.breaksWith()); + addJoined(lines, "Conflicts", publishedGroup.conflicts()); } else { - lines.add("Group " + groupId + " (category " + declared.getKey() + ")"); - ServerConfigJsons.GroupDeclaration declaration = declared.getValue(); - addField(lines, "Display name", declaration.displayName); + String catSuffix = declaration.category == null || declaration.category.isBlank() ? "" : " (category " + declaration.category + ")"; + lines.add("Group " + groupId + catSuffix); + addField(lines, "Name", declaration.name); addField(lines, "Description", declaration.description); - lines.add("Flags: " + flags(declaration.selection)); + lines.add("Selection: " + selectionLabel(declaration.selection)); + lines.add("Auto-exclude server mods: " + (declaration.autoExcludeServerSideMods != null ? declaration.autoExcludeServerSideMods : "inherited (" + modpack.autoExcludeServerSideMods + ")")); addJoined(lines, "Platforms", declaration.compatiblePlatforms); addJoined(lines, "Requires", declaration.requires); - addJoined(lines, "Breaks with", declaration.breaksWith); + addJoined(lines, "Conflicts", declaration.conflicts); addRules(lines, "From server", declaration.fromServer); addRules(lines, "Exclude", declaration.exclude); addRules(lines, "Editable", declaration.editable); @@ -71,12 +98,60 @@ public static Optional> detail(Map imported = new ArrayList<>(); + List skipped = new ArrayList<>(); + List warnings = new ArrayList<>(); + if (!Files.isDirectory(groupRoot)) { + warnings.add("host-modpack directory does not exist: " + groupRoot); + return new ImportResult(imported, skipped, warnings); + } + + Set declared = modpack != null && modpack.groups != null ? modpack.groups.keySet() : Set.of(); + Map toInsert = new TreeMap<>(); + if (singleFolder != null && !singleFolder.isBlank()) { + Path target = groupRoot.resolve(singleFolder).normalize(); + if (!GroupManifestValidator.isValidIdentifier(singleFolder)) { + warnings.add("Invalid group ID '" + singleFolder + "' (allowed: lowercase [a-z0-9][a-z0-9_-]*, no reserved names)"); + } else if (!target.startsWith(groupRoot) || !Files.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) { + warnings.add("Folder does not exist under host-modpack/: " + singleFolder); + } else if (declared.contains(singleFolder)) { + skipped.add(singleFolder + " (already declared)"); + } else { + toInsert.put(singleFolder, new ServerConfigJsons.GroupDeclaration()); + imported.add(singleFolder); + } + } else { + List dirs; + try (Stream stream = Files.list(groupRoot)) { + dirs = stream.filter(p -> Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)).sorted().toList(); + } + for (Path dir : dirs) { + String name = dir.getFileName().toString(); + if (declared.contains(name)) continue; + if (!GroupManifestValidator.isValidIdentifier(name)) { + warnings.add("Skipped invalid folder name '" + name + "'"); + continue; + } + if (FileTrees.containsNoFiles(dir)) { + skipped.add(name + " (empty folder)"); + continue; + } + toInsert.put(name, new ServerConfigJsons.GroupDeclaration()); + imported.add(name); + } + } + + if (!toInsert.isEmpty()) TomlConfigs.insertImportedGroups(serverConfigFile, toInsert); + return new ImportResult(List.copyOf(imported), List.copyOf(skipped), List.copyOf(warnings)); + } + private static String summaryLine(String groupId, ServerConfigJsons.GroupDeclaration declaration, GroupManifest.Group published) { StringBuilder line = new StringBuilder(groupId); - if (!declaration.displayName.isBlank()) line.append(" - ").append(declaration.displayName); - if (declaration.selection == GroupSelectionMode.REQUIRED) line.append(" [required]"); - if (declaration.selection == GroupSelectionMode.RECOMMENDED) line.append(" [recommended]"); - if (!declaration.compatiblePlatforms.isEmpty()) line.append(" [").append(joined(declaration.compatiblePlatforms)).append("]"); + if (declaration.name != null && !declaration.name.isBlank()) line.append(" - ").append(declaration.name); + line.append(" [").append(selectionLabel(declaration.selection)).append("]"); + if (declaration.compatiblePlatforms != null && !declaration.compatiblePlatforms.isEmpty()) line.append(" [").append(joined(declaration.compatiblePlatforms)).append("]"); if (published == null) line.append(" (not published yet)"); else line.append(" ").append(published.files().size()).append(" files, ").append(ByteFormat.formatSize(totalSize(published))); return line.toString(); @@ -97,14 +172,6 @@ private static void filesSection(List lines, GroupManifest.Group group) lines.add(" " + file.getKey() + " - " + ByteFormat.formatSize(file.getValue().size())); } - private static Map.Entry declaredGroup(Map> modpack, String groupId) { - for (var category : modpack.entrySet()) { - ServerConfigJsons.GroupDeclaration declaration = category.getValue().get(groupId); - if (declaration != null) return Map.entry(category.getKey(), declaration); - } - return null; - } - private static Map publishedGroups(GroupManifest published) { return published == null ? Map.of() : published.groups(); } @@ -119,10 +186,8 @@ private static long totalSize(GroupManifest.Group group) { return total; } - private static String flags(GroupSelectionMode selection) { - if (selection == GroupSelectionMode.REQUIRED) return "required"; - if (selection == GroupSelectionMode.RECOMMENDED) return "recommended"; - return "none"; + private static String selectionLabel(GroupSelectionMode selection) { + return selection == null ? "optional" : selection.name().toLowerCase(Locale.ROOT); } private static void addField(List lines, String label, String value) { @@ -130,12 +195,12 @@ private static void addField(List lines, String label, String value) { } private static void addJoined(List lines, String label, Set values) { - if (!values.isEmpty()) lines.add(label + ": " + joined(values)); + if (values != null && !values.isEmpty()) lines.add(label + ": " + joined(values)); } /** Rule sets always print, an empty one as {@code (none)}: an empty rule is a deliberate posture, not missing data. */ private static void addRules(List lines, String label, Set rules) { - lines.add(label + ": " + (rules.isEmpty() ? "(none)" : joined(rules))); + lines.add(label + ": " + (rules == null || rules.isEmpty() ? "(none)" : joined(rules))); } private static String joined(Set values) { diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/ModpackExecutor.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/ModpackExecutor.java index e15da68df..38dd304fa 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/ModpackExecutor.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/ModpackExecutor.java @@ -8,16 +8,22 @@ import java.io.IOException; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; +import java.util.ArrayDeque; +import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.TreeMap; +import java.util.TreeSet; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -40,16 +46,18 @@ import pl.skidam.automodpack_core.modpack.generation.GenerationStore; import pl.skidam.automodpack_core.modpack.generation.JournalEntry; import pl.skidam.automodpack_core.modpack.generation.PackDocument; +import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.GroupManifest; -import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; -import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionResolver; import pl.skidam.automodpack_core.modpack.group.ModpackPathPolicy; +import pl.skidam.automodpack_core.modpack.group.SelectionResolutionException; import pl.skidam.automodpack_core.platforms.PlatformSideVerdicts; import pl.skidam.automodpack_core.platforms.PlatformSourceLookup; import pl.skidam.automodpack_core.protocol.netty.NettyServer; import pl.skidam.automodpack_core.storage.DataRootResolver; import pl.skidam.automodpack_core.storage.GameDirectory; import pl.skidam.automodpack_core.utils.CustomThreadFactoryBuilder; +import pl.skidam.automodpack_core.utils.FileTrees; import pl.skidam.automodpack_core.utils.HashUtils; import pl.skidam.automodpack_core.utils.Throwables; import pl.skidam.automodpack_core.utils.cache.FileCache; @@ -392,6 +400,7 @@ private ModpackCandidate buildCandidate(ServerConfigJsons.ServerConfigFieldsV3 s throws IOException, CandidateBuildException { validateConfiguration(serverConfig); prepareDirectories(serverConfig); + warnUndeclaredGroupFolders(serverConfig); String modpackId = previous == null ? ModpackId.generate() : ModpackId.requireValid(previous.manifest().modpackId()); try (ModFileCache modFileCache = ModFileCache.open(dataLayout.modCacheDirectory())) { // Unadvertised versions leave the manifest fields empty, so clients see a files-only pack instead of a @@ -401,7 +410,7 @@ private ModpackCandidate buildCandidate(ServerConfigJsons.ServerConfigFieldsV3 s ModpackCandidateScanner.Request request = new ModpackCandidateScanner.Request(modpackId, serverConfig.modpack.name, Environment.current().modVersion(), advertiseVersions ? Environment.current().loader() : null, advertiseVersions ? Environment.current().loaderVersion() : null, advertiseVersions ? Environment.current().mcVersion() : null, serverRoot, groupRoot, - serverConfig.modpack.categories, materializeMissingObjects, generationRoot.resolve(SERVER_STAGING_DIR.getFileName()), + serverConfig.modpack, materializeMissingObjects, generationRoot.resolve(SERVER_STAGING_DIR.getFileName()), creationExecutor, generationStore.objectRoot(), fileCache, modFileCache, materializeMissingObjects, ownedElsewhere.read()); ModpackCandidate candidate = candidateScan.scan(request); for (ExcludedCandidate exclusion : candidate.exclusions()) @@ -437,21 +446,50 @@ static PackAbsence absenceOf(GroupManifest manifest) { if (manifest.groups().values().stream().allMatch(group -> group.files().isEmpty())) return new PackAbsence(Kind.NOTHING_FOUND, "Nothing to sync: the published generation holds no files for any of the " + manifest.groups().size() + " configured groups (" + String.join(", ", manifest.groups().keySet()) + ")."); - if (manifest.groups().values().stream().noneMatch(group -> group.selection() != GroupSelectionMode.OPTIONAL && !group.files().isEmpty())) + Set defaultActive = defaultSelectedGroups(manifest); + boolean anyDefaultHasFiles = defaultActive.stream().anyMatch(id -> !manifest.groups().get(id).files().isEmpty()); + if (!anyDefaultHasFiles) return new PackAbsence(Kind.NOTHING_SELECTED, "Nothing to sync: the modpack holds " + fileCount(manifest) - + " files, but no group that is required or recommended carries any of them. Mark a group that carries files required or recommended."); + + " files, but no group selected by default carries any of them. Mark a group that carries files REQUIRED or RECOMMENDED."); return null; } - /** - * A group that is required or recommended and carries no files is dead configuration: every default client - * is handed it and receives nothing through it. It is a receipt, not a refusal, because the operator may be - * mid-edit and other groups may still carry the pack. - */ + private static Set defaultSelectedGroups(GroupManifest manifest) { + Set platforms = new TreeSet<>(ClientPlatform.builtIns()); + platforms.addAll(manifest.declaredPlatforms()); + Set active = new HashSet<>(); + for (ClientPlatform platform : platforms) { + try { + active.addAll(GroupSelectionResolver.resolveDefault(manifest, platform).selectedGroups()); + } catch (SelectionResolutionException invalidDefaults) { + LOGGER.warn("Default group selection is invalid on {}; it contributes nothing to the absence check: {}", platform.id(), invalidDefaults.errors()); + } + } + return active; + } + private static void warnUnusableSelectedGroups(GroupManifest manifest) { - for (var entry : manifest.groups().entrySet()) - if (entry.getValue().files().isEmpty() && entry.getValue().selection() != GroupSelectionMode.OPTIONAL) - LOGGER.warn("Group '{}' is required or recommended but carries no files; a default client receives nothing through it", entry.getKey()); + Set reachableFromSelectable = new HashSet<>(); + for (var entry : manifest.groups().entrySet()) { + if (entry.getValue().selection().automatic()) continue; + ArrayDeque queue = new ArrayDeque<>(); + queue.add(entry.getKey()); + while (!queue.isEmpty()) { + String id = queue.removeFirst(); + if (!reachableFromSelectable.add(id)) continue; + GroupManifest.Group group = manifest.groups().get(id); + if (group != null) queue.addAll(group.requires()); + } + } + for (var entry : manifest.groups().entrySet()) { + GroupManifest.Group group = entry.getValue(); + if (group.selection().automatic() && !reachableFromSelectable.contains(entry.getKey())) { + LOGGER.warn("Group '{}' is AUTOMATIC but no other group requires it; it will never be installed", entry.getKey()); + } else if (group.arrivesSelected() && group.files().isEmpty()) { + LOGGER.warn("Group '{}' is {} but carries no files; a default client receives nothing through it", entry.getKey(), + group.selection().name().toLowerCase(Locale.ROOT)); + } + } } private static int fileCount(GroupManifest manifest) { @@ -509,33 +547,18 @@ private void consumePatchNotes(GenerationPatchNotes.Resolution notes) { } private void validateConfiguration(ServerConfigJsons.ServerConfigFieldsV3 serverConfig) throws CandidateBuildException { - if (serverConfig == null || serverConfig.modpack.categories.isEmpty()) - throw new CandidateBuildException("Server group configuration is missing"); - for (var categoryEntry : serverConfig.modpack.categories.entrySet()) { - var category = categoryEntry.getValue(); - if (category == null) throw new CandidateBuildException("Category '" + categoryEntry.getKey() + "' has no declaration"); - for (var entry : category.entrySet()) { - try { - GroupManifestValidator.requireIdentifier(entry.getKey()); - } catch (IllegalArgumentException e) { - throw new CandidateBuildException(e.getMessage(), e); - } - if (entry.getValue() == null) throw new CandidateBuildException("Group '" + entry.getKey() + "' has no declaration"); - } - } + if (serverConfig == null) throw new CandidateBuildException("Server configuration is missing"); + ModpackCandidateScanner.validateDeclarations(serverConfig.modpack); } private void prepareDirectories(ServerConfigJsons.ServerConfigFieldsV3 serverConfig) throws IOException, CandidateBuildException { Map groupDirectories = new TreeMap<>(); - for (var categoryEntry : serverConfig.modpack.categories.entrySet()) { - if (categoryEntry.getValue() == null) continue; - for (String groupId : categoryEntry.getValue().keySet()) { - Path groupDirectory = groupRoot.resolve(groupId).normalize(); - if (!groupDirectory.startsWith(groupRoot)) throw new CandidateBuildException("Group directory escapes host-modpack: " + groupId); - if (groupDirectory.startsWith(generationRoot) || generationRoot.startsWith(groupDirectory)) - throw new CandidateBuildException("Group directory overlaps managed generation store: " + groupId); - groupDirectories.put(groupId, groupDirectory); - } + for (String groupId : serverConfig.modpack.groups.keySet()) { + Path groupDirectory = groupRoot.resolve(groupId).normalize(); + if (!groupDirectory.startsWith(groupRoot)) throw new CandidateBuildException("Group directory escapes host-modpack: " + groupId); + if (groupDirectory.startsWith(generationRoot) || generationRoot.startsWith(groupDirectory)) + throw new CandidateBuildException("Group directory overlaps managed generation store: " + groupId); + groupDirectories.put(groupId, groupDirectory); } Files.createDirectories(groupRoot); GenerationPatchNotes.ensurePresent(patchNotesFile); @@ -548,6 +571,23 @@ private void prepareDirectories(ServerConfigJsons.ServerConfigFieldsV3 serverCon Files.createDirectories(main.resolve(ModpackPathPolicy.RESOURCEPACKS_ROOT)); } + private void warnUndeclaredGroupFolders(ServerConfigJsons.ServerConfigFieldsV3 serverConfig) { + if (!Files.isDirectory(groupRoot)) return; + try (Stream children = Files.list(groupRoot)) { + for (Path child : children.toList()) { + if (!Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) continue; + String folder = child.getFileName().toString(); + if (serverConfig.modpack.groups.containsKey(folder)) continue; + if (!FileTrees.containsNoFiles(child)) { + LOGGER.warn("Folder '{}' under host-modpack/ has files but is not declared in server.toml; run '/automodpack groups import {}' or add [groups.{}] to include it", + folder, folder, folder); + } + } + } catch (IOException e) { + LOGGER.warn("Failed to check for undeclared group folders under {}", groupRoot, e); + } + } + public boolean isGenerating() { return locks.isPublishing(); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/candidate/ModpackCandidateScanner.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/candidate/ModpackCandidateScanner.java index 88d7a372d..b11b42c95 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/candidate/ModpackCandidateScanner.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/candidate/ModpackCandidateScanner.java @@ -37,28 +37,45 @@ public ModpackCandidateScanner(PlatformSideVerdicts sideVerdicts) { this.sideVerdicts = sideVerdicts; } - public ModpackCandidate scan(Request request) throws CandidateBuildException { - Objects.requireNonNull(request); - if (request.modpack() == null || request.modpack().isEmpty()) throw new CandidateBuildException("No groups are configured"); - Map declarations = new LinkedHashMap<>(); - Map categoryByGroup = new LinkedHashMap<>(); - Map rulesByGroup = new LinkedHashMap<>(); - for (var categoryEntry : request.modpack().entrySet()) { - var category = categoryEntry.getValue(); - if (category == null) throw new CandidateBuildException("Category '" + categoryEntry.getKey() + "' has no declaration"); - for (var entry : category.entrySet()) { + /** + * The one declaration check: a set that declares no groups ships nothing, and an unnamed or undeclared entry cannot become a manifest. The executor calls it before touching disk; {@link #scan} calls it for + * every other caller. + */ + public static void validateDeclarations(ServerConfigJsons.ModpackFields modpack) throws CandidateBuildException { + if (modpack == null || modpack.groups == null || modpack.groups.isEmpty()) + throw new CandidateBuildException("server.toml declares no [groups.*] tables, so the pack would ship nothing; declare at least [groups.main] or run '/automodpack groups import '"); + if (modpack.categories != null) { + for (var categoryEntry : modpack.categories.entrySet()) { try { - GroupManifestValidator.requireIdentifier(entry.getKey()); + GroupManifestValidator.requireIdentifier(categoryEntry.getKey()); } catch (IllegalArgumentException e) { - throw new CandidateBuildException(e.getMessage(), e); + throw new CandidateBuildException("Invalid category ID: " + categoryEntry.getKey(), e); } - if (declarations.containsKey(entry.getKey())) throw new CandidateBuildException("Group '" + entry.getKey() + "' is declared more than once"); - if (entry.getValue() == null) throw new CandidateBuildException("Group '" + entry.getKey() + "' has no declaration"); - declarations.put(entry.getKey(), entry.getValue()); - categoryByGroup.put(entry.getKey(), categoryEntry.getKey()); - rulesByGroup.put(entry.getKey(), compileRules(entry.getKey(), entry.getValue())); + if (categoryEntry.getValue() == null) throw new CandidateBuildException("Category '" + categoryEntry.getKey() + "' has no declaration"); } } + for (var entry : modpack.groups.entrySet()) { + try { + GroupManifestValidator.requireIdentifier(entry.getKey()); + } catch (IllegalArgumentException e) { + throw new CandidateBuildException("Invalid group ID: " + entry.getKey(), e); + } + if (entry.getValue() == null) throw new CandidateBuildException("Group '" + entry.getKey() + "' has no declaration"); + } + } + + public ModpackCandidate scan(Request request) throws CandidateBuildException { + Objects.requireNonNull(request); + ServerConfigJsons.ModpackFields modpack = request.modpack(); + validateDeclarations(modpack); + Map categories = modpack.categories == null ? Map.of() : modpack.categories; + Map declarations = new LinkedHashMap<>(); + Map rulesByGroup = new LinkedHashMap<>(); + ServerSideModExclusion packExclusion = ServerSideModExclusion.orDefault(modpack.autoExcludeServerSideMods); + for (var entry : modpack.groups.entrySet()) { + declarations.put(entry.getKey(), entry.getValue()); + rulesByGroup.put(entry.getKey(), compileRules(entry.getKey(), modpack, entry.getValue())); + } List ruleExclusions = new ArrayList<>(); Map sources = new TreeMap<>(); @@ -116,7 +133,7 @@ public ModpackCandidate scan(Request request) throws CandidateBuildException { try { for (SourcePair pair : sources.values()) futures.add(CompletableFuture.supplyAsync(() -> { try { - return process(pair, rulesByGroup.get(pair.groupId()), exclusionMode(declarations.get(pair.groupId())), request); + return process(pair, rulesByGroup.get(pair.groupId()), exclusionMode(declarations.get(pair.groupId()), packExclusion), request); } catch (CandidateBuildException e) { throw new CompletionException(e); } @@ -164,22 +181,32 @@ public ModpackCandidate scan(Request request) throws CandidateBuildException { fields.loader = request.loader(); fields.loaderVersion = request.loaderVersion(); fields.mcVersion = request.mcVersion(); - Map> categories = new LinkedHashMap<>(); + Map categoryFields = new LinkedHashMap<>(); + for (var catEntry : categories.entrySet()) { + ServerConfigJsons.CategoryDeclaration cat = catEntry.getValue(); + ModpackJsons.CompleteModpackContentFields.CategoryFields cf = new ModpackJsons.CompleteModpackContentFields.CategoryFields(); + cf.name = cat.name; + cf.description = cat.description; + cf.pick = cat.pick; + categoryFields.put(catEntry.getKey(), cf); + } + fields.categories = categoryFields; + Map groupFields = new LinkedHashMap<>(); for (var entry : declarations.entrySet()) { ServerConfigJsons.GroupDeclaration declaration = entry.getValue(); ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.displayName = declaration.displayName; + group.name = declaration.name; group.description = declaration.description; - group.required = declaration.selection.alwaysInstalled(); - group.defaultSelected = declaration.selection.arrivesSelected(); - group.breaksWith = sortedSet(declaration.breaksWith); + group.category = declaration.category; + group.selection = declaration.selection; group.requires = sortedSet(declaration.requires); + group.conflicts = sortedSet(declaration.conflicts); group.compatiblePlatforms = sortedSet(declaration.compatiblePlatforms); group.files = filesByGroup.get(entry.getKey()); - categories.computeIfAbsent(categoryByGroup.get(entry.getKey()), ignored -> new LinkedHashMap<>()).put(entry.getKey(), group); + groupFields.put(entry.getKey(), group); } - fields.categories = categories; - auditEditableRules(declarations, filesByGroup); + fields.groups = groupFields; + auditEditableRules(modpack, declarations, filesByGroup); GroupManifest manifest = GroupManifestValidator.validateForPublish(fields); return new ModpackCandidate(manifest, new TreeMap<>(objects), new TreeMap<>(provenance), exclusions); } catch (Exception e) { @@ -275,18 +302,46 @@ private void applyPlatformSideVerdicts(List results, Request request } } - private static ServerSideModExclusion exclusionMode(ServerConfigJsons.GroupDeclaration declaration) { - return ServerSideModExclusion.orDefault(declaration == null ? null : declaration.autoExcludeServerSideMods); + private static ServerSideModExclusion exclusionMode(ServerConfigJsons.GroupDeclaration declaration, ServerSideModExclusion packDefault) { + return declaration != null && declaration.autoExcludeServerSideMods != null ? declaration.autoExcludeServerSideMods : packDefault; + } + + private static GroupRules compileRules(String groupId, ServerConfigJsons.ModpackFields modpack, ServerConfigJsons.GroupDeclaration declaration) throws CandidateBuildException { + return new GroupRules(compileRuleSet(declaration.fromServer, groupId, "from-server"), + compileRuleSet(mergeRules(modpack.exclude, declaration.exclude), groupId, "exclude"), + compileRuleSet(mergeRules(modpack.editable, declaration.editable), groupId, "editable")); } - private static GroupRules compileRules(String groupId, ServerConfigJsons.GroupDeclaration declaration) throws CandidateBuildException { - return new GroupRules(compileRuleSet(declaration.fromServer, groupId, "from-server"), compileRuleSet(declaration.exclude, groupId, "exclude"), - compileRuleSet(declaration.editable, groupId, "editable")); + private static List mergeRules(Set packRules, Set groupRules) { + List merged = new ArrayList<>(); + if (packRules != null) merged.addAll(packRules); + if (groupRules != null) merged.addAll(groupRules); + return merged; } /** Warns about editable rules that match no pack files, and about rules matching active mods, which load from the standard mods folder instead of the projection. */ - private static void auditEditableRules(Map declarations, + private static void auditEditableRules(ServerConfigJsons.ModpackFields modpack, Map declarations, Map> filesByGroup) { + if (modpack.editable != null && !modpack.editable.isEmpty()) { + Set allPackPaths = new LinkedHashSet<>(); + for (var groupFiles : filesByGroup.values()) allPackPaths.addAll(groupFiles.keySet()); + for (String rule : modpack.editable) { + if (rule == null || rule.startsWith("!")) continue; + PathRuleSet matcher = new PathRuleSet(List.of(rule)); + boolean matched = false; + long matchedMods = 0; + for (String path : allPackPaths) if (matcher.matches(path)) { + matched = true; + if (ModpackPathPolicy.isActiveMod(path)) matchedMods++; + } + if (!matched) LOGGER.warn("pack-wide editable rule '{}' matched no pack files", rule); + else + if (matchedMods > 0) + LOGGER.warn( + "pack-wide editable rule '{}' matches {} active mod(s), which will load from the standard mods folder instead of the modpack projection. Not recommended: such mods need a restart to update and fall outside in-place mod management. Use this only for mods that break when loaded in place.", + rule, matchedMods); + } + } for (var entry : declarations.entrySet()) { Set rules = entry.getValue().editable; if (rules == null || rules.isEmpty()) continue; @@ -310,7 +365,7 @@ private static void auditEditableRules(Map rules, String groupId, String name) throws CandidateBuildException { + private static PathRuleSet compileRuleSet(Collection rules, String groupId, String name) throws CandidateBuildException { try { return new PathRuleSet(rules); } catch (IllegalArgumentException e) { @@ -457,7 +512,7 @@ public record Request( String mcVersion, Path serverRoot, Path groupRoot, - Map> modpack, + ServerConfigJsons.ModpackFields modpack, boolean applyPlatformExclusions, Path stagingDirectory, Executor executor, diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/generation/GenerationDiff.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/generation/GenerationDiff.java index 9ecdf68c2..945b54ba7 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/generation/GenerationDiff.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/generation/GenerationDiff.java @@ -11,6 +11,7 @@ public record GenerationDiff( List files, MetadataSummary packMetadata, + MetadataSummary categoryMetadata, MetadataSummary groupMetadata) { public GenerationDiff { files = files == null @@ -19,6 +20,7 @@ public record GenerationDiff( .thenComparingInt(change -> change.classification().ordinal()).thenComparing(change -> Objects.toString(change.before(), "")) .thenComparing(change -> Objects.toString(change.after(), ""))).toList(); packMetadata = Objects.requireNonNull(packMetadata); + categoryMetadata = Objects.requireNonNull(categoryMetadata); groupMetadata = Objects.requireNonNull(groupMetadata); } @@ -41,7 +43,7 @@ public static GenerationDiff between(GroupManifest parent, GroupManifest child) else continue; changes.add(new FileChange(key.groupId(), key.logicalPath(), classification, oldFile, newFile)); } - return new GenerationDiff(changes, packSummary(parent, child), groupSummary(parent, child)); + return new GenerationDiff(changes, packSummary(parent, child), categorySummary(parent, child), groupSummary(parent, child)); } public boolean isEmpty() { @@ -67,6 +69,7 @@ public ChangeSet changeSet() { } List effects = new ArrayList<>(); appendMetadataEffects(effects, "pack", packMetadata); + appendMetadataEffects(effects, "category", categoryMetadata); appendMetadataEffects(effects, "group", groupMetadata); return ChangeSet.of(changes, effects); } @@ -75,6 +78,7 @@ public ChangeSet changeSet() { public List humanReadableChanges() { List changes = new ArrayList<>(); appendMetadataChanges(changes, "pack metadata", packMetadata); + appendMetadataChanges(changes, "category", categoryMetadata); appendMetadataChanges(changes, "group", groupMetadata); for (FileChange change : files) { changes.add(change.classification().action() + " file '" + change.groupId() + "/" + change.logicalPath() + "'"); @@ -170,6 +174,11 @@ private static MetadataSummary packSummary(GroupManifest parent, GroupManifest c return new MetadataSummary(List.of(), modified, List.of()); } + private static MetadataSummary categorySummary(GroupManifest parent, GroupManifest child) { + Map before = parent == null ? Map.of() : parent.categories(); + return compareKeys(before, child.categories(), GroupManifest.Category::hasSameMetadata); + } + private static MetadataSummary groupSummary(GroupManifest parent, GroupManifest child) { Map before = parent == null ? Map.of() : parent.groups(); return compareKeys(before, child.groups(), GroupManifest.Group::hasSameMetadata); diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/generation/GenerationStore.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/generation/GenerationStore.java index e571d7550..fc71d7ee0 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/generation/GenerationStore.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/generation/GenerationStore.java @@ -26,6 +26,7 @@ import pl.skidam.automodpack_core.config.ConfigTools; import pl.skidam.automodpack_core.config.GenerationJsons; import pl.skidam.automodpack_core.config.ModpackJsons; +import pl.skidam.automodpack_core.config.Rc7PolicyMigration; import pl.skidam.automodpack_core.modpack.candidate.ModpackCandidate; import pl.skidam.automodpack_core.modpack.candidate.ServerObjectStore; import pl.skidam.automodpack_core.modpack.group.GroupManifest; @@ -60,6 +61,7 @@ public final class GenerationStore { private Journal journal; private Current current; + private boolean projectionMigrated; public GenerationStore(Path root, Path objectsDirectory) { this(root, objectsDirectory, new DataRootResolver.Location(objectsDirectory.getParent(), legacyOwnerId(objectsDirectory), @@ -188,6 +190,11 @@ private void archiveUnusableState(Exception cause) throws IOException { * loud log before the rebuild below recreates the projection. */ private Current loadFromProjection(boolean repairing) throws IOException { + if (!projectionMigrated) { + projectionMigrated = true; + // The projection is the served head document, so this convergence also updates what clients fetch. + Rc7PolicyMigration.migrateProjection(projectionFile); + } Function complete = document -> { if (document.policy == null || document.ownershipLedger == null) throw new IllegalArgumentException("Projection document is missing its policy or ownership ledger"); return document; @@ -478,7 +485,7 @@ private GroupManifest loadPolicy(String policySha1) throws IOException { // nowhere else, so bytes that no longer hash to their name would otherwise replay into hosting truth. byte[] bytes = Files.readAllBytes(object); if (!HashUtils.sha1(bytes).equalsIgnoreCase(policySha1)) throw new Journal.UnusableContentException("Policy document content does not match its address: " + policySha1); - return GroupManifestValidator.validate(ConfigTools.parse(new String(bytes, StandardCharsets.UTF_8), ModpackJsons.CompleteModpackContentFields.class)); + return GroupManifestValidator.validate(ConfigTools.parse(new String(bytes, StandardCharsets.UTF_8), ModpackJsons.CompleteModpackContentFields.class, Rc7PolicyMigration::policyDocument)); } catch (RuntimeException e) { throw new Journal.UnusableContentException("Policy document is unusable: " + policySha1, e); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/CategoryPickMode.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/CategoryPickMode.java new file mode 100644 index 000000000..ee26e18d0 --- /dev/null +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/CategoryPickMode.java @@ -0,0 +1,11 @@ +package pl.skidam.automodpack_core.modpack.group; + +public enum CategoryPickMode { + ANY, + AT_MOST_ONE, + EXACTLY_ONE; + + public boolean isExclusive() { + return this != ANY; + } +} diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/ClientSelectionStore.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/ClientSelectionStore.java index d4fed7090..45e85a79a 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/ClientSelectionStore.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/ClientSelectionStore.java @@ -8,15 +8,7 @@ import pl.skidam.automodpack_core.config.SelectionJsons; import pl.skidam.automodpack_core.modpack.ModpackId; -/** - * The persisted per-modpack group selection: the player's declared desire, written at every consent moment. - * - *

- * Writers must hold the game-directory mutation lock, like every other durable state file; the consent moments - * (save, update confirm, removal confirm) and the generation store's forget path already do. Reads are safe - * without it because every write is an atomic replacement. - *

- */ +/** The player's sparse per-modpack group selection, written at every consent. */ public final class ClientSelectionStore { private final Path path; @@ -27,8 +19,8 @@ public ClientSelectionStore(Path path) { public Optional get(String modpackId) { ModpackId.requireValid(modpackId); SelectionJsons.ClientSelectionStoreFields fields = read(); - SelectionJsons.ClientSelectionStoreFields.ModpackSelection selection = fields.selections.get(modpackId); - return selection == null ? Optional.empty() : Optional.of(intent(selection)); + SelectionJsons.SelectionFields selection = fields.selections.get(modpackId); + return selection == null ? Optional.empty() : Optional.of(selection.toIntent()); } /** Records the desire verbatim: the store is the player's declared choice, and the last consent wins. */ @@ -36,8 +28,7 @@ public void put(String modpackId, SelectionIntent target) throws IOException { ModpackId.requireValid(modpackId); Objects.requireNonNull(target); SelectionJsons.ClientSelectionStoreFields fields = read(); - fields.selections.put(modpackId, new SelectionJsons.ClientSelectionStoreFields.ModpackSelection(new LinkedHashSet<>(target.requestedGroups()), - new LinkedHashSet<>(target.requestedCategories()), new LinkedHashSet<>(target.excludedGroups()), target.platform() == null ? null : target.platform().id())); + fields.selections.put(modpackId, SelectionJsons.SelectionFields.from(target)); fields.selections = new LinkedHashMap<>(new TreeMap<>(fields.selections)); ConfigTools.writeAtomic(path, fields); } @@ -51,16 +42,6 @@ public void remove(String modpackId) throws IOException { ConfigTools.writeAtomic(path, fields); } - private static SelectionIntent intent(SelectionJsons.ClientSelectionStoreFields.ModpackSelection selection) { - return new SelectionIntent(selection.requestedGroups, selection.requestedCategories, selection.excludedGroups, platform(selection.platform)); - } - - private static ClientPlatform platform(String platform) { - // Strict on purpose: a stored platform this build cannot parse is corrupt durable state, so the - // read's set-aside path handles it loudly instead of silently re-resolving under another platform. - return platform == null ? null : ClientPlatform.parse(platform); - } - private SelectionJsons.ClientSelectionStoreFields read() { try { SelectionJsons.ClientSelectionStoreFields fields = ConfigTools.readState(path, SelectionJsons.ClientSelectionStoreFields.class, "Client group selection", ClientSelectionStore::validated) @@ -74,9 +55,15 @@ private SelectionJsons.ClientSelectionStoreFields read() { /** The document's completeness contract: unusable content is set aside as evidence and reads as no selection. */ private static SelectionJsons.ClientSelectionStoreFields validated(SelectionJsons.ClientSelectionStoreFields fields) { - if (fields.DO_NOT_CHANGE_IT != 1) throw new IllegalArgumentException("Client group selection file version " + fields.DO_NOT_CHANGE_IT + " is not supported"); + if (fields.schemaVersion != 2) throw new IllegalArgumentException("Client group selection file version " + fields.schemaVersion + " is not supported"); if (fields.selections == null) fields.selections = new LinkedHashMap<>(); - for (SelectionJsons.ClientSelectionStoreFields.ModpackSelection selection : fields.selections.values()) platform(selection.platform); + for (var entry : fields.selections.entrySet()) { + ModpackId.requireValid(entry.getKey()); + SelectionJsons.SelectionFields value = entry.getValue(); + if (value == null || value.enabled == null || value.disabled == null) + throw new IllegalArgumentException("Selection entry for " + entry.getKey() + " is incomplete"); + value.toIntent(); + } return fields; } } diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupManifest.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupManifest.java index b7df4e924..ca8d7e872 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupManifest.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupManifest.java @@ -4,11 +4,7 @@ import pl.skidam.automodpack_core.config.ModpackJsons; -/** - * The flat group model of one generation. {@link Group#category()} holds the category NAME (never empty); category order is - * the first-occurrence order of {@code category} while iterating {@code groups}, since every category's groups are contiguous - * in it. Insertion order carries the declared category and group order, so every map here preserves it. - */ +/** The groups of one generation, with optional categories they reference by id. Insertion order is the declared order. */ public record GroupManifest( String modpackId, String modpackName, @@ -16,8 +12,10 @@ public record GroupManifest( String loader, String loaderVersion, String mcVersion, + Map categories, Map groups) { public GroupManifest { + categories = immutableMap(categories); groups = immutableMap(groups); } @@ -28,6 +26,48 @@ public Set declaredPlatforms() { return platforms; } + public boolean hasDeclaredPlatforms() { + return groups.values().stream().anyMatch(group -> !group.compatiblePlatforms().isEmpty()); + } + + public boolean hasChoosableGroups() { + return groups.values().stream().anyMatch(group -> group.selection().choosable()); + } + + public Category categoryOf(String groupId) { + Group group = groups.get(groupId); + if (group == null || group.category().isEmpty()) return null; + return categories.get(group.category()); + } + + /** The groups declared in one category, in declared order; "" names the uncategorized groups. */ + public List groupsOf(String categoryId) { + String wanted = categoryId == null ? "" : categoryId; + List members = new ArrayList<>(); + for (var entry : groups.entrySet()) if (wanted.equals(entry.getValue().category())) members.add(entry.getKey()); + return List.copyOf(members); + } + + public String displayName(String groupId) { + Group group = groups.get(groupId); + return group == null || group.name().isBlank() ? groupId : group.name(); + } + + public String categoryDisplayName(String categoryId) { + Category category = categories.get(categoryId); + return category == null || category.name().isBlank() ? categoryId : category.name(); + } + + /** Conflicts are declared on one side only; this returns the other side too. */ + public Set conflictsOf(String groupId) { + Set conflicts = new TreeSet<>(); + if (!groups.containsKey(groupId)) return conflicts; + conflicts.addAll(groups.get(groupId).conflicts()); + for (var entry : groups.entrySet()) if (entry.getValue().conflicts().contains(groupId)) conflicts.add(entry.getKey()); + conflicts.remove(groupId); + return conflicts; + } + public ModpackJsons.CompleteModpackContentFields toFields() { ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = modpackId; @@ -37,27 +77,35 @@ public ModpackJsons.CompleteModpackContentFields toFields() { fields.loaderVersion = loaderVersion; fields.mcVersion = mcVersion; - Map> serializedCategories = new LinkedHashMap<>(); + Map serializedCategories = new LinkedHashMap<>(); + for (var entry : categories.entrySet()) { + Category category = entry.getValue(); + ModpackJsons.CompleteModpackContentFields.CategoryFields serialized = new ModpackJsons.CompleteModpackContentFields.CategoryFields(); + serialized.name = category.name(); + serialized.description = category.description(); + serialized.pick = category.pick(); + serializedCategories.put(entry.getKey(), serialized); + } + fields.categories = serializedCategories; + + Map serializedGroups = new LinkedHashMap<>(); for (var entry : groups.entrySet()) { Group group = entry.getValue(); ModpackJsons.CompleteModpackContentFields.ModpackGroupFields serialized = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - serialized.displayName = group.displayName(); + serialized.name = group.name(); serialized.description = group.description(); - serialized.required = group.selection().alwaysInstalled(); - serialized.defaultSelected = group.selection().arrivesSelected(); - serialized.breaksWith = new LinkedHashSet<>(group.breaksWith()); + serialized.category = group.category(); + serialized.selection = group.selection(); serialized.requires = new LinkedHashSet<>(group.requires()); + serialized.conflicts = new LinkedHashSet<>(group.conflicts()); serialized.compatiblePlatforms = group.compatiblePlatforms().stream().map(ClientPlatform::id) .collect(LinkedHashSet::new, LinkedHashSet::add, LinkedHashSet::addAll); Map files = new LinkedHashMap<>(); - for (var fileEntry : group.files().entrySet()) { - GroupFile file = fileEntry.getValue(); - files.put(fileEntry.getKey(), publishedFile(fileEntry.getKey(), file)); - } + for (var fileEntry : group.files().entrySet()) files.put(fileEntry.getKey(), publishedFile(fileEntry.getKey(), fileEntry.getValue())); serialized.files = files; - serializedCategories.computeIfAbsent(group.category(), ignored -> new LinkedHashMap<>()).put(entry.getKey(), serialized); + serializedGroups.put(entry.getKey(), serialized); } - fields.categories = serializedCategories; + fields.groups = serializedGroups; return fields; } @@ -85,24 +133,41 @@ private static Set immutablePlatforms(Collection return Collections.unmodifiableSet(platforms); } + public record Category(String name, String description, CategoryPickMode pick) { + public Category { + name = name == null ? "" : name; + description = description == null ? "" : description; + pick = Objects.requireNonNull(pick, "pick"); + } + + public boolean hasSameMetadata(Category other) { + return other != null && Objects.equals(name, other.name) && Objects.equals(description, other.description) && pick == other.pick; + } + } + public record Group( - String displayName, + String name, String description, String category, GroupSelectionMode selection, - Set breaksWith, Set requires, Set compatiblePlatforms, - Map files) { + Map files, + Set conflicts) { public Group { - displayName = displayName == null ? "" : displayName; + name = name == null ? "" : name; description = description == null ? "" : description; category = category == null ? "" : category; selection = Objects.requireNonNull(selection, "selection"); - breaksWith = immutableSet(breaksWith); requires = immutableSet(requires); compatiblePlatforms = immutablePlatforms(compatiblePlatforms); files = immutableMap(files); + conflicts = immutableSet(conflicts); + } + + public Group(String name, String description, String category, GroupSelectionMode selection, Set requires, + Set compatiblePlatforms, Map files) { + this(name, description, category, selection, requires, compatiblePlatforms, files, Set.of()); } public boolean alwaysInstalled() { @@ -119,11 +184,13 @@ public boolean supports(ClientPlatform platform) { } public boolean hasSameMetadata(Group other) { - return other != null && Objects.equals(displayName, other.displayName) && Objects.equals(description, other.description) - && Objects.equals(category, other.category) && selection == other.selection && Objects.equals(breaksWith, other.breaksWith) - && Objects.equals(requires, other.requires) && Objects.equals(compatiblePlatforms, other.compatiblePlatforms); + return other != null && Objects.equals(name, other.name) && Objects.equals(description, other.description) + && Objects.equals(category, other.category) && selection == other.selection + && Objects.equals(requires, other.requires) && Objects.equals(compatiblePlatforms, other.compatiblePlatforms) + && Objects.equals(conflicts, other.conflicts); } } + public record GroupFile(long size, boolean editable, String sha1, String murmur) { public boolean sameEffectiveState(GroupFile other) { return other != null && size == other.size && editable == other.editable && sha1.equalsIgnoreCase(other.sha1); diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupManifestValidator.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupManifestValidator.java index 065c303cc..5b09e1ae9 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupManifestValidator.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupManifestValidator.java @@ -13,10 +13,9 @@ import pl.skidam.automodpack_core.utils.PathFold; public final class GroupManifestValidator { - private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9._-]{0,63}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9_-]{0,63}"); private static final Pattern ILLEGAL_WINDOWS_COMPONENT = Pattern.compile(".*[<>:\"|?*\\\\\\p{Cntrl}].*"); private static final Pattern CONTROL_CHARACTER = Pattern.compile("\\p{Cntrl}"); - // Deliberately matches the group ID cap: both name things a player browses in the same UI rows. private static final int CATEGORY_NAME_MAX = 64; private GroupManifestValidator() {} @@ -37,48 +36,89 @@ private static GroupManifest validate(ModpackJsons.CompleteModpackContentFields List errors = new ArrayList<>(); if (fields == null) throw new GroupValidationException(List.of("Complete modpack catalogue is missing")); if (!ModpackId.isValid(fields.modpackId)) errors.add("Invalid modpack ID"); - if (fields.categories == null || fields.categories.isEmpty()) errors.add("Group catalogue is empty"); - Map groups = new LinkedHashMap<>(); - Map seenCategoryNames = new LinkedHashMap<>(); - if (fields.categories != null) for (var categoryEntry : fields.categories.entrySet()) { - String category = validateCategoryName(categoryEntry.getKey(), seenCategoryNames, errors); - if (categoryEntry.getValue() == null || categoryEntry.getValue().isEmpty()) { - errors.add("Category '" + value(categoryEntry.getKey()) + "' is empty"); - continue; + + Map categories = new LinkedHashMap<>(); + Map seenCategoryLabels = new LinkedHashMap<>(); + if (fields.categories != null) { + for (var categoryEntry : fields.categories.entrySet()) { + String catId = categoryEntry.getKey(); + if (!isValidIdentifier(catId)) { + errors.add("Invalid category ID: " + catId); + continue; + } + ModpackJsons.CompleteModpackContentFields.CategoryFields category = categoryEntry.getValue(); + if (category == null) { + errors.add("Category '" + catId + "' is missing its declaration"); + continue; + } + String name = validateCategoryDisplayName(catId, category.name, seenCategoryLabels, errors); + String description = value(category.description); + if (CONTROL_CHARACTER.matcher(description).find()) errors.add("Category '" + catId + "' description contains control characters"); + if (category.pick == null) { + errors.add("Category '" + catId + "' is missing its pick mode"); + continue; + } + categories.put(catId, new GroupManifest.Category(name, description, category.pick)); } - for (var entry : categoryEntry.getValue().entrySet()) { + } + + if (fields.groups == null || fields.groups.isEmpty()) errors.add("Group catalogue is empty"); + Map groups = new LinkedHashMap<>(); + Set populatedCategories = new HashSet<>(); + if (fields.groups != null) { + for (var entry : fields.groups.entrySet()) { String id = entry.getKey(); + if (!isValidIdentifier(id)) { + errors.add("Invalid group ID: " + id); + continue; + } if (groups.containsKey(id)) { errors.add("Group '" + id + "' is declared more than once"); continue; } ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = entry.getValue(); - if (!isValidIdentifier(id)) { - errors.add("Invalid group ID: " + id); - continue; - } if (group == null) { errors.add("Group '" + id + "' is missing its declaration"); continue; } - Set breaksWith = validateIds("Group '" + id + "' breaksWith", group.breaksWith, errors); + if (group.selection == null) { + errors.add("Group '" + id + "' is missing its selection mode"); + continue; + } + String name = value(group.name); + if (CONTROL_CHARACTER.matcher(name).find()) errors.add("Group '" + id + "' name contains control characters"); + String description = value(group.description); + if (CONTROL_CHARACTER.matcher(description).find()) errors.add("Group '" + id + "' description contains control characters"); + + String category = value(group.category); + if (!category.isEmpty()) { + if (!categories.containsKey(category)) { + errors.add("Group '" + id + "' references unknown category '" + category + "'"); + } else { + populatedCategories.add(category); + if (categories.get(category).pick().isExclusive() && !group.selection.choosable()) + errors.add("Group '" + id + "' cannot use selection " + group.selection + " in exclusive category '" + category + "'"); + } + } + Set requires = validateIds("Group '" + id + "' requires", group.requires, errors); + Set conflicts = validateIds("Group '" + id + "' conflicts with", group.conflicts, errors); Set platforms = validatePlatforms(id, group.compatiblePlatforms, errors); Map files = validateFiles(id, group.files, errors); - if (group.required == null || group.defaultSelected == null) { - errors.add("Group '" + id + "' is missing its selection flags"); - continue; - } - groups.put(id, new GroupManifest.Group(group.displayName, group.description, category, GroupSelectionMode.of(group.required, group.defaultSelected), breaksWith, requires, platforms, files)); + groups.put(id, new GroupManifest.Group(name, description, category, group.selection, requires, platforms, files, conflicts)); } } + for (String catId : categories.keySet()) { + if (!populatedCategories.contains(catId)) errors.add("Category '" + catId + "' has no groups"); + } + validateReferences(groups, errors); validateCycles(groups, errors); if (!errors.isEmpty()) throw new GroupValidationException(errors.stream().distinct().sorted().toList()); GroupManifest manifest = new GroupManifest(fields.modpackId, value(fields.modpackName), value(fields.automodpackVersion), value(fields.loader), - value(fields.loaderVersion), value(fields.mcVersion), groups); + value(fields.loaderVersion), value(fields.mcVersion), categories, groups); PairMemo pairs = new PairMemo(manifest); if (publishing) for (var group : manifest.groups().entrySet()) @@ -151,9 +191,9 @@ private static void validatePlatformPaths(GroupManifest manifest, boolean publis .add(new PathOwner(groupId, path)); } } - validateAliasOwners(platform, manifest, aliases, false, errors, pairs); - validateAncestorOwners(platform, manifest, aliases, errors, pairs); - validateAliasOwners(platform, manifest, modBasenameAliases, true, errors, pairs); + validateAliasOwners(platform, aliases, false, errors, pairs); + validateAncestorOwners(platform, aliases, errors, pairs); + validateAliasOwners(platform, modBasenameAliases, true, errors, pairs); } } @@ -162,7 +202,7 @@ private static void validatePlatformPaths(GroupManifest manifest, boolean publis * map, so the conflicts come out of strict '/'-boundary prefix lookups instead of a pairwise scan over every * file owner. Equal keys are aliases, never ancestor pairs. */ - private static void validateAncestorOwners(ClientPlatform platform, GroupManifest manifest, Map> aliases, List errors, PairMemo pairs) { + private static void validateAncestorOwners(ClientPlatform platform, Map> aliases, List errors, PairMemo pairs) { for (var entry : aliases.entrySet()) for (PathOwner descendant : entry.getValue()) for (String ancestorKey : ancestorKeys(entry.getKey())) { List ancestors = aliases.get(ancestorKey); if (ancestors == null) continue; @@ -185,7 +225,7 @@ private static void reportAncestor(ClientPlatform platform, PairMemo pairs, Path errors.add(platform.id() + ": file path '" + ancestor.path() + "' cannot be an ancestor of '" + descendant.path() + "' in " + ownerDescription); } - private static void validateAliasOwners(ClientPlatform platform, GroupManifest manifest, Map> aliases, boolean modBasenames, + private static void validateAliasOwners(ClientPlatform platform, Map> aliases, boolean modBasenames, List errors, PairMemo pairs) { String prefix = modBasenames ? "mod files" : "paths"; String suffix = modBasenames ? " share a basename in the live mods directory" : " differ only in letter case or Unicode form, so case-insensitive filesystems would make them one file"; @@ -223,9 +263,11 @@ private static void validateReferences(Map groups, String id = entry.getKey(); GroupManifest.Group group = entry.getValue(); if (group.requires().contains(id)) errors.add("Group '" + id + "' cannot require itself"); - if (group.breaksWith().contains(id)) errors.add("Group '" + id + "' cannot conflict with itself"); for (String dependency : group.requires()) if (!groups.containsKey(dependency)) errors.add("Group '" + id + "' requires missing group '" + dependency + "'"); - for (String conflict : group.breaksWith()) if (!groups.containsKey(conflict)) errors.add("Group '" + id + "' conflicts with missing group '" + conflict + "'"); + for (String conflict : group.conflicts()) { + if (conflict.equals(id)) errors.add("Group '" + id + "' cannot conflict with itself"); + else if (!groups.containsKey(conflict)) errors.add("Group '" + id + "' conflicts with missing group '" + conflict + "'"); + } } } @@ -255,14 +297,13 @@ private static void validateDefaultAndIndividualSelections(GroupManifest manifes for (String error : e.errors()) errors.add(platform.id() + ": " + error); } for (var entry : manifest.groups().entrySet()) { - if (!entry.getValue().supports(platform)) continue; - try { - ResolvedSelection selection = GroupSelectionResolver.resolve(manifest, new SelectionIntent(Set.of(entry.getKey())), platform); - if (!selection.selectedGroups().contains(entry.getKey()) && !isOptionalUnavailable(manifest, entry.getKey(), selection)) - errors.add(platform.id() + ": Group '" + entry.getKey() + "' cannot be selected on this platform"); - } catch (SelectionResolutionException e) { - if (!isOptionalUnavailable(manifest, entry.getKey(), e.resolution())) for (String error : e.errors()) errors.add(platform.id() + ": " + error); - } + GroupManifest.Group group = entry.getValue(); + if (!group.supports(platform) || !group.selection().choosable()) continue; + GroupSelectionResolver.SelectionUpdate update = GroupSelectionResolver.activateGroup(manifest, SelectionIntent.DEFAULTS, entry.getKey(), platform); + ResolvedSelection resolution = update.resolution(); + boolean selectable = update.ok() && resolution != null && resolution.selectedGroups().contains(entry.getKey()); + if (!selectable && (resolution == null || !isOptionalUnavailable(manifest, entry.getKey(), resolution))) + errors.add(platform.id() + ": Group '" + entry.getKey() + "' cannot be selected on this platform"); } } if (!errors.isEmpty()) throw new GroupValidationException(errors.stream().distinct().sorted().toList()); @@ -311,10 +352,12 @@ private static void validateOverlaps(GroupManifest manifest, List errors */ private static final class PairMemo { private final GroupManifest manifest; + private final Map> activatorsByGroup; private final Map cache = new HashMap<>(); PairMemo(GroupManifest manifest) { this.manifest = manifest; + this.activatorsByGroup = computeActivators(manifest); } boolean coSelectable(String first, String second) { @@ -323,18 +366,62 @@ boolean coSelectable(String first, String second) { } private boolean computeCoSelectable(String first, String second) { + Set firstTriggers = activatorsByGroup.getOrDefault(first, Set.of()); + Set secondTriggers = activatorsByGroup.getOrDefault(second, Set.of()); + if (firstTriggers.isEmpty() || secondTriggers.isEmpty()) return false; for (ClientPlatform platform : coveredPlatforms(manifest)) { GroupManifest.Group firstGroup = manifest.groups().get(first); GroupManifest.Group secondGroup = manifest.groups().get(second); if (!firstGroup.supports(platform) || !secondGroup.supports(platform)) continue; - try { - ResolvedSelection selection = GroupSelectionResolver.resolve(manifest, new SelectionIntent(Set.of(first, second)), platform); - if (selection.selectedGroups().contains(first) && selection.selectedGroups().contains(second)) return true; - } catch (SelectionResolutionException ignored) { + for (String t1 : firstTriggers) { + if (!manifest.groups().get(t1).supports(platform)) continue; + for (String t2 : secondTriggers) { + if (!manifest.groups().get(t2).supports(platform)) continue; + SelectionIntent activation = activationIntent(t1, t2, platform); + if (activation == null) continue; + try { + ResolvedSelection selection = GroupSelectionResolver.resolve(manifest, activation, platform); + if (selection.selectedGroups().contains(first) && selection.selectedGroups().contains(second)) return true; + } catch (SelectionResolutionException ignored) { + } + } } } return false; } + + /** Switches both triggers on through the resolver; a REQUIRED trigger is already on, so only RECOMMENDED and OPTIONAL need a click. */ + private SelectionIntent activationIntent(String firstTrigger, String secondTrigger, ClientPlatform platform) { + SelectionIntent intent = SelectionIntent.DEFAULTS; + for (String trigger : new LinkedHashSet<>(List.of(firstTrigger, secondTrigger))) { + if (!manifest.groups().get(trigger).selection().choosable()) continue; + GroupSelectionResolver.SelectionUpdate update = GroupSelectionResolver.activateGroup(manifest, intent, trigger, platform); + if (!update.ok()) return null; + intent = update.intent(); + } + return intent; + } + + private static Map> computeActivators(GroupManifest manifest) { + Map> activators = new LinkedHashMap<>(); + for (String id : manifest.groups().keySet()) activators.put(id, new LinkedHashSet<>()); + for (var entry : manifest.groups().entrySet()) { + String root = entry.getKey(); + if (entry.getValue().selection().automatic()) continue; + activators.get(root).add(root); + ArrayDeque queue = new ArrayDeque<>(entry.getValue().requires()); + Set seen = new HashSet<>(); + while (!queue.isEmpty()) { + String dep = queue.removeFirst(); + if (!seen.add(dep)) continue; + GroupManifest.Group depGroup = manifest.groups().get(dep); + if (depGroup == null) continue; + if (depGroup.selection().automatic()) activators.get(dep).add(root); + queue.addAll(depGroup.requires()); + } + } + return activators; + } } private static Set validatePlatforms(String groupId, Set input, List errors) { @@ -371,12 +458,12 @@ private static Set validateIds(String description, Set input, Li } public static String requireIdentifier(String id) { - if (!isValidIdentifier(id)) throw new IllegalArgumentException("Invalid group ID: " + id); + if (!isValidIdentifier(id)) throw new IllegalArgumentException("Invalid identifier: " + id); return id; } - private static boolean isValidIdentifier(String id) { - return id != null && ID.matcher(id).matches(); + public static boolean isValidIdentifier(String id) { + return id != null && ID.matcher(id).matches() && !OsPaths.isReservedWindowsDeviceName(id); } private static void validateId(String description, String id, List errors) { @@ -387,22 +474,18 @@ private static void validateId(String description, String id, List error } } - /** - * Category names are player-facing display strings, not ids. Guards run on the raw key: it must carry no leading/trailing - * whitespace, be non-blank, hold no control characters, fit the length cap, and be case-insensitively unique. - */ - private static String validateCategoryName(String raw, Map seenNames, List errors) { - if (raw == null) { - errors.add("Category name is missing"); - return ""; + private static String validateCategoryDisplayName(String catId, String rawName, Map seenLabels, List errors) { + String name = value(rawName); + if (CONTROL_CHARACTER.matcher(name).find()) errors.add("Category '" + catId + "' name contains control characters"); + if (!name.isEmpty()) { + if (!name.equals(name.strip())) errors.add("Category '" + catId + "' name has leading or trailing whitespace"); + if (name.strip().isEmpty()) errors.add("Category '" + catId + "' name is blank"); + if (name.length() > CATEGORY_NAME_MAX) errors.add("Category '" + catId + "' name is longer than " + CATEGORY_NAME_MAX + " characters"); } - if (!raw.equals(raw.strip())) errors.add("Category '" + raw + "' has leading or trailing whitespace"); - if (raw.strip().isEmpty()) errors.add("Category '" + raw + "' is blank"); - if (CONTROL_CHARACTER.matcher(raw).find()) errors.add("Category '" + raw + "' contains control characters"); - if (raw.length() > CATEGORY_NAME_MAX) errors.add("Category '" + raw + "' is longer than " + CATEGORY_NAME_MAX + " characters"); - String first = seenNames.putIfAbsent(raw.toLowerCase(Locale.ROOT), raw); - if (first != null) errors.add("Category '" + raw + "' duplicates category '" + first + "'"); - return raw; + String effectiveLabel = name.isEmpty() ? catId : name; + String first = seenLabels.putIfAbsent(effectiveLabel.toLowerCase(Locale.ROOT), catId); + if (first != null) errors.add("Category '" + catId + "' label '" + effectiveLabel + "' duplicates category '" + first + "'"); + return name; } private static String value(String value) { diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupResolution.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupResolution.java index 858eb161d..8a4e92332 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupResolution.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupResolution.java @@ -40,15 +40,17 @@ public enum Status { } public enum Reason { - EXPLICIT_GROUP, REQUIRED, - FORCED, - DEFAULT_SELECTED, + EXPLICIT_ENABLE, + RECOMMENDED, + CATEGORY_DEFAULT, DEPENDENCY, - EXPLICIT_EXCLUSION, + EXPLICIT_DISABLE, PLATFORM_INCOMPATIBLE, - EXPLICIT_REQUEST_UNAVAILABLE, + EXPLICIT_ENABLE_UNAVAILABLE, BLOCKED_BY_DEPENDENCY, - CONFLICTING_GROUP + EXCLUSIVE_CONFLICT, + PAIRWISE_CONFLICT, + AUTOMATIC_UNUSED } } diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionMode.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionMode.java index ff3baad57..94a3dd14b 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionMode.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionMode.java @@ -1,41 +1,25 @@ package pl.skidam.automodpack_core.modpack.group; -/** How a player receives a group: REQUIRED is always installed, RECOMMENDED arrives preselected, OPTIONAL starts unchecked. */ +/** REQUIRED always installs, RECOMMENDED starts selected, OPTIONAL starts unselected, AUTOMATIC installs only when a selected group requires it. */ public enum GroupSelectionMode { REQUIRED, RECOMMENDED, - OPTIONAL; + OPTIONAL, + AUTOMATIC; - /** Always installed, independent of the player's request. */ public boolean alwaysInstalled() { return this == REQUIRED; } - /** Arrives selected: required groups and recommended ones. */ public boolean arrivesSelected() { - return this != OPTIONAL; + return this == REQUIRED || this == RECOMMENDED; } - /** The policy document's required flag. */ - public boolean policyRequired() { - return alwaysInstalled(); + public boolean choosable() { + return this == RECOMMENDED || this == OPTIONAL; } - /** The policy document's default-selected flag. */ - public boolean policyDefaultSelected() { - return arrivesSelected(); - } - - /** - * The mode a legacy flag pair means. One combination has no mode of its own: required together with - * not-preselected. It collapses to REQUIRED, whose preselection is the part no player could ever act on anyway. - */ - public static GroupSelectionMode of(boolean required, boolean defaultSelected) { - return required ? REQUIRED : defaultSelected ? RECOMMENDED : OPTIONAL; - } - - /** Whether {@link #of} had to collapse such a pair, so the migration says so instead of quietly rewriting the operator's words. */ - public static boolean collapsed(boolean required, boolean defaultSelected) { - return required && !defaultSelected; + public boolean automatic() { + return this == AUTOMATIC; } } diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionResolver.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionResolver.java index b61264a70..c69d3cd3b 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionResolver.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionResolver.java @@ -5,357 +5,721 @@ public final class GroupSelectionResolver { private GroupSelectionResolver() {} - public static SelectionIntent defaultIntent(GroupManifest manifest) { - Objects.requireNonNull(manifest); - Set requestedGroups = new TreeSet<>(); - for (var entry : manifest.groups().entrySet()) { - GroupManifest.Group group = entry.getValue(); - if (group.selection() == GroupSelectionMode.RECOMMENDED) requestedGroups.add(entry.getKey()); + public record SelectionUpdate(SelectionIntent intent, ResolvedSelection resolution, NavigableSet turnedOff, String error, boolean turnedOffByConflict) { + public SelectionUpdate { + intent = Objects.requireNonNull(intent, "intent"); + turnedOff = turnedOff == null ? Collections.emptyNavigableSet() : Collections.unmodifiableNavigableSet(new TreeSet<>(turnedOff)); + error = error == null ? "" : error; + } + + public SelectionUpdate(SelectionIntent intent, ResolvedSelection resolution, NavigableSet turnedOff, String error) { + this(intent, resolution, turnedOff, error, false); + } + + public boolean ok() { + return error.isEmpty() && resolution != null; } - return new SelectionIntent(requestedGroups); } public static ResolvedSelection resolveDefault(GroupManifest manifest, ClientPlatform platform) { - return resolveInternal(manifest, defaultIntent(manifest), platform, true); + return resolve(manifest, SelectionIntent.DEFAULTS, platform); } public static ResolvedSelection resolve(GroupManifest manifest, SelectionIntent intent, ClientPlatform platform) { - return resolveInternal(manifest, intent, platform, false); + Resolution resolution = new Resolution(manifest, intent, platform); + resolution.markAvailability(); + resolution.selectRequired(); + resolution.selectChoosable(); + resolution.resolveExclusiveCategories(); + resolution.expandDependencies(); + resolution.lockCoreDependencies(); + resolution.rejectConflicts(); + ResolvedSelection resolved = resolution.build(); + if (!resolution.errors.isEmpty()) throw new SelectionResolutionException(resolution.errors.stream().distinct().toList(), resolved); + return resolved; } - private static ResolvedSelection resolveInternal(GroupManifest manifest, SelectionIntent intent, ClientPlatform platform, boolean defaultSelection) { - Objects.requireNonNull(manifest); - Objects.requireNonNull(intent); - ResolutionState state = new ResolutionState(manifest, intent, platform); - state.initializeMandatoryGroups(); - state.collectStaleChoices(); + private record Conflicts(Map> categories, Set pairwise) {} - for (String groupId : state.requiredGroups) state.resolveRoot(groupId, Source.REQUIRED, true); - for (String category : intent.requestedCategories()) for (var entry : manifest.groups().entrySet()) { - GroupManifest.Group group = entry.getValue(); - if (category.equals(group.category()) && !group.alwaysInstalled() && group.supports(platform)) state.resolveRoot(entry.getKey(), Source.EXPLICIT, false); + private static final class Resolution { + private final GroupManifest manifest; + private final SelectionIntent intent; + private final ClientPlatform platform; + private final NavigableSet staleGroups = new TreeSet<>(); + private final Map> reasons = new LinkedHashMap<>(); + private final Map> related = new LinkedHashMap<>(); + private final NavigableSet selected = new TreeSet<>(); + private final NavigableSet coreRoots = new TreeSet<>(); + private final NavigableSet unavailable = new TreeSet<>(); + private final NavigableSet requestedUnavailable = new TreeSet<>(); + private final Map> blockedBy = new LinkedHashMap<>(); + private final List errors = new ArrayList<>(); + private final NavigableSet requiredGroups = new TreeSet<>(); + private final NavigableSet dependencyGroups = new TreeSet<>(); + private Map> exclusiveMembers; + private Conflicts conflicts; + + Resolution(GroupManifest manifest, SelectionIntent intent, ClientPlatform platform) { + Objects.requireNonNull(manifest, "manifest"); + Objects.requireNonNull(intent, "selection intent"); + this.manifest = manifest; + this.intent = intent; + this.platform = platform; + + Map groups = manifest.groups(); + for (String id : intent.enabled()) { + if (!groups.containsKey(id)) staleGroups.add(id); + } + + for (String id : groups.keySet()) { + reasons.put(id, new LinkedHashSet<>()); + related.put(id, new LinkedHashSet<>()); + } } - for (String groupId : intent.requestedGroups()) if (manifest.groups().containsKey(groupId)) { - GroupManifest.Group group = manifest.groups().get(groupId); - state.resolveRoot(groupId, defaultSelection && group.arrivesSelected() ? Source.DEFAULT_SELECTED : Source.EXPLICIT, false); + + void markAvailability() { + Map groups = manifest.groups(); + for (var entry : groups.entrySet()) { + String id = entry.getKey(); + if (!entry.getValue().supports(platform)) { + unavailable.add(id); + reasons.get(id).add(GroupResolution.Reason.PLATFORM_INCOMPATIBLE); + } else { + Set badDeps = incompatibleTransitiveDeps(manifest, id, platform); + if (!badDeps.isEmpty()) blockedBy.put(id, badDeps); + } + } } - state.checkConflicts(); - ResolvedSelection resolved = state.result(); - if (!state.errors.isEmpty()) throw new SelectionResolutionException(state.errors.stream().distinct().sorted().toList(), resolved); - return resolved; - } + // REQUIRED groups: a platform-scoped one stays unavailable, not an error. + void selectRequired() { + Map groups = manifest.groups(); + for (var entry : groups.entrySet()) { + String id = entry.getKey(); + GroupManifest.Group group = entry.getValue(); + if (group.selection() != GroupSelectionMode.REQUIRED) continue; + if (!group.supports(platform)) continue; + coreRoots.add(id); + if (blockedBy.containsKey(id)) { + errors.add("Required group '" + id + "' requires incompatible groups on " + platformLabel(platform) + ": " + String.join(", ", blockedBy.get(id))); + } else { + selected.add(id); + reasons.get(id).add(GroupResolution.Reason.REQUIRED); + } + } + } - public static SelectionIntent prefer(GroupManifest manifest, SelectionIntent current, String clicked, ClientPlatform platform) { - Objects.requireNonNull(manifest); - Objects.requireNonNull(current); - Objects.requireNonNull(clicked); - Set requestedGroups = new TreeSet<>(current.requestedGroups()); - Set requestedCategories = new TreeSet<>(current.requestedCategories()); - Set excludedGroups = new TreeSet<>(current.excludedGroups()); - GroupManifest.Group clickedGroup = manifest.groups().get(clicked); - if (clickedGroup != null && requestedCategories.remove(clickedGroup.category())) { - for (var entry : manifest.groups().entrySet()) { + // Uncategorized and ANY-category groups. + void selectChoosable() { + Map groups = manifest.groups(); + for (var entry : groups.entrySet()) { + String id = entry.getKey(); GroupManifest.Group group = entry.getValue(); - if (clickedGroup.category().equals(group.category()) && !group.alwaysInstalled() && group.supports(platform)) requestedGroups.add(entry.getKey()); + if (!group.selection().choosable()) continue; + GroupManifest.Category cat = manifest.categoryOf(id); + if (cat != null && cat.pick().isExclusive()) continue; + + if (intent.enabled().contains(id)) { + if (!group.supports(platform)) { + requestedUnavailable.add(id); + reasons.get(id).add(GroupResolution.Reason.EXPLICIT_ENABLE_UNAVAILABLE); + } else if (blockedBy.containsKey(id)) { + requestedUnavailable.add(id); + reasons.get(id).add(GroupResolution.Reason.EXPLICIT_ENABLE_UNAVAILABLE); + } else { + selected.add(id); + reasons.get(id).add(GroupResolution.Reason.EXPLICIT_ENABLE); + } + } else if (group.selection() == GroupSelectionMode.RECOMMENDED) { + if (intent.disabled().contains(id)) { + reasons.get(id).add(GroupResolution.Reason.EXPLICIT_DISABLE); + } else if (group.supports(platform) && !blockedBy.containsKey(id)) { + selected.add(id); + reasons.get(id).add(GroupResolution.Reason.RECOMMENDED); + } + } } } - if (!requestedGroups.add(clicked)) requestedGroups.remove(clicked); - excludedGroups.remove(clicked); - return new SelectionIntent(requestedGroups, requestedCategories, excludedGroups); - } - /** Persists a category request and clears the per-group choices inside it, so the category speaks with one voice. */ - public static SelectionIntent preferCategory(GroupManifest manifest, SelectionIntent current, String category, ClientPlatform platform) { - Objects.requireNonNull(manifest); - Objects.requireNonNull(current); - Objects.requireNonNull(category); - Set requestedGroups = new TreeSet<>(current.requestedGroups()); - Set requestedCategories = new TreeSet<>(current.requestedCategories()); - Set excludedGroups = new TreeSet<>(current.excludedGroups()); - requestedCategories.add(category); - clearCategoryChoices(categoryGroups(manifest, category, platform), requestedGroups, excludedGroups); - return new SelectionIntent(requestedGroups, requestedCategories, excludedGroups); - } + // Exclusive categories. + void resolveExclusiveCategories() { + Map groups = manifest.groups(); + Map categories = manifest.categories(); + exclusiveMembers = exclusiveCategoryMembers(manifest); + for (var catEntry : exclusiveMembers.entrySet()) { + String catId = catEntry.getKey(); + GroupManifest.Category cat = categories.get(catId); + List compatible = new ArrayList<>(); + for (String id : catEntry.getValue()) { + GroupManifest.Group group = groups.get(id); + if (!group.supports(platform) || blockedBy.containsKey(id)) { + if (intent.enabled().contains(id)) { + requestedUnavailable.add(id); + reasons.get(id).add(GroupResolution.Reason.EXPLICIT_ENABLE_UNAVAILABLE); + } + } else { + compatible.add(id); + } + } - /** Excludes every optional group in the category and drops the category request, so one click turns the whole category off - even groups that are on by default. */ - public static SelectionIntent excludeCategory(GroupManifest manifest, SelectionIntent current, String category, ClientPlatform platform) { - Objects.requireNonNull(manifest); - Objects.requireNonNull(current); - Objects.requireNonNull(category); - Set requestedGroups = new TreeSet<>(current.requestedGroups()); - Set requestedCategories = new TreeSet<>(current.requestedCategories()); - Set excludedGroups = new TreeSet<>(current.excludedGroups()); - requestedCategories.remove(category); - Set categoryGroups = categoryGroups(manifest, category, platform); - clearCategoryChoices(categoryGroups, requestedGroups, excludedGroups); - excludedGroups.addAll(categoryGroups); - return new SelectionIntent(requestedGroups, requestedCategories, excludedGroups); - } + List explicit = compatible.stream().filter(intent.enabled()::contains).toList(); + if (explicit.size() > 1) { + for (String id : explicit) { + reasons.get(id).add(GroupResolution.Reason.EXCLUSIVE_CONFLICT); + for (String other : explicit) if (!other.equals(id)) related.get(id).add(other); + } + errors.add("Multiple groups selected in exclusive category '" + catId + "': " + String.join(", ", explicit)); + } else if (explicit.size() == 1) { + String winner = explicit.get(0); + selected.add(winner); + reasons.get(winner).add(GroupResolution.Reason.EXPLICIT_ENABLE); + for (String id : compatible) { + if (!id.equals(winner) && groups.get(id).selection() == GroupSelectionMode.RECOMMENDED && intent.disabled().contains(id)) + reasons.get(id).add(GroupResolution.Reason.EXPLICIT_DISABLE); + } + } else { + List recommended = new ArrayList<>(); + for (String id : compatible) { + GroupManifest.Group group = groups.get(id); + if (group.selection() != GroupSelectionMode.RECOMMENDED) continue; + if (intent.disabled().contains(id)) reasons.get(id).add(GroupResolution.Reason.EXPLICIT_DISABLE); + else recommended.add(id); + } + if (recommended.size() > 1) { + for (String id : recommended) { + reasons.get(id).add(GroupResolution.Reason.EXCLUSIVE_CONFLICT); + for (String other : recommended) if (!other.equals(id)) related.get(id).add(other); + } + errors.add("Exclusive category '" + catId + "' has multiple RECOMMENDED defaults: " + String.join(", ", recommended)); + } else if (recommended.size() == 1) { + String winner = recommended.get(0); + selected.add(winner); + reasons.get(winner).add(GroupResolution.Reason.RECOMMENDED); + } else if (cat.pick() == CategoryPickMode.EXACTLY_ONE && !compatible.isEmpty()) { + String fallback = null; + for (String id : compatible) { + if (!intent.disabled().contains(id)) { + fallback = id; + break; + } + } + if (fallback != null) { + selected.add(fallback); + reasons.get(fallback).add(GroupResolution.Reason.CATEGORY_DEFAULT); + } else { + errors.add("Category '" + catId + "' requires selecting one option"); + } + } + } + } + } - private static Set categoryGroups(GroupManifest manifest, String category, ClientPlatform platform) { - Set categoryGroups = new TreeSet<>(); - for (var entry : manifest.groups().entrySet()) if (category.equals(entry.getValue().category()) && !entry.getValue().alwaysInstalled() && entry.getValue().supports(platform)) categoryGroups.add(entry.getKey()); - return categoryGroups; - } + // Dependency closure; tracks core-locked and dependency groups. + void expandDependencies() { + Map groups = manifest.groups(); + requiredGroups.addAll(coreRoots); + + ArrayDeque queue = new ArrayDeque<>(selected); + Set expanded = new HashSet<>(); + while (!queue.isEmpty()) { + String parent = queue.removeFirst(); + if (!expanded.add(parent)) continue; + boolean parentFromCore = requiredGroups.contains(parent); + for (String dep : groups.get(parent).requires()) { + GroupManifest.Group depGroup = groups.get(dep); + if (depGroup == null) { + errors.add("Group '" + parent + "' requires missing group '" + dep + "'"); + continue; + } + if (!depGroup.supports(platform)) { + blockedBy.computeIfAbsent(parent, ignored -> new LinkedHashSet<>()).add(dep); + errors.add("Group '" + parent + "' requires '" + dep + "', which is not available on " + platformLabel(platform)); + continue; + } + selected.add(dep); + dependencyGroups.add(dep); + if (parentFromCore) requiredGroups.add(dep); + reasons.get(dep).add(GroupResolution.Reason.DEPENDENCY); + related.get(dep).add(parent); + queue.addLast(dep); + } + } + } - private static void clearCategoryChoices(Set categoryGroups, Set requestedGroups, Set excludedGroups) { - for (String groupId : categoryGroups) { - requestedGroups.remove(groupId); - excludedGroups.remove(groupId); + // Re-propagate core-locked when a non-core group reached a dependency first. + void lockCoreDependencies() { + Map groups = manifest.groups(); + ArrayDeque coreQueue = new ArrayDeque<>(coreRoots); + Set coreVisited = new HashSet<>(); + while (!coreQueue.isEmpty()) { + String coreId = coreQueue.removeFirst(); + if (!coreVisited.add(coreId)) continue; + GroupManifest.Group coreGroup = groups.get(coreId); + if (coreGroup == null) continue; + for (String dep : coreGroup.requires()) { + if (selected.contains(dep) && requiredGroups.add(dep)) coreQueue.addLast(dep); + } + } } - } - public static boolean conflicts(GroupManifest manifest, String first, String second) { - if (Objects.equals(first, second)) return false; - GroupManifest.Group firstGroup = manifest.groups().get(first); - GroupManifest.Group secondGroup = manifest.groups().get(second); - return (firstGroup != null && firstGroup.breaksWith().contains(second)) || (secondGroup != null && secondGroup.breaksWith().contains(first)); - } + // Reject exclusive categories and conflicting pairs that dependency expansion produced. + void rejectConflicts() { + Map> categoryConflicts = new LinkedHashMap<>(); + for (var catEntry : exclusiveMembers.entrySet()) { + String catId = catEntry.getKey(); + List chosenInCat = new ArrayList<>(); + for (String id : catEntry.getValue()) if (selected.contains(id)) chosenInCat.add(id); + if (chosenInCat.size() > 1) { + categoryConflicts.put(catId, chosenInCat); + errors.add("Exclusive category '" + catId + "' cannot install multiple groups together: " + String.join(", ", chosenInCat)); + } + } - /** Builds the deterministic intent that keeps newly preferred groups and removes the choices which conflict with them. */ - public static Optional replaceConflicts(GroupManifest manifest, SelectionIntent candidate, Set preferredGroups, - ClientPlatform platform, ResolvedSelection partial) { - Objects.requireNonNull(manifest); - Objects.requireNonNull(candidate); - Objects.requireNonNull(preferredGroups); - if (preferredGroups.isEmpty() || partial == null) return Optional.empty(); - Set conflicts = new TreeSet<>(); - for (String preferred : preferredGroups) { - GroupResolution resolution = partial.resolution(preferred); - if (resolution != null && resolution.status() == GroupResolution.Status.CONFLICT) conflicts.addAll(resolution.relatedGroups()); - } - conflicts.removeAll(preferredGroups); - if (conflicts.isEmpty()) return Optional.empty(); - - Set requestedGroups = new TreeSet<>(candidate.requestedGroups()); - requestedGroups.removeIf(groupId -> !preferredGroups.contains(groupId) && selectsAny(manifest, new SelectionIntent(Set.of(groupId)), platform, conflicts)); - Set requestedCategories = new TreeSet<>(candidate.requestedCategories()); - Set expandedGroups = new TreeSet<>(); - for (String category : new TreeSet<>(requestedCategories)) { - if (!selectsAny(manifest, new SelectionIntent(Set.of(), Set.of(category), Set.of()), platform, conflicts)) continue; - requestedCategories.remove(category); - for (var entry : manifest.groups().entrySet()) { - GroupManifest.Group group = entry.getValue(); - if (!category.equals(group.category()) || group.alwaysInstalled() || !group.supports(platform)) continue; - if (!selectsAny(manifest, new SelectionIntent(Set.of(entry.getKey())), platform, conflicts)) expandedGroups.add(entry.getKey()); + Set pairwiseConflicts = new TreeSet<>(); + for (String first : selected) for (String second : manifest.conflictsOf(first)) { + if (first.compareTo(second) >= 0 || !selected.contains(second)) continue; + pairwiseConflicts.add(first); + pairwiseConflicts.add(second); + reasons.get(first).add(GroupResolution.Reason.PAIRWISE_CONFLICT); + reasons.get(second).add(GroupResolution.Reason.PAIRWISE_CONFLICT); + related.get(first).add(second); + related.get(second).add(first); + errors.add("Groups '" + first + "' and '" + second + "' conflict with each other"); } + conflicts = new Conflicts(categoryConflicts, pairwiseConflicts); } - requestedGroups.addAll(expandedGroups); - SelectionIntent replacement = new SelectionIntent(requestedGroups, requestedCategories, candidate.excludedGroups()); - try { - resolve(manifest, replacement, platform); - return Optional.of(new ConflictReplacement(replacement, conflicts)); - } catch (SelectionResolutionException ignored) { - return Optional.empty(); - } - } - private static boolean selectsAny(GroupManifest manifest, SelectionIntent intent, ClientPlatform platform, Set groupIds) { - try { - return !Collections.disjoint(resolve(manifest, intent, platform).selectedGroups(), groupIds); - } catch (SelectionResolutionException exception) { - return exception.resolution() != null && !Collections.disjoint(exception.resolution().selectedGroups(), groupIds); - } - } + ResolvedSelection build() { + Map groups = manifest.groups(); + NavigableMap groupResolutions = new TreeMap<>(); + for (var entry : groups.entrySet()) { + String id = entry.getKey(); + GroupManifest.Group group = entry.getValue(); + String catId = group.category(); + List catConflicts = catId.isEmpty() ? List.of() : conflicts.categories().getOrDefault(catId, List.of()); - public record ConflictReplacement(SelectionIntent intent, Set conflictingGroups) { - public ConflictReplacement { - intent = Objects.requireNonNull(intent); - conflictingGroups = Set.copyOf(new TreeSet<>(conflictingGroups)); + GroupResolution.Status status; + if (conflicts.pairwise().contains(id)) { + status = GroupResolution.Status.CONFLICT; + } else if (catConflicts.size() > 1 && catConflicts.contains(id)) { + status = GroupResolution.Status.CONFLICT; + reasons.get(id).add(GroupResolution.Reason.EXCLUSIVE_CONFLICT); + for (String other : catConflicts) if (!other.equals(id)) related.get(id).add(other); + } else if (unavailable.contains(id)) { + status = GroupResolution.Status.UNAVAILABLE; + } else if (blockedBy.containsKey(id)) { + status = GroupResolution.Status.BLOCKED; + reasons.get(id).add(GroupResolution.Reason.BLOCKED_BY_DEPENDENCY); + related.get(id).addAll(blockedBy.get(id)); + } else if (selected.contains(id)) { + status = GroupResolution.Status.SELECTED; + } else if (reasons.get(id).contains(GroupResolution.Reason.EXPLICIT_DISABLE)) { + status = GroupResolution.Status.EXCLUDED; + } else if (reasons.get(id).contains(GroupResolution.Reason.EXCLUSIVE_CONFLICT)) { + status = GroupResolution.Status.CONFLICT; + } else { + status = GroupResolution.Status.AVAILABLE; + if (group.selection() == GroupSelectionMode.AUTOMATIC) reasons.get(id).add(GroupResolution.Reason.AUTOMATIC_UNUSED); + } + groupResolutions.put(id, new GroupResolution(id, status, reasons.get(id), related.get(id))); + } + return new ResolvedSelection(intent, selected, staleGroups, requiredGroups, dependencyGroups, unavailable, requestedUnavailable, groupResolutions); } } - /** Names the resolution context in messages: the platform id, or the plain fact that nothing is known about the platform. */ - private static String platformName(ClientPlatform platform) { - return platform == null ? "no platform detected" : "platform " + platform.id(); + /** Activates a group and resolves any displaced category pick or conflict. */ + public static SelectionUpdate activateGroup(GroupManifest manifest, SelectionIntent current, String groupId, ClientPlatform platform) { + Objects.requireNonNull(manifest, "manifest"); + Objects.requireNonNull(current, "current"); + GroupManifest.Group group = manifest.groups().get(groupId); + if (group == null) return failure(current, null, "Unknown group: " + groupId); + if (!group.selection().choosable()) return failure(current, null, "Group cannot be toggled directly"); + ResolvedSelection previous = safeResolve(manifest, current, platform); + if (previous == null) return failure(current, null, "Current selection is invalid"); + return activateGroup(manifest, current, groupId, platform, previous); } - private enum Source { - REQUIRED, - DEFAULT_SELECTED, - EXPLICIT + private static SelectionUpdate activateGroup(GroupManifest manifest, SelectionIntent current, String groupId, ClientPlatform platform, ResolvedSelection previous) { + GroupManifest.Group group = manifest.groups().get(groupId); + GroupManifest.Category category = manifest.categoryOf(groupId); + if (category != null && category.pick().isExclusive()) return pickInCategory(manifest, current, group.category(), groupId, platform); + if (!group.supports(platform)) return failure(current, previous, "Not available on this platform"); + Set blockers = incompatibleTransitiveDeps(manifest, groupId, platform); + if (!blockers.isEmpty()) return failure(current, previous, blockedOn(groupId, blockers, platform)); + + Set enabled = new TreeSet<>(current.enabled()); + Set disabled = new TreeSet<>(current.disabled()); + enableGroupTree(manifest, groupId, enabled, disabled, platform); + Set cleared = new LinkedHashSet<>(); + String conflictError = clearConflictingSelection(manifest, previous, activationClosure(manifest, groupId), enabled, disabled, cleared); + if (!conflictError.isEmpty()) return failure(current, previous, conflictError); + + SelectionIntent nextIntent = new SelectionIntent(enabled, disabled, current.platform()); + return settleTransition(manifest, current, previous, nextIntent, Set.of(groupId), platform, !cleared.isEmpty()); } - private static final class ResolutionState { - private final GroupManifest manifest; - private final SelectionIntent intent; - private final ClientPlatform platform; - private final NavigableSet selected = new TreeSet<>(); - private final NavigableSet staleGroups = new TreeSet<>(); - private final NavigableSet requiredGroups = new TreeSet<>(); - private final NavigableSet forcedGroups = new TreeSet<>(); - private final NavigableSet dependencyGroups = new TreeSet<>(); - private final NavigableSet unavailableGroups = new TreeSet<>(); - private final NavigableSet requestedUnavailableGroups = new TreeSet<>(); - private final NavigableSet blockedGroups = new TreeSet<>(); - private final NavigableSet excludedGroups = new TreeSet<>(); - private final NavigableSet conflictGroups = new TreeSet<>(); - private final Map> reasons = new TreeMap<>(); - private final Map> relatedGroups = new TreeMap<>(); - private final List errors = new ArrayList<>(); + public static SelectionUpdate toggleGroup(GroupManifest manifest, SelectionIntent current, String groupId, ClientPlatform platform) { + Objects.requireNonNull(manifest, "manifest"); + Objects.requireNonNull(current, "current"); + GroupManifest.Group group = manifest.groups().get(groupId); + if (group == null) return failure(current, null, "Unknown group: " + groupId); + if (!group.selection().choosable()) return failure(current, null, "Group cannot be toggled directly"); + + GroupManifest.Category category = manifest.categoryOf(groupId); + ResolvedSelection previous = safeResolve(manifest, current, platform); + if (previous == null) return failure(current, null, "Current selection is invalid"); + + boolean currentlySelected = previous.selectedGroups().contains(groupId); + if (!currentlySelected) { + // An unselected group can only sit in the intent as an ask that took no effect here, so toggling forgets the ask; anything else asks for it. + if (current.enabled().contains(groupId)) { + Set enabled = new TreeSet<>(current.enabled()); + enabled.remove(groupId); + Set disabled = new TreeSet<>(current.disabled()); + if (group.selection() == GroupSelectionMode.RECOMMENDED) disabled.add(groupId); + return settleTransition(manifest, current, previous, new SelectionIntent(enabled, disabled, current.platform()), Set.of(groupId), platform, false); + } + return activateGroup(manifest, current, groupId, platform, previous); + } - private ResolutionState(GroupManifest manifest, SelectionIntent intent, ClientPlatform platform) { - this.manifest = manifest; - this.intent = intent; - this.platform = platform; + if (previous.requiredGroups().contains(groupId)) return failure(current, previous, "Required by core modpack"); + if (category != null && category.pick().isExclusive()) { + if (category.pick() == CategoryPickMode.EXACTLY_ONE) return failure(current, previous, "This category requires keeping one option selected"); + return pickInCategory(manifest, current, group.category(), null, platform); } - private void initializeMandatoryGroups() { - for (var entry : manifest.groups().entrySet()) if (entry.getValue().alwaysInstalled()) { - requiredGroups.add(entry.getKey()); - forcedGroups.add(entry.getKey()); - addReason(entry.getKey(), GroupResolution.Reason.REQUIRED); - addReason(entry.getKey(), GroupResolution.Reason.FORCED); + Set enabled = new TreeSet<>(current.enabled()); + Set disabled = new TreeSet<>(current.disabled()); + Set cascade = selectedDependentsClosure(manifest, previous.selectedGroups(), groupId); + for (String off : cascade) { + GroupManifest.Group offGroup = manifest.groups().get(off); + if (offGroup == null || !offGroup.selection().choosable()) continue; + if (previous.requiredGroups().contains(off)) + return failure(current, previous, "Cannot turn off because '" + manifest.displayName(off) + "' is required"); + GroupManifest.Category offCat = manifest.categoryOf(off); + if (offCat != null && offCat.pick() == CategoryPickMode.EXACTLY_ONE) { + return failure(current, previous, "Cannot turn off mandatory option '" + manifest.displayName(off) + "'"); } + enabled.remove(off); + if (offGroup.selection() == GroupSelectionMode.RECOMMENDED) disabled.add(off); } + // RECOMMENDED groups are on by default, so their enables are redundant. + pruneEnabledNonExclusive(manifest, enabled, disabled); - private void collectStaleChoices() { - for (String groupId : intent.requestedGroups()) if (!manifest.groups().containsKey(groupId)) staleGroups.add(groupId); + SelectionIntent nextIntent = new SelectionIntent(enabled, disabled, current.platform()); + return settleTransition(manifest, current, previous, nextIntent, Set.of(groupId), platform, false); + } + + public static SelectionUpdate pickInCategory(GroupManifest manifest, SelectionIntent current, String categoryId, String chosenGroupId, ClientPlatform platform) { + Objects.requireNonNull(manifest, "manifest"); + Objects.requireNonNull(current, "current"); + String chosenId = (chosenGroupId == null || chosenGroupId.isEmpty()) ? null : chosenGroupId; + GroupManifest.Category category = manifest.categories().get(categoryId); + if (category == null || !category.pick().isExclusive()) return failure(current, null, "Not an exclusive category: " + categoryId); + if (chosenId == null && category.pick() == CategoryPickMode.EXACTLY_ONE) + return failure(current, safeResolve(manifest, current, platform), "Category requires one option"); + if (chosenId != null) { + GroupManifest.Group chosen = manifest.groups().get(chosenId); + if (chosen == null || !categoryId.equals(chosen.category())) return failure(current, null, "Group does not belong to category: " + categoryId); + if (!chosen.supports(platform)) return failure(current, safeResolve(manifest, current, platform), "Not available on this platform"); + Set blockers = incompatibleTransitiveDeps(manifest, chosenId, platform); + if (!blockers.isEmpty()) return failure(current, safeResolve(manifest, current, platform), blockedOn(chosenId, blockers, platform)); } - private void resolveRoot(String groupId, Source source, boolean forced) { - Closure closure = resolveClosure(groupId, source, forced, false, new LinkedHashSet<>()); - if (closure.success()) selected.addAll(closure.groups()); - else if (source == Source.EXPLICIT) { - if (unavailableGroups.stream().anyMatch(closure.groups()::contains)) { - requestedUnavailableGroups.add(groupId); - addReason(groupId, GroupResolution.Reason.EXPLICIT_REQUEST_UNAVAILABLE); - errors.add("Group '" + groupId + "' was explicitly requested but is unavailable on " + platformName(platform)); - } else if (!closure.excluded()) { - errors.add("Group '" + groupId + "' was explicitly requested but could not be selected"); + ResolvedSelection previous = safeResolve(manifest, current, platform); + if (previous == null) return failure(current, null, "Current selection is invalid"); + + Set enabled = new TreeSet<>(current.enabled()); + Set disabled = new TreeSet<>(current.disabled()); + List members = manifest.groupsOf(categoryId); + + // Turn off selected dependents outside the category that relied on a displaced sibling. + for (String sibling : members) { + if (sibling.equals(chosenId) || !previous.selectedGroups().contains(sibling)) continue; + for (String dep : selectedDependentsClosure(manifest, previous.selectedGroups(), sibling)) { + GroupManifest.Group depGroup = manifest.groups().get(dep); + if (depGroup != null && !categoryId.equals(depGroup.category()) && depGroup.selection().choosable() && !previous.requiredGroups().contains(dep)) { + enabled.remove(dep); + if (depGroup.selection() == GroupSelectionMode.RECOMMENDED) disabled.add(dep); } } } - private Closure resolveClosure(String groupId, Source source, boolean forced, boolean dependency, Set active) { - GroupManifest.Group group = manifest.groups().get(groupId); - if (group == null) { - if (forced) errors.add("Group '" + groupId + "' is missing"); - return Closure.failure(Set.of()); - } - markSource(groupId, source, forced, dependency, group); - if (intent.excludedGroups().contains(groupId)) { - excludedGroups.add(groupId); - addReason(groupId, GroupResolution.Reason.EXPLICIT_EXCLUSION); - if (forced) errors.add("Group '" + groupId + "' is required and cannot be excluded"); - return Closure.excluded(Set.of(groupId)); - } - if (!group.supports(platform)) { - unavailableGroups.add(groupId); - addReason(groupId, GroupResolution.Reason.PLATFORM_INCOMPATIBLE); - if (forced) errors.add("Group '" + groupId + "' is unavailable on " + platformName(platform)); - return Closure.failure(Set.of(groupId)); - } - if (selected.contains(groupId)) return Closure.success(Set.of(groupId)); - if (!active.add(groupId)) { - errors.add("Group dependency cycle includes '" + groupId + "'"); - return Closure.failure(Set.of(groupId)); + for (String sibling : members) { + enabled.remove(sibling); + disabled.remove(sibling); + } + + boolean clearedConflicts = false; + if (chosenId == null) { + for (String sibling : members) { + GroupManifest.Group siblingGroup = manifest.groups().get(sibling); + if (siblingGroup != null && siblingGroup.supports(platform) && siblingGroup.selection() == GroupSelectionMode.RECOMMENDED) disabled.add(sibling); } - Set closure = new TreeSet<>(); + } else { + enableGroupTree(manifest, chosenId, enabled, disabled, platform); + Set cleared = new LinkedHashSet<>(); + String conflictError = clearConflictingSelection(manifest, previous, activationClosure(manifest, chosenId), enabled, disabled, cleared); + if (!conflictError.isEmpty()) return failure(current, previous, conflictError); + clearedConflicts = !cleared.isEmpty(); + // Drop the enable when the defaults already select it. + Set probeEnabled = new TreeSet<>(enabled); + probeEnabled.remove(chosenId); try { - for (String dependencyId : group.requires()) { - Closure dependencyClosure = resolveClosure(dependencyId, source, forced || group.alwaysInstalled(), true, active); - if (!dependencyClosure.success()) { - Set blocked = new TreeSet<>(dependencyClosure.groups()); - blocked.add(groupId); - blockedGroups.addAll(blocked); - addReason(groupId, GroupResolution.Reason.BLOCKED_BY_DEPENDENCY); - relate(groupId, dependencyId); - if (dependencyClosure.excluded()) errors.add("Group '" + groupId + "' cannot be selected because dependency '" + dependencyId + "' was excluded"); - else if (forced) errors.add("Group '" + groupId + "' cannot be selected because dependency '" + dependencyId + "' is unavailable"); - return Closure.failure(blocked, dependencyClosure.excluded()); - } - relate(dependencyId, groupId); - closure.addAll(dependencyClosure.groups()); - } - closure.add(groupId); - return Closure.success(closure); - } finally { - active.remove(groupId); + ResolvedSelection probe = resolve(manifest, new SelectionIntent(probeEnabled, disabled, current.platform()), platform); + if (probe.selectedGroups().contains(chosenId)) enabled.remove(chosenId); + } catch (SelectionResolutionException ignored) { } } - private void markSource(String groupId, Source source, boolean forced, boolean dependency, GroupManifest.Group group) { - if (dependency) { - addReason(groupId, GroupResolution.Reason.DEPENDENCY); - dependencyGroups.add(groupId); + SelectionIntent nextIntent = new SelectionIntent(enabled, disabled, current.platform()); + Set suppressed = chosenId == null ? Set.copyOf(members) : Set.of(chosenId); + return settleTransition(manifest, current, previous, nextIntent, suppressed, platform, clearedConflicts); + } + + /** The category members a select-all / clear-all acts on: choosable, not locked by the core pack, and not platform-excluded. Enabling filters installability on its own. */ + public static List bulkToggleTargets(GroupManifest manifest, ResolvedSelection resolution, String categoryId, ClientPlatform platform) { + List targets = new ArrayList<>(); + for (String id : manifest.groupsOf(categoryId)) { + GroupManifest.Group group = manifest.groups().get(id); + if (group == null || !group.selection().choosable() || !group.supports(platform)) continue; + if (resolution != null && resolution.requiredGroups().contains(id)) continue; + targets.add(id); + } + return targets; + } + + public static SelectionUpdate setCategoryAll(GroupManifest manifest, SelectionIntent current, String categoryId, boolean selectAll, ClientPlatform platform) { + Objects.requireNonNull(manifest, "manifest"); + Objects.requireNonNull(current, "current"); + GroupManifest.Category category = manifest.categories().get(categoryId); + if (category == null || category.pick().isExclusive()) return failure(current, null, "Bulk toggle is only valid on ANY categories"); + + ResolvedSelection previous = safeResolve(manifest, current, platform); + if (previous == null) return failure(current, null, "Current selection is invalid"); + + Set enabled = new TreeSet<>(current.enabled()); + Set disabled = new TreeSet<>(current.disabled()); + List members = bulkToggleTargets(manifest, previous, categoryId, platform); + + boolean clearedConflicts = false; + if (selectAll) { + Set activating = new LinkedHashSet<>(); + for (String id : members) { + // Enabling asks for content to install here, so a member whose dependency is unavailable stays out. + if (!installable(manifest, id, platform)) continue; + enableGroupTree(manifest, id, enabled, disabled, platform); + activating.addAll(activationClosure(manifest, id)); } - if (forced || group.alwaysInstalled()) { - forcedGroups.add(groupId); - addReason(groupId, GroupResolution.Reason.FORCED); + Set cleared = new LinkedHashSet<>(); + String conflictError = clearConflictingSelection(manifest, previous, activating, enabled, disabled, cleared); + if (!conflictError.isEmpty()) return failure(current, previous, conflictError); + clearedConflicts = !cleared.isEmpty(); + } else { + Set toClear = new LinkedHashSet<>(); + for (String id : members) { + GroupManifest.Group g = manifest.groups().get(id); + if (previous.selectedGroups().contains(id)) toClear.addAll(selectedDependentsClosure(manifest, previous.selectedGroups(), id)); + else { + enabled.remove(id); + if (g.selection() == GroupSelectionMode.RECOMMENDED) disabled.add(id); + } } - if (group.alwaysInstalled()) { - requiredGroups.add(groupId); - addReason(groupId, GroupResolution.Reason.REQUIRED); + for (String off : toClear) { + GroupManifest.Group offGroup = manifest.groups().get(off); + if (offGroup == null || !offGroup.selection().choosable() || previous.requiredGroups().contains(off)) continue; + GroupManifest.Category offCat = manifest.categoryOf(off); + if (offCat != null && offCat.pick() == CategoryPickMode.EXACTLY_ONE) + return failure(current, previous, "Cannot clear because '" + manifest.displayName(off) + "' is mandatory"); + enabled.remove(off); + if (offGroup.selection() == GroupSelectionMode.RECOMMENDED) disabled.add(off); } - if (source == Source.DEFAULT_SELECTED) addReason(groupId, GroupResolution.Reason.DEFAULT_SELECTED); - if (source == Source.EXPLICIT) addReason(groupId, GroupResolution.Reason.EXPLICIT_GROUP); - } - - private void checkConflicts() { - List ordered = new ArrayList<>(selected); - for (int i = 0; i < ordered.size(); i++) for (int j = i + 1; j < ordered.size(); j++) { - String first = ordered.get(i); - String second = ordered.get(j); - if (!conflicts(manifest, first, second)) continue; - conflictGroups.add(first); - conflictGroups.add(second); - addReason(first, GroupResolution.Reason.CONFLICTING_GROUP); - addReason(second, GroupResolution.Reason.CONFLICTING_GROUP); - relate(first, second); - relate(second, first); - errors.add("Groups '" + first + "' and '" + second + "' cannot be selected together"); + } + + SelectionIntent nextIntent = new SelectionIntent(enabled, disabled, current.platform()); + Set suppressed = new HashSet<>(manifest.groupsOf(categoryId)); + return settleTransition(manifest, current, previous, nextIntent, suppressed, platform, clearedConflicts); + } + + public static SelectionUpdate withPlatform(GroupManifest manifest, SelectionIntent current, ClientPlatform override, ClientPlatform effectivePlatform) { + Objects.requireNonNull(manifest, "manifest"); + Objects.requireNonNull(current, "current"); + ResolvedSelection previous = safeResolve(manifest, current, effectivePlatform); + SelectionIntent nextIntent = current.withPlatform(override); + try { + return new SelectionUpdate(nextIntent, resolve(manifest, nextIntent, effectivePlatform), Collections.emptyNavigableSet(), ""); + } catch (SelectionResolutionException e) { + return new SelectionUpdate(current, previous, Collections.emptyNavigableSet(), String.join("; ", e.errors())); + } + } + + private static SelectionUpdate settleTransition(GroupManifest manifest, SelectionIntent previousIntent, ResolvedSelection previous, + SelectionIntent candidateIntent, Set suppressFromNotice, ClientPlatform platform, boolean turnedOffByConflict) { + try { + ResolvedSelection next = resolve(manifest, candidateIntent, platform); + NavigableSet turnedOff = new TreeSet<>(); + for (String id : previous.selectedGroups()) { + if (next.selectedGroups().contains(id) || suppressFromNotice.contains(id)) continue; + GroupManifest.Group g = manifest.groups().get(id); + if (g != null && !g.selection().automatic()) turnedOff.add(id); } + return new SelectionUpdate(candidateIntent, next, turnedOff, "", turnedOffByConflict && !turnedOff.isEmpty()); + } catch (SelectionResolutionException e) { + String msg = e.errors().isEmpty() ? "Selection cannot be resolved" : e.errors().get(0); + return new SelectionUpdate(previousIntent, previous, Collections.emptyNavigableSet(), msg); } + } - private ResolvedSelection result() { - NavigableMap explanations = new TreeMap<>(); - for (var entry : manifest.groups().entrySet()) { - String groupId = entry.getKey(); - GroupManifest.Group group = entry.getValue(); - EnumSet groupReasons = reasons.getOrDefault(groupId, EnumSet.noneOf(GroupResolution.Reason.class)); - if (!group.supports(platform)) { - unavailableGroups.add(groupId); - groupReasons.add(GroupResolution.Reason.PLATFORM_INCOMPATIBLE); + private static void enableGroupTree(GroupManifest manifest, String groupId, Set enabled, Set disabled, ClientPlatform platform) { + GroupManifest.Group target = manifest.groups().get(groupId); + if (target == null) return; + if (target.selection() == GroupSelectionMode.OPTIONAL) enabled.add(groupId); + disabled.remove(groupId); + + // Clear disabled on dependencies and make room in exclusive categories. + ArrayDeque queue = new ArrayDeque<>(target.requires()); + Set visited = new HashSet<>(); + visited.add(groupId); + while (!queue.isEmpty()) { + String depId = queue.removeFirst(); + if (!visited.add(depId)) continue; + GroupManifest.Group dep = manifest.groups().get(depId); + if (dep == null || !dep.supports(platform)) continue; + disabled.remove(depId); + GroupManifest.Category depCat = manifest.categoryOf(depId); + if (depCat != null && depCat.pick().isExclusive()) { + for (String sibling : manifest.groupsOf(dep.category())) { + if (!sibling.equals(depId)) enabled.remove(sibling); } - GroupResolution.Status status; - if (conflictGroups.contains(groupId)) status = GroupResolution.Status.CONFLICT; - else if (selected.contains(groupId)) status = GroupResolution.Status.SELECTED; - else if (excludedGroups.contains(groupId) || intent.excludedGroups().contains(groupId)) status = GroupResolution.Status.EXCLUDED; - else if (unavailableGroups.contains(groupId)) status = GroupResolution.Status.UNAVAILABLE; - else if (blockedGroups.contains(groupId)) status = GroupResolution.Status.BLOCKED; - else status = GroupResolution.Status.AVAILABLE; - explanations.put(groupId, new GroupResolution(groupId, status, groupReasons, relatedGroups.get(groupId))); + if (dep.selection().choosable()) enabled.add(depId); } - dependencyGroups.retainAll(selected); - return new ResolvedSelection(intent, selected, staleGroups, requiredGroups, forcedGroups, dependencyGroups, unavailableGroups, requestedUnavailableGroups, explanations); + queue.addAll(dep.requires()); } + } - private void addReason(String groupId, GroupResolution.Reason reason) { - reasons.computeIfAbsent(groupId, ignored -> EnumSet.noneOf(GroupResolution.Reason.class)).add(reason); + private static void pruneEnabledNonExclusive(GroupManifest manifest, Set enabled, Set disabled) { + Iterator it = enabled.iterator(); + while (it.hasNext()) { + String id = it.next(); + GroupManifest.Group g = manifest.groups().get(id); + if (g == null) continue; + GroupManifest.Category cat = manifest.categoryOf(id); + if ((cat == null || !cat.pick().isExclusive()) && g.selection() == GroupSelectionMode.RECOMMENDED) it.remove(); } + } - private void relate(String groupId, String relatedGroupId) { - relatedGroups.computeIfAbsent(groupId, ignored -> new TreeSet<>()).add(relatedGroupId); + private static Set selectedDependentsClosure(GroupManifest manifest, Set selectedGroups, String targetId) { + Set closure = new LinkedHashSet<>(); + closure.add(targetId); + boolean changed = true; + while (changed) { + changed = false; + for (String candidate : selectedGroups) { + if (closure.contains(candidate)) continue; + GroupManifest.Group g = manifest.groups().get(candidate); + if (g == null) continue; + for (String dep : g.requires()) { + if (closure.contains(dep)) { + closure.add(candidate); + changed = true; + break; + } + } + } } + return closure; } - private record Closure(boolean success, Set groups, boolean excluded) { - private static Closure success(Set groups) { - return new Closure(true, Set.copyOf(groups), false); + /** The group and everything it requires. */ + private static Set activationClosure(GroupManifest manifest, String groupId) { + Set closure = new LinkedHashSet<>(); + ArrayDeque queue = new ArrayDeque<>(); + closure.add(groupId); + queue.addLast(groupId); + while (!queue.isEmpty()) { + GroupManifest.Group group = manifest.groups().get(queue.removeFirst()); + if (group == null) continue; + for (String dependency : group.requires()) if (closure.add(dependency)) queue.addLast(dependency); } + return closure; + } - private static Closure failure(Set groups) { - return failure(groups, false); + /** Turns off selected groups that conflict with the ones being activated; refuses when a REQUIRED root locks one of them. */ + private static String clearConflictingSelection(GroupManifest manifest, ResolvedSelection previous, Set activating, Set enabled, Set disabled, + Set cleared) { + for (String activated : activating) for (String conflicting : manifest.conflictsOf(activated)) { + if (!previous.selectedGroups().contains(conflicting)) continue; + GroupManifest.Group other = manifest.groups().get(conflicting); + if (other == null) continue; + if (previous.requiredGroups().contains(conflicting)) + return "Cannot select '" + manifest.displayName(activated) + "' because '" + manifest.displayName(conflicting) + "' is required and conflicts with it"; + for (String off : selectedDependentsClosure(manifest, previous.selectedGroups(), conflicting)) { + GroupManifest.Group offGroup = manifest.groups().get(off); + if (offGroup == null) continue; + if (previous.requiredGroups().contains(off)) + return "Cannot select '" + manifest.displayName(activated) + "' because '" + manifest.displayName(off) + "' is required and depends on '" + manifest.displayName(conflicting) + "'"; + if (!offGroup.selection().choosable()) continue; + enabled.remove(off); + GroupManifest.Category offCat = manifest.categoryOf(off); + if (offGroup.selection() == GroupSelectionMode.RECOMMENDED || (offCat != null && offCat.pick() == CategoryPickMode.EXACTLY_ONE)) disabled.add(off); + cleared.add(off); + } } + return ""; + } + + private static SelectionUpdate failure(SelectionIntent current, ResolvedSelection fallback, String message) { + return new SelectionUpdate(current, fallback, Collections.emptyNavigableSet(), message); + } + + private static ResolvedSelection safeResolve(GroupManifest manifest, SelectionIntent intent, ClientPlatform platform) { + try { + return resolve(manifest, intent, platform); + } catch (SelectionResolutionException e) { + return e.resolution(); + } + } - private static Closure failure(Set groups, boolean excluded) { - return new Closure(false, Set.copyOf(groups), excluded); + private static Set incompatibleTransitiveDeps(GroupManifest manifest, String groupId, ClientPlatform platform) { + Set bad = new LinkedHashSet<>(); + ArrayDeque queue = new ArrayDeque<>(manifest.groups().get(groupId).requires()); + Set visited = new HashSet<>(); + while (!queue.isEmpty()) { + String depId = queue.removeFirst(); + if (!visited.add(depId)) continue; + GroupManifest.Group dep = manifest.groups().get(depId); + if (dep == null) continue; + if (!dep.supports(platform)) bad.add(depId); + queue.addAll(dep.requires()); } + return bad; + } - private static Closure excluded(Set groups) { - return new Closure(false, Set.copyOf(groups), true); + /** Whether this platform can install the group at all: it supports the platform and every transitive dependency does too. */ + private static boolean installable(GroupManifest manifest, String groupId, ClientPlatform platform) { + GroupManifest.Group group = manifest.groups().get(groupId); + return group != null && group.supports(platform) && incompatibleTransitiveDeps(manifest, groupId, platform).isEmpty(); + } + + private static String blockedOn(String groupId, Set blockers, ClientPlatform platform) { + return "Group '" + groupId + "' is blocked on " + platformLabel(platform) + " by: " + String.join(", ", blockers); + } + + private static Map> exclusiveCategoryMembers(GroupManifest manifest) { + Map> members = new LinkedHashMap<>(); + for (var entry : manifest.categories().entrySet()) { + if (entry.getValue().pick().isExclusive()) members.put(entry.getKey(), new ArrayList<>()); } + if (members.isEmpty()) return Map.of(); + for (var entry : manifest.groups().entrySet()) { + String catId = entry.getValue().category(); + List list = members.get(catId); + if (list != null) list.add(entry.getKey()); + } + return members; + } + + private static String platformLabel(ClientPlatform platform) { + return platform == null ? "undetected platform" : platform.id(); } } diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/ResolvedSelection.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/ResolvedSelection.java index f00f6d82c..a4b5f14bc 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/ResolvedSelection.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/ResolvedSelection.java @@ -5,24 +5,22 @@ public record ResolvedSelection( SelectionIntent intent, NavigableSet selectedGroups, - NavigableSet staleRequestedGroups, + NavigableSet staleGroups, NavigableSet requiredGroups, - NavigableSet forcedGroups, NavigableSet dependencyGroups, NavigableSet unavailableGroups, NavigableSet requestedUnavailableGroups, NavigableMap groupResolutions) { - public ResolvedSelection(SelectionIntent intent, Collection selectedGroups, Collection staleRequestedGroups) { - this(intent, immutableSet(selectedGroups), immutableSet(staleRequestedGroups), immutableSet(Set.of()), immutableSet(Set.of()), immutableSet(Set.of()), immutableSet(Set.of()), + public ResolvedSelection(SelectionIntent intent, Collection selectedGroups, Collection staleGroups) { + this(intent, immutableSet(selectedGroups), immutableSet(staleGroups), immutableSet(Set.of()), immutableSet(Set.of()), immutableSet(Set.of()), immutableSet(Set.of()), immutableMap(Map.of())); } public ResolvedSelection { intent = Objects.requireNonNull(intent); selectedGroups = immutableSet(selectedGroups); - staleRequestedGroups = immutableSet(staleRequestedGroups); + staleGroups = immutableSet(staleGroups); requiredGroups = immutableSet(requiredGroups); - forcedGroups = immutableSet(forcedGroups); dependencyGroups = immutableSet(dependencyGroups); unavailableGroups = immutableSet(unavailableGroups); requestedUnavailableGroups = immutableSet(requestedUnavailableGroups); diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/SelectionIntent.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/SelectionIntent.java index 1278ccad5..0614223f1 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/group/SelectionIntent.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/group/SelectionIntent.java @@ -2,43 +2,52 @@ import java.util.*; -public record SelectionIntent(NavigableSet requestedGroups, NavigableSet requestedCategories, NavigableSet excludedGroups, ClientPlatform platform) { - public SelectionIntent(Collection requestedGroups) { - this(requestedGroups, Set.of(), Set.of()); +/** Sparse player choice over choosable groups. Empty sets ({@link #DEFAULTS}) follow server defaults, so new RECOMMENDED groups arrive selected. */ +public record SelectionIntent(NavigableSet enabled, NavigableSet disabled, ClientPlatform platform) { + public static final SelectionIntent DEFAULTS = new SelectionIntent(Set.of(), Set.of(), null); + + public static SelectionIntent ofEnabled(Collection enabled) { + return new SelectionIntent(enabled, Set.of(), null); } - public SelectionIntent(Collection requestedGroups, Collection requestedCategories, Collection excludedGroups) { - this(requestedGroups, requestedCategories, excludedGroups, null); + public SelectionIntent(Collection enabled, Collection disabled) { + this(enabled, disabled, null); } - public SelectionIntent(Collection requestedGroups, Collection requestedCategories, Collection excludedGroups, ClientPlatform platform) { - this(toGroupIdSet(requestedGroups), toNameSet(requestedCategories), toGroupIdSet(excludedGroups), platform); + public SelectionIntent(Collection enabled, Collection disabled, ClientPlatform platform) { + this(toGroupIdSet(enabled), toGroupIdSet(disabled), platform); } public SelectionIntent { - requestedGroups = toGroupIdSet(requestedGroups); - requestedCategories = toNameSet(requestedCategories); - excludedGroups = toGroupIdSet(excludedGroups); + enabled = toGroupIdSet(enabled); + disabled = toGroupIdSet(disabled); + if (!Collections.disjoint(enabled, disabled)) { + Set overlap = new TreeSet<>(enabled); + overlap.retainAll(disabled); + throw new IllegalArgumentException("SelectionIntent cannot both enable and disable: " + overlap); + } + } + + public boolean isDefaults() { + return enabled.isEmpty() && disabled.isEmpty(); } /** Returns the same choice carrying a per-pack platform override; null keeps following the detected platform. */ public SelectionIntent withPlatform(ClientPlatform platform) { - return new SelectionIntent(requestedGroups, requestedCategories, excludedGroups, platform); + return new SelectionIntent(enabled, disabled, platform); } - // The platform rides along with the choice but never affects choice equality: recovery flows rebuild - // intents without it and must keep comparing equal to the stored selection, and a transaction commit - // may overwrite the stored platform with the platform its plan resolved under. + // Equality ignores the platform: recovery flows rebuild intents without it, and ModpackUpdater compares the override separately. @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof SelectionIntent intent)) return false; - return requestedGroups.equals(intent.requestedGroups) && requestedCategories.equals(intent.requestedCategories) && excludedGroups.equals(intent.excludedGroups); + return enabled.equals(intent.enabled) && disabled.equals(intent.disabled); } @Override public int hashCode() { - return Objects.hash(requestedGroups, requestedCategories, excludedGroups); + return Objects.hash(enabled, disabled); } private static NavigableSet toGroupIdSet(Collection values) { @@ -46,11 +55,4 @@ private static NavigableSet toGroupIdSet(Collection values) { if (values != null) for (String value : values) sorted.add(GroupManifestValidator.requireIdentifier(value)); return Collections.unmodifiableNavigableSet(sorted); } - - /** Category entries are player-facing display names, so unlike group ids they skip the ID pattern. */ - private static NavigableSet toNameSet(Collection values) { - TreeSet sorted = new TreeSet<>(); - if (values != null) sorted.addAll(values); - return Collections.unmodifiableNavigableSet(sorted); - } } diff --git a/core/src/main/java/pl/skidam/automodpack_core/modpack/host/HostAdvertisement.java b/core/src/main/java/pl/skidam/automodpack_core/modpack/host/HostAdvertisement.java index e47cb586f..474832bad 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/modpack/host/HostAdvertisement.java +++ b/core/src/main/java/pl/skidam/automodpack_core/modpack/host/HostAdvertisement.java @@ -10,7 +10,6 @@ import org.apache.logging.log4j.Logger; import pl.skidam.automodpack_core.Environment; -import pl.skidam.automodpack_core.config.ConfigTools; import pl.skidam.automodpack_core.config.GenerationJsons; import pl.skidam.automodpack_core.config.ModpackJsons; import pl.skidam.automodpack_core.config.ServerConfigJsons; @@ -23,6 +22,7 @@ import pl.skidam.automodpack_core.modpack.group.GroupSelectionResolver; import pl.skidam.automodpack_core.modpack.group.ResolvedSelection; import pl.skidam.automodpack_core.modpack.group.SelectedTreeComposer; +import pl.skidam.automodpack_core.utils.ModpackContentTools; /** Builds the pre-serialized host advertisement served by GET /advertise. */ public final class HostAdvertisement { @@ -46,7 +46,7 @@ public static WireJsons.AdvertiseFields build(GenerationHosting hosting, PackAbs Path headPath = hosting == null ? null : hosting.get(GenerationHosting.HEAD_DOCUMENT_KEY); if (headPath != null && Files.isRegularFile(headPath)) { try { - GenerationJsons.HeadDocumentFields head = ConfigTools.parse(Files.readString(headPath, StandardCharsets.UTF_8), GenerationJsons.HeadDocumentFields.class); + GenerationJsons.HeadDocumentFields head = ModpackContentTools.readHeadDocument(headPath); if (head != null && head.policy != null) { ad.route = config != null && config.modpackHost ? WireJsons.RouteFields.fromServerConfig(config) : null; populateFromHead(ad, head); @@ -78,25 +78,22 @@ private static void populateFromHead(WireJsons.AdvertiseFields ad, GenerationJso } } catch (RuntimeException e) { Map uniqueFiles = new HashMap<>(); - if (policy.categories != null) { - for (var category : policy.categories.values()) { - if (category == null) continue; - for (var group : category.values()) { - if (group == null || group.files == null) continue; - if (!group.required && !group.defaultSelected) continue; - for (var entry : group.files.entrySet()) { - String path = entry.getKey(); - var file = entry.getValue(); - if (path == null || file == null) continue; - long size = 0L; - if (file.size != null && !file.size.isBlank()) { - try { - size = Long.parseLong(file.size); - } catch (NumberFormatException ignored) { - } + if (policy.groups != null) { + for (var group : policy.groups.values()) { + if (group == null || group.files == null) continue; + if (group.selection == null || !group.selection.arrivesSelected()) continue; + for (var entry : group.files.entrySet()) { + String path = entry.getKey(); + var file = entry.getValue(); + if (path == null || file == null) continue; + long size = 0L; + if (file.size != null && !file.size.isBlank()) { + try { + size = Long.parseLong(file.size); + } catch (NumberFormatException ignored) { } - uniqueFiles.putIfAbsent(path, Math.max(0L, size)); } + uniqueFiles.putIfAbsent(path, Math.max(0L, size)); } } } diff --git a/core/src/main/java/pl/skidam/automodpack_core/protocol/netty/ActivityView.java b/core/src/main/java/pl/skidam/automodpack_core/protocol/netty/ActivityView.java index 04e84fd9d..7a2d8282b 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/protocol/netty/ActivityView.java +++ b/core/src/main/java/pl/skidam/automodpack_core/protocol/netty/ActivityView.java @@ -28,7 +28,7 @@ public ActivityTracker.Snapshot snapshot() { Map names = new HashMap<>(); routePaths.apply(GenerationHosting.HEAD_DOCUMENT_KEY).ifPresent(head -> { GenerationJsons.HeadDocumentFields document = ModpackContentTools.readHeadDocument(head); - if (document != null) document.policy.categories.forEach((category, groups) -> groups.forEach((group, fields) -> fields.files.forEach((path, file) -> names.put(file.sha1, path)))); + if (document != null && document.policy.groups != null) document.policy.groups.forEach((group, fields) -> fields.files.forEach((path, file) -> names.put(file.sha1, path))); }); long throughput = lastWriteThroughput.getAsLong(); if (throughput >= 0) tracker.writeThroughput(throughput); diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/ActivePackPointer.java b/core/src/main/java/pl/skidam/automodpack_core/update/ActivePackPointer.java index 6b6a88a69..780ed77b9 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/ActivePackPointer.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/ActivePackPointer.java @@ -5,12 +5,12 @@ import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.time.Instant; -import java.util.List; import java.util.Objects; import pl.skidam.automodpack_core.config.ClientConfigJsons; import pl.skidam.automodpack_core.config.ClientStorageJsons; import pl.skidam.automodpack_core.config.ConfigTools; +import pl.skidam.automodpack_core.config.SelectionJsons; import pl.skidam.automodpack_core.modpack.ModpackId; import pl.skidam.automodpack_core.modpack.generation.ContentTree; import pl.skidam.automodpack_core.modpack.generation.OwnershipLedger; @@ -140,11 +140,7 @@ void setDetached(String modpackId, boolean detached) throws IOException { } private void write(SelectionIntent applied, ClientStorageJsons.ClientGenerationStateFields state) throws IOException { - SelectionIntent selection = Objects.requireNonNull(applied, "applied selection"); - state.selectedGroups = List.copyOf(selection.requestedGroups()); - state.selectedCategories = List.copyOf(selection.requestedCategories()); - state.excludedGroups = List.copyOf(selection.excludedGroups()); - state.selectedPlatform = selection.platform() == null ? null : selection.platform().id(); + state.selection = SelectionJsons.SelectionFields.from(Objects.requireNonNull(applied, "applied selection")); publish(state); } @@ -179,10 +175,7 @@ private static ClientStorageJsons.ClientGenerationStateFields copy(ClientStorage copy.manifest = state.manifest; copy.manifestSha1 = state.manifestSha1; copy.createdAt = state.createdAt; - copy.selectedGroups = state.selectedGroups; - copy.selectedCategories = state.selectedCategories; - copy.excludedGroups = state.excludedGroups; - copy.selectedPlatform = state.selectedPlatform; + copy.selection = state.selection == null ? null : state.selection.copy(); copy.detached = state.detached; return copy; } diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/ClientGenerationStore.java b/core/src/main/java/pl/skidam/automodpack_core/update/ClientGenerationStore.java index 35c9f4c31..12ba06442 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/ClientGenerationStore.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/ClientGenerationStore.java @@ -23,6 +23,7 @@ import pl.skidam.automodpack_core.config.ConfigTools; import pl.skidam.automodpack_core.config.GenerationJsons; import pl.skidam.automodpack_core.config.ModpackJsons; +import pl.skidam.automodpack_core.config.Rc7PolicyMigration; import pl.skidam.automodpack_core.modpack.ModpackId; import pl.skidam.automodpack_core.modpack.candidate.PackOwnedFiles; import pl.skidam.automodpack_core.modpack.generation.ContentTree; @@ -43,6 +44,7 @@ import pl.skidam.automodpack_core.utils.FileTrees; import pl.skidam.automodpack_core.utils.HashUtils; import pl.skidam.automodpack_core.utils.ImmutableFiles; +import pl.skidam.automodpack_core.utils.ModpackContentTools; import pl.skidam.automodpack_core.utils.VerifiedFileTransfer; import pl.skidam.automodpack_core.utils.cache.FileCache; @@ -232,8 +234,8 @@ public GenerationHosting hosting(String modpackId) throws IOException { Path journal = storage.historyJournalFile(state.modpackId); if (!Files.isRegularFile(head, LinkOption.NOFOLLOW_LINKS) || !Files.isRegularFile(journal, LinkOption.NOFOLLOW_LINKS)) throw new IOException("The active modpack's mirror is incomplete: " + state.modpackId); - GenerationJsons.HeadDocumentFields headFields = ConfigTools.read(head, GenerationJsons.HeadDocumentFields.class) - .orElseThrow(() -> new IOException("The active modpack's head document is empty: " + head)); + GenerationJsons.HeadDocumentFields headFields = ModpackContentTools.readHeadDocument(head); + if (headFields == null) throw new IOException("The active modpack's head document is empty: " + head); if (!sameGeneration(state, headFields)) throw new IOException("The active modpack's mirror head names a different generation than the active state: " + state.modpackId); GroupManifest manifest = policyDocument(headFields.policySha1); @@ -296,9 +298,8 @@ public Optional appliedSelection(String modpackId) throws IOExc private Optional appliedSelection(ClientStorageJsons.ClientGenerationStateFields state, String modpackId) throws IOException { String normalizedModpackId = ModpackId.requireValid(modpackId); if (state == null || !normalizedModpackId.equals(state.modpackId)) return Optional.empty(); - if (state.selectedGroups == null) return new ClientSelectionStore(storage.selectionFile()).get(normalizedModpackId); - return Optional.of(new SelectionIntent(state.selectedGroups, state.selectedCategories, state.excludedGroups, - state.selectedPlatform == null ? null : ClientPlatform.parse(state.selectedPlatform))); + if (state.selection == null) return new ClientSelectionStore(storage.selectionFile()).get(normalizedModpackId); + return Optional.of(state.selection.toIntent()); } private SelectedModpackTarget resolveActive(ClientStorageJsons.ClientGenerationStateFields state, ClientPlatform platform) throws IOException { @@ -352,6 +353,10 @@ public PackDocument document(String modpackId, JournalEntry entry, ClientStorage return document(normalizedModpackId, entry, replayedLedger(normalizedModpackId, entry)); } + GroupManifest manifestForGeneration(String modpackId, String contentToken) throws IOException { + return policyDocument(mirrorEntry(modpackId, contentToken).policySha1()); + } + /** * Whether one mirror generation can be restored without the server: its policy document sits in the client CAS and every * object of its folded tree is in the CAS or still materialized at its live path. The server hosts only head objects, so @@ -389,7 +394,7 @@ public GroupManifest policyDocument(String policySha1) throws IOException { requirePolicyObject(hash); Path object = storage.objectFile(hash); try { - ModpackJsons.CompleteModpackContentFields fields = ConfigTools.read(object, ModpackJsons.CompleteModpackContentFields.class) + ModpackJsons.CompleteModpackContentFields fields = ConfigTools.read(object, ModpackJsons.CompleteModpackContentFields.class, Rc7PolicyMigration::policyDocument) .orElseThrow(() -> new IOException("Client policy document is empty: " + object)); return GroupManifestValidator.validate(fields); } catch (RuntimeException e) { @@ -578,9 +583,7 @@ boolean reconcileActiveClaim(InstanceTree.LiveIdentity identity) throws IOExcept } SelectionIntent applied = appliedSelection(identity, modpackId); if (current != null && modpackId.equals(current.modpackId) && document.contentToken().equals(current.contentToken) && current.detached - && Objects.equals(current.selectedGroups, List.copyOf(applied.requestedGroups())) - && Objects.equals(current.selectedCategories, List.copyOf(applied.requestedCategories())) - && Objects.equals(current.excludedGroups, List.copyOf(applied.excludedGroups()))) + && current.selection != null && current.selection.toIntent().equals(applied)) return false; storage.writeActiveState(document, applied, true); makeProjectionEditable(); @@ -612,7 +615,7 @@ private PackDocument snapshotDocument(String modpackId, String contentToken) { private SelectionIntent appliedSelection(InstanceTree.LiveIdentity identity, String modpackId) { SelectionIntent stored = new ClientSelectionStore(storage.selectionFile()).get(modpackId).orElse(null); SelectionIntent applied = identity.selection() == null ? stored : identity.selection(); - if (applied == null) return new SelectionIntent(Set.of()); + if (applied == null) return SelectionIntent.DEFAULTS; return stored == null ? applied : applied.withPlatform(stored.platform()); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/ClientStorage.java b/core/src/main/java/pl/skidam/automodpack_core/update/ClientStorage.java index 62891c0d2..37982f637 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/ClientStorage.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/ClientStorage.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.lang.ref.WeakReference; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; import java.util.HashMap; import java.util.List; @@ -21,8 +22,11 @@ import pl.skidam.automodpack_core.config.ClientConfigStore; import pl.skidam.automodpack_core.config.ClientStorageJsons; import pl.skidam.automodpack_core.config.ConfigTools; +import pl.skidam.automodpack_core.config.Rc7ClientSelectionMigration; import pl.skidam.automodpack_core.modpack.ModpackId; import pl.skidam.automodpack_core.modpack.generation.PackDocument; +import pl.skidam.automodpack_core.modpack.group.GroupManifest; +import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; import pl.skidam.automodpack_core.modpack.group.LogicalPath; import pl.skidam.automodpack_core.modpack.group.ModpackPathPolicy; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; @@ -516,11 +520,39 @@ private void initialize() throws IOException { FileTrees.createManagedDirectory(historyDirectory, "client journal mirrors"); FileTrees.createManagedDirectory(stateHistoryDirectory, "client state history"); FileTrees.createManagedDirectory(stateHistoryTreesDirectory(), "instance trees"); + ClientStorageMutation.run(this, () -> { + Rc7ClientSelectionMigration.PolicyLookup policies = rc7Policies(); + Rc7ClientSelectionMigration.migrateActiveState(stateFile, policies); + Rc7ClientSelectionMigration.migrateClientSelections(selectionFile, policies); + return null; + }); // The only place a durable migration runs, under the mutation lock: a reader that rewrote state made every // unlocked caller a writer, and two processes racing the index dropped each other's entries. GeneratedCopyState.migrateLegacyTree(this); } + /** + * The generation catalogues the rc.7 read migrations answer from: the generation a document names, else the pack's + * newest. One definition, because the active pointer and every legacy instance tree ask the same question. + */ + Rc7ClientSelectionMigration.PolicyLookup rc7Policies() { + ClientGenerationStore generations = new ClientGenerationStore(this); + return new Rc7ClientSelectionMigration.PolicyLookup() { + @Override + public GroupManifest generation(String modpackId, String contentToken) throws IOException { + return generations.manifestForGeneration(modpackId, contentToken); + } + + @Override + public GroupManifest latest(String modpackId) throws IOException { + ClientStorageJsons.ClientGenerationStateFields active = readActiveState(); + if (!Files.exists(historyJournalFile(modpackId), LinkOption.NOFOLLOW_LINKS) && active != null && modpackId.equals(active.modpackId) && active.manifest != null) + return GroupManifestValidator.validate(active.manifest); + return generations.newestDocument(modpackId, null).manifest(); + } + }; + } + /** Why selected and active-state disagree, or null when the projection may load (matching pointer, or no pointer). */ public static String activeSelectionMismatch(ClientConfigJsons.SelectedModpackFields selected, ClientStorageJsons.ClientGenerationStateFields state) { return ActivePackPointer.selectionMismatch(selected, state); diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/GeneratedCopyState.java b/core/src/main/java/pl/skidam/automodpack_core/update/GeneratedCopyState.java index 6eef9d228..2a6164455 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/GeneratedCopyState.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/GeneratedCopyState.java @@ -215,29 +215,35 @@ private static GeneratedCopyState chooseImported(List candid } /** - * Re-derives the active generation's record from what is installed, so a set-aside index costs one boot of - * generated-copy knowledge instead of the whole instance's. The identity is the active pointer plus the selection it - * committed under; the entries are the reserved bundle file, the one game-directory path no manifest can ship. A - * generation that already has a record is left alone - the apply that wrote it is the authority, and re-deriving from - * the live file would replace a planned identity with a drifted one. + * Re-derives the active generation's record from what is installed, so a set-aside index or a record under a + * superseded selection digest costs one boot of generated-copy knowledge instead of the whole instance's. The + * identity is the active pointer plus the selection it committed under; the entries are the reserved bundle file, + * the one game-directory path no manifest can ship. A record that answers that selection is left alone - the apply + * that wrote it is the authority, and re-deriving from the live file would replace a planned identity with a drifted + * one. */ public static void rebuildActive(ClientStorage storage) throws IOException { ClientStorageMutation.run(storage, () -> { ClientStorageJsons.ClientGenerationStateFields state = storage.readActiveState(); if (state == null) return null; String contentToken = HashUtils.requireDigest(state.contentToken, "generation ID"); - if (find(readIndex(storage), state.modpackId, contentToken) != null) return null; SelectionIntent applied = new ClientGenerationStore(storage).appliedSelection(state.modpackId).orElse(null); if (applied == null) return null; + String selectionDigest = UpdateTransaction.digest(applied); + // A record under another digest answers a selection no reader asks for any more - rc.7 hashed the selection + // differently - so its generation is as unrecorded as a lost index and the installed bundle is all the + // evidence left of what it holds. + GeneratedCopyState existing = find(readIndex(storage), state.modpackId, contentToken); + if (existing != null && existing.selectionDigest().equals(selectionDigest)) return null; String logicalPath = ModpackPathPolicy.generatedBundlePath(); Path bundle = storage.gamePath(logicalPath); if (!Files.isRegularFile(bundle, LinkOption.NOFOLLOW_LINKS)) return null; try (FileCache cache = FileCache.open(storage.fileCacheDirectory())) { String hash = FileIntegrity.identityHash(bundle, cache); if (hash == null) throw new IOException("Cannot hash the generated dependency bundle: " + bundle); - GeneratedCopyState rebuilt = new GeneratedCopyState(state.modpackId, contentToken, UpdateTransaction.digest(applied), List.of(new Entry(logicalPath, hash, Files.size(bundle)))); + GeneratedCopyState rebuilt = new GeneratedCopyState(state.modpackId, contentToken, selectionDigest, List.of(new Entry(logicalPath, hash, Files.size(bundle)))); rebuilt.write(storage); - LOGGER.warn("Rebuilt the generated-copy state of {} from the installed bundle; the index had been lost", state.modpackId); + LOGGER.warn("Rebuilt the generated-copy state of {} from the installed bundle; no record answered its applied selection", state.modpackId); } return null; }); diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/InstanceTree.java b/core/src/main/java/pl/skidam/automodpack_core/update/InstanceTree.java index 6a0494efc..8ad5f0559 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/InstanceTree.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/InstanceTree.java @@ -6,6 +6,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; @@ -15,15 +16,21 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.NavigableSet; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; + import pl.skidam.automodpack_core.Environment; import pl.skidam.automodpack_core.config.ClientStorageJsons; import pl.skidam.automodpack_core.config.ConfigTools; +import pl.skidam.automodpack_core.config.Rc7ClientSelectionMigration; +import pl.skidam.automodpack_core.config.SelectionJsons; import pl.skidam.automodpack_core.modpack.ModpackId; import pl.skidam.automodpack_core.modpack.group.LogicalPath; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; @@ -155,14 +162,41 @@ public static InstanceTree read(ClientStorage storage, String sha1) throws IOExc if (!attributes.isRegularFile()) throw new IOException("Instance tree is missing: " + normalized); VerifiedTree memo = VERIFIED_TREES.get(normalized); if (memo != null && memo.modified().equals(attributes.lastModifiedTime()) && memo.size() == attributes.size()) return memo.tree(); - ClientStorageJsons.InstanceTreeFields fields = ConfigTools.readUnique(file, ClientStorageJsons.InstanceTreeFields.class, "Instance tree", parsed -> parsed) - .orElseThrow(() -> new IOException("Instance tree is missing: " + normalized)); - InstanceTree tree = fromFields(fields); - if (!tree.sha1.equals(normalized)) throw new IOException("Instance tree hash does not match its file: " + normalized); + InstanceTree tree = readVerified(storage, file, normalized); VERIFIED_TREES.put(normalized, new VerifiedTree(attributes.lastModifiedTime(), attributes.size(), tree)); return tree; } + /** + * A tree is named by the compact serialization of the document its write persisted, and rc.7 persisted the selection + * as three legacy fields. So the name is proven against the document exactly as stored, and only then does the rc.7 + * migration rewrite it in memory: the file keeps its bytes, because every snapshot already points at this name. + */ + private static InstanceTree readVerified(ClientStorage storage, Path file, String storedName) throws IOException { + JsonObject document = document(file, storedName); + if (!HashUtils.sha1(ConfigTools.COMPACT.toJson(document).getBytes(StandardCharsets.UTF_8)).equals(storedName)) + throw new IOException("Instance tree hash does not match its file: " + storedName); + try { + Rc7ClientSelectionMigration.instanceTree(document, storage.rc7Policies()); + return fromFields(ConfigTools.parse(document, ClientStorageJsons.InstanceTreeFields.class)); + } catch (RuntimeException unusable) { + throw new IOException("Instance tree is unusable: " + storedName, unusable); + } + } + + private static JsonObject document(Path file, String storedName) throws IOException { + JsonElement tree; + try { + tree = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)); + } catch (NoSuchFileException missing) { + throw new IOException("Instance tree is missing: " + storedName, missing); + } catch (JsonParseException invalid) { + throw new IOException("Instance tree is not valid JSON: " + storedName, invalid); + } + if (!tree.isJsonObject()) throw new IOException("Instance tree is not a JSON object: " + storedName); + return tree.getAsJsonObject(); + } + public void write(ClientStorage storage) throws IOException { Path file = storage.stateHistoryTreeFile(sha1); if (Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) return; @@ -273,10 +307,7 @@ private static ClientStorageJsons.InstanceTreeFields toFields(LiveIdentity ident fields.activeModpackId = identity.activeModpackId(); fields.contentToken = identity.contentToken(); fields.detached = identity.detached(); - SelectionIntent selection = identity.selection(); - fields.requestedGroups = selection == null ? List.of() : List.copyOf(selection.requestedGroups()); - fields.requestedCategories = selection == null ? List.of() : List.copyOf(selection.requestedCategories()); - fields.excludedGroups = selection == null ? List.of() : List.copyOf(selection.excludedGroups()); + fields.selection = SelectionJsons.SelectionFields.from(identity.selection()); List tombstones = new ArrayList<>(); for (Tombstone tombstone : identity.tombstones()) { ClientStorageJsons.InstanceTreeFields.TombstoneFields row = new ClientStorageJsons.InstanceTreeFields.TombstoneFields(); @@ -307,13 +338,7 @@ private static InstanceTree fromFields(ClientStorageJsons.InstanceTreeFields fie List tombstones = new ArrayList<>(); for (ClientStorageJsons.InstanceTreeFields.TombstoneFields row : fields.tombstones) tombstones.add(new Tombstone(row.modpackId, row.deletedPaths == null ? List.of() : row.deletedPaths)); - SelectionIntent selection = fields.activeModpackId == null || fields.activeModpackId.isBlank() - ? null - : new SelectionIntent(set(fields.requestedGroups), set(fields.requestedCategories), set(fields.excludedGroups)); + SelectionIntent selection = fields.selection == null ? null : fields.selection.toIntent(); return of(new LiveIdentity(fields.activeModpackId, fields.contentToken, fields.detached, selection, tombstones), files); } - - private static NavigableSet set(List values) { - return new TreeSet<>(values == null ? List.of() : values); - } } diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/ProjectionState.java b/core/src/main/java/pl/skidam/automodpack_core/update/ProjectionState.java index 9e07b1ad7..41b36d76a 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/ProjectionState.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/ProjectionState.java @@ -110,7 +110,7 @@ public record Row(String path, String sha1, long size) { /** The persisted shape; only this class reads or writes it. */ static final class Fields { - int version = 1; + int schemaVersion = 1; Phase phase; long revision; String transactionId; @@ -254,7 +254,7 @@ static ProjectionState read(Path file, int attempts, long retryMillis) throws IO } catch (JsonParseException | IllegalStateException e) { throw new UnreadableException("Projection state is unreadable: " + file, e); } - if (fields == null || fields.phase == null || fields.version != 1 || fields.revision < 0) throw new UnreadableException("Projection state is invalid: " + file, null); + if (fields == null || fields.phase == null || fields.schemaVersion != 1 || fields.revision < 0) throw new UnreadableException("Projection state is invalid: " + file, null); if (fields.phase == Phase.CONVERGING && fields.fallbackSource == null) throw new UnreadableException("Converging projection state does not name its fallback source: " + file, null); List rows = new ArrayList<>(); try { diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/RelayConsent.java b/core/src/main/java/pl/skidam/automodpack_core/update/RelayConsent.java index af4ffb481..1ac0c17ad 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/RelayConsent.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/RelayConsent.java @@ -32,7 +32,7 @@ public static void setRelayed(ClientStorage storage, String modpackId, boolean r private static ClientStorageJsons.RelayConsentFields read(ClientStorage storage) throws IOException { ClientStorageJsons.RelayConsentFields fields = ConfigTools.readState(storage.relayConsentFile(), ClientStorageJsons.RelayConsentFields.class, "Relay consent", document -> { - if (document.DO_NOT_CHANGE_IT != 1) throw new IllegalArgumentException("Relay consent file version " + document.DO_NOT_CHANGE_IT + " is not supported"); + if (document.schemaVersion != 1) throw new IllegalArgumentException("Relay consent file version " + document.schemaVersion + " is not supported"); return document; }).orElseGet(ClientStorageJsons.RelayConsentFields::new); fields.modpackIds = fields.modpackIds == null ? new TreeSet<>() : new TreeSet<>(fields.modpackIds); diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/UpdateLoopDetector.java b/core/src/main/java/pl/skidam/automodpack_core/update/UpdateLoopDetector.java index 5085d9a7f..6b3189093 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/UpdateLoopDetector.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/UpdateLoopDetector.java @@ -102,7 +102,7 @@ private void write(State state) { } private static boolean isValid(State state) { - return state != null && state.version == STATE_VERSION && state.fingerprint != null && !state.fingerprint.isBlank() && state.allowedRestarts > 0 && state.lastAllowedRestartMillis >= 0; + return state != null && state.schemaVersion == STATE_VERSION && state.fingerprint != null && !state.fingerprint.isBlank() && state.allowedRestarts > 0 && state.lastAllowedRestartMillis >= 0; } public enum Decision { @@ -112,7 +112,7 @@ public enum Decision { public record Outcome(Decision decision, int restarts, int maxRestarts, int suppressed) {} private static final class State { - private final int version = STATE_VERSION; + private final int schemaVersion = STATE_VERSION; private final String fingerprint; private final int allowedRestarts; private final long lastAllowedRestartMillis; diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/UpdatePreview.java b/core/src/main/java/pl/skidam/automodpack_core/update/UpdatePreview.java index 931f2e3b6..5707fcec7 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/UpdatePreview.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/UpdatePreview.java @@ -11,7 +11,6 @@ import pl.skidam.automodpack_core.change.ChangeSet; import pl.skidam.automodpack_core.modpack.generation.JournalEntry; import pl.skidam.automodpack_core.modpack.group.GroupManifest; -import pl.skidam.automodpack_core.modpack.group.GroupResolution; import pl.skidam.automodpack_core.modpack.group.ResolvedSelection; import pl.skidam.automodpack_core.update.UpdatePlan.Conflict; import pl.skidam.automodpack_core.update.UpdatePlan.OperationType; @@ -48,10 +47,17 @@ public static UpdatePreview create(UpdatePlan decision, ResolvedSelection select Objects.requireNonNull(decision, "reconciliation decision"); GroupConsequences consequences = selection == null ? new GroupConsequences(Set.of(), Set.of(), Set.of()) - : new GroupConsequences(selection.intent().requestedGroups(), selection.selectedGroups(), selection.staleRequestedGroups(), selection.groupResolutions()); + : new GroupConsequences(selection.selectedGroups(), uninstalledRequests(selection), Set.of()); return new UpdatePreview(decision, consequences, patchNotes, journal, mode, decision.consequences(), Map.of(), List.of(), null); } + /** Picks this pack will not install: groups that vanished and groups this platform cannot install. The preview calls both "no longer available". */ + private static Set uninstalledRequests(ResolvedSelection selection) { + Set lost = new TreeSet<>(selection.staleGroups()); + lost.addAll(selection.requestedUnavailableGroups()); + return lost; + } + public static UpdatePreview create(UpdatePlan decision, ResolvedSelection selection, Mode mode) { return create(decision, selection, mode, "", List.of()); } @@ -105,13 +111,18 @@ public UpdatePreview withUnownedLocalMods(List paths) { paths == null ? List.of() : new ArrayList<>(new TreeSet<>(paths)), remainingWireBytes); } + public UpdatePreview withNewGroups(Set newGroups) { + GroupConsequences updated = new GroupConsequences(groupConsequences.resolvedGroups(), groupConsequences.staleGroups(), newGroups); + return new UpdatePreview(decision, updated, patchNotes, journal, mode, changeSet, featureNames, unownedLocalMods, remainingWireBytes); + } + /** Adds presentation names (unnamed groups present their id) without reclassifying any planned disposition. */ public UpdatePreview withFeatureManifest(GroupManifest manifest) { Objects.requireNonNull(manifest, "feature manifest"); Map names = new TreeMap<>(); Map> ownersByPath = new TreeMap<>(); manifest.groups().forEach((groupId, group) -> { - names.put(groupId, group.displayName().isBlank() ? groupId : group.displayName()); + names.put(groupId, manifest.displayName(groupId)); group.files().keySet().forEach(path -> ownersByPath.computeIfAbsent(path, ignored -> new ArrayList<>()).add(groupId)); }); List changes = new ArrayList<>(changeSet.changes().size()); @@ -202,16 +213,11 @@ private static long largestOccurrence(ChangeSet.Change change) { public record Summary(int changedFiles, int removedFiles, int preservedFiles, int unsafeFiles, int otherEffects) {} - public record GroupConsequences(Set explicitGroups, Set resolvedGroups, Set staleGroups, Map resolutions) { - public GroupConsequences(Set explicitGroups, Set resolvedGroups, Set staleGroups) { - this(explicitGroups, resolvedGroups, staleGroups, Map.of()); - } - + public record GroupConsequences(Set resolvedGroups, Set staleGroups, Set newGroups) { public GroupConsequences { - explicitGroups = immutable(explicitGroups); resolvedGroups = immutable(resolvedGroups); staleGroups = immutable(staleGroups); - resolutions = Map.copyOf(new TreeMap<>(resolutions == null ? Map.of() : resolutions)); + newGroups = immutable(newGroups); } private static Set immutable(Set values) { diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/UpdateTransaction.java b/core/src/main/java/pl/skidam/automodpack_core/update/UpdateTransaction.java index b9187f496..85a07fea5 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/UpdateTransaction.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/UpdateTransaction.java @@ -2,14 +2,14 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.util.ArrayList; import java.util.HexFormat; -import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.UUID; import pl.skidam.automodpack_core.config.ClientConfigJsons; import pl.skidam.automodpack_core.config.GenerationJsons; +import pl.skidam.automodpack_core.config.SelectionJsons; import pl.skidam.automodpack_core.modpack.generation.OwnershipLedger; import pl.skidam.automodpack_core.modpack.generation.PackTarget; import pl.skidam.automodpack_core.modpack.group.ClientPlatform; @@ -24,21 +24,15 @@ * execution phase is not part of it: {@link UpdateJournal} owns that, one file, one carrier. */ public final class UpdateTransaction { - public static final int CURRENT_SCHEMA_VERSION = 2; + public static final int CURRENT_SCHEMA_VERSION = 3; public int schemaVersion; public String transactionId; public Purpose purpose; /** The durable plan. A class tree, not records: the Gson shipped in Minecraft 1.18 cannot deserialize records. */ public UpdatePlan plan; - public String targetPlatform; - public boolean expectedPriorSelectionPresent; - public List expectedPriorRequestedGroups; - public List expectedPriorRequestedCategories; - public List expectedPriorExcludedGroups; - public List requestedGroups; - public List requestedCategories; - public List excludedGroups; + public SelectionJsons.SelectionFields expectedPriorSelection; + public SelectionJsons.SelectionFields targetSelection; public String overlayDigest; public ClientConfigJsons.ClientConfigFieldsV3 expectedClientConfig; public String expectedSelectedModpackId; @@ -75,14 +69,9 @@ public static UpdateTransaction create(UpdatePlan plan, SelectedModpackTarget ta UpdateTransaction transaction = base(Purpose.MODPACK_UPDATE); fillGeneration(transaction, plan.packTarget(), target.document().ownershipLedger()); - transaction.targetPlatform = target.platform() == null ? null : target.platform().id(); - transaction.expectedPriorSelectionPresent = target.expectedPriorIntent() != null; - transaction.expectedPriorRequestedGroups = intentValues(target.expectedPriorIntent(), IntentPart.GROUPS); - transaction.expectedPriorRequestedCategories = intentValues(target.expectedPriorIntent(), IntentPart.CATEGORIES); - transaction.expectedPriorExcludedGroups = intentValues(target.expectedPriorIntent(), IntentPart.EXCLUDED); - transaction.requestedGroups = new ArrayList<>(target.selection().intent().requestedGroups()); - transaction.requestedCategories = new ArrayList<>(target.selection().intent().requestedCategories()); - transaction.excludedGroups = new ArrayList<>(target.selection().intent().excludedGroups()); + transaction.expectedPriorSelection = SelectionJsons.SelectionFields.from(target.expectedPriorIntent()); + SelectionIntent targetIntent = target.selection().intent().withPlatform(target.platform()); + transaction.targetSelection = SelectionJsons.SelectionFields.from(targetIntent); transaction.overlayDigest = overlayDigest == null ? "" : overlayDigest; transaction.expectedClientConfig = plannedAgainst.clientConfig(); transaction.expectedSelectedModpackId = plannedAgainst.selectedModpackId(); @@ -106,14 +95,8 @@ private static UpdateTransaction createRemovalLike(Purpose purpose, UpdatePlan p OwnershipLedger ledger = OwnershipLedger.fromFields(Objects.requireNonNull(plannedAgainst.installedLedger(), "plannedAgainst.installedLedger")); UpdateTransaction transaction = base(purpose); fillGeneration(transaction, plan.packTarget(), ledger); - transaction.targetPlatform = platform == null ? null : platform.id(); - transaction.expectedPriorSelectionPresent = expectedPriorIntent != null; - transaction.expectedPriorRequestedGroups = intentValues(expectedPriorIntent, IntentPart.GROUPS); - transaction.expectedPriorRequestedCategories = intentValues(expectedPriorIntent, IntentPart.CATEGORIES); - transaction.expectedPriorExcludedGroups = intentValues(expectedPriorIntent, IntentPart.EXCLUDED); - transaction.requestedGroups = List.of(); - transaction.requestedCategories = List.of(); - transaction.excludedGroups = List.of(); + transaction.expectedPriorSelection = SelectionJsons.SelectionFields.from(expectedPriorIntent); + transaction.targetSelection = SelectionJsons.SelectionFields.from(new SelectionIntent(Set.of(), Set.of(), platform)); transaction.overlayDigest = overlayDigest == null ? "" : overlayDigest; transaction.expectedClientConfig = plannedAgainst.clientConfig(); transaction.expectedSelectedModpackId = plannedAgainst.selectedModpackId(); @@ -137,19 +120,6 @@ private static UpdateTransaction base(Purpose purpose) { return transaction; } - private enum IntentPart { - GROUPS, CATEGORIES, EXCLUDED - } - - private static List intentValues(SelectionIntent intent, IntentPart part) { - if (intent == null) return List.of(); - return switch (part) { - case GROUPS -> new ArrayList<>(intent.requestedGroups()); - case CATEGORIES -> new ArrayList<>(intent.requestedCategories()); - case EXCLUDED -> new ArrayList<>(intent.excludedGroups()); - }; - } - public UpdatePlan plan() { return plan; } @@ -163,7 +133,7 @@ public PackTarget packTarget() { } public ClientPlatform platform() { - return targetPlatform == null ? null : ClientPlatform.parse(targetPlatform); + return targetSelection == null || targetSelection.platform == null ? null : ClientPlatform.parse(targetSelection.platform); } /** The installed projection this plan was planned against, or null when the plan saw no installed generation. */ @@ -172,12 +142,12 @@ public OwnershipLedger expectedInstalled() { } public SelectionIntent expectedPriorIntent() { - return expectedPriorSelectionPresent ? new SelectionIntent(expectedPriorRequestedGroups, expectedPriorRequestedCategories, expectedPriorExcludedGroups) : null; + return expectedPriorSelection == null ? null : expectedPriorSelection.toIntent(); } /** The target selection carrying the platform this transaction resolved under, so the commit pins the exact resolution. */ public SelectionIntent targetIntent() { - return new SelectionIntent(requestedGroups, requestedCategories, excludedGroups, platform()); + return targetSelection.toIntent(); } /** The selection the transaction plans for; generated-copy state is keyed by it. */ @@ -188,10 +158,9 @@ public String selectionDigest() { public static String digest(SelectionIntent intent) { if (intent == null) return ""; MessageDigest digest = HashUtils.newSha1Digest(); - digest.update("automodpack-selection-v2\n".getBytes(StandardCharsets.UTF_8)); - for (String value : intent.requestedGroups().stream().sorted().toList()) digest.update(("group=" + value + "\n").getBytes(StandardCharsets.UTF_8)); - for (String value : intent.requestedCategories().stream().sorted().toList()) digest.update(("category=" + value + "\n").getBytes(StandardCharsets.UTF_8)); - for (String value : intent.excludedGroups().stream().sorted().toList()) digest.update(("excluded=" + value + "\n").getBytes(StandardCharsets.UTF_8)); + digest.update("automodpack-selection-v3\n".getBytes(StandardCharsets.UTF_8)); + for (String value : intent.enabled().stream().sorted().toList()) digest.update(("enabled=" + value + "\n").getBytes(StandardCharsets.UTF_8)); + for (String value : intent.disabled().stream().sorted().toList()) digest.update(("disabled=" + value + "\n").getBytes(StandardCharsets.UTF_8)); return HexFormat.of().formatHex(digest.digest()); } diff --git a/core/src/main/java/pl/skidam/automodpack_core/update/UpdateTransactionValidator.java b/core/src/main/java/pl/skidam/automodpack_core/update/UpdateTransactionValidator.java index 25f4660b8..01150c40e 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/update/UpdateTransactionValidator.java +++ b/core/src/main/java/pl/skidam/automodpack_core/update/UpdateTransactionValidator.java @@ -22,7 +22,6 @@ import pl.skidam.automodpack_core.modpack.generation.OwnershipLedger; import pl.skidam.automodpack_core.modpack.generation.PackDocument; import pl.skidam.automodpack_core.modpack.generation.PackTarget; -import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.LogicalPath; import pl.skidam.automodpack_core.modpack.group.ModpackPathPolicy; @@ -291,22 +290,15 @@ private void validateStoredClientState(UpdateTransaction transaction) throws IOE } private void validateSelectionMetadata(UpdateTransaction transaction) throws IOException { - if (transaction.expectedPriorRequestedGroups == null || transaction.expectedPriorRequestedCategories == null - || transaction.expectedPriorExcludedGroups == null || transaction.requestedGroups == null || transaction.requestedCategories == null || transaction.excludedGroups == null) - throw new IOException("Selection metadata is incomplete"); - if (!isCanonicalIntentList(transaction.expectedPriorRequestedGroups) - || !isCanonicalIntentList(transaction.expectedPriorRequestedCategories) - || !isCanonicalIntentList(transaction.expectedPriorExcludedGroups) - || !isCanonicalIntentList(transaction.requestedGroups) || !isCanonicalIntentList(transaction.requestedCategories) - || !isCanonicalIntentList(transaction.excludedGroups)) - throw new IOException("Selection metadata is not canonical"); + if (transaction.targetSelection == null || !transaction.targetSelection.isCanonical()) + throw new IOException("Target selection metadata is invalid or non-canonical"); + if (transaction.expectedPriorSelection != null && !transaction.expectedPriorSelection.isCanonical()) + throw new IOException("Prior selection metadata is invalid or non-canonical"); try { if (!transaction.selectionDigest().equals(UpdateTransaction.digest(transaction.purpose == UpdateTransaction.Purpose.MODPACK_UPDATE ? transaction.targetIntent() : transaction.expectedPriorIntent()))) throw new IOException("Selection digest does not match selection metadata"); - if (transaction.targetPlatform != null && !ClientPlatform.parse(transaction.targetPlatform).id().equals(transaction.targetPlatform)) - throw new IOException("Selection platform is not canonical"); } catch (RuntimeException e) { throw new IOException("Selection metadata is invalid", e); } @@ -349,10 +341,6 @@ private void validateManifest(ModpackJsons.ModpackContentFields manifest, String } } - private static boolean isCanonicalIntentList(List values) { - return values != null && values.equals(values.stream().distinct().sorted().toList()); - } - Map validateFinalState(List entries, String modpackId) throws IOException { Map finalState = new LinkedHashMap<>(); Set physicalTargets = new HashSet<>(); diff --git a/core/src/main/java/pl/skidam/automodpack_core/utils/FileTrees.java b/core/src/main/java/pl/skidam/automodpack_core/utils/FileTrees.java index 193f4c907..1796130ff 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/utils/FileTrees.java +++ b/core/src/main/java/pl/skidam/automodpack_core/utils/FileTrees.java @@ -19,6 +19,7 @@ import java.util.List; import java.util.Objects; import java.util.Set; +import java.util.stream.Stream; import pl.skidam.automodpack_core.utils.cache.FileCache; @@ -112,6 +113,13 @@ public static void requireDirectory(Path directory, String description) throws I if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException(description + " is not a directory: " + directory); } + /** True when nothing below {@code directory} is a regular file, so an empty tree and a tree of empty folders both count. */ + public static boolean containsNoFiles(Path directory) throws IOException { + try (Stream walk = Files.walk(directory)) { + return walk.noneMatch(Files::isRegularFile); + } + } + /** Requires a path that is not a symbolic link. */ public static void requireNoSymbolicLink(Path path, String description) throws IOException { if (isRedirectingLink(path)) throw new IOException(description + " contains a symbolic link: " + path); diff --git a/core/src/main/java/pl/skidam/automodpack_core/utils/ModpackContentTools.java b/core/src/main/java/pl/skidam/automodpack_core/utils/ModpackContentTools.java index 96f2bcf58..698e64df4 100644 --- a/core/src/main/java/pl/skidam/automodpack_core/utils/ModpackContentTools.java +++ b/core/src/main/java/pl/skidam/automodpack_core/utils/ModpackContentTools.java @@ -4,9 +4,11 @@ import pl.skidam.automodpack_core.config.ConfigTools; import pl.skidam.automodpack_core.config.GenerationJsons; +import pl.skidam.automodpack_core.config.Rc7PolicyMigration; public class ModpackContentTools { + /** Reads one head document: a mirror holds the server's bytes verbatim behind its etag, so an rc.7 shape converts at read instead of converging on disk. */ public static GenerationJsons.HeadDocumentFields readHeadDocument(Path path) { - return ConfigTools.read(path, GenerationJsons.HeadDocumentFields.class).orElse(null); + return ConfigTools.read(path, GenerationJsons.HeadDocumentFields.class, Rc7PolicyMigration::headDocument).orElse(null); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/auth/ConnectionStoreTest.java b/core/src/test/java/pl/skidam/automodpack_core/auth/ConnectionStoreTest.java index 91a4ed073..434f2d571 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/auth/ConnectionStoreTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/auth/ConnectionStoreTest.java @@ -18,7 +18,8 @@ import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; -import pl.skidam.automodpack_core.modpack.group.GroupSelectionResolver; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; +import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.protocol.ModpackConnectionMode; import pl.skidam.automodpack_core.storage.TestDataRoot; import pl.skidam.automodpack_core.update.ClientStorage; @@ -93,8 +94,8 @@ void stalePacksAreTheInstalledOnesThisOriginNoLongerServes() throws Exception { TestPacks.stageGeneration(storage, TestPacks.document(manifestFor("xyz9876", "stale", "config/b.txt", "b"))); TestPacks.stageGeneration(storage, TestPacks.document(manifestFor("pqr5432", "other origin", "config/c.txt", "c"))); ClientSelectionStore selections = new ClientSelectionStore(storage.selectionFile()); - selections.put("xyz9876", GroupSelectionResolver.defaultIntent(manifestFor("xyz9876", "stale", "config/b.txt", "b"))); - selections.put("pqr5432", GroupSelectionResolver.defaultIntent(manifestFor("pqr5432", "other origin", "config/c.txt", "c"))); + selections.put("xyz9876", SelectionIntent.DEFAULTS); + selections.put("pqr5432", SelectionIntent.DEFAULTS); assertEquals(List.of("xyz9876"), ConnectionStore.staleSameOriginPackIds(storage, "abc1234")); // A mirror fetch without consent is cache, and the active pack is never its own leftover. @@ -106,12 +107,11 @@ private static GroupManifest manifestFor(String modpackId, String description, S ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = modpackId; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = description; String sha1 = HashUtils.sha1(content.getBytes(StandardCharsets.UTF_8)); group.files = new TreeMap<>(Map.of(path, new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(content.length()), false, sha1, null))); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return GroupManifestValidator.validate(fields); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/change/ChangeBrowserProjectionTest.java b/core/src/test/java/pl/skidam/automodpack_core/change/ChangeBrowserProjectionTest.java index 0271a1d51..1246b6bfd 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/change/ChangeBrowserProjectionTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/change/ChangeBrowserProjectionTest.java @@ -47,9 +47,9 @@ void listUsesTheSameFilterAndDoesNotExposeTreeAncestors() { @Test void catalogueChangesUseTheSameProjectionAsDiffChanges() { GroupManifest.GroupFile file = new GroupManifest.GroupFile(5, false, HASH, null); - GroupManifest.Group group = new GroupManifest.Group("Main", "", "General", GroupSelectionMode.RECOMMENDED, new TreeSet<>(), new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/example.jar", file))); + GroupManifest.Group group = new GroupManifest.Group("Main", "", "", GroupSelectionMode.RECOMMENDED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/example.jar", file))); - ChangeSet catalogue = ChangeSet.catalogue(new GroupManifest("pack", "Pack", "1", "fabric", "1", "1.21", new TreeMap<>(Map.of("main", group)))); + ChangeSet catalogue = ChangeSet.catalogue(new GroupManifest("pack", "Pack", "1", "fabric", "1", "1.21", Map.of(), new TreeMap<>(Map.of("main", group)))); ChangeBrowserProjection.FileRow row = ChangeBrowserProjection.project(catalogue, ChangeBrowserProjection.Mode.LIST).files().get(0); assertEquals(ChangeSet.Kind.PRESERVED, row.kind()); diff --git a/core/src/test/java/pl/skidam/automodpack_core/change/PlatformReferencesTest.java b/core/src/test/java/pl/skidam/automodpack_core/change/PlatformReferencesTest.java index 1c98349d7..d94a49384 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/change/PlatformReferencesTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/change/PlatformReferencesTest.java @@ -86,7 +86,7 @@ private static ChangeSet.Change change(String path, ChangeSet.Kind kind, String private static ChangeSet catalogue() { GroupManifest.GroupFile file = new GroupManifest.GroupFile(1, false, SHA1, null); - GroupManifest.Group group = new GroupManifest.Group("Main", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/example.jar", file))); - return ChangeSet.catalogue(new GroupManifest("pack", "Pack", "1", "fabric", "1", "1.21", new TreeMap<>(Map.of("main", group)))); + GroupManifest.Group group = new GroupManifest.Group("Main", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/example.jar", file))); + return ChangeSet.catalogue(new GroupManifest("pack", "Pack", "1", "fabric", "1", "1.21", Map.of(), new TreeMap<>(Map.of("main", group)))); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/BootRecoveryStaleReviewTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/BootRecoveryStaleReviewTest.java index 664a91b55..c73aa2dd5 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/BootRecoveryStaleReviewTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/BootRecoveryStaleReviewTest.java @@ -53,7 +53,7 @@ public void loadModpack(ModpackLoadRequest request) {} GroupManifest manifest = TestPacks.manifest("test pack", "config/a.txt", "hello"); String modpackId = manifest.modpackId(); TestPacks.stageGeneration(storage, TestPacks.document(manifest)); - SelectionIntent selected = new SelectionIntent(Set.of("main")); + SelectionIntent selected = SelectionIntent.ofEnabled(Set.of("main")); new ClientSelectionStore(storage.selectionFile()).put(modpackId, selected); SelectedModpackTarget target = SelectedModpackTarget.prepare(TestPacks.document(manifest), selected, selected, ClientPlatform.LINUX); String hash = HashUtils.sha1("hello".getBytes(StandardCharsets.UTF_8)); diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/InstalledPackOwnershipTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/InstalledPackOwnershipTest.java index 04bd008f1..2abc235f5 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/InstalledPackOwnershipTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/InstalledPackOwnershipTest.java @@ -26,6 +26,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.storage.TestDataRoot; @@ -44,7 +45,7 @@ * removals happened in between. */ class InstalledPackOwnershipTest { - private static final SelectionIntent MAIN = new SelectionIntent(Set.of("main")); + private static final SelectionIntent MAIN = SelectionIntent.ofEnabled(Set.of("main")); private static final String SHARED = "config/shared.toml"; private static final String EDITABLE = "config/editable.toml"; private static final String OTHER = "config/other.toml"; @@ -263,10 +264,9 @@ private static SelectedModpackTarget generation(ClientStorage storage, String mo fields.loaderVersion = ""; fields.mcVersion = ""; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; group.files = files; - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); var manifest = GroupManifestValidator.validate(fields); PackDocument document = parent == null ? TestPacks.document(manifest) : TestPacks.document(manifest, parent.document().ownershipLedger(), TestPacks.CREATED.plusSeconds(version)); TestPacks.stageGeneration(storage, document); diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/InstalledPacksTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/InstalledPacksTest.java index a34ebf5d6..00a60154f 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/InstalledPacksTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/InstalledPacksTest.java @@ -84,7 +84,7 @@ private static GroupManifest installed(ClientStorage storage) throws Exception { PackDocument document = TestPacks.document(manifest); TestPacks.stageGeneration(storage, document); storage.writeActiveState(document); - new ClientSelectionStore(storage.selectionFile()).put(manifest.modpackId(), new SelectionIntent(Set.of("main"))); + new ClientSelectionStore(storage.selectionFile()).put(manifest.modpackId(), SelectionIntent.ofEnabled(Set.of("main"))); return manifest; } diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/ReconcileEditableStateTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/ReconcileEditableStateTest.java index a867046bb..511b8789e 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/ReconcileEditableStateTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/ReconcileEditableStateTest.java @@ -24,6 +24,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.storage.TestDataRoot; @@ -138,15 +139,14 @@ private static ModpackJsons.ModpackContentFields install(ClientStorage storage, fields.modpackId = PACK_ID; fields.modpackName = "Test"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; Map files = new LinkedHashMap<>(); files.put(EDITABLE_PATH, new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(packBytes.length), editable, HashUtils.sha1(packBytes), "0")); group.files = files; - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); PackDocument document = TestPacks.document(GroupManifestValidator.validate(fields)); TestPacks.stageGeneration(storage, document); - SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); new ClientSelectionStore(storage.selectionFile()).put(document.manifest().modpackId(), target.selection().intent()); storage.writeActiveState(document); return flatTarget(HashUtils.sha1(packBytes), editable); diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/RepairPinnedModsTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/RepairPinnedModsTest.java index 5941bf1e2..bfa8b0bfa 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/RepairPinnedModsTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/RepairPinnedModsTest.java @@ -28,6 +28,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.storage.TestDataRoot; @@ -54,7 +55,7 @@ void pinnedJarsSurviveRepairWhileUnpinnedStaleJarsAreArchived() throws Exception OwnershipLedger parent = TestPacks.document(manifest(earlier)).ownershipLedger(); PackDocument document = TestPacks.document(manifest(Map.of("config/kept.toml", kept)), parent, TestPacks.CREATED); TestPacks.stageGeneration(storage, document); - SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, new SelectionIntent(Set.of("main")), ClientPlatform.current()); + SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.current()); new ClientSelectionStore(storage.selectionFile()).put(document.manifest().modpackId(), target.selection().intent()); storage.writeActiveState(document); write(storage.activePath("config/kept.toml"), kept); @@ -96,12 +97,11 @@ private static GroupManifest manifest(Map contents) { fields.modpackId = "abc1234"; fields.modpackName = "Test"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; Map files = new LinkedHashMap<>(); contents.forEach((path, bytes) -> files.put(path, new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(bytes.length), false, HashUtils.sha1(bytes), "0"))); group.files = files; - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return GroupManifestValidator.validate(fields); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/ReviewSessionTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/ReviewSessionTest.java index cd09d85a5..c32d47d0f 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/ReviewSessionTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/ReviewSessionTest.java @@ -165,7 +165,7 @@ void firstInstallKeepExistingAndLaunchConsentSurviveReselectAndCancelRebuild() t harness.actions().setFirstInstallLocalModCleanup().accept(false); harness.actions().setLaunchWritesUnverified().accept(true); - harness.actions().reselectAndPreview().accept(new SelectionIntent(Set.of("main"))); + harness.actions().reselectAndPreview().accept(SelectionIntent.ofEnabled(Set.of("main"))); assertEquals(RecordingScreens.Kind.WELCOME, screens.last); assertTrue(screens.lastWelcome.keepExistingMods()); diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/StackedInGameActionsTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/StackedInGameActionsTest.java index 2ed2705fd..2982f24fb 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/StackedInGameActionsTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/StackedInGameActionsTest.java @@ -40,6 +40,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.storage.TestDataRoot; @@ -64,7 +65,7 @@ class StackedInGameActionsTest { private static final String ADDED = "config/added.toml"; private static final String FABRIC = "net.fabricmc.fabric-loader"; private static final String INSTALLED_LOADER = "0.16.0"; - private static final SelectionIntent MAIN = new SelectionIntent(Set.of("main")); + private static final SelectionIntent MAIN = SelectionIntent.ofEnabled(Set.of("main")); @TempDir Path temporaryDirectory; @@ -370,10 +371,9 @@ private static SelectedModpackTarget generation(ClientStorage storage, SelectedM fields.loaderVersion = parts[0]; fields.mcVersion = parts[1]; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; group.files = files; - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); GroupManifest manifest = GroupManifestValidator.validate(fields); PackDocument document = parent == null ? TestPacks.document(manifest) : TestPacks.document(manifest, parent.document().ownershipLedger(), TestPacks.CREATED.plusSeconds(version)); TestPacks.stageGeneration(storage, document); diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/SyncTransitionsTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/SyncTransitionsTest.java index 0940f7c38..b6de9e2a3 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/SyncTransitionsTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/SyncTransitionsTest.java @@ -31,6 +31,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.storage.TestDataRoot; @@ -49,7 +50,7 @@ * earlier pack left behind. */ class SyncTransitionsTest { - private static final SelectionIntent MAIN = new SelectionIntent(Set.of("main")); + private static final SelectionIntent MAIN = SelectionIntent.ofEnabled(Set.of("main")); private static final String F = "config/shared.toml"; private static final String E = "config/editable.toml"; private static final String G = "config/other.toml"; @@ -836,8 +837,7 @@ private static SelectedModpackTarget grouped(ClientStorage storage, String modpa files.put(entry.getKey(), new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(content.length), entry.getValue().editable(), HashUtils.sha1(content), "0")); } ModpackJsons.CompleteModpackContentFields.ModpackGroupFields fields = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - fields.required = groupEntry.getValue().required(); - fields.defaultSelected = groupEntry.getValue().required(); + fields.selection = groupEntry.getValue().required() ? GroupSelectionMode.REQUIRED : GroupSelectionMode.OPTIONAL; fields.compatiblePlatforms = groupEntry.getValue().platforms(); fields.files = files; groupFields.put(groupEntry.getKey(), fields); @@ -848,11 +848,11 @@ private static SelectedModpackTarget grouped(ClientStorage storage, String modpa fields.loader = ""; fields.loaderVersion = ""; fields.mcVersion = ""; - fields.categories = Map.of("General", groupFields); + fields.groups = groupFields; var manifest = GroupManifestValidator.validate(fields); PackDocument document = parent == null ? TestPacks.document(manifest) : TestPacks.document(manifest, parent.document().ownershipLedger(), TestPacks.CREATED.plusSeconds(version)); TestPacks.stageGeneration(storage, document); - SelectionIntent intent = new SelectionIntent(requested); + SelectionIntent intent = SelectionIntent.ofEnabled(requested); return SelectedModpackTarget.prepare(document, parent == null ? null : parent.selection().intent(), intent, ClientPlatform.current()); } @@ -947,18 +947,16 @@ private static SelectedModpackTarget generation(ClientStorage storage, String mo fields.loaderVersion = ""; fields.mcVersion = ""; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; group.files = files; if (linuxOnly) { ModpackJsons.CompleteModpackContentFields.ModpackGroupFields linux = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - linux.required = false; - linux.defaultSelected = true; + linux.selection = GroupSelectionMode.RECOMMENDED; linux.compatiblePlatforms = Set.of(ClientPlatform.LINUX.id()); linux.files = files; group.files = Map.of(); - fields.categories = Map.of("General", Map.of("main", group, "linux", linux)); - } else fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group, "linux", linux); + } else fields.groups = Map.of("main", group); var manifest = GroupManifestValidator.validate(fields); PackDocument document = parent == null ? TestPacks.document(manifest) : TestPacks.document(manifest, parent.document().ownershipLedger(), TestPacks.CREATED.plusSeconds(version)); TestPacks.stageGeneration(storage, document); @@ -967,7 +965,7 @@ private static SelectedModpackTarget generation(ClientStorage storage, String mo Journal journal = Journal.open(storage.historyJournalFile(modpackId)); journal.append(new JournalEntry(journal.head().seq() + 1, document.contentToken(), document.policySha1(), document.createdAt(), "", JournalEntry.NO_RESTORE, List.of())); } - SelectionIntent intent = linuxOnly ? new SelectionIntent(Set.of("main", "linux")) : MAIN; + SelectionIntent intent = linuxOnly ? SelectionIntent.ofEnabled(Set.of("main", "linux")) : MAIN; return SelectedModpackTarget.prepare(document, parent == null ? null : intent, intent, ClientPlatform.current()); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/client/UnownedLocalModsTest.java b/core/src/test/java/pl/skidam/automodpack_core/client/UnownedLocalModsTest.java index 4a8aaf70d..2e5e6a672 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/client/UnownedLocalModsTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/client/UnownedLocalModsTest.java @@ -48,7 +48,7 @@ void aPackChangeListsLocalJarsItWouldLeaveBesideTheNewPack() throws Exception { storeContent(storage, "installed"); TestPacks.stageGeneration(storage, installed); storage.writeActiveState(installed); - new ClientSelectionStore(storage.selectionFile()).put(installed.manifest().modpackId(), new SelectionIntent(Set.of("main"))); + new ClientSelectionStore(storage.selectionFile()).put(installed.manifest().modpackId(), SelectionIntent.ofEnabled(Set.of("main"))); GroupManifest replacementManifest = pack("def5678", "config/replacement.txt", "replacement"); PackDocument replacement = PackDocument.create(replacementManifest, TestPacks.policySha1(replacementManifest), TestPacks.CREATED, null); @@ -57,12 +57,12 @@ void aPackChangeListsLocalJarsItWouldLeaveBesideTheNewPack() throws Exception { ClientUpdatePlanBuilder builder = builder(storage); try (FileCache cache = FileCache.open(storage.fileCacheDirectory()); ModFileCache modCache = ModFileCache.open(storage.modCacheDirectory())) { - SelectedModpackTarget target = SelectedModpackTarget.prepare(replacement, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(replacement, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); ClientUpdatePlanBuilder.PreparedPlan switchPlan = builder.buildPlan(new ClientUpdatePlanBuilder.Input(target, null, new ClientConfigJsons.ClientConfigFieldsV3()), ClientProjectionView.observe(storage), cache, modCache); assertEquals(List.of("mods/local.jar"), List.copyOf(switchPlan.unownedLocalMods().keySet())); - SelectedModpackTarget samePack = SelectedModpackTarget.prepare(installed, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget samePack = SelectedModpackTarget.prepare(installed, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); ClientUpdatePlanBuilder.PreparedPlan updatePlan = builder.buildPlan(new ClientUpdatePlanBuilder.Input(samePack, null, new ClientConfigJsons.ClientConfigFieldsV3()), ClientProjectionView.observe(storage), cache, modCache); assertTrue(updatePlan.unownedLocalMods().isEmpty()); @@ -83,8 +83,8 @@ private static void storeContent(ClientStorage storage, String content) throws E private static GroupManifest pack(String modpackId, String path, String content) { byte[] bytes = content.getBytes(StandardCharsets.UTF_8); GroupManifest.GroupFile file = new GroupManifest.GroupFile(bytes.length, false, HashUtils.sha1(bytes), null); - GroupManifest.Group group = new GroupManifest.Group("", modpackId, "General", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Set.of(), Map.of(path, file)); - return new GroupManifest(modpackId, modpackId, "", "", "", "", Map.of("main", group)); + GroupManifest.Group group = new GroupManifest.Group("", modpackId, "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of(path, file)); + return new GroupManifest(modpackId, modpackId, "", "", "", "", Map.of(), Map.of("main", group)); } private static ClientUpdatePlanBuilder builder(ClientStorage storage) { diff --git a/core/src/test/java/pl/skidam/automodpack_core/config/ConfigToolsTest.java b/core/src/test/java/pl/skidam/automodpack_core/config/ConfigToolsTest.java index 1dcc27101..efb2e6c39 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/config/ConfigToolsTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/config/ConfigToolsTest.java @@ -157,7 +157,13 @@ void unknownTopLevelAndNestedKeysAreCollected() { { "syncedfile": "typo", "modpack": { - "General": { + "unknown-pack-opt": true, + "categories": { + "shaders": { + "bogus-cat": 1 + } + }, + "groups": { "main": {"syncedfile": "typo"}, "extra": {"displayName": "Extra", "bogus": true} } @@ -165,8 +171,8 @@ void unknownTopLevelAndNestedKeysAreCollected() { } """; - assertEquals(List.of("syncedfile", "modpack.General.main.syncedfile", "modpack.General.extra.displayName", "modpack.General.extra.bogus"), - ConfigTools.unknownKeys(json, ServerConfigJsons.ServerConfigFieldsV3.class)); + assertEquals(List.of("syncedfile", "modpack.unknown-pack-opt", "modpack.categories.shaders.bogus-cat", "modpack.groups.main.syncedfile", + "modpack.groups.extra.displayName", "modpack.groups.extra.bogus"), ConfigTools.unknownKeys(json, ServerConfigJsons.ServerConfigFieldsV3.class)); } @Test @@ -175,7 +181,7 @@ void repeatedUnknownKeyScansAgreeDespiteTheCachedFieldMaps() { { "syncedfile": "typo", "modpack": { - "General": { + "groups": { "main": {"syncedfile": "typo"}, "extra": {"displayName": "Extra", "bogus": true} } @@ -185,7 +191,7 @@ void repeatedUnknownKeyScansAgreeDespiteTheCachedFieldMaps() { List first = ConfigTools.unknownKeys(json, ServerConfigJsons.ServerConfigFieldsV3.class); List second = ConfigTools.unknownKeys(json, ServerConfigJsons.ServerConfigFieldsV3.class); - assertEquals(List.of("syncedfile", "modpack.General.main.syncedfile", "modpack.General.extra.displayName", "modpack.General.extra.bogus"), first); + assertEquals(List.of("syncedfile", "modpack.groups.main.syncedfile", "modpack.groups.extra.displayName", "modpack.groups.extra.bogus"), first); assertEquals(first, second); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/config/ConfigUtilsTest.java b/core/src/test/java/pl/skidam/automodpack_core/config/ConfigUtilsTest.java index 0f29a58a7..c6be4fda1 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/config/ConfigUtilsTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/config/ConfigUtilsTest.java @@ -17,7 +17,7 @@ void preservesPathRuleOrder() { ServerConfigJsons.GroupDeclaration group = new ServerConfigJsons.GroupDeclaration(); group.fromServer = new LinkedHashSet<>(List.of("third", "first", "second")); group.editable = new LinkedHashSet<>(List.of("third", "first", "second")); - config.modpack.categories = Map.of("General", new LinkedHashMap<>(Map.of("main", group))); + config.modpack.groups = new LinkedHashMap<>(Map.of("main", group)); ConfigUtils.normalizeServerConfig(config); @@ -28,14 +28,18 @@ void preservesPathRuleOrder() { @Test void normalizesRulePathsAndKeepsSetLocalNegations() { ServerConfigJsons.ServerConfigFieldsV3 config = new ServerConfigJsons.ServerConfigFieldsV3(); + config.modpack.exclude = new LinkedHashSet<>(List.of("/logs/*.log", "!/logs/keep.log")); + config.modpack.editable = new LinkedHashSet<>(List.of("//options.txt", "!/config/locked.json")); ServerConfigJsons.GroupDeclaration group = new ServerConfigJsons.GroupDeclaration(); group.fromServer = new LinkedHashSet<>(List.of("/mods/*.jar", "/automodpack/host-modpack/main/extra", "!kubejs/server_scripts/**", "!/kubejs/assets/**")); group.exclude = new LinkedHashSet<>(List.of("/automodpack/host-modpack/main/secret.bin", "!/automodpack/host-modpack/main/keep.bin")); group.editable = new LinkedHashSet<>(List.of("//config/**")); - config.modpack.categories = Map.of("General", new LinkedHashMap<>(Map.of("main", group))); + config.modpack.groups = new LinkedHashMap<>(Map.of("main", group)); ConfigUtils.normalizeServerConfig(config); + assertEquals(List.of("logs/*.log", "!logs/keep.log"), List.copyOf(config.modpack.exclude)); + assertEquals(List.of("options.txt", "!config/locked.json"), List.copyOf(config.modpack.editable)); assertEquals(List.of("mods/*.jar", "!kubejs/server_scripts/**", "!kubejs/assets/**"), List.copyOf(group.fromServer)); assertEquals(List.of("secret.bin", "!keep.bin"), List.copyOf(group.exclude)); assertEquals(List.of("config/**"), List.copyOf(group.editable)); @@ -48,7 +52,7 @@ void hostModpackRulesStripOnlyTheirOwnGroupPrefix() { group.fromServer = new LinkedHashSet<>(List.of("automodpack/host-modpack/main/extra", "!automodpack/host-modpack/main/skip/**")); group.exclude = new LinkedHashSet<>( List.of("automodpack/host-modpack/main/**", "automodpack/host-modpack/other/**", "/automodpack/host-modpack/main", "automodpack/host-modpack/main/**/**", "automodpack/host-modpack/main/**/*")); - config.modpack.categories = Map.of("General", new LinkedHashMap<>(Map.of("main", group))); + config.modpack.groups = new LinkedHashMap<>(Map.of("main", group)); ConfigUtils.normalizeServerConfig(config); @@ -62,14 +66,14 @@ void hostModpackRulesStripOnlyTheirOwnGroupPrefix() { @Test void nullGroupAndCategoryDeclarationsAreInvalid() { ServerConfigJsons.ServerConfigFieldsV3 nullCategory = new ServerConfigJsons.ServerConfigFieldsV3(); - nullCategory.modpack.categories = new LinkedHashMap<>(Map.of("General", new LinkedHashMap<>(Map.of("main", new ServerConfigJsons.GroupDeclaration())))); - nullCategory.modpack.categories.put("Broken", null); + nullCategory.modpack.categories = new LinkedHashMap<>(); + nullCategory.modpack.categories.put("broken", null); assertThrows(ConfigTools.ConfigParseException.class, () -> ConfigUtils.normalizeServerConfig(nullCategory)); ServerConfigJsons.ServerConfigFieldsV3 nullGroup = new ServerConfigJsons.ServerConfigFieldsV3(); Map groups = new LinkedHashMap<>(); groups.put("main", null); - nullGroup.modpack.categories = new LinkedHashMap<>(Map.of("General", groups)); + nullGroup.modpack.groups = groups; assertThrows(ConfigTools.ConfigParseException.class, () -> ConfigUtils.normalizeServerConfig(nullGroup)); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/config/HumanConfigMigrationTest.java b/core/src/test/java/pl/skidam/automodpack_core/config/HumanConfigMigrationTest.java index d8ec57c68..eb2ae7637 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/config/HumanConfigMigrationTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/config/HumanConfigMigrationTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -47,16 +48,18 @@ void migratesV4ServerJsonOnReadAndStopsUsingTheBackup() throws Exception { ServerConfigJsons.ServerConfigFieldsV3 config = TomlConfigs.read(toml, ServerConfigJsons.ServerConfigFieldsV3.class).orElseThrow(); assertEquals("My Pack", config.modpack.name); - assertEquals(Set.of("mods/*.jar", "kubejs/**", "!kubejs/server_scripts/**"), config.modpack.categories.get("General").get("main").fromServer); - assertTrue(config.modpack.categories.get("General").get("main").fromServer.contains("!kubejs/server_scripts/**")); - assertEquals(Set.of("options.txt", "config/**"), config.modpack.categories.get("General").get("main").editable); + assertEquals("", config.modpack.groups.get("main").name, "the migrated core group carries the same defaults as a fresh server.toml"); + assertEquals("", config.modpack.groups.get("main").description); + assertEquals(Set.of("mods/*.jar", "kubejs/**", "!kubejs/server_scripts/**"), config.modpack.groups.get("main").fromServer); + assertTrue(config.modpack.groups.get("main").fromServer.contains("!kubejs/server_scripts/**")); + assertEquals(Set.of("options.txt", "config/**"), config.modpack.editable); assertTrue(config.requireModpack); assertEquals("play.example.com", config.advertisedEndpointHost); assertEquals(ModpackConnectionMode.HOLEPUNCH, config.connectionMode); - assertTrue(config.modpack.categories.get("General").get("main").exclude.contains("**/.*")); - assertFalse(config.modpack.categories.get("General").get("main").exclude.contains("kubejs/server_scripts/**")); - assertEquals(GroupSelectionMode.REQUIRED, config.modpack.categories.get("General").get("main").selection, "the migrated core group must stay required"); - assertEquals(ServerSideModExclusion.METADATA, config.modpack.categories.get("General").get("main").autoExcludeServerSideMods); + assertTrue(config.modpack.exclude.contains("**/.*")); + assertFalse(config.modpack.exclude.contains("kubejs/server_scripts/**")); + assertEquals(GroupSelectionMode.REQUIRED, config.modpack.groups.get("main").selection, "the migrated core group must stay required"); + assertEquals(ServerSideModExclusion.METADATA, config.modpack.autoExcludeServerSideMods); assertTrue(Files.isRegularFile(toml)); assertTrue(Files.isRegularFile(dir.resolve("automodpack-server.json.backup"))); assertFalse(Files.exists(json)); @@ -107,11 +110,13 @@ void migratesV5RcServerConfToTomlAndBacksUpConf() throws Exception { assertEquals(ModpackConnectionMode.HTTP, config.connectionMode); assertFalse(config.validateSecrets); assertEquals(Set.of("fabric", "neoforge"), config.acceptedLoaders); - assertEquals(GroupSelectionMode.REQUIRED, config.modpack.categories.get("General").get("main").selection); - assertEquals(ServerSideModExclusion.DISABLED, config.modpack.categories.get("General").get("main").autoExcludeServerSideMods); - assertEquals(Set.of("mods/*.jar", "kubejs/**"), config.modpack.categories.get("General").get("main").fromServer); - assertEquals(GroupSelectionMode.RECOMMENDED, config.modpack.categories.get("General").get("extras").selection); - assertEquals(ServerSideModExclusion.PLATFORMS, config.modpack.categories.get("General").get("extras").autoExcludeServerSideMods); + assertEquals(GroupSelectionMode.REQUIRED, config.modpack.groups.get("main").selection); + assertNull(config.modpack.groups.get("main").autoExcludeServerSideMods); + assertEquals(ServerSideModExclusion.DISABLED, config.modpack.autoExcludeServerSideMods); + assertEquals(Set.of("mods/*.jar", "kubejs/**"), config.modpack.groups.get("main").fromServer); + assertEquals(GroupSelectionMode.RECOMMENDED, config.modpack.groups.get("extras").selection); + assertEquals(ServerSideModExclusion.PLATFORMS, config.modpack.groups.get("extras").autoExcludeServerSideMods); + assertTrue(config.modpack.categories.isEmpty(), "lone legacy General category flattens into top-level groups"); assertTrue(Files.isRegularFile(toml)); assertTrue(Files.isRegularFile(dir.resolve("server.conf.backup"))); assertFalse(Files.exists(conf)); @@ -121,8 +126,77 @@ void migratesV5RcServerConfToTomlAndBacksUpConf() throws Exception { assertEquals("RC Pack", reread.modpack.name); assertEquals(25570, reread.bindPort); assertEquals(ModpackConnectionMode.HTTP, reread.connectionMode); - assertEquals(ServerSideModExclusion.DISABLED, reread.modpack.categories.get("General").get("main").autoExcludeServerSideMods); - assertEquals(ServerSideModExclusion.PLATFORMS, reread.modpack.categories.get("General").get("extras").autoExcludeServerSideMods); + assertEquals(ServerSideModExclusion.DISABLED, reread.modpack.autoExcludeServerSideMods); + assertEquals(ServerSideModExclusion.PLATFORMS, reread.modpack.groups.get("extras").autoExcludeServerSideMods); + } + + @Test + void legacyCustomCategorySlugifiesOrFlattensAllRequiredCategories() { + ServerConfigJsons.ServerConfigFieldsV3 migrated = HumanConfigMigration.mapServer(JsonParser.parseString(""" + { + "modpack": { + "Core Mods": { + "main": { "selection": "REQUIRED" } + }, + "Visual Extras!": { + "shaders": { "selection": "OPTIONAL", "breaks-with": ["old"] } + } + } + } + """).getAsJsonObject()); + assertEquals("", migrated.modpack.groups.get("main").category, "all-REQUIRED legacy category flattens to uncategorized"); + assertFalse(migrated.modpack.categories.containsKey("core-mods")); + assertEquals("visual-extras", migrated.modpack.groups.get("shaders").category); + assertEquals("Visual Extras!", migrated.modpack.categories.get("visual-extras").name); + assertEquals(Set.of("old"), migrated.modpack.groups.get("shaders").conflicts, "legacy breaks-with survives as group conflicts"); + } + + @Test + void migratesV5Rc7CategoriesAndConflictsIntoTheToml() throws Exception { + Path toml = dir.resolve("server.toml"); + Path conf = dir.resolve("server.conf"); + Files.writeString(conf, """ + # v5-rc.7 server config + modpack { + name: "RC7 Pack" + "Core Mods" { + main { + required: true + default-selected: true + from-server: [mods/*.jar] + } + } + "Visuals" { + shaders { + required: false + default-selected: true + breaks-with: [vanilla-shaders] + from-server: [shaderpacks/**] + } + vanilla-shaders { + required: false + default-selected: false + } + } + } + """, StandardCharsets.UTF_8); + + ServerConfigJsons.ServerConfigFieldsV3 config = TomlConfigs.read(toml, ServerConfigJsons.ServerConfigFieldsV3.class).orElseThrow(); + assertEquals("RC7 Pack", config.modpack.name); + assertEquals(GroupSelectionMode.REQUIRED, config.modpack.groups.get("main").selection); + assertEquals("", config.modpack.groups.get("main").category, "the all-REQUIRED Core Mods category flattens"); + assertEquals(GroupSelectionMode.RECOMMENDED, config.modpack.groups.get("shaders").selection); + assertEquals("visuals", config.modpack.groups.get("shaders").category); + assertEquals(Set.of("vanilla-shaders"), config.modpack.groups.get("shaders").conflicts); + assertEquals(GroupSelectionMode.OPTIONAL, config.modpack.groups.get("vanilla-shaders").selection); + assertTrue(config.modpack.categories.containsKey("visuals")); + assertTrue(Files.isRegularFile(dir.resolve("server.conf.backup"))); + assertFalse(Files.exists(conf)); + + ServerConfigJsons.ServerConfigFieldsV3 reread = TomlConfigs.read(toml, ServerConfigJsons.ServerConfigFieldsV3.class).orElseThrow(); + assertEquals(Set.of("vanilla-shaders"), reread.modpack.groups.get("shaders").conflicts); + assertEquals("visuals", reread.modpack.groups.get("shaders").category); + assertTrue(Files.readString(toml, StandardCharsets.UTF_8).contains("conflicts = "), "the generated toml must carry the migrated conflicts"); } @Test @@ -196,7 +270,6 @@ void v4ClientJsonCopiesSettingsAndDoesNotInventAFollowId() throws Exception { void legacyGroupBooleansMapOntoTheSelectionEnum() { assertEquals(GroupSelectionMode.REQUIRED, selectionOf(mappedGroup("\"required\": true, \"default-selected\": true")), "(true, true) is the required core group"); assertEquals(GroupSelectionMode.REQUIRED, selectionOf(mappedGroup("\"required\": true, \"default-selected\": false")), "the one pair with no mode of its own collapses to required"); - assertTrue(GroupSelectionMode.collapsed(true, false)); assertEquals(GroupSelectionMode.REQUIRED, selectionOf(mappedGroup("\"required\": true")), "required alone still wins over a missing flag"); assertEquals(GroupSelectionMode.RECOMMENDED, selectionOf(mappedGroup("\"defaultSelected\": true"))); assertEquals(GroupSelectionMode.OPTIONAL, selectionOf(mappedGroup("\"required\": false, \"default-selected\": false"))); @@ -222,19 +295,21 @@ void nonStringSelectionAndNonBooleanLegacyFlagsFailLoudly() { } @Test - void packLevelServerSideExclusionFalseDisablesGroupsThatOmitTheKey() { + void packLevelServerSideExclusionFalseSetsPackDefaultAndPreservesGroupOverride() { ServerConfigJsons.ServerConfigFieldsV3 config = HumanConfigMigration.mapServer(JsonParser.parseString(""" {"autoExcludeServerSideMods": false, "modpack": {"General": {"main": {}, "kept": {"auto-exclude-server-side-mods": "PLATFORMS"}}}} """).getAsJsonObject()); - assertEquals(ServerSideModExclusion.DISABLED, config.modpack.categories.get("General").get("main").autoExcludeServerSideMods); - assertEquals(ServerSideModExclusion.PLATFORMS, config.modpack.categories.get("General").get("kept").autoExcludeServerSideMods); + assertEquals(ServerSideModExclusion.DISABLED, config.modpack.autoExcludeServerSideMods); + assertNull(config.modpack.groups.get("main").autoExcludeServerSideMods); + assertEquals(ServerSideModExclusion.PLATFORMS, config.modpack.groups.get("kept").autoExcludeServerSideMods); } @Test - void packLevelServerSideExclusionTrueLeavesGroupsAtMetadata() { - assertEquals(ServerSideModExclusion.METADATA, - HumanConfigMigration.mapServer(JsonParser.parseString("{\"auto-exclude-server-side-mods\": true, \"modpack\": {\"General\": {\"main\": {}}}}").getAsJsonObject()).modpack.categories.get("General") - .get("main").autoExcludeServerSideMods); + void packLevelServerSideExclusionTrueLeavesPackAtMetadata() { + ServerConfigJsons.ServerConfigFieldsV3 config = HumanConfigMigration + .mapServer(JsonParser.parseString("{\"auto-exclude-server-side-mods\": true, \"modpack\": {\"General\": {\"main\": {}}}}").getAsJsonObject()); + assertEquals(ServerSideModExclusion.METADATA, config.modpack.autoExcludeServerSideMods); + assertNull(config.modpack.groups.get("main").autoExcludeServerSideMods); } private static ServerConfigJsons.ServerConfigFieldsV3 mappedGroup(String members) { @@ -242,6 +317,6 @@ private static ServerConfigJsons.ServerConfigFieldsV3 mappedGroup(String members } private static GroupSelectionMode selectionOf(ServerConfigJsons.ServerConfigFieldsV3 config) { - return config.modpack.categories.get("General").get("main").selection; + return config.modpack.groups.get("main").selection; } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/config/Rc7MigrationTest.java b/core/src/test/java/pl/skidam/automodpack_core/config/Rc7MigrationTest.java new file mode 100644 index 000000000..6cdb1cdd7 --- /dev/null +++ b/core/src/test/java/pl/skidam/automodpack_core/config/Rc7MigrationTest.java @@ -0,0 +1,265 @@ +package pl.skidam.automodpack_core.config; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import pl.skidam.automodpack_core.modpack.group.GroupManifest; +import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; + +class Rc7MigrationTest { + @Test + void migratesThePolicyOfALegacyHeadDocument() { + GenerationJsons.HeadDocumentFields head = ConfigTools.parse(RC7_HEAD_DOCUMENT, GenerationJsons.HeadDocumentFields.class, Rc7PolicyMigration::headDocument); + + GroupManifest policy = GroupManifestValidator.validate(head.policy); + + assertEquals("7fb5edcecc0e281ea399d9e17fa6e8078af05e57", head.contentToken); + assertEquals(GroupSelectionMode.REQUIRED, policy.groups().get("main").selection()); + assertEquals("Core", policy.categories().get("core").name()); + } + + @Test + void aCurrentHeadDocumentPassesThroughUnchanged() { + GenerationJsons.HeadDocumentFields head = ConfigTools.parse(CURRENT_HEAD_DOCUMENT, GenerationJsons.HeadDocumentFields.class, Rc7PolicyMigration::headDocument); + + assertEquals("core", head.policy.groups.get("main").category); + assertEquals(GroupSelectionMode.REQUIRED, head.policy.groups.get("main").selection); + } + + @Test + void migratesALegacyPolicyDocument() { + ModpackJsons.CompleteModpackContentFields policy = ConfigTools.parse(RC7_POLICY_DOCUMENT, ModpackJsons.CompleteModpackContentFields.class, Rc7PolicyMigration::policyDocument); + + GroupManifest manifest = GroupManifestValidator.validate(policy); + + assertEquals(GroupSelectionMode.OPTIONAL, manifest.groups().get("extras").selection()); + assertEquals("Visuals", manifest.categories().get("visuals").name()); + } + + @Test + void convergesTheProjectionInPlace(@TempDir Path temporaryDirectory) throws Exception { + Path projection = temporaryDirectory.resolve("generation-projection.json"); + Files.writeString(projection, RC7_HEAD_DOCUMENT, StandardCharsets.UTF_8); + + Rc7PolicyMigration.migrateProjection(projection); + + GenerationJsons.HeadDocumentFields head = ConfigTools.read(projection, GenerationJsons.HeadDocumentFields.class).orElseThrow(); + assertEquals("core", head.policy.groups.get("main").category); + assertFalse(Files.readString(projection, StandardCharsets.UTF_8).contains("displayName"), Files.readString(projection, StandardCharsets.UTF_8)); + } + + @Test + void leavesACurrentProjectionUnchanged(@TempDir Path temporaryDirectory) throws Exception { + Path projection = temporaryDirectory.resolve("generation-projection.json"); + Files.writeString(projection, CURRENT_HEAD_DOCUMENT, StandardCharsets.UTF_8); + + Rc7PolicyMigration.migrateProjection(projection); + + assertEquals(CURRENT_HEAD_DOCUMENT.strip(), Files.readString(projection, StandardCharsets.UTF_8).strip()); + } + + @Test + void expandsCategorySubscriptionsIntoTheGroupPicksTheyStoodFor(@TempDir Path temporaryDirectory) throws Exception { + Path state = temporaryDirectory.resolve("active-state.json"); + Files.writeString(state, RC7_ACTIVE_STATE_WITH_CATEGORY, StandardCharsets.UTF_8); + + Rc7ClientSelectionMigration.migrateActiveState(state, lookup(null)); + + ClientStorageJsons.ClientGenerationStateFields migrated = ConfigTools.read(state, ClientStorageJsons.ClientGenerationStateFields.class).orElseThrow(); + assertEquals(List.of("optional", "picked"), migrated.selection.enabled); + assertEquals(List.of(), migrated.selection.disabled); + assertEquals("linux", migrated.selection.platform); + assertFalse(Files.readString(state, StandardCharsets.UTF_8).contains("selectedCategories")); + } + + @Test + void resolvesAnOldPointerWithoutAnEmbeddedManifestFromItsGeneration(@TempDir Path temporaryDirectory) throws Exception { + Path state = temporaryDirectory.resolve("active-state.json"); + String oldState = """ + { + "modpackId": "abc1234", + "contentToken": "b2f90cbc7787346c7ab724cc916237c306bf5cb5", + "status": "ACTIVE", + "ownershipLedger": {"modpackId": "abc1234", "entries": [], "digest": "fda88dc787178ee1fa60f880e82e0cf65faeaf24"}, + "selectedCategories": ["Visuals"], + "selectedPlatform": "linux" + } + """; + Files.writeString(state, oldState, StandardCharsets.UTF_8); + + Rc7ClientSelectionMigration.migrateActiveState(state, lookup(policyManifest())); + + ClientStorageJsons.ClientGenerationStateFields migrated = ConfigTools.read(state, ClientStorageJsons.ClientGenerationStateFields.class).orElseThrow(); + assertEquals(List.of("extras"), migrated.selection.enabled); + assertEquals("linux", migrated.selection.platform); + } + + @Test + void keepsAnUnmappableCategorySelectionUntouched(@TempDir Path temporaryDirectory) throws Exception { + Path state = temporaryDirectory.resolve("active-state.json"); + String oldState = """ + {"modpackId":"abc1234","contentToken":"b2f90cbc7787346c7ab724cc916237c306bf5cb5","selectedCategories":["Visuals"]} + """; + Files.writeString(state, oldState, StandardCharsets.UTF_8); + + assertThrows(IOException.class, () -> Rc7ClientSelectionMigration.migrateActiveState(state, new Rc7ClientSelectionMigration.PolicyLookup() { + @Override + public GroupManifest generation(String modpackId, String contentToken) throws IOException { + throw new IOException("No generation catalogue is available"); + } + + @Override + public GroupManifest latest(String modpackId) { + throw new AssertionError(); + } + })); + + assertEquals(oldState, Files.readString(state, StandardCharsets.UTF_8)); + } + + @Test + void expandsTheCategoryPickOfALegacyTreeAndKeepsItsGroupPicks() { + JsonObject document = JsonParser.parseString("{\"activeModpackId\":\"abc1234\",\"contentToken\":\"b2f90cbc7787346c7ab724cc916237c306bf5cb5\",\"detached\":false," + + "\"requestedGroups\":[\"picked\"],\"requestedCategories\":[\"Visuals\"],\"excludedGroups\":[\"off\"],\"tombstones\":[],\"files\":[]}").getAsJsonObject(); + + Rc7ClientSelectionMigration.instanceTree(document, lookup(policyManifest())); + + SelectionJsons.SelectionFields selection = ConfigTools.parse(document, ClientStorageJsons.InstanceTreeFields.class).selection; + assertEquals(List.of("extras", "picked"), selection.enabled); + assertEquals(List.of("off"), selection.disabled); + assertFalse(document.has("requestedCategories"), document.toString()); + } + + @Test + void aLegacyTreeWithoutAPackRecordsNoSelectionAtAll() { + JsonObject document = JsonParser.parseString("{\"activeModpackId\":\"\",\"contentToken\":\"\",\"detached\":false,\"requestedGroups\":[],\"requestedCategories\":[]," + + "\"excludedGroups\":[],\"tombstones\":[],\"files\":[]}").getAsJsonObject(); + + Rc7ClientSelectionMigration.instanceTree(document, lookup(null)); + + assertNull(ConfigTools.parse(document, ClientStorageJsons.InstanceTreeFields.class).selection); + assertFalse(document.has("requestedGroups"), document.toString()); + } + + private static Rc7ClientSelectionMigration.PolicyLookup lookup(GroupManifest manifest) { + return new Rc7ClientSelectionMigration.PolicyLookup() { + @Override + public GroupManifest generation(String modpackId, String contentToken) { + return manifest; + } + + @Override + public GroupManifest latest(String modpackId) { + return manifest; + } + }; + } + + private static GroupManifest policyManifest() { + return GroupManifestValidator.validate(ConfigTools.parse(RC7_POLICY_DOCUMENT, ModpackJsons.CompleteModpackContentFields.class, Rc7PolicyMigration::policyDocument)); + } + + /** The same policy in both shapes; the group carries no files, so both name the same (empty) content token. */ + private static final String RC7_HEAD_DOCUMENT = """ + { + "contentToken": "7fb5edcecc0e281ea399d9e17fa6e8078af05e57", + "policySha1": "8f2a4c0d1e6b3a5c7d9e0f1a2b3c4d5e6f7a8b9c", + "createdAt": "2026-01-02T03:04:05Z", + "journalHead": 7, + "ownershipLedger": {"modpackId": "abc1234", "entries": [], "digest": "fda88dc787178ee1fa60f880e82e0cf65faeaf24"}, + "policy": { + "modpackId": "abc1234", + "modpackName": "Test Pack", + "automodpackVersion": "5.0.0-rc.7", + "loader": "fabric", + "loaderVersion": "0.16.9", + "mcVersion": "1.21.1", + "categories": { + "Core": { + "main": {"displayName": "Core", "description": "", "required": true, "defaultSelected": true, "breaksWith": [], "requires": [], "compatiblePlatforms": [], "files": {}} + } + } + } + } + """; + + private static final String CURRENT_HEAD_DOCUMENT = """ + { + "contentToken": "7fb5edcecc0e281ea399d9e17fa6e8078af05e57", + "policySha1": "8f2a4c0d1e6b3a5c7d9e0f1a2b3c4d5e6f7a8b9c", + "createdAt": "2026-01-02T03:04:05Z", + "journalHead": 7, + "ownershipLedger": {"modpackId": "abc1234", "entries": [], "digest": "fda88dc787178ee1fa60f880e82e0cf65faeaf24"}, + "policy": { + "modpackId": "abc1234", + "modpackName": "Test Pack", + "automodpackVersion": "5.0.0-rc.7", + "loader": "fabric", + "loaderVersion": "0.16.9", + "mcVersion": "1.21.1", + "categories": {"core": {"name": "Core", "description": "", "pick": "ANY"}}, + "groups": {"main": {"name": "Core", "description": "", "category": "core", "selection": "REQUIRED", "requires": [], "conflicts": [], "compatiblePlatforms": [], "files": {}}} + } + } + """; + + private static final String RC7_POLICY_DOCUMENT = """ + { + "modpackId": "abc1234", + "modpackName": "Test Pack", + "automodpackVersion": "5.0.0-rc.7", + "loader": "fabric", + "loaderVersion": "0.16.9", + "mcVersion": "1.21.1", + "categories": { + "Visuals": { + "extras": {"displayName": "Extras", "description": "", "required": false, "defaultSelected": false, "breaksWith": [], "requires": [], "compatiblePlatforms": [], "files": {}} + } + } + } + """; + + /** One rc.7 active state whose only record of a category-wide pick is {@code selectedCategories}. */ + private static final String RC7_ACTIVE_STATE_WITH_CATEGORY = """ + { + "modpackId": "abc1234", + "contentToken": "b2f90cbc7787346c7ab724cc916237c306bf5cb5", + "status": "ACTIVE", + "manifest": { + "modpackId": "abc1234", + "modpackName": "Test Pack", + "automodpackVersion": "5.0.0-rc.7", + "loader": "fabric", + "loaderVersion": "0.16.9", + "mcVersion": "1.21.1", + "categories": { + "Visuals": { + "core": {"required": true, "defaultSelected": true, "breaksWith": [], "requires": [], "compatiblePlatforms": [], "files": {}}, + "optional": {"required": false, "defaultSelected": false, "breaksWith": [], "requires": [], "compatiblePlatforms": [], "files": {}}, + "win_only": {"required": false, "defaultSelected": false, "breaksWith": [], "requires": [], "compatiblePlatforms": ["windows"], "files": {}} + } + } + }, + "selectedGroups": ["picked"], + "selectedCategories": ["Visuals"], + "excludedGroups": [], + "selectedPlatform": "linux", + "detached": false + } + """; +} diff --git a/core/src/test/java/pl/skidam/automodpack_core/config/TomlConfigsTest.java b/core/src/test/java/pl/skidam/automodpack_core/config/TomlConfigsTest.java index 46381b53f..8fad9dfd1 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/config/TomlConfigsTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/config/TomlConfigsTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -9,12 +10,15 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import pl.skidam.automodpack_core.config.ServerConfigJsons.ServerConfigFieldsV3; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.ServerSideModExclusion; import pl.skidam.automodpack_core.protocol.ModpackConnectionMode; @@ -39,17 +43,22 @@ void freshGenerationIsCanonicalTomlWithTablesCommentsAndLiteralGlobs() throws IO assertTrue(text.contains("[nag]"), text); assertTrue(text.contains("[export-http]"), text); assertTrue(text.contains("[modpack]"), text); - assertTrue(text.contains("[modpack.groups.General.main]"), text); + assertTrue(text.contains("[groups.main]"), text); + assertFalse(text.contains("[groups]\n"), "the section comment must not force an empty header:\n" + text); + assertTrue(text.contains("# Each group maps 1:1 to host-modpack//. selection: REQUIRED, RECOMMENDED, OPTIONAL, AUTOMATIC.\n[groups.main]"), text); + assertFalse(text.contains("[modpack.groups"), text); + assertFalse(text.contains("[categories"), text); assertTrue(text.contains("from-server = [\"mods/*.jar\", \"kubejs/**\", \"emotes/*\"]"), text); - assertTrue(text.contains("# extra paths from the server root"), text); - assertTrue(text.contains("name = \"\""), text); - assertTrue(text.contains("# REQUIRED is always installed. RECOMMENDED is pre-selected, players can opt out. OPTIONAL starts unchecked."), text); + assertFalse(text.contains("name = \"Core\""), "the main group must not ship a name the admin never wrote:\n" + text); assertTrue(text.contains("selection = \"REQUIRED\""), text); + assertTrue(text.indexOf("[modpack]") < text.indexOf("[groups.main]") && text.indexOf("[groups.main]") < text.indexOf("[network]"), + "sections must run [modpack], [groups.*], then [network]:\n" + text); assertTrue(text.contains("auto-exclude-server-side-mods = \"METADATA\""), text); - assertTrue(text.contains("Use exclude for anything else."), text); assertFalse(text.contains("default-selected"), text); assertEquals("", config.modpack.name); - assertEquals(ServerSideModExclusion.METADATA, config.modpack.categories.get("General").get("main").autoExcludeServerSideMods); + assertEquals("", config.modpack.groups.get("main").name); + assertEquals(ServerSideModExclusion.METADATA, config.modpack.autoExcludeServerSideMods); + assertNull(config.modpack.groups.get("main").autoExcludeServerSideMods); } @Test @@ -96,9 +105,9 @@ void saveDoesNotRestoreDeletedCommentsOnExistingMembers() throws IOException { String text = Files.readString(serverConfig(), StandardCharsets.UTF_8); String withoutComments = text .replaceAll("(?m)^[ \\t]*# require a login-issued download secret\\R", "") - .replaceAll("(?m)^[ \\t]*# extra paths from the server root\\R", ""); + .replaceAll("(?m)^[ \\t]*# host-modpack// is included in full.*\\R", ""); assertFalse(withoutComments.contains("require a login-issued download secret")); - assertFalse(withoutComments.contains("extra paths from the server root")); + assertFalse(withoutComments.contains("host-modpack// is included in full")); Files.writeString(serverConfig(), withoutComments, StandardCharsets.UTF_8); ServerConfigFieldsV3 config = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); @@ -106,11 +115,35 @@ void saveDoesNotRestoreDeletedCommentsOnExistingMembers() throws IOException { String after = Files.readString(serverConfig(), StandardCharsets.UTF_8); assertFalse(after.contains("require a login-issued download secret"), after); - assertFalse(after.contains("extra paths from the server root"), after); + assertFalse(after.contains("host-modpack// is included in full"), after); assertTrue(after.contains("validate = true"), after); assertTrue(after.contains("from-server ="), after); } + @Test + void modpackWithoutGroupsDeclaresNoGroupsInsteadOfInventingMain() throws IOException { + Files.writeString(serverConfig(), "[modpack]\nname = \"x\"\n", StandardCharsets.UTF_8); + ServerConfigFieldsV3 config = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); + + assertEquals("x", config.modpack.name); + assertTrue(config.modpack.groups.isEmpty(), "the document is authoritative: no [groups] means no groups"); + assertEquals(Set.copyOf(ServerConfigJsons.FACTORY_EXCLUDE), Set.copyOf(config.modpack.exclude), "an omitted exclude keeps its documented default"); + assertEquals(Set.copyOf(ServerConfigJsons.FACTORY_EDITABLE), Set.copyOf(config.modpack.editable)); + + TomlConfigs.save(serverConfig(), config, ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); + assertFalse(Files.readString(serverConfig(), StandardCharsets.UTF_8).contains("[groups.main]"), "a save must not add a group nobody declared"); + } + + @Test + void creatingAConfigIsTheOnlyPathThatDeclaresMainAndSavingKeepsIt() throws IOException { + ServerConfigFieldsV3 config = TomlConfigs.readOrCreate(serverConfig(), ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); + assertEquals(Set.of("main"), config.modpack.groups.keySet()); + assertTrue(Files.readString(serverConfig(), StandardCharsets.UTF_8).contains("[groups.main]")); + + TomlConfigs.save(serverConfig(), config, ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); + assertEquals(Set.of("main"), TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow().modpack.groups.keySet()); + } + @Test void saveIsIdempotent() throws IOException { ServerConfigFieldsV3 config = TomlConfigs.readOrCreate(serverConfig(), ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); @@ -146,18 +179,18 @@ void unknownKeysWarnButSurviveSaves() throws IOException { @Test void saveRemovesArrayElementsTheModelDropped() throws IOException { String userFile = """ - [modpack.groups.General.main] + [groups.main] from-server = ['mods/*.jar', 'kubejs/**'] """; Files.writeString(serverConfig(), userFile, StandardCharsets.UTF_8); ServerConfigFieldsV3 config = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); - config.modpack.categories.get("General").get("main").fromServer = Set.of("mods/*.jar"); + config.modpack.groups.get("main").fromServer = Set.of("mods/*.jar"); TomlConfigs.save(serverConfig(), config, ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); String text = Files.readString(serverConfig(), StandardCharsets.UTF_8); assertTrue(text.contains("mods/*.jar"), "kept rule lost:\n" + text); - assertFalse(text.contains("kubejs"), "removed rule resurrected:\n" + text); + assertFalse(text.contains("kubejs/**"), "removed rule resurrected:\n" + text); assertEquals(Set.of("mods/*.jar"), - TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow().modpack.categories.get("General").get("main").fromServer); + TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow().modpack.groups.get("main").fromServer); } @Test @@ -166,25 +199,38 @@ void humanEnumsForgiveCaseAndSaveCanonically() throws IOException { [network] connection-mode = "holepunch" - [modpack.groups.General.main] + [modpack] + auto-exclude-server-side-mods = "platforms" + + [categories.shaders] + pick = "at_most_one" + + [groups.main] + category = "shaders" selection = "recommended" auto-exclude-server-side-mods = "metadata" """; Files.writeString(serverConfig(), mixed, StandardCharsets.UTF_8); ServerConfigFieldsV3 config = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); assertEquals(ModpackConnectionMode.HOLEPUNCH, config.connectionMode); - assertEquals(GroupSelectionMode.RECOMMENDED, config.modpack.categories.get("General").get("main").selection); - assertEquals(ServerSideModExclusion.METADATA, config.modpack.categories.get("General").get("main").autoExcludeServerSideMods); + assertEquals(ServerSideModExclusion.PLATFORMS, config.modpack.autoExcludeServerSideMods); + assertEquals(CategoryPickMode.AT_MOST_ONE, config.modpack.categories.get("shaders").pick); + assertEquals(GroupSelectionMode.RECOMMENDED, config.modpack.groups.get("main").selection); + assertEquals(ServerSideModExclusion.METADATA, config.modpack.groups.get("main").autoExcludeServerSideMods); assertEquals(mixed, Files.readString(serverConfig(), StandardCharsets.UTF_8)); TomlConfigs.save(serverConfig(), config, ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); String text = Files.readString(serverConfig(), StandardCharsets.UTF_8); assertTrue(text.contains("connection-mode = \"HOLEPUNCH\""), text); + assertTrue(text.contains("pick = \"AT_MOST_ONE\""), text); assertTrue(text.contains("selection = \"RECOMMENDED\""), text); + assertTrue(text.contains("auto-exclude-server-side-mods = \"PLATFORMS\""), text); assertTrue(text.contains("auto-exclude-server-side-mods = \"METADATA\""), text); - assertFalse(text.contains("connection-mode = \"holepunch\""), text); - assertFalse(text.contains("selection = \"recommended\""), text); - assertFalse(text.contains("auto-exclude-server-side-mods = \"metadata\""), text); + assertFalse(text.contains("\"holepunch\""), text); + assertFalse(text.contains("\"at_most_one\""), text); + assertFalse(text.contains("\"recommended\""), text); + assertFalse(text.contains("\"platforms\""), text); + assertFalse(text.contains("\"metadata\""), text); } @Test @@ -195,17 +241,114 @@ void unknownHumanEnumFailsLoudly() throws IOException { } @Test - void categoryNamedNameDoesNotCollideWithModpackName() throws IOException { - String src = """ - [modpack] - name = "My Pack" + void categoryAndGroupTablesRoundTripSparselyWithoutBloatingOptionalKeys() throws IOException { + ServerConfigFieldsV3 config = new ServerConfigFieldsV3(); + ServerConfigJsons.CategoryDeclaration shaders = new ServerConfigJsons.CategoryDeclaration(); + shaders.name = "Shaders"; + shaders.pick = CategoryPickMode.AT_MOST_ONE; + config.modpack.categories.put("shaders", shaders); + ServerConfigJsons.GroupDeclaration bsl = new ServerConfigJsons.GroupDeclaration(); + bsl.name = "BSL Shaders"; + bsl.category = "shaders"; + bsl.selection = GroupSelectionMode.RECOMMENDED; + config.modpack.groups.put("bsl", bsl); + + TomlConfigs.save(serverConfig(), config, ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); + String text = Files.readString(serverConfig(), StandardCharsets.UTF_8); + assertTrue(text.contains("[categories.shaders]"), text); + assertTrue(text.contains("[groups.bsl]"), text); + assertFalse(text.contains("[groups.bsl]\nname = \"BSL Shaders\"\ndescription"), "blank description should stay omitted sparsely:\n" + text); + ServerConfigFieldsV3 reread = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); + assertEquals("Shaders", reread.modpack.categories.get("shaders").name); + assertEquals(CategoryPickMode.AT_MOST_ONE, reread.modpack.categories.get("shaders").pick); + assertEquals(GroupSelectionMode.RECOMMENDED, reread.modpack.groups.get("bsl").selection); + assertNull(reread.modpack.groups.get("bsl").autoExcludeServerSideMods); + } - [modpack.groups.name.main] - selection = "REQUIRED" + @Test + void groupConflictsRoundTripAndStayOmittedWhenEmpty() throws IOException { + ServerConfigFieldsV3 config = new ServerConfigFieldsV3(); + ServerConfigJsons.GroupDeclaration audio = new ServerConfigJsons.GroupDeclaration(); + audio.selection = GroupSelectionMode.OPTIONAL; + audio.conflicts = Set.of("zoom"); + config.modpack.groups.put("audio", audio); + + TomlConfigs.save(serverConfig(), config, ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); + String text = Files.readString(serverConfig(), StandardCharsets.UTF_8); + assertTrue(text.contains("conflicts = [\"zoom\"]"), text); + assertFalse(text.contains("[groups.main]\nselection = \"REQUIRED\"\nconflicts"), "an empty conflict list must stay omitted:\n" + text); + ServerConfigFieldsV3 reread = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); + assertEquals(Set.of("zoom"), reread.modpack.groups.get("audio").conflicts); + assertTrue(reread.modpack.groups.get("main").conflicts.isEmpty()); + } + + @Test + void insertImportedGroupsAppendsNewGroupsLosslesslyWithoutTouchingExistingTables() throws IOException { + String existing = "# header comment\r\nmodpack-host = true\r\n\r\n[groups.main]\r\nselection = \"REQUIRED\" # keep inline\r\n"; + Files.writeString(serverConfig(), existing, StandardCharsets.UTF_8); + Map imported = new LinkedHashMap<>(); + ServerConfigJsons.GroupDeclaration extras = new ServerConfigJsons.GroupDeclaration(); + extras.selection = GroupSelectionMode.OPTIONAL; + imported.put("extras", extras); + imported.put("main", new ServerConfigJsons.GroupDeclaration()); + + TomlConfigs.insertImportedGroups(serverConfig(), imported); + String after = Files.readString(serverConfig(), StandardCharsets.UTF_8); + assertTrue(after.contains("# header comment\r\n"), after); + assertTrue(after.contains("selection = \"REQUIRED\" # keep inline"), after); + assertTrue(after.contains("[groups.extras]"), after); + ServerConfigFieldsV3 reread = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); + assertEquals(GroupSelectionMode.REQUIRED, reread.modpack.groups.get("main").selection, "existing main must not be overwritten"); + assertEquals(GroupSelectionMode.OPTIONAL, reread.modpack.groups.get("extras").selection); + } + + @Test + void saveSynchronizesAddedUpdatedAndRemovedCategoriesAndGroupsWhileKeepingComments() throws IOException { + String initial = """ + # keep banner + modpack-host = true + + [categories.shaders] + name = "Shaders" # keep category note + pick = "AT_MOST_ONE" + + [categories.obsolete] + name = "Obsolete" + + [groups.main] + selection = "REQUIRED" # keep group note + + [groups.legacy] + selection = "OPTIONAL" """; - Files.writeString(serverConfig(), src, StandardCharsets.UTF_8); + Files.writeString(serverConfig(), initial, StandardCharsets.UTF_8); ServerConfigFieldsV3 config = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); - assertEquals("My Pack", config.modpack.name); - assertEquals(GroupSelectionMode.REQUIRED, config.modpack.categories.get("name").get("main").selection); + config.modpack.categories.remove("obsolete"); + config.modpack.groups.remove("legacy"); + ServerConfigJsons.CategoryDeclaration lighting = new ServerConfigJsons.CategoryDeclaration(); + lighting.name = "Lighting"; + lighting.pick = CategoryPickMode.EXACTLY_ONE; + config.modpack.categories.put("lighting", lighting); + ServerConfigJsons.GroupDeclaration iris = new ServerConfigJsons.GroupDeclaration(); + iris.name = "Iris"; + iris.category = "shaders"; + iris.selection = GroupSelectionMode.RECOMMENDED; + config.modpack.groups.put("iris", iris); + + TomlConfigs.save(serverConfig(), config, ServerConfigFieldsV3.class, ServerConfigFieldsV3::new); + String after = Files.readString(serverConfig(), StandardCharsets.UTF_8); + assertTrue(after.contains("# keep banner"), after); + assertTrue(after.contains("name = \"Shaders\" # keep category note"), after); + assertTrue(after.contains("selection = \"REQUIRED\" # keep group note"), after); + assertTrue(after.contains("[categories.lighting]"), after); + assertTrue(after.contains("[groups.iris]"), after); + assertFalse(after.contains("[categories.obsolete]"), after); + assertFalse(after.contains("[groups.legacy]"), after); + + ServerConfigFieldsV3 reread = TomlConfigs.read(serverConfig(), ServerConfigFieldsV3.class).orElseThrow(); + assertEquals(CategoryPickMode.EXACTLY_ONE, reread.modpack.categories.get("lighting").pick); + assertEquals(GroupSelectionMode.RECOMMENDED, reread.modpack.groups.get("iris").selection); + assertFalse(reread.modpack.categories.containsKey("obsolete")); + assertFalse(reread.modpack.groups.containsKey("legacy")); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/ModpackExecutorTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/ModpackExecutorTest.java index af9f534a0..5eb6eac81 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/ModpackExecutorTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/ModpackExecutorTest.java @@ -28,11 +28,13 @@ import pl.skidam.automodpack_core.config.ModpackJsons; import pl.skidam.automodpack_core.config.ServerConfigJsons; import pl.skidam.automodpack_core.config.ServerConfigStore; +import pl.skidam.automodpack_core.config.TomlConfigs; import pl.skidam.automodpack_core.loader.LoaderManagerService.ModPlatform; import pl.skidam.automodpack_core.modpack.candidate.CandidateBuildException; import pl.skidam.automodpack_core.modpack.candidate.ModpackCandidateScanner; import pl.skidam.automodpack_core.modpack.generation.GenerationHosting; import pl.skidam.automodpack_core.modpack.generation.GenerationStore; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; @@ -623,7 +625,7 @@ void aServerWithNothingToPublishBootsIntoAnAbsence() throws Exception { assertEquals(PackAbsence.Kind.NOTHING_FOUND, previewed.absence().orElseThrow().kind()); // Files that no group would hand out are refused too, and named as the group configuration they are. - ServerConfigStore.install(config(false, false)); + ServerConfigStore.install(config(GroupSelectionMode.OPTIONAL)); Files.createDirectories(groups.resolve("main/config")); Files.writeString(groups.resolve("main/config/example.txt"), "one", StandardCharsets.UTF_8); ModpackExecutor.PublishResult.NothingToPublish unselected = assertInstanceOf(ModpackExecutor.PublishResult.NothingToPublish.class, executor.publish()); @@ -631,7 +633,7 @@ void aServerWithNothingToPublishBootsIntoAnAbsence() throws Exception { assertTrue(executor.currentDocument().isEmpty()); // A group selected by default is enough; only a required one is not the sole way out. - ServerConfigStore.install(config(false, true)); + ServerConfigStore.install(config(GroupSelectionMode.RECOMMENDED)); assertInstanceOf(ModpackExecutor.Published.class, executor.publish()); assertNull(executor.packAbsence()); assertTrue(executor.currentDocument().isPresent()); @@ -640,7 +642,7 @@ void aServerWithNothingToPublishBootsIntoAnAbsence() throws Exception { // earlier generation re-advertises it the same way a publish does. Files.writeString(groups.resolve("main/config/example.txt"), "two", StandardCharsets.UTF_8); assertInstanceOf(ModpackExecutor.Published.class, executor.publish()); - ServerConfigStore.install(config(false, false)); + ServerConfigStore.install(config(GroupSelectionMode.OPTIONAL)); ModpackExecutor.PublishResult.NothingToPublish refusedAgain = assertInstanceOf(ModpackExecutor.PublishResult.NothingToPublish.class, executor.publish()); assertEquals(PackAbsence.Kind.NOTHING_SELECTED, refusedAgain.absence().kind()); assertNotNull(executor.packAbsence()); @@ -659,49 +661,87 @@ void aServerWithNothingToPublishBootsIntoAnAbsence() throws Exception { @Test void theAbsenceVerdictIsAPropertyOfTheManifest() { // An all-empty manifest refuses regardless of flags: there is nothing any selection could hand out. - assertEquals(PackAbsence.Kind.NOTHING_FOUND, ModpackExecutor.absenceOf(manifestOf(Map.of("main", new boolean[]{true, true}), Map.of())).kind()); + assertEquals(PackAbsence.Kind.NOTHING_FOUND, ModpackExecutor.absenceOf(manifestOf(Map.of("main", GroupSelectionMode.REQUIRED), Map.of())).kind()); // The flags alone satisfy nobody: a selected-but-empty group next to files nobody receives is refused too. - PackAbsence unselected = ModpackExecutor.absenceOf(manifestOf(Map.of("main", new boolean[]{true, false}, "extra", new boolean[]{false, false}), - Map.of("main", Map.of(), "extra", Map.of("config/extra.txt", "extra")))); + PackAbsence unselected = ModpackExecutor.absenceOf(manifestOf(Map.of("main", GroupSelectionMode.REQUIRED, "extra", GroupSelectionMode.OPTIONAL, "unused-auto", GroupSelectionMode.AUTOMATIC), + Map.of("main", Map.of(), "extra", Map.of("config/extra.txt", "extra"), "unused-auto", Map.of("config/auto.txt", "auto")))); assertEquals(PackAbsence.Kind.NOTHING_SELECTED, unselected.kind()); // A group that carries files and would be received is all the pack needs. - assertNull(ModpackExecutor.absenceOf(manifestOf(Map.of("main", new boolean[]{false, true}), Map.of("main", Map.of("config/a.txt", "a"))))); + assertNull(ModpackExecutor.absenceOf(manifestOf(Map.of("main", GroupSelectionMode.RECOMMENDED), Map.of("main", Map.of("config/a.txt", "a"))))); + + // An EXACTLY_ONE category auto-picks its first option even when marked OPTIONAL, satisfying default selection. + ModpackJsons.CompleteModpackContentFields exclusiveFields = new ModpackJsons.CompleteModpackContentFields(); + exclusiveFields.modpackId = "abc1234"; + var shaders = new ModpackJsons.CompleteModpackContentFields.CategoryFields(); + shaders.pick = CategoryPickMode.EXACTLY_ONE; + exclusiveFields.categories = Map.of("shaders", shaders); + var shaderA = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); + shaderA.category = "shaders"; + shaderA.selection = GroupSelectionMode.OPTIONAL; + String sha = HashUtils.sha1("s".getBytes(StandardCharsets.UTF_8)); + shaderA.files = Map.of("shaderpacks/a.zip", new ModpackJsons.CompleteModpackContentFields.GroupFileFields("1", false, sha, null)); + exclusiveFields.groups = Map.of("shader-a", shaderA); + assertNull(ModpackExecutor.absenceOf(GroupManifestValidator.validate(exclusiveFields))); + } + + @Test + void importFoldersAddsNonEmptyValidFoldersIntoServerToml() throws Exception { + Path serverToml = tempDir.resolve("server.toml"); + ServerConfigJsons.ServerConfigFieldsV3 initial = TomlConfigs.readOrCreate(serverToml, ServerConfigJsons.ServerConfigFieldsV3.class, ServerConfigJsons.ServerConfigFieldsV3::new); + Path groupRoot = tempDir.resolve("host-modpack"); + Files.createDirectories(groupRoot.resolve("main")); + Files.createDirectories(groupRoot.resolve("shaders")); + Files.writeString(groupRoot.resolve("shaders/pack.txt"), "s", StandardCharsets.UTF_8); + Files.createDirectories(groupRoot.resolve("empty-dir")); + Files.createDirectories(groupRoot.resolve("Invalid.Name")); + Files.writeString(groupRoot.resolve("Invalid.Name/x.txt"), "x", StandardCharsets.UTF_8); + + GroupInspector.ImportResult result = GroupInspector.importFolders(serverToml, groupRoot, initial.modpack, null); + + assertEquals(List.of("shaders"), result.imported()); + assertEquals(List.of("empty-dir (empty folder)"), result.skipped()); + assertTrue(result.warnings().stream().anyMatch(w -> w.contains("Invalid.Name")), result.warnings().toString()); + ServerConfigJsons.ServerConfigFieldsV3 reread = TomlConfigs.read(serverToml, ServerConfigJsons.ServerConfigFieldsV3.class).orElseThrow(); + assertTrue(reread.modpack.groups.containsKey("shaders")); + assertEquals(GroupSelectionMode.OPTIONAL, reread.modpack.groups.get("shaders").selection); } private static ServerConfigJsons.ServerConfigFieldsV3 config() { - return config(true, false); + return config(GroupSelectionMode.REQUIRED); } - private static ServerConfigJsons.ServerConfigFieldsV3 config(boolean required, boolean defaultSelected) { + private static ServerConfigJsons.ServerConfigFieldsV3 config(GroupSelectionMode selection) { ServerConfigJsons.ServerConfigFieldsV3 config = new ServerConfigJsons.ServerConfigFieldsV3(); ServerConfigJsons.GroupDeclaration main = new ServerConfigJsons.GroupDeclaration(); - main.selection = GroupSelectionMode.of(required, defaultSelected); + main.selection = selection; main.fromServer = Set.of(); main.autoExcludeServerSideMods = ServerSideModExclusion.DISABLED; - config.modpack.categories = Map.of("General", Map.of("main", main)); + config.modpack.autoExcludeServerSideMods = ServerSideModExclusion.DISABLED; + config.modpack.exclude = Set.of(); + config.modpack.editable = Set.of(); + config.modpack.groups = Map.of("main", main); config.validateSecrets = false; return config; } - private static GroupManifest manifestOf(Map groups, Map> filesByGroup) { + private static GroupManifest manifestOf(Map groups, Map> filesByGroup) { ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; - Map category = new HashMap<>(); + Map groupFields = new HashMap<>(); for (var entry : groups.entrySet()) { ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = entry.getValue()[0]; - group.defaultSelected = entry.getValue()[1]; + group.selection = entry.getValue(); Map files = new HashMap<>(); for (var file : filesByGroup.getOrDefault(entry.getKey(), Map.of()).entrySet()) { String sha1 = HashUtils.sha1(file.getValue().getBytes(StandardCharsets.UTF_8)); files.put(file.getKey(), new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(file.getValue().length()), false, sha1, null)); } group.files = files; - category.put(entry.getKey(), group); + groupFields.put(entry.getKey(), group); } - fields.categories = Map.of("General", category); + fields.groups = groupFields; return GroupManifestValidator.validate(fields); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/candidate/ModpackCandidateScannerTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/candidate/ModpackCandidateScannerTest.java index 2ffceff5c..a7422ada0 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/candidate/ModpackCandidateScannerTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/candidate/ModpackCandidateScannerTest.java @@ -102,8 +102,8 @@ void groupFolderShadowsSyncedSourceAndRecordsProvenance() throws Exception { assertEquals(CandidateSource.SourceKind.GROUP_DIRECTORY, provenance.selectedSource().kind()); assertEquals("config/example.txt", provenance.selectedSource().logicalPath()); assertEquals("config/example.txt", candidate.manifest().groups().get("main").files().keySet().iterator().next()); - assertEquals("General", candidate.manifest().groups().get("main").category()); - assertEquals("main", candidate.manifest().toFields().categories.get("General").keySet().iterator().next()); + assertEquals("", candidate.manifest().groups().get("main").category()); + assertEquals("main", candidate.manifest().toFields().groups.keySet().iterator().next()); } @Test @@ -363,7 +363,11 @@ void filesAnInstalledPackOwnsAreNeverGeneratedAsThisInstancesOwn() throws Except .historic("config/edited.txt", HashUtils.sha1("as the pack shipped it".getBytes(StandardCharsets.UTF_8))) .historic("config/explicit.txt", HashUtils.sha1("from an installed pack".getBytes(StandardCharsets.UTF_8))).managed("config/managed.txt").build(); - var request = new ModpackCandidateScanner.Request("abc1234", "Test", "1", "fabric", "1", "1", server, groups, Map.of("General", Map.of("main", group("/config/**"))), true, + var ownedModpack = new ServerConfigJsons.ModpackFields(); + ownedModpack.exclude = Set.of(); + ownedModpack.editable = Set.of(); + ownedModpack.groups = Map.of("main", group("/config/**")); + var request = new ModpackCandidateScanner.Request("abc1234", "Test", "1", "fabric", "1", "1", server, groups, ownedModpack, true, tempDir.resolve("staging"), Runnable::run, null, null, null, true, owned); ModpackCandidate candidate = new ModpackCandidateScanner(null).scan(request); @@ -385,8 +389,17 @@ private ModpackCandidate scan(Path server, Path groups, Map declarations, boolean applyPlatformExclusions, PlatformSideVerdicts sideVerdicts) throws Exception { + var modpack = new ServerConfigJsons.ModpackFields(); + modpack.exclude = Set.of(); + modpack.editable = Set.of(); + modpack.groups = declarations; + return scan(server, groups, modpack, applyPlatformExclusions, sideVerdicts); + } + + private ModpackCandidate scan(Path server, Path groups, ServerConfigJsons.ModpackFields modpack, boolean applyPlatformExclusions, PlatformSideVerdicts sideVerdicts) + throws Exception { Executor direct = Runnable::run; - var request = new ModpackCandidateScanner.Request("abc1234", "Test", "1", "fabric", "1", "1", server, groups, Map.of("General", declarations), applyPlatformExclusions, tempDir.resolve("staging"), + var request = new ModpackCandidateScanner.Request("abc1234", "Test", "1", "fabric", "1", "1", server, groups, modpack, applyPlatformExclusions, tempDir.resolve("staging"), direct, null, null, null, true, PackOwnedFiles.NONE); return new ModpackCandidateScanner(sideVerdicts).scan(request); } @@ -544,7 +557,7 @@ void freshConfigDefaultsFilterJunkThroughSeededRules() throws Exception { Files.writeString(groups.resolve("main/config/.gitkeep"), "keep", StandardCharsets.UTF_8); Files.writeString(groups.resolve("main/config/kept.txt"), "kept", StandardCharsets.UTF_8); - ModpackCandidate candidate = scan(server, groups, new ServerConfigJsons.ServerConfigFieldsV3().modpack.categories.get("General")); + ModpackCandidate candidate = scan(server, groups, new ServerConfigJsons.ServerConfigFieldsV3().modpack, true, null); var files = candidate.manifest().groups().get("main").files(); assertTrue(files.containsKey("config/kept.txt")); @@ -757,6 +770,44 @@ void neoforgeJarWithMinecraftSideServerIsDroppedWhenModrinthSaysDedicatedServerO assertEquals("modrinth environment dedicated_server_only", candidate.exclusions().get(0).message()); } + @Test + void packWideExcludeEditableAndServerExclusionApplyUnlessGroupNegatesOrOverrides() throws Exception { + Path server = tempDir.resolve("server"); + Path groups = tempDir.resolve("groups"); + Files.createDirectories(groups.resolve("main/config")); + Files.createDirectories(groups.resolve("extras/config")); + Files.writeString(groups.resolve("main/config/skip.txt"), "skip", StandardCharsets.UTF_8); + Files.writeString(groups.resolve("main/config/client.txt"), "client", StandardCharsets.UTF_8); + Files.writeString(groups.resolve("extras/config/skip.txt"), "keep-me", StandardCharsets.UTF_8); + Files.writeString(groups.resolve("extras/config/extra-client.txt"), "locked", StandardCharsets.UTF_8); + writeModJar(groups.resolve("main/server.jar"), "server"); + writeModJar(groups.resolve("extras/server.jar"), "server"); + + var modpack = new ServerConfigJsons.ModpackFields(); + modpack.autoExcludeServerSideMods = ServerSideModExclusion.METADATA; + modpack.exclude = new LinkedHashSet<>(List.of("config/skip.txt")); + modpack.editable = new LinkedHashSet<>(List.of("config/*.txt")); + + ServerConfigJsons.GroupDeclaration main = group(); + ServerConfigJsons.GroupDeclaration extras = group(); + extras.autoExcludeServerSideMods = ServerSideModExclusion.DISABLED; + extras.exclude = new LinkedHashSet<>(List.of("!config/skip.txt")); + extras.editable = new LinkedHashSet<>(List.of("!config/extra-client.txt")); + modpack.groups = new LinkedHashMap<>(Map.of("main", main, "extras", extras)); + + ModpackCandidate candidate = scan(server, groups, modpack, true, null); + var mainFiles = candidate.manifest().groups().get("main").files(); + var extrasFiles = candidate.manifest().groups().get("extras").files(); + + assertFalse(mainFiles.containsKey("config/skip.txt")); + assertFalse(mainFiles.containsKey("server.jar")); + assertTrue(mainFiles.get("config/client.txt").editable()); + + assertTrue(extrasFiles.containsKey("config/skip.txt"), "group ! negation overrides pack exclude"); + assertTrue(extrasFiles.containsKey("server.jar"), "group override DISABLED beats pack METADATA"); + assertFalse(extrasFiles.get("config/extra-client.txt").editable(), "group ! negation locks pack-editable file"); + } + private static void writePlainJar(Path path) throws IOException { try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(path))) { jar.putNextEntry(new JarEntry("readme.txt")); diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/ClientHostSharedRootTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/ClientHostSharedRootTest.java index c0fd77bfa..4309938ed 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/ClientHostSharedRootTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/ClientHostSharedRootTest.java @@ -18,6 +18,7 @@ import pl.skidam.automodpack_core.modpack.candidate.ModpackCandidate; import pl.skidam.automodpack_core.modpack.candidate.StagedObject; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.storage.DataRootResolver; import pl.skidam.automodpack_core.storage.TestDataRoot; import pl.skidam.automodpack_core.update.ClientObjectStore; @@ -126,11 +127,10 @@ private static ModpackCandidate candidate(Path state, String modpackId, String c ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = modpackId; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; group.description = "g"; group.files = Map.of("config/x.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(content.length()), false, hash, null)); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return new ModpackCandidate(GroupManifestValidator.validate(fields), new TreeMap<>(Map.of(hash, new StagedObject(hash, content.length(), staged))), new TreeMap<>(), List.of()); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/ContentTreeTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/ContentTreeTest.java index 233860b61..294cac349 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/ContentTreeTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/ContentTreeTest.java @@ -11,8 +11,10 @@ import org.junit.jupiter.api.Test; import pl.skidam.automodpack_core.config.ModpackJsons; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.utils.HashUtils; class ContentTreeTest { @@ -49,19 +51,22 @@ void aNewVariantAtAnExistingPathDiffsAsAdded() { } private static GroupManifest exclusive(String performanceContent, String fantasyContent) { - var performance = group(performanceContent, "fantasy"); - var fantasy = group(fantasyContent, "performance"); + var cat = new ModpackJsons.CompleteModpackContentFields.CategoryFields(); + cat.name = "Variant"; + cat.pick = CategoryPickMode.AT_MOST_ONE; + var performance = group(performanceContent); + var fantasy = group(fantasyContent); ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; - fields.categories = Map.of("General", Map.of("performance", performance, "fantasy", fantasy)); + fields.categories = Map.of("variant", cat); + fields.groups = Map.of("performance", performance, "fantasy", fantasy); return GroupManifestValidator.validate(fields); } - private static ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group(String content, String breaksWith) { + private static ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group(String content) { var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; - group.breaksWith = Set.of(breaksWith); + group.category = "variant"; + group.selection = GroupSelectionMode.OPTIONAL; group.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(content.length()), false, sha1(content), null)); return group; } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/GenerationDiffTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/GenerationDiffTest.java index 12afbe608..57006e104 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/GenerationDiffTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/GenerationDiffTest.java @@ -11,17 +11,18 @@ import pl.skidam.automodpack_core.config.ModpackJsons; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; class GenerationDiffTest { @Test void reportsAllFileClassesMetadataAndCanonicalOrder() { GroupManifest parent = manifest("parent", Map.of("z-removed", file("1", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", null), "b-modified", file("1", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", null), - "a-metadata", file("1", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", "old")), "old description", "old-category", + "a-metadata", file("1", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", "old")), "old description", "", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8"); GroupManifest child = manifest("child", Map.of("a-added", file("1", "e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98", null), "b-modified", file("1", "e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98", null), - "a-metadata", file("1", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", "new")), "new description", "new-category", + "a-metadata", file("1", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", "new")), "new description", "", "e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98"); GenerationDiff diff = GenerationDiff.between(parent, child); @@ -41,12 +42,14 @@ void reportsAllFileClassesMetadataAndCanonicalOrder() { } @Test - void reportsGroupCategoryMetadataChanges() { - GroupManifest parent = categorizedManifest("old-category"); - GroupManifest child = categorizedManifest("new-category"); + void reportsGroupCategoryMetadataAndCategoryDefinitionChanges() { + GroupManifest parent = categorizedManifest("cat-a", "Old Category"); + GroupManifest child = categorizedManifest("cat-b", "New Category"); GenerationDiff diff = GenerationDiff.between(parent, child); + assertEquals(List.of("cat-a"), diff.categoryMetadata().removed()); + assertEquals(List.of("cat-b"), diff.categoryMetadata().added()); assertEquals(List.of("main"), diff.groupMetadata().modified()); assertFalse(diff.isEmpty()); } @@ -75,14 +78,17 @@ void summaryCountsOneEffectivePathWhenGroupsRepeatIt() { assertEquals(new GenerationDiff.Summary(0, 1, 0, 0, 0), diff.summary()); } - private static GroupManifest categorizedManifest(String category) { + private static GroupManifest categorizedManifest(String categoryId, String categoryName) { ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; + var cat = new ModpackJsons.CompleteModpackContentFields.CategoryFields(); + cat.name = categoryName; + fields.categories = Map.of(categoryId, cat); var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.category = categoryId; + group.selection = GroupSelectionMode.OPTIONAL; group.files = Map.of(); - fields.categories = Map.of(category, Map.of("main", group)); + fields.groups = Map.of("main", group); return GroupManifestValidator.validate(fields); } @@ -101,15 +107,16 @@ private static GroupManifest manifestWithGroups(String id, Map declarations = new LinkedHashMap<>(); + if (!category.isEmpty()) fields.categories = Map.of(category, new ModpackJsons.CompleteModpackContentFields.CategoryFields()); for (var entry : groups.entrySet()) { var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; + group.category = category; group.description = entry.getKey().equals("main") ? description : ""; group.files = entry.getValue(); declarations.put(entry.getKey(), group); } - fields.categories = Map.of(category.isEmpty() ? "General" : category, declarations); + fields.groups = declarations; return GroupManifestValidator.validate(fields); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/GenerationStoreTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/GenerationStoreTest.java index 93206b0e2..de6a7f1f2 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/GenerationStoreTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/GenerationStoreTest.java @@ -31,9 +31,11 @@ import pl.skidam.automodpack_core.config.ModpackJsons; import pl.skidam.automodpack_core.modpack.candidate.ModpackCandidate; import pl.skidam.automodpack_core.modpack.candidate.StagedObject; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.GroupSelectionResolver; import pl.skidam.automodpack_core.modpack.group.SelectedTreeComposer; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; @@ -55,7 +57,7 @@ void publishesRestoresAndCollectsHeadUnreachableObjects() throws Exception { GenerationStore.Current current = store.loadCurrent().orElseThrow(); assertEquals(root.entry().seq(), current.seq()); assertEquals("First", root.entry().notes()); - assertEquals("one", current.manifest().toFields().categories.get("General").get("main").description); + assertEquals("one", current.manifest().toFields().groups.get("main").description); assertEquals(1, current.seq()); GenerationStore.Publication second = store.publish(candidate("two", "content-two"), "Second", null); @@ -105,8 +107,8 @@ void publishesMutuallyExclusiveVariantsAtTheSamePath() throws Exception { ContentTree tree = ContentTree.fromManifest(publication.manifest()); assertEquals(2, tree.size()); assertEquals(Set.of(performanceHash, fantasyHash), tree.objectHashes()); - var performance = SelectedTreeComposer.compose(publication.manifest(), GroupSelectionResolver.resolve(publication.manifest(), new SelectionIntent(Set.of("performance")), ClientPlatform.LINUX)); - var fantasy = SelectedTreeComposer.compose(publication.manifest(), GroupSelectionResolver.resolve(publication.manifest(), new SelectionIntent(Set.of("fantasy")), ClientPlatform.LINUX)); + var performance = SelectedTreeComposer.compose(publication.manifest(), GroupSelectionResolver.resolve(publication.manifest(), SelectionIntent.ofEnabled(Set.of("performance")), ClientPlatform.LINUX)); + var fantasy = SelectedTreeComposer.compose(publication.manifest(), GroupSelectionResolver.resolve(publication.manifest(), SelectionIntent.ofEnabled(Set.of("fantasy")), ClientPlatform.LINUX)); assertEquals(performanceHash, performance.list.iterator().next().sha1); assertEquals(fantasyHash, fantasy.list.iterator().next().sha1); assertNotEquals(ContentTree.tokenOf(TestPacks.manifest("only", "config/example.txt", performanceText)), publication.entry().contentToken()); @@ -433,7 +435,7 @@ void policyOnlyRepublishLandsInTheJournalAndSurvivesAStoreReload() throws Except GenerationStore reopened = new GenerationStore(state, objects); GenerationStore.Current current = reopened.loadCurrent().orElseThrow(); assertEquals(2, current.seq()); - assertEquals("renamed", current.manifest().toFields().categories.get("General").get("main").description); + assertEquals("renamed", current.manifest().toFields().groups.get("main").description); // Republishing the very same policy again changes nothing at all: the head stays where it is. GenerationStore.Publication unchanged = reopened.publish(candidate("renamed", "content-one"), "Nothing", null); @@ -504,11 +506,10 @@ void tamperedPolicyBytesAreRejectedByRestoreAndArchivedAsideByTheRebuild() throw ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = "one"; group.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields("8", false, sha1("tampered"), null)); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); Path policyObject = DataRootResolver.objectFile(objects, root.entry().policySha1()); Files.write(policyObject, ConfigTools.GSON.toJson(fields).getBytes(StandardCharsets.UTF_8)); @@ -540,18 +541,17 @@ void headDocumentCarriesIdentityPolicyAndLedger() throws Exception { } private static ModpackJsons.CompleteModpackContentFields.GroupFileFields fileEntry(GenerationJsons.HeadDocumentFields fields) { - return fields.policy.categories.get("General").get("main").files.get("config/example.txt"); + return fields.policy.groups.get("main").files.get("config/example.txt"); } private static GroupManifest manifest(String description, String content) { ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = description; group.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(content.length()), false, sha1(content), null)); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return GroupManifestValidator.validate(fields); } @@ -578,11 +578,10 @@ private ModpackCandidate candidate(Map files) throws IOException ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = "multi"; group.files = entries; - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return new ModpackCandidate(GroupManifestValidator.validate(fields), staged, new TreeMap<>(), List.of()); } @@ -594,19 +593,21 @@ private ModpackCandidate exclusiveCandidate(String performanceContent, String fa Files.writeString(fantasyFile, fantasyContent, StandardCharsets.UTF_8); String performanceHash = sha1(performanceContent); String fantasyHash = sha1(fantasyContent); + var variant = new ModpackJsons.CompleteModpackContentFields.CategoryFields(); + variant.name = "Variant"; + variant.pick = CategoryPickMode.AT_MOST_ONE; var performance = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - performance.required = false; - performance.defaultSelected = false; - performance.breaksWith = Set.of("fantasy"); + performance.category = "variant"; + performance.selection = GroupSelectionMode.OPTIONAL; performance.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(performanceContent.length()), false, performanceHash, null)); var fantasy = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - fantasy.required = false; - fantasy.defaultSelected = false; - fantasy.breaksWith = Set.of("performance"); + fantasy.category = "variant"; + fantasy.selection = GroupSelectionMode.OPTIONAL; fantasy.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(fantasyContent.length()), false, fantasyHash, null)); ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; - fields.categories = Map.of("General", Map.of("performance", performance, "fantasy", fantasy)); + fields.categories = Map.of("variant", variant); + fields.groups = Map.of("performance", performance, "fantasy", fantasy); TreeMap staged = new TreeMap<>(); staged.put(performanceHash, stagedObject(performanceFile, performanceHash, performanceContent.length())); staged.put(fantasyHash, stagedObject(fantasyFile, fantasyHash, fantasyContent.length())); @@ -621,11 +622,10 @@ private ModpackCandidate candidate(String description, String content) throws IO ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = description; group.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(content.length()), false, hash, null)); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); GroupManifest manifest = GroupManifestValidator.validate(fields); return new ModpackCandidate(manifest, new TreeMap<>(Map.of(hash, stagedObject(staged, hash, content.length()))), new TreeMap<>(), List.of()); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/TestPacks.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/TestPacks.java index a8a8d6f29..4aff58b48 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/TestPacks.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/generation/TestPacks.java @@ -12,6 +12,7 @@ import pl.skidam.automodpack_core.config.ModpackJsons; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.update.ClientObjectStore; import pl.skidam.automodpack_core.update.ClientStorage; import pl.skidam.automodpack_core.utils.HashUtils; @@ -26,12 +27,11 @@ public static GroupManifest manifest(String description, String path, String con ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = description; String sha1 = HashUtils.sha1(content.getBytes(StandardCharsets.UTF_8)); group.files = new TreeMap<>(Map.of(path, new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(content.length()), false, sha1, null))); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return GroupManifestValidator.validate(fields); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/ClientSelectionStoreTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/ClientSelectionStoreTest.java index fb9d45a32..4389dbc40 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/ClientSelectionStoreTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/ClientSelectionStoreTest.java @@ -7,12 +7,15 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; +import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import pl.skidam.automodpack_core.config.ConfigTools; +import pl.skidam.automodpack_core.config.Rc7ClientSelectionMigration; import pl.skidam.automodpack_core.config.SelectionJsons; class ClientSelectionStoreTest { @@ -20,45 +23,129 @@ class ClientSelectionStoreTest { Path temporaryDirectory; @Test - void roundTripsGroupsAndExclusionsWithoutDerivedGroups() throws Exception { + void roundTripsEnabledAndDisabledWithoutDerivedGroups() throws Exception { Path path = temporaryDirectory.resolve("selection.json"); ClientSelectionStore store = new ClientSelectionStore(path); - SelectionIntent intent = new SelectionIntent(Set.of("optional", "stale-group"), Set.of("client"), Set.of("variant")); + SelectionIntent intent = new SelectionIntent(Set.of("optional", "stale-group"), Set.of("variant"), null); store.put("abc1234", intent); assertEquals(intent, store.get("abc1234").orElseThrow()); SelectionJsons.ClientSelectionStoreFields fields = ConfigTools.read(path, SelectionJsons.ClientSelectionStoreFields.class).orElseThrow(); - SelectionJsons.ClientSelectionStoreFields.ModpackSelection selection = fields.selections.get("abc1234"); - assertEquals(Set.of("optional", "stale-group"), selection.requestedGroups); - assertEquals(Set.of("client"), selection.requestedCategories); - assertEquals(Set.of("variant"), selection.excludedGroups); + SelectionJsons.SelectionFields selection = fields.selections.get("abc1234"); + assertEquals(List.of("optional", "stale-group"), selection.enabled); + assertEquals(List.of("variant"), selection.disabled); } @Test void preservesStaleGroupIdsWhenSaved() throws Exception { ClientSelectionStore store = new ClientSelectionStore(temporaryDirectory.resolve("selection.json")); - SelectionIntent intent = new SelectionIntent(Set.of("removed-group")); + SelectionIntent intent = SelectionIntent.ofEnabled(Set.of("removed-group")); store.put("abc1234", intent); - assertEquals(Set.of("removed-group"), store.get("abc1234").orElseThrow().requestedGroups()); + assertEquals(Set.of("removed-group"), store.get("abc1234").orElseThrow().enabled()); } @Test void savingPersistsTheResolutionPlatformAndTheLastConsentWins() throws Exception { ClientSelectionStore store = new ClientSelectionStore(temporaryDirectory.resolve("selection.json")); - SelectionIntent intent = new SelectionIntent(Set.of("optional"), Set.of(), Set.of(), ClientPlatform.LINUX); + SelectionIntent intent = new SelectionIntent(Set.of("optional"), Set.of(), ClientPlatform.LINUX); store.put("abc1234", intent); // The stored platform is what later boots re-resolve under; equality still ignores it, so a // platform-less expected intent still matches the stored selection with one. assertEquals(ClientPlatform.LINUX, store.get("abc1234").orElseThrow().platform()); - store.put("abc1234", new SelectionIntent(Set.of("optional"), Set.of(), Set.of(), ClientPlatform.WINDOWS)); + store.put("abc1234", new SelectionIntent(Set.of("optional"), Set.of(), ClientPlatform.WINDOWS)); assertEquals(ClientPlatform.WINDOWS, store.get("abc1234").orElseThrow().platform()); } + @Test + void migratesLegacyV1SelectionFileToV2() throws Exception { + Path path = temporaryDirectory.resolve("selection.json"); + Files.writeString(path, """ + { + "DO_NOT_CHANGE_IT": 1, + "selections": { + "abc1234": { + "requestedGroups": ["zeta", "alpha", "alpha", " "], + "requestedCategories": ["visuals"], + "excludedGroups": ["alpha", "beta", "beta"], + "platform": " LINUX " + } + } + } + """, StandardCharsets.UTF_8); + Rc7ClientSelectionMigration.migrateClientSelections(path, policyLookup()); + + ClientSelectionStore store = new ClientSelectionStore(path); + + SelectionIntent intent = store.get("abc1234").orElseThrow(); + assertEquals(Set.of("alpha", "zeta", "category-member"), intent.enabled()); + assertEquals(Set.of("beta"), intent.disabled(), "an excluded group that is also requested stays enabled"); + assertEquals(ClientPlatform.LINUX, intent.platform()); + + String rewritten = Files.readString(path, StandardCharsets.UTF_8); + SelectionJsons.ClientSelectionStoreFields fields = ConfigTools.parse(rewritten, SelectionJsons.ClientSelectionStoreFields.class); + assertEquals(2, fields.schemaVersion); + SelectionJsons.SelectionFields selection = fields.selections.get("abc1234"); + assertEquals(List.of("alpha", "category-member", "zeta"), selection.enabled); + assertEquals(List.of("beta"), selection.disabled); + assertEquals("linux", selection.platform); + assertFalse(rewritten.contains("requestedCategories"), rewritten); + + assertEquals(intent, store.get("abc1234").orElseThrow()); + } + + @Test + void migrationPreservesTheDesiredSelectionInsteadOfCopyingTheAppliedPointer() throws Exception { + Path path = temporaryDirectory.resolve("selection.json"); + Files.writeString(path, """ + { + "DO_NOT_CHANGE_IT": 1, + "selections": { + "abc1234": { + "requestedGroups": ["newer"], + "requestedCategories": ["Visuals"], + "excludedGroups": ["old-off"], + "platform": "linux" + } + } + } + """, StandardCharsets.UTF_8); + Files.writeString(temporaryDirectory.resolve("active-state.json"), """ + { + "modpackId": "abc1234", + "selection": {"enabled": ["old-applied"], "disabled": ["applied-off"], "platform": "linux"} + } + """, StandardCharsets.UTF_8); + Rc7ClientSelectionMigration.migrateClientSelections(path, policyLookup()); + + SelectionIntent intent = new ClientSelectionStore(path).get("abc1234").orElseThrow(); + + assertEquals(Set.of("newer", "category-member"), intent.enabled()); + assertEquals(Set.of("old-off"), intent.disabled()); + assertEquals(ClientPlatform.LINUX, intent.platform()); + } + + private static Rc7ClientSelectionMigration.PolicyLookup policyLookup() { + GroupManifest manifest = new GroupManifest("abc1234", "Test Pack", "", "fabric", "", "1.21.1", + Map.of("visuals", new GroupManifest.Category("Visuals", "", CategoryPickMode.ANY)), + Map.of("category-member", new GroupManifest.Group("Member", "", "visuals", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of()))); + return new Rc7ClientSelectionMigration.PolicyLookup() { + @Override + public GroupManifest generation(String modpackId, String contentToken) { + return manifest; + } + + @Override + public GroupManifest latest(String modpackId) { + return manifest; + } + }; + } + @Test void corruptStoreContentIsSetAsideAndReadsAsNoSelection() throws Exception { Path path = temporaryDirectory.resolve("selection.json"); diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/GroupManifestValidatorTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/GroupManifestValidatorTest.java index 161d20461..347488cbf 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/GroupManifestValidatorTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/GroupManifestValidatorTest.java @@ -13,132 +13,190 @@ class GroupManifestValidatorTest { @Test void acceptsIdenticalSharedFileAndPreservesDeclarationOrder() { var fields = catalogue(); - fields.categories = linkedCategories("General", linkedGroups("visuals", group(file("a")), "main", group(file("a")))); + fields.groups = linkedGroups("visuals", group(file("a")), "main", group(file("a"))); GroupManifest manifest = GroupManifestValidator.validate(fields); assertEquals(List.of("visuals", "main"), new ArrayList<>(manifest.groups().keySet())); assertEquals(ConfigTools.GSON.toJson(manifest.toFields()), ConfigTools.GSON.toJson(GroupManifestValidator.validate(manifest.toFields()).toFields())); } @Test - void validatesCategoryNameAndRoundTrips() { + void validatesCategoryAndRoundTrips() { var fields = catalogue(); - fields.categories = linkedCategories("Visuals", linkedGroups("main", group(file("a")))); + fields.categories = linkedCategories("visuals", category("Visuals", CategoryPickMode.AT_MOST_ONE)); + var main = group(file("a")); + main.category = "visuals"; + fields.groups = linkedGroups("main", main); GroupManifest manifest = GroupManifestValidator.validate(fields); - assertEquals("Visuals", manifest.groups().get("main").category()); + assertEquals("visuals", manifest.groups().get("main").category()); + assertEquals("Visuals", manifest.categoryDisplayName("visuals")); assertEquals(ConfigTools.GSON.toJson(manifest.toFields()), ConfigTools.GSON.toJson(GroupManifestValidator.validate(manifest.toFields()).toFields())); } @Test - void everyValidatedGroupCarriesItsCategoryName() { + void uncategorizedGroupCarriesEmptyCategory() { var fields = catalogue(); - fields.categories = linkedCategories("General", linkedGroups("main", group(file("a")))); + fields.groups = linkedGroups("main", group(file("a"))); GroupManifest manifest = GroupManifestValidator.validate(fields); - assertEquals("General", manifest.groups().get("main").category()); + assertEquals("", manifest.groups().get("main").category()); } @Test - void rejectsMissingSelectionFlags() { + void rejectsMissingSelectionMode() { var fields = catalogue(); var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); group.files = Map.of("mods/example.jar", file("a")); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); GroupValidationException failure = assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); - assertTrue(failure.getMessage().contains("missing its selection flags")); + assertTrue(failure.getMessage().contains("missing its selection mode"), failure.getMessage()); } @Test - void rejectsEmptyCategory() { - var fields = catalogue(); - fields.categories = linkedCategories("General", linkedGroups("main", group(file("a"))), "Empty", linkedGroups()); + void rejectsEmptyCategoryAndUnknownGroupCategory() { + var emptyCat = catalogue(); + emptyCat.categories = linkedCategories("empty", category("Empty", CategoryPickMode.ANY)); + emptyCat.groups = linkedGroups("main", group(file("a"))); + assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(emptyCat)); - assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); + var unknownCat = catalogue(); + var group = group(file("a")); + group.category = "missing"; + unknownCat.groups = linkedGroups("main", group); + assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(unknownCat)); } @Test - void rejectsDuplicateGroupIdsAcrossCategories() { - var fields = catalogue(); - fields.categories = linkedCategories("General", linkedGroups("main", group(file("a"))), "Visuals", linkedGroups("main", group(file("a")))); - - assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); + void rejectsRequiredOrAutomaticGroupInsideExclusiveCategory() { + for (GroupSelectionMode forbidden : List.of(GroupSelectionMode.REQUIRED, GroupSelectionMode.AUTOMATIC)) { + var fields = catalogue(); + fields.categories = linkedCategories("shaders", category("Shaders", CategoryPickMode.AT_MOST_ONE)); + var g = group(file("a")); + g.category = "shaders"; + g.selection = forbidden; + fields.groups = linkedGroups("shader-a", g); + assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields), forbidden.name()); + } } @Test - void rejectsCaseInsensitiveDuplicateCategoryNames() { - var fields = catalogue(); - fields.categories = linkedCategories("General", linkedGroups("main", group(file("a"))), "general", linkedGroups("other", group(file("a")))); - - assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); - } + void rejectsInvalidIdentifiersAndWindowsDeviceNames() { + for (String bad : List.of("", " ", "Main", "padded ", "my.group", "../bad", "con", "nul", "com1", "x".repeat(65))) { + var badGroup = catalogue(); + badGroup.groups = linkedGroups(bad, group(file("a"))); + assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(badGroup), "group:" + bad); - @Test - void rejectsBlankPaddedControlCharacterAndOverlongCategoryNames() { - for (String name : List.of("", " ", " padded", "control\u0007char", "x".repeat(65))) { - var fields = catalogue(); - fields.categories = linkedCategories(name, linkedGroups("main", group(file("a")))); - assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields), name); + var badCategory = catalogue(); + badCategory.categories = linkedCategories(bad, category("Bad", CategoryPickMode.ANY)); + var g = group(file("a")); + g.category = bad; + badCategory.groups = linkedGroups("main", g); + assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(badCategory), "cat:" + bad); } } @Test void preservesDeclarationOrderThroughValidateAndSerializeRoundTrip() { var fields = catalogue(); - fields.categories = linkedCategories("Visuals", linkedGroups("z-shaders", group(file("a")), "a-packs", group(file("a"))), "General", linkedGroups("main", group(file("a")))); + fields.categories = linkedCategories("visuals", category("Visuals", CategoryPickMode.ANY), "extras", category("Extras", CategoryPickMode.ANY)); + var z = group(file("a")); + z.category = "visuals"; + var a = group(file("a")); + a.category = "visuals"; + var main = group(file("a")); + main.category = "extras"; + fields.groups = linkedGroups("z-shaders", z, "a-packs", a, "main", main); GroupManifest manifest = GroupManifestValidator.validate(fields); - assertEquals(List.of("Visuals", "General"), manifest.groups().values().stream().map(GroupManifest.Group::category).distinct().toList()); + assertEquals(List.of("visuals", "extras"), new ArrayList<>(manifest.categories().keySet())); assertEquals(List.of("z-shaders", "a-packs", "main"), new ArrayList<>(manifest.groups().keySet())); var roundTripped = GroupManifestValidator.validate(manifest.toFields()).toFields(); - assertEquals(List.of("Visuals", "General"), new ArrayList<>(roundTripped.categories.keySet())); - assertEquals(List.of("z-shaders", "a-packs"), new ArrayList<>(roundTripped.categories.get("Visuals").keySet())); - assertEquals(List.of("main"), new ArrayList<>(roundTripped.categories.get("General").keySet())); + assertEquals(List.of("visuals", "extras"), new ArrayList<>(roundTripped.categories.keySet())); + assertEquals(List.of("z-shaders", "a-packs", "main"), new ArrayList<>(roundTripped.groups.keySet())); var parsed = ConfigTools.parse(ConfigTools.GSON.toJson(fields), ModpackJsons.CompleteModpackContentFields.class); - assertEquals(List.of("Visuals", "General"), new ArrayList<>(parsed.categories.keySet())); - assertEquals(List.of("z-shaders", "a-packs", "main"), parsed.categories.values().stream().flatMap(category -> category.keySet().stream()).toList()); + assertEquals(List.of("visuals", "extras"), new ArrayList<>(parsed.categories.keySet())); + assertEquals(List.of("z-shaders", "a-packs", "main"), new ArrayList<>(parsed.groups.keySet())); } @Test void rejectsDifferentCoSelectableVariant() { var fields = catalogue(); - fields.categories = oneCategory("main", group(file("a")), "visuals", group(file("b"))); + fields.groups = linkedGroups("main", group(file("a")), "visuals", group(file("b"))); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @Test - void acceptsDifferentMutuallyExclusiveVariant() { + void acceptsDifferentExclusiveCategoryVariants() { var fields = catalogue(); + fields.categories = linkedCategories("shaders", category("Shaders", CategoryPickMode.AT_MOST_ONE)); var first = group(file("a")); + first.category = "shaders"; var second = group(file("b")); - first.breaksWith = Set.of("second"); - fields.categories = oneCategory("first", first, "second", second); + second.category = "shaders"; + fields.groups = linkedGroups("first", first, "second", second); assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); } @Test - void rejectsConflictingDefaultSelections() { + void rejectsConflictingRecommendedSelectionsInExclusiveCategory() { var fields = catalogue(); + fields.categories = linkedCategories("shaders", category("Shaders", CategoryPickMode.AT_MOST_ONE)); var first = group(file("a")); + first.category = "shaders"; + first.selection = GroupSelectionMode.RECOMMENDED; var second = group(file("b")); - first.defaultSelected = true; - second.defaultSelected = true; - first.breaksWith = Set.of("second"); - fields.categories = oneCategory("first", first, "second", second); + second.category = "shaders"; + second.selection = GroupSelectionMode.RECOMMENDED; + fields.groups = linkedGroups("first", first, "second", second); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @Test - void rejectsGroupThatConflictsWithForcedGroup() { + void acceptsOptionalGroupRequiringNonDefaultExclusiveCategoryMember() { + var fields = catalogue(); + fields.categories = linkedCategories("shaders", category("Shaders", CategoryPickMode.EXACTLY_ONE)); + var bsl = group(file("a")); + bsl.category = "shaders"; + bsl.selection = GroupSelectionMode.RECOMMENDED; + var comp = group(file("b")); + comp.category = "shaders"; + comp.selection = GroupSelectionMode.OPTIONAL; + var addon = group(file("b")); + addon.requires = Set.of("comp"); + fields.groups = linkedGroups("bsl", bsl, "comp", comp, "addon", addon); + assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); + } + + @Test + void rejectsAutomaticGroupWithDifferentFileWhenCoSelectableViaActivator() { var fields = catalogue(); - var forced = group(file("a")); - var optional = group(file("b")); - forced.required = true; - optional.breaksWith = Set.of("forced"); - fields.categories = oneCategory("forced", forced, "optional", optional); + var auto = groupAt("mods/shared.jar", file("a")); + auto.selection = GroupSelectionMode.AUTOMATIC; + var consumer = groupAt("mods/shared.jar", file("b")); + consumer.requires = Set.of("auto"); + fields.groups = linkedGroups("auto", auto, "consumer", consumer); + assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); + } + + @Test + void rejectsRequiredGroupWithMutualConflictThroughExclusiveCategory() { + var fields = catalogue(); + fields.categories = linkedCategories("mode", category("Mode", CategoryPickMode.EXACTLY_ONE)); + var main = group(file("a")); + main.selection = GroupSelectionMode.REQUIRED; + main.requires = Set.of("mode-a"); + var modeA = group(file("a")); + modeA.category = "mode"; + modeA.selection = GroupSelectionMode.RECOMMENDED; + var modeB = group(file("b")); + modeB.category = "mode"; + modeB.selection = GroupSelectionMode.OPTIONAL; + main.requires = Set.of("mode-a", "mode-b"); + fields.groups = linkedGroups("main", main, "mode-a", modeA, "mode-b", modeB); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -149,30 +207,21 @@ void acceptsOptionalGroupBlockedByUnavailableDependency() { dependency.compatiblePlatforms = Set.of("windows"); var optional = group(file("a")); optional.requires = Set.of("dependency"); - fields.categories = oneCategory("dependency", dependency, "optional", optional); + fields.groups = linkedGroups("dependency", dependency, "optional", optional); assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); } @Test - void rejectsRequiredOrForcedGroupBlockedByUnavailableDependency() { + void rejectsRequiredGroupBlockedByUnavailableDependency() { var requiredFields = catalogue(); var requiredDependency = group(file("a")); requiredDependency.compatiblePlatforms = Set.of("windows"); var required = group(file("a")); - required.required = true; + required.selection = GroupSelectionMode.REQUIRED; required.requires = Set.of("dependency"); - requiredFields.categories = oneCategory("dependency", requiredDependency, "required", required); + requiredFields.groups = linkedGroups("dependency", requiredDependency, "required", required); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(requiredFields)); - - var forcedFields = catalogue(); - var forcedDependency = group(file("a")); - forcedDependency.compatiblePlatforms = Set.of("windows"); - var forced = group(file("a")); - forced.required = true; - forced.requires = Set.of("dependency"); - forcedFields.categories = oneCategory("dependency", forcedDependency, "forced", forced); - assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(forcedFields)); } @Test @@ -180,7 +229,7 @@ void rejectsPlatformIndependentAbsolutePath() { var fields = catalogue(); var group = group(file("a")); group.files = Map.of("C:/escape.jar", file("a")); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -189,7 +238,7 @@ void rejectsDriveQualifiedPath() { var fields = catalogue(); var group = group(file("a")); group.files = Map.of("C:escape.jar", file("a")); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -198,7 +247,7 @@ void rejectsCaseVariantOfReservedMetadataPath() { var fields = catalogue(); var group = group(file("a")); group.files = Map.of("AUTOMODPACK-CONTENT.JSON", file("a")); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -208,7 +257,7 @@ void rejectsInvalidGraphAndUnsafePath() { var group = group(file("a")); group.requires = Set.of("missing"); group.files = Map.of("../escape", file("a")); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -217,7 +266,7 @@ void ignoresALeftoverTypeFieldOnFileMetadata() { var file = ConfigTools.GSON.fromJson("{\"size\":\"1\",\"type\":\"other\",\"editable\":false,\"sha1\":\"86f7e437faa5a7fce15d1ddcb9eaeaea377667b8\"}", ModpackJsons.CompleteModpackContentFields.GroupFileFields.class); var fields = catalogue(); - fields.categories = oneCategory("main", groupAt("mods/example.jar", file)); + fields.groups = linkedGroups("main", groupAt("mods/example.jar", file)); assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); } @@ -225,7 +274,7 @@ void ignoresALeftoverTypeFieldOnFileMetadata() { void rejectsReservedRoots() { for (String invalid : List.of("saves/world.dat", "logs/latest.log", "screenshots/image.png")) { var fields = catalogue(); - fields.categories = oneCategory("main", groupAt(invalid, fileOfType("other"))); + fields.groups = linkedGroups("main", groupAt(invalid, fileOfType("other"))); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields), invalid); } } @@ -234,7 +283,7 @@ void rejectsReservedRoots() { void acceptsModFilesAtAnyNonReservedPath() { for (String path : List.of("mods/example.jar", "resourcepacks/example.jar", "shaderpacks/example.jar", "config/example.jar", "outside/example.jar")) { var fields = catalogue(); - fields.categories = oneCategory("main", groupAt(path, fileOfType("mod"))); + fields.groups = linkedGroups("main", groupAt(path, fileOfType("mod"))); assertDoesNotThrow(() -> GroupManifestValidator.validate(fields), path); } } @@ -242,7 +291,7 @@ void acceptsModFilesAtAnyNonReservedPath() { @Test void acceptsGenericFilesInsideMods() { var fields = catalogue(); - fields.categories = oneCategory("main", groupAt("mods/README.txt", fileOfType("other"))); + fields.groups = linkedGroups("main", groupAt("mods/README.txt", fileOfType("other"))); assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); } @@ -252,7 +301,7 @@ void rejectsReservedRootFilesAndCaseVariantsForMods() { for (String path : List.of("mods", "config", "shaderpacks", "resourcepacks", "MODS/example.jar", "Config/example.jar", "ShaderPacks/example.jar", "ResourcePacks/example.jar")) { var fields = catalogue(); - fields.categories = oneCategory("main", groupAt(path, fileOfType("mod"))); + fields.groups = linkedGroups("main", groupAt(path, fileOfType("mod"))); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields), path); } } @@ -260,7 +309,7 @@ void rejectsReservedRootFilesAndCaseVariantsForMods() { @Test void rejectsCoSelectableModsThatShareALiveBasename() { var fields = catalogue(); - fields.categories = oneCategory("main", groupAt("mods/main.jar", fileOfType("mod")), "visuals", groupAt("mods/nested/main.jar", fileOfType("mod"))); + fields.groups = linkedGroups("main", groupAt("mods/main.jar", fileOfType("mod")), "visuals", groupAt("mods/nested/main.jar", fileOfType("mod"))); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -270,7 +319,7 @@ void rejectsFileDirectoryConflictWithinOneGroup() { var fields = catalogue(); var group = group(fileOfType("mod")); group.files = Map.of("outside", fileOfType("mod"), "outside/nested.jar", fileOfType("mod")); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -278,7 +327,7 @@ void rejectsFileDirectoryConflictWithinOneGroup() { @Test void rejectsCoSelectableFileDirectoryConflict() { var fields = catalogue(); - fields.categories = oneCategory("main", groupAt("outside", fileOfType("mod")), "visuals", groupAt("outside/nested.jar", fileOfType("mod"))); + fields.groups = linkedGroups("main", groupAt("outside", fileOfType("mod")), "visuals", groupAt("outside/nested.jar", fileOfType("mod"))); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -286,6 +335,7 @@ void rejectsCoSelectableFileDirectoryConflict() { @Test void prefixWalkReportsEveryAncestorConflictOfANestedAndAliasedCatalogue() { var fields = catalogue(); + fields.categories = linkedCategories("pair", category("Pair", CategoryPickMode.AT_MOST_ONE)); var trunk = group(fileOfType("mod")); trunk.compatiblePlatforms = Set.of("linux"); trunk.files = Map.of("outside/t", fileOfType("mod"), "outside/t/u", fileOfType("mod"), "outside/t/u/v.jar", fileOfType("mod")); @@ -296,11 +346,12 @@ void prefixWalkReportsEveryAncestorConflictOfANestedAndAliasedCatalogue() { var fork3 = groupAt("outside/k/z.jar", fileOfType("mod")); fork3.compatiblePlatforms = Set.of("linux"); var exclusive = groupAt("outside/e", fileOfType("mod")); + exclusive.category = "pair"; exclusive.compatiblePlatforms = Set.of("linux"); - exclusive.breaksWith = Set.of("leaf"); var leaf = groupAt("outside/e/f.jar", fileOfType("mod")); + leaf.category = "pair"; leaf.compatiblePlatforms = Set.of("linux"); - fields.categories = oneCategory("trunk", trunk, "fork1", fork1, "fork2", fork2, "fork3", fork3, "exclusive", exclusive, "leaf", leaf); + fields.groups = linkedGroups("trunk", trunk, "fork1", fork1, "fork2", fork2, "fork3", fork3, "exclusive", exclusive, "leaf", leaf); // The aliased key 'outside/k' (two owners) pairs with the descendant once per owner, the chain pairs every // ancestor depth once, and the mutually exclusive pair is silent: exactly the pairwise scan's conflict set. @@ -313,11 +364,14 @@ void prefixWalkReportsEveryAncestorConflictOfANestedAndAliasedCatalogue() { } @Test - void acceptsFileDirectoryPathsForMutuallyExclusiveGroups() { + void acceptsFileDirectoryPathsForExclusiveGroups() { var fields = catalogue(); + fields.categories = linkedCategories("pair", category("Pair", CategoryPickMode.AT_MOST_ONE)); var first = groupAt("outside", fileOfType("mod")); - first.breaksWith = Set.of("second"); - fields.categories = oneCategory("first", first, "second", groupAt("outside/nested.jar", fileOfType("mod"))); + first.category = "pair"; + var second = groupAt("outside/nested.jar", fileOfType("mod")); + second.category = "pair"; + fields.groups = linkedGroups("first", first, "second", second); assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); } @@ -325,7 +379,7 @@ void acceptsFileDirectoryPathsForMutuallyExclusiveGroups() { @Test void acceptsSameModBasenameOutsideLiveModsDirectory() { var fields = catalogue(); - fields.categories = oneCategory("main", groupAt("mods/main.jar", fileOfType("mod")), "resourcepack", groupAt("resourcepacks/main.jar", fileOfType("mod")), + fields.groups = linkedGroups("main", groupAt("mods/main.jar", fileOfType("mod")), "resourcepack", groupAt("resourcepacks/main.jar", fileOfType("mod")), "shaderpack", groupAt("shaderpacks/main.jar", fileOfType("mod"))); assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); @@ -337,7 +391,7 @@ void rejectsWindowsIllegalAndReservedComponents() { var group = group(file("a")); group.compatiblePlatforms = Set.of("windows"); group.files = Map.of("mods/CON.txt", file("a"), "config/bad?.json", file("a")); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @@ -347,47 +401,43 @@ void rejectsCaseAliasForWindowsButAllowsItForLinuxOnly() { var windowsGroup = group(file("a")); windowsGroup.compatiblePlatforms = Set.of("windows"); windowsGroup.files = Map.of("mods/A.jar", file("a"), "mods/a.jar", file("a")); - windows.categories = oneCategory("main", windowsGroup); + windows.groups = linkedGroups("main", windowsGroup); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(windows)); var linux = catalogue(); var linuxGroup = group(file("a")); linuxGroup.compatiblePlatforms = Set.of("linux"); linuxGroup.files = Map.of("mods/A.jar", file("a"), "mods/a.jar", file("a")); - linux.categories = oneCategory("main", linuxGroup); + linux.groups = linkedGroups("main", linuxGroup); assertDoesNotThrow(() -> GroupManifestValidator.validate(linux)); } @Test - void acceptsConflictingGroupsInOneCategoryUntilRequestedTogether() { - var fields = catalogue(); - var first = group(file("a")); - first.breaksWith = Set.of("second"); - var second = group(file("a")); - fields.categories = linkedCategories("bundle", linkedGroups("first", first, "second", second)); - - assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); - } - - @Test - void rejectsDifferentSamePathContentInsideOneCategoryBundle() { + void rejectsDifferentSamePathContentInsideAnyCategory() { var fields = catalogue(); + fields.categories = linkedCategories("bundle", category("Bundle", CategoryPickMode.ANY)); var first = group(file("a")); + first.category = "bundle"; var second = group(file("b")); - fields.categories = linkedCategories("bundle", linkedGroups("first", first, "second", second)); + second.category = "bundle"; + fields.groups = linkedGroups("first", first, "second", second); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); } @Test - void acceptsCategoryWithDependencyConflictUntilRequestedTogether() { + void rejectsDependencyCrossingBackIntoExclusiveCategoryFromOtherGroup() { var fields = catalogue(); - var dependency = group(file("a")); + fields.categories = linkedCategories("mode", category("Mode", CategoryPickMode.EXACTLY_ONE)); var first = group(file("a")); - first.requires = Set.of("dependency"); + first.category = "mode"; + first.selection = GroupSelectionMode.RECOMMENDED; var second = group(file("a")); - second.breaksWith = Set.of("dependency"); - fields.categories = linkedCategories("bundle", linkedGroups("first", first, "second", second), "General", linkedGroups("dependency", dependency)); + second.category = "mode"; + second.selection = GroupSelectionMode.OPTIONAL; + var wrapper = group(file("a")); + wrapper.requires = Set.of("second"); + fields.groups = linkedGroups("first", first, "second", second, "wrapper", wrapper); assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); } @@ -397,7 +447,7 @@ void acceptsAdminDeclaredPlatformAndRejectsBlankNames() { var fields = catalogue(); var group = group(file("a")); group.compatiblePlatforms = Set.of("Android"); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); GroupManifest manifest = GroupManifestValidator.validate(fields); @@ -407,7 +457,7 @@ void acceptsAdminDeclaredPlatformAndRejectsBlankNames() { var blank = catalogue(); var blankGroup = group(file("a")); blankGroup.compatiblePlatforms = Set.of(" "); - blank.categories = oneCategory("main", blankGroup); + blank.groups = linkedGroups("main", blankGroup); assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(blank)); } @@ -415,12 +465,12 @@ void acceptsAdminDeclaredPlatformAndRejectsBlankNames() { void validatesRulesForDeclaredOnlyPlatforms() { var fields = catalogue(); var app = group(file("a")); - app.required = true; + app.selection = GroupSelectionMode.REQUIRED; app.compatiblePlatforms = Set.of("android"); app.requires = Set.of("win-lib"); var winLib = group(file("a")); winLib.compatiblePlatforms = Set.of("windows"); - fields.categories = oneCategory("app", app, "win-lib", winLib); + fields.groups = linkedGroups("app", app, "win-lib", winLib); // No detectable platform can see this graph, so only the declared android coverage can reject the impossible requirement. GroupValidationException failure = assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); @@ -432,10 +482,9 @@ void validatesRulesForDeclaredOnlyPlatforms() { void publishingRefusesNamesOnlyABroaderCaseFoldJoinsWhileLoadingKeepsThem() { var fields = catalogue(); var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; group.files = Map.of("config/stra\u00DFe.toml", fileOfType("config"), "config/strasse.toml", fileOfType("config")); - fields.categories = oneCategory("main", group); + fields.groups = linkedGroups("main", group); GroupManifestValidator.validate(fields); GroupValidationException failure = assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validateForPublish(fields)); @@ -446,7 +495,7 @@ void publishingRefusesNamesOnlyABroaderCaseFoldJoinsWhileLoadingKeepsThem() { @Test void theSamePolicyDocumentAlwaysValidatesToTheSameManifest() { var fields = catalogue(); - fields.categories = oneCategory("main", group(file("a"))); + fields.groups = linkedGroups("main", group(file("a"))); GroupManifest first = GroupManifestValidator.validate(fields); @@ -454,21 +503,115 @@ void theSamePolicyDocumentAlwaysValidatesToTheSameManifest() { assertEquals(first.groups(), GroupManifestValidator.validateForPublish(fields).groups(), "publishing validates the same document under the wider rule"); } + @Test + void acceptsOsScopedRequiredGroupOnEveryCoveredPlatform() { + var fields = catalogue(); + var winCore = groupAt("mods/win-core.jar", file("b")); + winCore.selection = GroupSelectionMode.REQUIRED; + winCore.compatiblePlatforms = Set.of("windows"); + winCore.requires = Set.of("win-lib"); + var winLib = groupAt("mods/win-lib.jar", file("c")); + winLib.compatiblePlatforms = Set.of("windows"); + fields.groups = linkedGroups("main", group(file("a")), "win-core", winCore, "win-lib", winLib); + + GroupManifest manifest = GroupManifestValidator.validate(fields); + + assertTrue(manifest.groups().get("win-core").supports(ClientPlatform.WINDOWS)); + assertFalse(manifest.groups().get("win-core").supports(ClientPlatform.LINUX)); + } + + @Test + void rejectsSelfConflictAndUnknownConflictTarget() { + var self = catalogue(); + var selfGroup = group(file("a")); + selfGroup.conflicts = Set.of("main"); + self.groups = linkedGroups("main", selfGroup); + GroupValidationException selfFailure = assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(self)); + assertTrue(selfFailure.getMessage().contains("cannot conflict with itself"), selfFailure.getMessage()); + + var unknown = catalogue(); + var unknownGroup = group(file("a")); + unknownGroup.conflicts = Set.of("missing"); + unknown.groups = linkedGroups("main", unknownGroup); + GroupValidationException unknownFailure = assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(unknown)); + assertTrue(unknownFailure.getMessage().contains("conflicts with missing group 'missing'"), unknownFailure.getMessage()); + } + + @Test + void acceptsOverlappingFilesBetweenGroupsThatConflict() { + var fields = catalogue(); + var first = group(file("a")); + first.conflicts = Set.of("second"); + var second = group(file("b")); + fields.groups = linkedGroups("first", first, "second", second); + + assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); + } + + @Test + void rejectsTwoConflictingRecommendedDefaults() { + var fields = catalogue(); + var first = group(file("a")); + first.selection = GroupSelectionMode.RECOMMENDED; + first.conflicts = Set.of("second"); + var second = groupAt("mods/second.jar", file("b")); + second.selection = GroupSelectionMode.RECOMMENDED; + fields.groups = linkedGroups("first", first, "second", second); + + assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validate(fields)); + } + + @Test + void acceptsOptionalGroupThatConflictsWithARecommendedDefault() { + var fields = catalogue(); + var recommended = group(file("a")); + recommended.selection = GroupSelectionMode.RECOMMENDED; + var optional = groupAt("mods/optional.jar", file("b")); + optional.conflicts = Set.of("recommended"); + fields.groups = linkedGroups("recommended", recommended, "optional", optional); + + assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); + } + + @Test + void acceptsOptionalWhoseAutomaticDependencyConflictsWithRecommended() { + var fields = catalogue(); + var core = groupAt("mods/core.jar", file("a")); + core.selection = GroupSelectionMode.REQUIRED; + var engine = groupAt("mods/engine.jar", file("a")); + engine.selection = GroupSelectionMode.AUTOMATIC; + var recommended = groupAt("mods/recommended.jar", file("a")); + recommended.selection = GroupSelectionMode.RECOMMENDED; + recommended.conflicts = Set.of("engine"); + var optional = groupAt("mods/optional.jar", file("b")); + optional.selection = GroupSelectionMode.OPTIONAL; + optional.requires = Set.of("engine"); + fields.groups = linkedGroups("main", core, "engine", engine, "recommended", recommended, "optional", optional); + + assertDoesNotThrow(() -> GroupManifestValidator.validate(fields)); + } + private static ModpackJsons.CompleteModpackContentFields catalogue() { var fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; - fields.categories = new LinkedHashMap<>(); + fields.groups = new LinkedHashMap<>(); return fields; } + private static ModpackJsons.CompleteModpackContentFields.CategoryFields category(String name, CategoryPickMode pick) { + var cat = new ModpackJsons.CompleteModpackContentFields.CategoryFields(); + cat.name = name; + cat.pick = pick; + return cat; + } + private static ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group(ModpackJsons.CompleteModpackContentFields.GroupFileFields file) { return groupAt("mods/example.jar", file); } private static ModpackJsons.CompleteModpackContentFields.ModpackGroupFields groupAt(String path, ModpackJsons.CompleteModpackContentFields.GroupFileFields file) { var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.files = Map.of(path, file); return group; } @@ -494,14 +637,9 @@ private static Map> linkedCategories(Object... values) { - Map> categories = new LinkedHashMap<>(); - for (int i = 0; i < values.length; i += 2) - categories.put((String) values[i], (Map) values[i + 1]); + private static Map linkedCategories(Object... values) { + Map categories = new LinkedHashMap<>(); + for (int i = 0; i < values.length; i += 2) categories.put((String) values[i], (ModpackJsons.CompleteModpackContentFields.CategoryFields) values[i + 1]); return categories; } - - private static Map> oneCategory(Object... values) { - return linkedCategories("General", linkedGroups(values)); - } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionResolverTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionResolverTest.java index 5d3e8b246..803ead040 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionResolverTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/GroupSelectionResolverTest.java @@ -8,165 +8,338 @@ class GroupSelectionResolverTest { @Test - void defaultSelectedGroupsEnterOnlyTheNewDefaultIntent() { - GroupManifest manifest = manifest(Map.of("default", group(GroupSelectionMode.RECOMMENDED, Set.of()), "optional", group(GroupSelectionMode.OPTIONAL, Set.of()))); + void recommendedArrivesSelectedUnderDefaultsAndRespectsExplicitOptOut() { + GroupManifest manifest = manifest(Map.of(), + Map.of("main", group(GroupSelectionMode.REQUIRED, Set.of()), "default", group(GroupSelectionMode.RECOMMENDED, Set.of()), + "optional", group(GroupSelectionMode.OPTIONAL, Set.of()))); - SelectionIntent defaults = GroupSelectionResolver.defaultIntent(manifest); - - assertEquals(Set.of("default"), defaults.requestedGroups()); - assertEquals(Set.of(), GroupSelectionResolver.resolve(manifest, new SelectionIntent(Set.of()), ClientPlatform.LINUX).selectedGroups()); - assertEquals(Set.of("default"), GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.LINUX).selectedGroups()); + ResolvedSelection defaults = GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.LINUX); + assertEquals(Set.of("main", "default"), defaults.selectedGroups()); + assertEquals(Set.of("main", "default"), GroupSelectionResolver.resolve(manifest, SelectionIntent.DEFAULTS, ClientPlatform.LINUX).selectedGroups()); + + GroupSelectionResolver.SelectionUpdate optedOut = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "default", ClientPlatform.LINUX); + assertEquals("", optedOut.error()); + assertEquals(Set.of("default"), optedOut.intent().disabled()); + assertEquals(Set.of("main"), optedOut.resolution().selectedGroups()); + + // A new RECOMMENDED group added later still arrives selected automatically without wiping prior opt-out. + GroupManifest evolved = manifest(Map.of(), + Map.of("main", group(GroupSelectionMode.REQUIRED, Set.of()), "default", group(GroupSelectionMode.RECOMMENDED, Set.of()), + "new-rec", group(GroupSelectionMode.RECOMMENDED, Set.of()))); + ResolvedSelection resolvedEvolved = GroupSelectionResolver.resolve(evolved, optedOut.intent(), ClientPlatform.LINUX); + assertEquals(Set.of("main", "new-rec"), resolvedEvolved.selectedGroups()); } @Test - void requiredGroupsRemainDistinctFromDefaultSelectedIntent() { - GroupManifest manifest = manifest(Map.of("required", group(GroupSelectionMode.REQUIRED, Set.of()), "default", group(GroupSelectionMode.RECOMMENDED, Set.of()))); + void aSavedEnableThisPlatformCannotInstallIsReportedNotFatal() { + GroupManifest manifest = manifest(Map.of(), + Map.of("windows", new GroupManifest.Group("Windows", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(ClientPlatform.WINDOWS), new TreeMap<>()))); - SelectionIntent defaults = GroupSelectionResolver.defaultIntent(manifest); - - assertEquals(Set.of("default"), defaults.requestedGroups()); - assertEquals(Set.of("default", "required"), GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.LINUX).selectedGroups()); - } + ResolvedSelection resolved = GroupSelectionResolver.resolve(manifest, SelectionIntent.ofEnabled(Set.of("windows")), ClientPlatform.LINUX); - @Test - void explicitlyRequestedUnavailableOptionalGroupInvalidatesResolution() { - GroupManifest manifest = manifest(Map.of("windows", new GroupManifest.Group("Windows", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), - Set.of(ClientPlatform.WINDOWS), new TreeMap<>()))); - - SelectionResolutionException failure = assertThrows(SelectionResolutionException.class, - () -> GroupSelectionResolver.resolve(manifest, new SelectionIntent(Set.of("windows")), ClientPlatform.LINUX)); + assertEquals(Set.of(), resolved.selectedGroups(), "the pick cannot install here, so the projection leaves it out"); + assertEquals(Set.of("windows"), resolved.requestedUnavailableGroups()); + assertEquals(Set.of("windows"), resolved.unavailableGroups()); - assertEquals(Set.of("windows"), failure.resolution().requestedUnavailableGroups()); - assertEquals(Set.of("windows"), failure.resolution().unavailableGroups()); - assertTrue(failure.errors().get(0).contains("explicitly requested")); + GroupSelectionResolver.SelectionUpdate refused = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "windows", ClientPlatform.LINUX); + assertFalse(refused.error().isEmpty(), "asking for it here is still refused at the point of the click"); + assertEquals(SelectionIntent.DEFAULTS, refused.intent()); } @Test - void explicitlyRequestedOptionalGroupBlockedByUnavailableDependencyIsHonest() { - GroupManifest.Group dependency = new GroupManifest.Group("Dependency", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(ClientPlatform.WINDOWS), new TreeMap<>()); - GroupManifest.Group feature = new GroupManifest.Group("Feature", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(Set.of("dependency")), Set.of(), new TreeMap<>()); - GroupManifest manifest = manifest(Map.of("dependency", dependency, "feature", feature)); - - SelectionResolutionException failure = assertThrows(SelectionResolutionException.class, - () -> GroupSelectionResolver.resolve(manifest, new SelectionIntent(Set.of("feature")), ClientPlatform.LINUX)); - - assertEquals(Set.of("feature"), failure.resolution().requestedUnavailableGroups()); - assertEquals(GroupResolution.Status.BLOCKED, failure.resolution().resolution("feature").status()); - assertEquals(Set.of("dependency"), failure.resolution().resolution("feature").relatedGroups()); + void aSavedEnableBlockedByAnUnavailableDependencyIsReportedAndClearable() { + GroupManifest.Group dependency = new GroupManifest.Group("Dependency", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(ClientPlatform.WINDOWS), new TreeMap<>()); + GroupManifest.Group feature = new GroupManifest.Group("Feature", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(Set.of("dependency")), Set.of(), new TreeMap<>()); + GroupManifest manifest = manifest(Map.of(), Map.of("dependency", dependency, "feature", feature)); + + ResolvedSelection resolved = GroupSelectionResolver.resolve(manifest, SelectionIntent.ofEnabled(Set.of("feature")), ClientPlatform.LINUX); + assertEquals(Set.of(), resolved.selectedGroups()); + assertEquals(Set.of("feature"), resolved.requestedUnavailableGroups()); + assertEquals(GroupResolution.Status.BLOCKED, resolved.resolution("feature").status()); + assertEquals(Set.of("dependency"), resolved.resolution("feature").relatedGroups()); + + GroupSelectionResolver.SelectionUpdate refused = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "feature", ClientPlatform.LINUX); + assertTrue(refused.error().contains("feature") && refused.error().contains("dependency"), refused.error()); + // The row carrying the ignored ask stays clickable, and the click forgets it instead of re-asking. + GroupSelectionResolver.SelectionUpdate cleared = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.ofEnabled(Set.of("feature")), "feature", ClientPlatform.LINUX); + assertEquals("", cleared.error()); + assertEquals(Set.of(), cleared.intent().enabled()); + assertEquals(Set.of(), cleared.resolution().selectedGroups()); } @Test void unsupportedGroupsNeverRequestedRemainOutsideRequestedUnavailableSubset() { - GroupManifest manifest = manifest(Map.of("windows", new GroupManifest.Group("Windows", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), - Set.of(ClientPlatform.WINDOWS), new TreeMap<>()))); + GroupManifest manifest = manifest(Map.of(), + Map.of("windows", new GroupManifest.Group("Windows", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(ClientPlatform.WINDOWS), new TreeMap<>()))); - ResolvedSelection resolved = GroupSelectionResolver.resolve(manifest, new SelectionIntent(Set.of()), ClientPlatform.LINUX); + ResolvedSelection resolved = GroupSelectionResolver.resolve(manifest, SelectionIntent.DEFAULTS, ClientPlatform.LINUX); assertEquals(Set.of("windows"), resolved.unavailableGroups()); assertTrue(resolved.requestedUnavailableGroups().isEmpty()); } @Test - void dependencyExplanationNamesTheSelectedGroupThatRequiresIt() { - GroupManifest manifest = manifest(Map.of("dependency", group(GroupSelectionMode.OPTIONAL, Set.of()), "feature", group(GroupSelectionMode.OPTIONAL, Set.of("dependency")))); + void dependencyExplanationAndAutomaticActivationFollowDependents() { + GroupManifest manifest = manifest(Map.of(), + Map.of("shader-base", group(GroupSelectionMode.AUTOMATIC, Set.of()), "iris", group(GroupSelectionMode.OPTIONAL, Set.of("shader-base")))); - ResolvedSelection resolved = GroupSelectionResolver.resolve(manifest, new SelectionIntent(Set.of("feature")), ClientPlatform.LINUX); + assertEquals(Set.of(), GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.LINUX).selectedGroups()); - assertEquals(Set.of("feature"), resolved.resolution("dependency").relatedGroups()); + GroupSelectionResolver.SelectionUpdate enabled = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "iris", ClientPlatform.LINUX); + assertEquals(Set.of("iris", "shader-base"), enabled.resolution().selectedGroups()); + assertEquals(Set.of("shader-base"), enabled.resolution().dependencyGroups()); + assertEquals(Set.of("iris"), enabled.resolution().resolution("shader-base").relatedGroups()); + + GroupSelectionResolver.SelectionUpdate disabled = GroupSelectionResolver.toggleGroup(manifest, enabled.intent(), "iris", ClientPlatform.LINUX); + assertEquals(Set.of(), disabled.resolution().selectedGroups()); } @Test - void categoryTogglePersistsCategoryWithoutPretendingItsGroupsWereClicked() { - GroupManifest manifest = manifest(Map.of("one", categorized("one", ClientPlatform.LINUX), "two", categorized("two", ClientPlatform.LINUX))); - - SelectionIntent selected = GroupSelectionResolver.preferCategory(manifest, new SelectionIntent(Set.of()), "visuals", ClientPlatform.LINUX); - - assertEquals(Set.of(), selected.requestedGroups()); - assertEquals(Set.of("visuals"), selected.requestedCategories()); - assertEquals(Set.of("one", "two"), GroupSelectionResolver.resolve(manifest, selected, ClientPlatform.LINUX).selectedGroups()); - assertEquals(Set.of(), selected.excludedGroups()); + void uncheckingDependencyCascadesToDependentsAndRequiredGroupRefusesUncheck() { + GroupManifest manifest = manifest(Map.of(), + Map.of("main", group(GroupSelectionMode.REQUIRED, Set.of()), "base", group(GroupSelectionMode.OPTIONAL, Set.of()), + "addon", group(GroupSelectionMode.OPTIONAL, Set.of("base")))); + + SelectionIntent both = SelectionIntent.ofEnabled(Set.of("base", "addon")); + GroupSelectionResolver.SelectionUpdate turnedOffBase = GroupSelectionResolver.toggleGroup(manifest, both, "base", ClientPlatform.LINUX); + assertEquals("", turnedOffBase.error()); + assertEquals(Set.of("main"), turnedOffBase.resolution().selectedGroups()); + assertEquals(Set.of("addon"), turnedOffBase.turnedOff()); + + GroupSelectionResolver.SelectionUpdate tryMain = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "main", ClientPlatform.LINUX); + assertFalse(tryMain.error().isEmpty()); + assertEquals(SelectionIntent.DEFAULTS, tryMain.intent()); } @Test - void individualGroupDoesNotSelectItsSingleGroupCategory() { - GroupManifest manifest = manifest(Map.of("one", categorized("one", ClientPlatform.LINUX))); + void exclusiveCategoriesEnforceAtMostOneAndExactlyOne() { + GroupManifest manifest = manifest( + Map.of("shaders", new GroupManifest.Category("Shaders", "", CategoryPickMode.AT_MOST_ONE), + "minimap", new GroupManifest.Category("Minimap", "", CategoryPickMode.EXACTLY_ONE)), + Map.of("bsl", categorized(GroupSelectionMode.RECOMMENDED, "shaders"), + "complementary", categorized(GroupSelectionMode.OPTIONAL, "shaders"), + "xaero", categorized(GroupSelectionMode.RECOMMENDED, "minimap"), + "journeymap", categorized(GroupSelectionMode.OPTIONAL, "minimap"))); - SelectionIntent selected = GroupSelectionResolver.prefer(manifest, new SelectionIntent(Set.of()), "one", ClientPlatform.LINUX); - - assertEquals(Set.of("one"), selected.requestedGroups()); - assertTrue(selected.requestedCategories().isEmpty()); - } + ResolvedSelection defaults = GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.LINUX); + assertEquals(Set.of("bsl", "xaero"), defaults.selectedGroups()); - @Test - void changingAChildConvertsTheRestOfItsSelectedCategoryToIndividualChoices() { - GroupManifest manifest = manifest(Map.of("one", categorized("one", ClientPlatform.LINUX), "two", categorized("two", ClientPlatform.LINUX))); - SelectionIntent category = GroupSelectionResolver.preferCategory(manifest, new SelectionIntent(Set.of()), "visuals", ClientPlatform.LINUX); + GroupSelectionResolver.SelectionUpdate switchShader = GroupSelectionResolver.pickInCategory(manifest, SelectionIntent.DEFAULTS, "shaders", "complementary", ClientPlatform.LINUX); + assertEquals("", switchShader.error()); + assertEquals(Set.of("complementary", "xaero"), switchShader.resolution().selectedGroups()); - SelectionIntent changed = GroupSelectionResolver.prefer(manifest, category, "one", ClientPlatform.LINUX); + GroupSelectionResolver.SelectionUpdate clearShader = GroupSelectionResolver.pickInCategory(manifest, switchShader.intent(), "shaders", "", ClientPlatform.LINUX); + assertEquals("", clearShader.error()); + assertEquals(Set.of("xaero"), clearShader.resolution().selectedGroups()); - assertEquals(Set.of("two"), changed.requestedGroups()); - assertTrue(changed.requestedCategories().isEmpty()); + GroupSelectionResolver.SelectionUpdate tryClearMinimap = GroupSelectionResolver.pickInCategory(manifest, clearShader.intent(), "minimap", "", ClientPlatform.LINUX); + assertFalse(tryClearMinimap.error().isEmpty()); + assertEquals(Set.of("xaero"), tryClearMinimap.resolution().selectedGroups()); } @Test - void conflictReplacementKeepsSafeMembersOfASelectedCategory() { - GroupManifest.Group dependency = group(GroupSelectionMode.OPTIONAL, Set.of()); - GroupManifest.Group oldFeature = new GroupManifest.Group("Old feature", "", "visuals", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(Set.of("dependency")), Set.of(ClientPlatform.LINUX), - new TreeMap<>()); - GroupManifest.Group safeFeature = categorized("Safe feature", ClientPlatform.LINUX); - GroupManifest.Group preferred = new GroupManifest.Group("Preferred", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(Set.of("dependency")), new TreeSet<>(), Set.of(), new TreeMap<>()); - GroupManifest manifest = manifest(Map.of("dependency", dependency, "old", oldFeature, "safe", safeFeature, "preferred", preferred)); - SelectionIntent category = GroupSelectionResolver.preferCategory(manifest, new SelectionIntent(Set.of()), "visuals", ClientPlatform.LINUX); - SelectionIntent candidate = GroupSelectionResolver.prefer(manifest, category, "preferred", ClientPlatform.LINUX); - SelectionResolutionException failure = assertThrows(SelectionResolutionException.class, () -> GroupSelectionResolver.resolve(manifest, candidate, ClientPlatform.LINUX)); + void setCategoryAllSelectsOrClearsOnlyCompatibleMembersInAnyCategory() { + GroupManifest manifest = manifest(Map.of("visuals", new GroupManifest.Category("Visuals", "", CategoryPickMode.ANY)), + Map.of("one", new GroupManifest.Group("One", "", "visuals", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(ClientPlatform.LINUX), Map.of()), + "two", new GroupManifest.Group("Two", "", "visuals", GroupSelectionMode.RECOMMENDED, Set.of(), Set.of(ClientPlatform.LINUX), Map.of()), + "win", new GroupManifest.Group("Win", "", "visuals", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(ClientPlatform.WINDOWS), Map.of()))); - GroupSelectionResolver.ConflictReplacement replacement = GroupSelectionResolver.replaceConflicts(manifest, candidate, Set.of("preferred"), ClientPlatform.LINUX, failure.resolution()).orElseThrow(); + GroupSelectionResolver.SelectionUpdate selectedAll = GroupSelectionResolver.setCategoryAll(manifest, SelectionIntent.DEFAULTS, "visuals", true, ClientPlatform.LINUX); + assertEquals(Set.of("one", "two"), selectedAll.resolution().selectedGroups()); - assertTrue(replacement.intent().requestedCategories().isEmpty()); - assertEquals(Set.of("preferred", "safe"), replacement.intent().requestedGroups()); - assertEquals(Set.of("dependency"), replacement.conflictingGroups()); - assertEquals(Set.of("preferred", "safe"), GroupSelectionResolver.resolve(manifest, replacement.intent(), ClientPlatform.LINUX).selectedGroups()); + GroupSelectionResolver.SelectionUpdate clearedAll = GroupSelectionResolver.setCategoryAll(manifest, selectedAll.intent(), "visuals", false, ClientPlatform.LINUX); + assertEquals(Set.of(), clearedAll.resolution().selectedGroups()); } @Test void declaredOnlyPlatformGroupIsNotAutoMatchedButIsSelectable() { ClientPlatform android = ClientPlatform.parse("android"); - GroupManifest.Group mobile = new GroupManifest.Group("Mobile", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(android), new TreeMap<>()); - GroupManifest.Group desktop = new GroupManifest.Group("Desktop", "", "General", GroupSelectionMode.RECOMMENDED, new TreeSet<>(), new TreeSet<>(), Set.of(ClientPlatform.LINUX), new TreeMap<>()); - GroupManifest manifest = manifest(Map.of("mobile", mobile, "desktop", desktop)); + GroupManifest.Group mobile = new GroupManifest.Group("Mobile", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(android), new TreeMap<>()); + GroupManifest.Group desktop = new GroupManifest.Group("Desktop", "", "", GroupSelectionMode.RECOMMENDED, new TreeSet<>(), Set.of(ClientPlatform.LINUX), new TreeMap<>()); + GroupManifest manifest = manifest(Map.of(), Map.of("mobile", mobile, "desktop", desktop)); - // Auto-detection never yields android, so the group stays out of the default resolution... ResolvedSelection defaults = GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.LINUX); assertFalse(defaults.selectedGroups().contains("mobile")); assertEquals(GroupResolution.Status.UNAVAILABLE, defaults.resolution("mobile").status()); assertEquals(Set.of("desktop"), defaults.selectedGroups()); - // ...but an explicit choice of that platform selects it. - SelectionIntent intent = new SelectionIntent(List.of("mobile"), List.of(), List.of(), android); + SelectionIntent intent = new SelectionIntent(Set.of("mobile"), Set.of(), android); assertTrue(GroupSelectionResolver.resolve(manifest, intent, android).selectedGroups().contains("mobile")); } @Test void noPlatformKeepsOnlyThePlatformAgnosticGroups() { GroupManifest.Group any = group(GroupSelectionMode.RECOMMENDED, Set.of()); - GroupManifest.Group windows = new GroupManifest.Group("Windows", "", "General", GroupSelectionMode.RECOMMENDED, new TreeSet<>(), new TreeSet<>(), Set.of(ClientPlatform.WINDOWS), new TreeMap<>()); - GroupManifest manifest = manifest(Map.of("any", any, "windows", windows)); + GroupManifest.Group windows = new GroupManifest.Group("Windows", "", "", GroupSelectionMode.RECOMMENDED, new TreeSet<>(), Set.of(ClientPlatform.WINDOWS), new TreeMap<>()); + GroupManifest manifest = manifest(Map.of(), Map.of("any", any, "windows", windows)); - // Without a detected or chosen platform nothing is known, so platform-specific groups fall away and agnostic ones stay. ResolvedSelection defaults = GroupSelectionResolver.resolveDefault(manifest, null); assertEquals(Set.of("any"), defaults.selectedGroups()); assertEquals(GroupResolution.Status.UNAVAILABLE, defaults.resolution("windows").status()); } - private static GroupManifest manifest(Map groups) { - return new GroupManifest("abc1234", "", "", "", "", "", new TreeMap<>(groups)); + @Test + void osScopedRequiredGroupInstallsOnlyOnItsPlatformWithoutError() { + GroupManifest.Group windowsCore = new GroupManifest.Group("Windows Runtime", "", "", GroupSelectionMode.REQUIRED, Set.of(), Set.of(ClientPlatform.WINDOWS), Map.of()); + GroupManifest.Group core = group(GroupSelectionMode.REQUIRED, Set.of()); + GroupManifest manifest = manifest(Map.of(), Map.of("main", core, "win-core", windowsCore)); + + ResolvedSelection windows = GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.WINDOWS); + assertEquals(Set.of("main", "win-core"), windows.selectedGroups()); + assertEquals(Set.of("main", "win-core"), windows.requiredGroups()); + + ResolvedSelection linux = GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.LINUX); + assertEquals(Set.of("main"), linux.selectedGroups()); + assertEquals(Set.of("main"), linux.requiredGroups()); + assertEquals(GroupResolution.Status.UNAVAILABLE, linux.resolution("win-core").status()); + assertTrue(linux.unavailableGroups().contains("win-core")); + } + + @Test + void pairwiseConflictsAreSymmetricInResolutionAndPossibleToDeclareFromEitherSide() { + GroupManifest.Group audio = new GroupManifest.Group("", "", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of(), Set.of("zoom")); + GroupManifest.Group zoom = new GroupManifest.Group("", "", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of(), Set.of()); + GroupManifest manifest = manifest(Map.of(), Map.of("audio", audio, "zoom", zoom)); + + assertEquals(Set.of("zoom"), manifest.conflictsOf("audio")); + assertEquals(Set.of("audio"), manifest.conflictsOf("zoom")); + + SelectionResolutionException failure = assertThrows(SelectionResolutionException.class, + () -> GroupSelectionResolver.resolve(manifest, SelectionIntent.ofEnabled(Set.of("audio", "zoom")), ClientPlatform.LINUX)); + assertTrue(failure.errors().contains("Groups 'audio' and 'zoom' conflict with each other"), failure.errors().toString()); + for (String id : List.of("audio", "zoom")) { + assertEquals(GroupResolution.Status.CONFLICT, failure.resolution().resolution(id).status()); + assertTrue(failure.resolution().resolution(id).reasons().contains(GroupResolution.Reason.PAIRWISE_CONFLICT)); + } + assertEquals(Set.of("zoom"), failure.resolution().resolution("audio").relatedGroups()); + assertEquals(Set.of("audio"), failure.resolution().resolution("zoom").relatedGroups()); + } + + @Test + void enablingAGroupTurnsOffTheConflictingChoosableGroup() { + GroupManifest.Group audio = new GroupManifest.Group("Ambient Sounds", "", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of(), Set.of("zoom")); + GroupManifest.Group zoom = new GroupManifest.Group("Zoomify", "", "", GroupSelectionMode.RECOMMENDED, Set.of(), Set.of(), Map.of()); + GroupManifest manifest = manifest(Map.of(), Map.of("audio", audio, "zoom", zoom)); + + ResolvedSelection defaults = GroupSelectionResolver.resolveDefault(manifest, ClientPlatform.LINUX); + assertEquals(Set.of("zoom"), defaults.selectedGroups()); + + GroupSelectionResolver.SelectionUpdate enabled = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "audio", ClientPlatform.LINUX); + assertEquals("", enabled.error()); + assertEquals(Set.of("audio"), enabled.resolution().selectedGroups()); + assertEquals(Set.of("zoom"), enabled.intent().disabled()); + assertEquals(Set.of("zoom"), enabled.turnedOff()); + } + + @Test + void conflictWithRequiredGroupRefusesTheToggleInsteadOfDroppingTheRequiredGroup() { + GroupManifest.Group core = group(GroupSelectionMode.REQUIRED, Set.of()); + GroupManifest.Group audio = new GroupManifest.Group("Ambient Sounds", "", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of(), Set.of("main")); + GroupManifest manifest = manifest(Map.of(), Map.of("main", core, "audio", audio)); + + GroupSelectionResolver.SelectionUpdate refused = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "audio", ClientPlatform.LINUX); + assertFalse(refused.error().isEmpty()); + assertTrue(refused.error().contains("Ambient Sounds") && refused.error().contains("required"), refused.error()); + assertEquals(SelectionIntent.DEFAULTS, refused.intent()); + assertEquals(Set.of("main"), refused.resolution().selectedGroups()); + } + + @Test + void toggleDisablesDependentOfConflictingAutomaticAndSetCategoryAllClearsExternalConflict() { + GroupManifest.Group core = new GroupManifest.Group("Core", "", "", GroupSelectionMode.REQUIRED, Set.of(), Set.of(), Map.of(), Set.of()); + GroupManifest.Group engine = new GroupManifest.Group("Engine", "", "", GroupSelectionMode.AUTOMATIC, Set.of(), Set.of(), Map.of(), Set.of()); + GroupManifest.Group shaders = new GroupManifest.Group("Shaders", "", "", GroupSelectionMode.RECOMMENDED, Set.of("engine"), Set.of(), Map.of(), Set.of()); + GroupManifest.Group lite = new GroupManifest.Group("Lite Mode", "", "extras", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of(), Set.of("engine")); + GroupManifest manifest = manifest(Map.of("extras", new GroupManifest.Category("Extras", "", CategoryPickMode.ANY)), + Map.of("main", core, "engine", engine, "shaders", shaders, "lite", lite)); + + GroupSelectionResolver.SelectionUpdate toggled = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "lite", ClientPlatform.LINUX); + assertTrue(toggled.ok(), toggled.error()); + assertEquals(Set.of("main", "lite"), toggled.resolution().selectedGroups()); + assertEquals(Set.of("shaders"), toggled.turnedOff()); + assertTrue(toggled.turnedOffByConflict()); + + GroupSelectionResolver.SelectionUpdate bulk = GroupSelectionResolver.setCategoryAll(manifest, SelectionIntent.DEFAULTS, "extras", true, ClientPlatform.LINUX); + assertTrue(bulk.ok(), bulk.error()); + assertEquals(Set.of("main", "lite"), bulk.resolution().selectedGroups()); + assertEquals(Set.of("shaders"), bulk.turnedOff()); + assertTrue(bulk.turnedOffByConflict()); + } + + @Test + void togglingASavedEnableThatThePlatformCannotInstallClearsItInsteadOfRefusing() { + GroupManifest.Group linux = new GroupManifest.Group("Linux Runtime", "", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(ClientPlatform.LINUX), Map.of()); + GroupManifest.Group windows = new GroupManifest.Group("Windows Runtime", "", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(ClientPlatform.WINDOWS), Map.of()); + GroupManifest manifest = manifest(Map.of(), Map.of("linux", linux, "windows", windows)); + + // Saved on Windows, the enable cannot install here; the row stays clickable exactly so the player can clear it. + GroupSelectionResolver.SelectionUpdate cleared = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.ofEnabled(Set.of("windows")), "windows", ClientPlatform.LINUX); + + assertEquals("", cleared.error()); + assertEquals(Set.of(), cleared.intent().enabled()); + assertEquals(Set.of(), cleared.resolution().selectedGroups()); + assertEquals(Set.of(), cleared.turnedOff(), "a group that never installed has no turn-off notice"); + + // Clearing one saved enable leaves the rest alone, and enabling an unavailable group from here still refuses. + assertTrue(GroupSelectionResolver.resolve(manifest, cleared.intent(), ClientPlatform.LINUX).selectedGroups().isEmpty()); + GroupSelectionResolver.SelectionUpdate refused = GroupSelectionResolver.toggleGroup(manifest, SelectionIntent.DEFAULTS, "windows", ClientPlatform.LINUX); + assertFalse(refused.error().isEmpty()); + assertEquals(SelectionIntent.DEFAULTS, refused.intent()); + } + + @Test + void anExclusiveCategorysUnavailableSavedEnableIsClearedTheSameWay() { + GroupManifest.Group shader = new GroupManifest.Group("Windows Shaders", "", "visuals", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(ClientPlatform.WINDOWS), Map.of()); + GroupManifest manifest = manifest(Map.of("visuals", new GroupManifest.Category("Visuals", "", CategoryPickMode.AT_MOST_ONE)), Map.of("shader", shader)); + + GroupSelectionResolver.SelectionUpdate cleared = GroupSelectionResolver.toggleGroup(manifest, new SelectionIntent(Set.of("shader"), Set.of(), ClientPlatform.LINUX), "shader", ClientPlatform.LINUX); + + assertEquals("", cleared.error()); + assertEquals(Set.of(), cleared.intent().enabled()); + assertEquals(Set.of(), cleared.resolution().selectedGroups()); + } + + @Test + void bulkSelectSkipsAGroupWhoseDependencyIsUnavailableHere() { + GroupManifest.Group dependency = new GroupManifest.Group("Dependency", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(ClientPlatform.WINDOWS), new TreeMap<>()); + GroupManifest.Group feature = new GroupManifest.Group("Feature", "", "visuals", GroupSelectionMode.OPTIONAL, new TreeSet<>(Set.of("dependency")), Set.of(), new TreeMap<>()); + GroupManifest.Group plain = new GroupManifest.Group("Plain", "", "visuals", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(), new TreeMap<>()); + GroupManifest manifest = manifest(Map.of("visuals", new GroupManifest.Category("Visuals", "", CategoryPickMode.ANY)), Map.of("dependency", dependency, "feature", feature, "plain", plain)); + + GroupSelectionResolver.SelectionUpdate selectedAll = GroupSelectionResolver.setCategoryAll(manifest, SelectionIntent.DEFAULTS, "visuals", true, ClientPlatform.LINUX); + + assertEquals("", selectedAll.error()); + assertEquals(Set.of("plain"), selectedAll.resolution().selectedGroups(), "select-all leaves out a member this platform cannot install"); + + GroupSelectionResolver.SelectionUpdate clearedAll = GroupSelectionResolver.setCategoryAll(manifest, SelectionIntent.ofEnabled(Set.of("feature")), "visuals", false, ClientPlatform.LINUX); + assertEquals("", clearedAll.error()); + assertEquals(Set.of(), clearedAll.intent().enabled(), "clear-all forgets a saved ask it could not install"); + } + + @Test + void switchingPlatformKeepsAPickThatOnlyAppliesToTheOtherOne() { + GroupManifest.Group windows = new GroupManifest.Group("Windows", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(ClientPlatform.WINDOWS), new TreeMap<>()); + GroupManifest manifest = manifest(Map.of(), Map.of("windows", windows)); + + GroupSelectionResolver.SelectionUpdate linux = GroupSelectionResolver.withPlatform(manifest, SelectionIntent.ofEnabled(Set.of("windows")), ClientPlatform.LINUX, ClientPlatform.LINUX); + assertEquals("", linux.error()); + assertEquals(Set.of("windows"), linux.intent().enabled(), "the pick stays saved"); + assertEquals(Set.of(), linux.resolution().selectedGroups(), "but it cannot install here"); + + GroupSelectionResolver.SelectionUpdate back = GroupSelectionResolver.withPlatform(manifest, linux.intent(), ClientPlatform.WINDOWS, ClientPlatform.WINDOWS); + assertEquals("", back.error()); + assertEquals(Set.of("windows"), back.resolution().selectedGroups()); + } + + private static GroupManifest manifest(Map categories, Map groups) { + return new GroupManifest("abc1234", "", "", "", "", "", new LinkedHashMap<>(categories), new LinkedHashMap<>(groups)); } private static GroupManifest.Group group(GroupSelectionMode selection, Set requires) { - return new GroupManifest.Group("", "", "General", selection, new TreeSet<>(), new TreeSet<>(requires), Set.of(), new TreeMap<>()); + return new GroupManifest.Group("", "", "", selection, new TreeSet<>(requires), Set.of(), new TreeMap<>()); } - private static GroupManifest.Group categorized(String name, ClientPlatform platform) { - return new GroupManifest.Group(name, "", "visuals", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(platform), new TreeMap<>()); + private static GroupManifest.Group categorized(GroupSelectionMode selection, String category) { + return new GroupManifest.Group("", "", category, selection, new TreeSet<>(), Set.of(), new TreeMap<>()); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/PlayerRuntimePathTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/PlayerRuntimePathTest.java index 81e3477d5..184f4e814 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/PlayerRuntimePathTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/PlayerRuntimePathTest.java @@ -17,10 +17,9 @@ void publishingIntoCrashReportsIsRefusedButAnOldPackStillLoads() { ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; group.files = Map.of("crash-reports/old.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields("4", false, "1".repeat(40), "0")); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); GroupValidationException refused = assertThrows(GroupValidationException.class, () -> GroupManifestValidator.validateForPublish(fields)); assertTrue(refused.getMessage().contains("crash-reports/old.txt")); diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/SelectedModpackTargetTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/SelectedModpackTargetTest.java index b99be6939..08cd4a619 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/SelectedModpackTargetTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/SelectedModpackTargetTest.java @@ -16,23 +16,20 @@ class SelectedModpackTargetTest { @Test void invalidPersistedIntentIsReportedWithStructuredResolution() throws Exception { - GroupManifest.Group first = group(Set.of()); - GroupManifest.Group second = new GroupManifest.Group("", "", "General", GroupSelectionMode.RECOMMENDED, new TreeSet<>(Set.of("first")), new TreeSet<>(), Set.of(), new TreeMap<>()); - GroupManifest manifest = new GroupManifest("abc1234", "", "", "", "", "", new TreeMap<>(Map.of("first", first, "second", second))); + GroupManifest.Category exclusive = new GroupManifest.Category("Shaders", "", CategoryPickMode.AT_MOST_ONE); + GroupManifest.Group first = new GroupManifest.Group("", "", "shaders", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(), new TreeMap<>()); + GroupManifest.Group second = new GroupManifest.Group("", "", "shaders", GroupSelectionMode.RECOMMENDED, new TreeSet<>(), Set.of(), new TreeMap<>()); + GroupManifest manifest = new GroupManifest("abc1234", "", "", "", "", "", Map.of("shaders", exclusive), new TreeMap<>(Map.of("first", first, "second", second))); ClientSelectionStore store = new ClientSelectionStore(temporaryDirectory.resolve("selection.json")); - SelectionIntent persisted = new SelectionIntent(Set.of("first", "second")); + SelectionIntent persisted = SelectionIntent.ofEnabled(Set.of("first", "second")); store.put(manifest.modpackId(), persisted); SelectionResolutionException failure = assertThrows(SelectionResolutionException.class, () -> SelectedModpackTarget.prepare(TestPacks.head(manifest), store, ClientPlatform.LINUX)); assertEquals(persisted, failure.resolution().intent()); - assertEquals(Set.of("first", "second"), failure.resolution().selectedGroups()); + assertTrue(failure.resolution().selectedGroups().isEmpty()); assertEquals(GroupResolution.Status.CONFLICT, failure.resolution().resolution("first").status()); assertEquals(GroupResolution.Status.CONFLICT, failure.resolution().resolution("second").status()); } - - private static GroupManifest.Group group(Set breaksWith) { - return new GroupManifest.Group("", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(breaksWith), new TreeSet<>(), Set.of(), new TreeMap<>()); - } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/SelectedTreeComposerTest.java b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/SelectedTreeComposerTest.java index 1c3a98319..4b1d9ee6b 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/modpack/group/SelectedTreeComposerTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/modpack/group/SelectedTreeComposerTest.java @@ -18,9 +18,9 @@ void deduplicatesSharedFileAndKeepsItWhileOneOwnerRemains() { GroupManifest manifest = manifest(Map.of("main", group(file), "visuals", group(file))); var both = SelectedTreeComposer.compose(manifest, - new ResolvedSelection(new SelectionIntent(Set.of("main", "visuals")), new TreeSet<>(Set.of("main", "visuals")), new TreeSet<>())); + GroupSelectionResolver.resolve(manifest, SelectionIntent.ofEnabled(Set.of("main", "visuals")), ClientPlatform.LINUX)); var one = SelectedTreeComposer.compose(manifest, - new ResolvedSelection(new SelectionIntent(Set.of("visuals")), new TreeSet<>(Set.of("visuals")), new TreeSet<>())); + GroupSelectionResolver.resolve(manifest, SelectionIntent.ofEnabled(Set.of("visuals")), ClientPlatform.LINUX)); assertEquals(1, both.list.size()); assertEquals(1, one.list.size()); @@ -34,8 +34,8 @@ void selectionChangeKeepsTargetIdentity() { GroupManifest manifest = manifest(Map.of("main", group(file), "visuals", group(file))); PackDocument document = TestPacks.document(manifest); - SelectedModpackTarget main = SelectedModpackTarget.prepare(TestPacks.head(manifest), null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); - SelectedModpackTarget visuals = SelectedModpackTarget.prepare(TestPacks.head(manifest), null, new SelectionIntent(Set.of("visuals")), ClientPlatform.LINUX); + SelectedModpackTarget main = SelectedModpackTarget.prepare(TestPacks.head(manifest), null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget visuals = SelectedModpackTarget.prepare(TestPacks.head(manifest), null, SelectionIntent.ofEnabled(Set.of("visuals")), ClientPlatform.LINUX); assertEquals(document.contentToken(), main.flatTarget().contentToken); assertEquals(main.flatTarget().contentToken, visuals.flatTarget().contentToken); @@ -52,7 +52,7 @@ void selectsCorrectMutuallyExclusiveVariant() { GroupManifest manifest = manifest(Map.of("first", group(first), "second", group(second))); var target = SelectedTreeComposer.compose(manifest, - new ResolvedSelection(new SelectionIntent(Set.of("second")), new TreeSet<>(Set.of("second")), new TreeSet<>())); + GroupSelectionResolver.resolve(manifest, SelectionIntent.ofEnabled(Set.of("second")), ClientPlatform.LINUX)); assertEquals(second.sha1(), target.list.iterator().next().sha1); } @@ -64,8 +64,8 @@ void composesCompleteCatalogueForPreloadWithoutChangingSelection() { GroupManifest.GroupFile second = new GroupManifest.GroupFile(1, false, "e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98", null); GroupManifest manifest = manifest( - Map.of("main", new GroupManifest.Group("", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("config/first.txt", first))), "optional", - new GroupManifest.Group("", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(), + Map.of("main", new GroupManifest.Group("", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("config/first.txt", first))), "optional", + new GroupManifest.Group("", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("config/second.txt", second))))); SelectedModpackTarget target = SelectedModpackTarget.prepareDefault(TestPacks.head(manifest), ClientPlatform.LINUX); @@ -89,8 +89,8 @@ void selectionSummaryCountsASharedPathOnce() { GroupManifest.GroupFile shared = new GroupManifest.GroupFile(7, false, "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", null); GroupManifest.GroupFile own = new GroupManifest.GroupFile(11, false, "e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98", null); GroupManifest manifest = manifest(Map.of("main", - new GroupManifest.Group("", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/shared.jar", shared))), "visuals", - new GroupManifest.Group("", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(), + new GroupManifest.Group("", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/shared.jar", shared))), "visuals", + new GroupManifest.Group("", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/own.jar", own, "mods/shared.jar", shared))))); assertEquals(new GroupSelectionSummary(18), GroupSelectionSummary.of(manifest, Set.of("main", "visuals"))); @@ -101,18 +101,18 @@ void selectionSummaryCountsSharedContentOnce() { GroupManifest.GroupFile first = new GroupManifest.GroupFile(9, false, "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", null); GroupManifest.GroupFile second = new GroupManifest.GroupFile(9, false, "86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8", null); GroupManifest manifest = manifest(Map.of("main", - new GroupManifest.Group("", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/first.jar", first))), "visuals", - new GroupManifest.Group("", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/second.jar", second))))); + new GroupManifest.Group("", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/first.jar", first))), "visuals", + new GroupManifest.Group("", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/second.jar", second))))); assertEquals(new GroupSelectionSummary(9), GroupSelectionSummary.of(manifest, Set.of("main", "visuals"))); } private static GroupManifest manifest(Map groups) { - return new GroupManifest("abc1234", "", "", "", "", "", new TreeMap<>(groups)); + return new GroupManifest("abc1234", "", "", "", "", "", Map.of(), new TreeMap<>(groups)); } private static GroupManifest.Group group(GroupManifest.GroupFile file) { - return new GroupManifest.Group("", "", "General", GroupSelectionMode.OPTIONAL, new TreeSet<>(), new TreeSet<>(), Set.of(), + return new GroupManifest.Group("", "", "", GroupSelectionMode.OPTIONAL, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/example.jar", file))); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/NettyServerObjectResolutionTest.java b/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/NettyServerObjectResolutionTest.java index d7fbf287f..4f00722bc 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/NettyServerObjectResolutionTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/NettyServerObjectResolutionTest.java @@ -23,6 +23,7 @@ import pl.skidam.automodpack_core.modpack.generation.GenerationHosting; import pl.skidam.automodpack_core.modpack.generation.GenerationStore; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.protocol.ModpackConnectionMode; import pl.skidam.automodpack_core.storage.DataRootResolver; import pl.skidam.automodpack_core.utils.HashUtils; @@ -174,11 +175,10 @@ private ModpackCandidate candidate(GenerationStore store, String description) th ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = description; group.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(bytes.length), false, hash, null)); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return new ModpackCandidate(GroupManifestValidator.validate(fields), new TreeMap<>(Map.of(hash, new StagedObject(hash, bytes.length, staged))), new TreeMap<>(), List.of()); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/AdvertiseEndpointTest.java b/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/AdvertiseEndpointTest.java index 060fd5727..353926d64 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/AdvertiseEndpointTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/AdvertiseEndpointTest.java @@ -31,6 +31,7 @@ import pl.skidam.automodpack_core.config.WireJsons; import pl.skidam.automodpack_core.modpack.PackAbsence; import pl.skidam.automodpack_core.modpack.generation.GenerationHosting; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.host.HostAdvertisement; import pl.skidam.automodpack_core.protocol.ModpackConnectionMode; import pl.skidam.automodpack_core.protocol.netty.NettyServer; @@ -114,19 +115,17 @@ void hostAdvertisementClearsRouteOnAbsenceAndCountsDefaultVariantOnly() throws E head.policy.loaderVersion = "0.16.10"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields core = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - core.required = true; - core.defaultSelected = true; + core.selection = GroupSelectionMode.REQUIRED; core.files = Map.of("mods/core.jar", new ModpackJsons.CompleteModpackContentFields.GroupFileFields("100", false, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", null)); ModpackJsons.CompleteModpackContentFields.ModpackGroupFields opt = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - opt.required = false; - opt.defaultSelected = false; + opt.selection = GroupSelectionMode.OPTIONAL; opt.files = Map.of("mods/optional.jar", new ModpackJsons.CompleteModpackContentFields.GroupFileFields("900", false, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", null)); Map groups = new LinkedHashMap<>(); groups.put("core", core); groups.put("optional", opt); - head.policy.categories = Map.of("Main", groups); + head.policy.groups = groups; Files.writeString(headFile, ConfigTools.GSON.toJson(head), StandardCharsets.UTF_8); WireJsons.AdvertiseFields ad = HostAdvertisement.build(new GenerationHosting(Map.of(GenerationHosting.HEAD_DOCUMENT_KEY, headFile)), null); diff --git a/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/AmmhGateHandlerTest.java b/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/AmmhGateHandlerTest.java index 9cc144aa9..b3f1939ea 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/AmmhGateHandlerTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/AmmhGateHandlerTest.java @@ -32,6 +32,7 @@ import pl.skidam.automodpack_core.modpack.candidate.StagedObject; import pl.skidam.automodpack_core.modpack.generation.GenerationStore; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.protocol.netty.NettyServer; import pl.skidam.automodpack_core.utils.HashUtils; @@ -190,11 +191,10 @@ private void fixture() throws Exception { ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = "test"; group.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(bytes.length), false, hash, null)); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); ModpackCandidate candidate = new ModpackCandidate(GroupManifestValidator.validate(fields), new TreeMap<>(Map.of(hash, new StagedObject(hash, bytes.length, staged))), new TreeMap<>(), List.of()); GenerationStore.Publication publication = store.publish(candidate, "", null); server.replacePaths(publication.hostingPaths()); diff --git a/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/HttpContractHandlerTest.java b/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/HttpContractHandlerTest.java index 132cbcef9..fe681ef15 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/HttpContractHandlerTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/protocol/netty/handler/HttpContractHandlerTest.java @@ -44,6 +44,7 @@ import pl.skidam.automodpack_core.modpack.generation.GenerationHosting; import pl.skidam.automodpack_core.modpack.generation.GenerationStore; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.protocol.NetUtils; import pl.skidam.automodpack_core.protocol.netty.NettyServer; import pl.skidam.automodpack_core.utils.HashUtils; @@ -794,11 +795,10 @@ private Fixture fixture() throws Exception { ModpackJsons.CompleteModpackContentFields fields = new ModpackJsons.CompleteModpackContentFields(); fields.modpackId = "abc1234"; var group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = false; - group.defaultSelected = false; + group.selection = GroupSelectionMode.OPTIONAL; group.description = "test"; group.files = Map.of("config/example.txt", new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(bytes.length), false, hash, null)); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); ModpackCandidate candidate = new ModpackCandidate(GroupManifestValidator.validate(fields), new TreeMap<>(Map.of(hash, new StagedObject(hash, bytes.length, staged))), new TreeMap<>(), List.of()); GenerationStore.Publication publication = store.publish(candidate, "", null); server = new NettyServer(); diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/ActivePackPointerTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/ActivePackPointerTest.java new file mode 100644 index 000000000..aeb0cf93b --- /dev/null +++ b/core/src/test/java/pl/skidam/automodpack_core/update/ActivePackPointerTest.java @@ -0,0 +1,161 @@ +package pl.skidam.automodpack_core.update; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import pl.skidam.automodpack_core.config.ClientStorageJsons; +import pl.skidam.automodpack_core.config.ModpackJsons; +import pl.skidam.automodpack_core.config.Rc7ClientSelectionMigration; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; +import pl.skidam.automodpack_core.modpack.group.GroupManifest; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; + +class ActivePackPointerTest { + @TempDir + Path temporaryDirectory; + + @Test + void readsTheActiveStateV5Rc7LeftBehind() throws Exception { + Path stateFile = temporaryDirectory.resolve("active-state.json"); + Files.writeString(stateFile, RC7_ACTIVE_STATE, StandardCharsets.UTF_8); + + Rc7ClientSelectionMigration.migrateActiveState(stateFile, new Rc7ClientSelectionMigration.PolicyLookup() { + @Override + public GroupManifest generation(String modpackId, String contentToken) { + throw new AssertionError("The pointer embeds its catalogue"); + } + + @Override + public GroupManifest latest(String modpackId) { + throw new AssertionError("Active state migration does not read the desire store"); + } + }); + + ClientStorageJsons.ClientGenerationStateFields state = new ActivePackPointer(stateFile).read(); + + assertNotNull(state); + assertEquals("abc1234", state.modpackId); + assertEquals("b2f90cbc7787346c7ab724cc916237c306bf5cb5", state.contentToken); + assertEquals("ACTIVE", state.status); + + ModpackJsons.CompleteModpackContentFields manifest = state.manifest; + assertEquals("5.0.0-rc.7", manifest.automodpackVersion); + assertEquals(Set.of("core", "extras"), manifest.categories.keySet(), "rc.7 category names became current category IDs"); + assertEquals("Core", manifest.categories.get("core").name); + assertEquals(CategoryPickMode.ANY, manifest.categories.get("core").pick); + assertEquals(Set.of("main", "shaders", "lowspec"), manifest.groups.keySet()); + + ModpackJsons.CompleteModpackContentFields.ModpackGroupFields main = manifest.groups.get("main"); + assertEquals("Core", main.name); + assertEquals("core", main.category); + assertEquals(GroupSelectionMode.REQUIRED, main.selection); + assertEquals(Set.of("mods/core.jar"), main.files.keySet()); + + ModpackJsons.CompleteModpackContentFields.ModpackGroupFields shaders = manifest.groups.get("shaders"); + assertEquals("Shaders", shaders.name); + assertEquals("extras", shaders.category); + assertEquals(GroupSelectionMode.OPTIONAL, shaders.selection); + assertEquals(Set.of("windows"), shaders.compatiblePlatforms); + assertEquals(Set.of("lowspec"), shaders.conflicts, "rc.7 breaksWith became conflicts"); + + assertEquals(List.of("lowspec", "shaders"), state.selection.enabled, "the saved enable and the subscribed category's members both survive as picks"); + assertEquals(List.of(), state.selection.disabled); + assertEquals("linux", state.selection.platform); + + String converged = Files.readString(stateFile, StandardCharsets.UTF_8); + assertFalse(converged.contains("selectedGroups"), converged); + assertEquals(state.manifest.groups.keySet(), new ActivePackPointer(stateFile).read().manifest.groups.keySet()); + } + + /** + * One v5.0.0-rc.7 active state: groups nested inside {@code categories}, and the applied selection as flat fields. + * The content token and the ledger digest are the ones rc.7 wrote for exactly these files. + */ + private static final String RC7_ACTIVE_STATE = """ + { + "modpackId": "abc1234", + "contentToken": "b2f90cbc7787346c7ab724cc916237c306bf5cb5", + "status": "ACTIVE", + "ownershipLedger": { + "modpackId": "abc1234", + "entries": [], + "digest": "fda88dc787178ee1fa60f880e82e0cf65faeaf24" + }, + "manifest": { + "modpackId": "abc1234", + "modpackName": "Test Pack", + "automodpackVersion": "5.0.0-rc.7", + "loader": "fabric", + "loaderVersion": "0.16.9", + "mcVersion": "1.21.1", + "categories": { + "Core": { + "main": { + "displayName": "Core", + "description": "Always installed", + "required": true, + "defaultSelected": true, + "breaksWith": [], + "requires": [], + "compatiblePlatforms": [], + "files": { + "mods/core.jar": { + "size": "4", + "editable": false, + "sha1": "94a0426e8d3203da5468ccf0c624f93cb37601e2", + "murmur": null + } + } + } + }, + "Extras": { + "shaders": { + "displayName": "Shaders", + "description": "Optional visuals", + "required": false, + "defaultSelected": false, + "breaksWith": ["lowspec"], + "requires": [], + "compatiblePlatforms": ["windows"], + "files": { + "shaderpacks/extra.zip": { + "size": "7", + "editable": false, + "sha1": "68477749788526fe4e350828be11ee864ef26548", + "murmur": null + } + } + }, + "lowspec": { + "displayName": "Low Spec", + "description": "", + "required": false, + "defaultSelected": false, + "breaksWith": [], + "requires": [], + "compatiblePlatforms": [], + "files": {} + } + } + } + }, + "manifestSha1": "", + "createdAt": "2026-01-02T03:04:05Z", + "selectedGroups": ["shaders"], + "selectedCategories": ["Extras"], + "excludedGroups": [], + "selectedPlatform": "linux", + "detached": false + } + """; +} diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/BestEffortApplyTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/BestEffortApplyTest.java index c3ab33093..71c895733 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/BestEffortApplyTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/BestEffortApplyTest.java @@ -40,6 +40,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.update.UpdatePlan.Operation; @@ -346,7 +347,7 @@ void anActionReplacingAJournalWithAnOwedProjectionConvergesOntoItsOwnTarget() th assertNull(ProjectionAvailability.stateStanding(storage.gameDirectory()).reason()); } - /** No markers: the journals this engine writes carry only the fields rc.5 already reads, so a downgrade replays them. */ + /** No unexpected marker fields: the v3 journals this engine writes carry only the documented selection and result schema. */ @Test void anOwedJournalSpeaksOnlyTheReleaseCandidateSchema() throws Exception { ClientStorage storage = UpdateTestFixtures.storage(temporaryDirectory); @@ -360,12 +361,14 @@ void anOwedJournalSpeaksOnlyTheReleaseCandidateSchema() throws Exception { try (var fixture = BestEffortApplyTest.class.getResourceAsStream("journals/" + release)) { released.addAll(keys(JsonParser.parseString(new String(fixture.readAllBytes(), StandardCharsets.UTF_8)), "")); } - // rc.5's UpdateTransaction declares both result fields; its fixtures only happen to leave them null. - released.addAll(Set.of("resultOperation", "resultPath")); + // rc.5's UpdateTransaction declares both result fields; its fixtures leave them null, and v3 replaced requested*/excluded* with SelectionFields. + released.addAll(Set.of("resultOperation", "resultPath", + "targetSelection", "targetSelection.enabled", "targetSelection.disabled", "targetSelection.platform", + "expectedPriorSelection", "expectedPriorSelection.enabled", "expectedPriorSelection.disabled", "expectedPriorSelection.platform")); Set unknown = new TreeSet<>(written); unknown.removeAll(released); - assertTrue(unknown.isEmpty(), "keys rc.5 never wrote: " + unknown); + assertTrue(unknown.isEmpty(), "unexpected UpdateTransaction keys written: " + unknown); UpdateJournal.Cursor owed = new UpdateJournal(storage).read(); assertTrue(Set.of(UpdateTransaction.Phase.PLANNED, UpdateTransaction.Phase.PREPARING).contains(owed.phase())); assertEquals(UpdateTransaction.Status.DEFERRED_LOCKED, owed.transaction().resultStatus); @@ -429,8 +432,7 @@ private static Generation generation(ClientStorage storage, Generation parent, i fields.modpackId = PACK; fields.modpackName = "Test"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; Map groupFiles = new LinkedHashMap<>(); for (var entry : files.entrySet()) { String hash = UpdateTestFixtures.store(storage, entry.getValue()); @@ -438,9 +440,9 @@ private static Generation generation(ClientStorage storage, Generation parent, i entry.getKey().equals(EDITABLE), hash, "0")); } group.files = groupFiles; - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); GroupManifest manifest = GroupManifestValidator.validate(fields); - SelectionIntent main = new SelectionIntent(Set.of("main")); + SelectionIntent main = SelectionIntent.ofEnabled(Set.of("main")); PackDocument document = parent == null ? TestPacks.document(manifest) : PackDocument.create(manifest, TestPacks.policySha1(manifest), Instant.parse("2026-01-01T00:00:00Z").plusSeconds(version), parent.target.document().ownershipLedger()); @@ -489,7 +491,7 @@ private Fixture twoGenerations() throws Exception { var manifest = GroupManifestValidator.validate(UpdateTestFixtures.fields(CONFIG, "config", true, lf, LF.length)); PackDocument document = PackDocument.create(manifest, TestPacks.policySha1(manifest), TestPacks.CREATED, oldTarget.document().ownershipLedger()); TestPacks.stageGeneration(storage, document); - SelectedModpackTarget target = SelectedModpackTarget.prepare(document, new SelectionIntent(Set.of("main")), new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(document, SelectionIntent.ofEnabled(Set.of("main")), SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); String baseline = HashUtils.sha1(CRLF); UpdatePlan plan = UpdateTestFixtures.plan(target, List.of(new Operation(Root.PROJECTION, CONFIG, OperationType.INSTALL_OBJECT, lf, LF.length, null), new Operation(Root.PROJECTION, "mods/old.jar", OperationType.DELETE, null, -1, old), new Operation(Root.GAME_DIR, CONFIG, OperationType.INSTALL_OBJECT, lf, LF.length, baseline)) diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/ClientGenerationStoreTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/ClientGenerationStoreTest.java index 0c11a65b8..0bba2d352 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/ClientGenerationStoreTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/ClientGenerationStoreTest.java @@ -65,12 +65,12 @@ void aMutatedReadCannotCorruptTheNextRead() throws Exception { String hash = store(storage, "projection-object"); PackDocument document = document(FIRST_PACK, hash, Files.size(storage.objectFile(hash)), TestPacks.CREATED); TestPacks.stageGeneration(storage, document); - storage.writeActiveState(document, new SelectionIntent(Set.of("main"))); + storage.writeActiveState(document, SelectionIntent.ofEnabled(Set.of("main"))); ClientStorageJsons.ClientGenerationStateFields read = storage.readActiveState(); read.contentToken = "0".repeat(40); read.detached = true; - read.selectedGroups = List.of("tampered"); + read.selection.enabled = List.of("tampered"); read.manifest = null; read.ownershipLedger = null; @@ -78,7 +78,7 @@ void aMutatedReadCannotCorruptTheNextRead() throws Exception { assertEquals(document.contentToken(), next.contentToken, "the parse is cached, the document it hands out is not"); assertFalse(next.detached); assertNotNull(next.manifest); - assertEquals(List.of("main"), next.selectedGroups); + assertEquals(List.of("main"), next.selection.enabled); assertEquals(document.contentToken(), new ClientGenerationStore(storage).activeDocument().orElseThrow().contentToken()); } @@ -92,11 +92,11 @@ void reconstructsTheActiveTargetFromMirrorCasAndActiveState() throws Exception { assertTrue(new ClientGenerationStore(storage).activeDocument().isEmpty()); storage.writeActiveState(document); - new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, new SelectionIntent(Set.of("main"))); + new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, SelectionIntent.ofEnabled(Set.of("main"))); SelectedModpackTarget target = new ClientGenerationStore(storage).readActiveTarget(ClientPlatform.LINUX).orElseThrow(); assertEquals(document, target.document()); - assertEquals(new SelectionIntent(Set.of("main")), target.selection().intent()); + assertEquals(SelectionIntent.ofEnabled(Set.of("main")), target.selection().intent()); assertEquals(document.contentToken(), target.flatTarget().contentToken); assertEquals(document.ownershipLedger(), target.document().ownershipLedger()); } @@ -107,7 +107,7 @@ void aDeactivatedPackOwnsOnlyItsOwnBytes() throws Exception { String hash = store(storage, "pack-jar"); PackDocument document = republished(FIRST_PACK, "mods/test.jar", hash, Files.size(storage.objectFile(hash)), TestPacks.CREATED); TestPacks.stageGeneration(storage, document); - new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, new SelectionIntent(Set.of("main"))); + new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, SelectionIntent.ofEnabled(Set.of("main"))); String fetched = store(storage, "fetched-only"); TestPacks.stageGeneration(storage, republished(SECOND_PACK, "mods/fetched.jar", fetched, 12, TestPacks.CREATED)); @@ -154,17 +154,17 @@ void aSavedDesireNeverMovesTheInstalledSelection() throws Exception { String hash = store(storage, "projection-object"); PackDocument document = document(FIRST_PACK, hash, Files.size(storage.objectFile(hash)), TestPacks.CREATED); TestPacks.stageGeneration(storage, document); - SelectionIntent applied = new SelectionIntent(Set.of("main")); + SelectionIntent applied = SelectionIntent.ofEnabled(Set.of("main")); storage.writeActiveState(document, applied); // The pointer carries the applied answer even when the store's desire has already moved ahead of it. - new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, new SelectionIntent(Set.of("main", "extra"))); + new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, SelectionIntent.ofEnabled(Set.of("main", "extra"))); assertEquals(applied, new ClientGenerationStore(storage).appliedSelection(FIRST_PACK).orElseThrow()); assertEquals(applied, new ClientGenerationStore(storage).readActiveTarget(ClientPlatform.LINUX).orElseThrow().selection().intent()); // A pointer written before the split falls back to the store, which was the applied record then. storage.writeActiveState(document); - assertEquals(new SelectionIntent(Set.of("main", "extra")), new ClientGenerationStore(storage).appliedSelection(FIRST_PACK).orElseThrow()); + assertEquals(SelectionIntent.ofEnabled(Set.of("main", "extra")), new ClientGenerationStore(storage).appliedSelection(FIRST_PACK).orElseThrow()); } @Test @@ -278,7 +278,7 @@ void aPolicyOnlyRepublishResolvesTheGenerationToTheWitnessedPolicy() throws Exce appendEntry(storage, second); storage.writeActiveState(second); - new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, new SelectionIntent(Set.of("main"))); + new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, SelectionIntent.ofEnabled(Set.of("main"))); SelectedModpackTarget target = new ClientGenerationStore(storage).readActiveTarget(ClientPlatform.LINUX).orElseThrow(); assertEquals(second.policySha1(), target.document().policySha1()); @@ -312,7 +312,7 @@ private void assertPendingUpdateManagesItsFiles(UpdateCommit.Probe probe) throws GroupManifest manifest = GroupManifestValidator.validate(UpdateTestFixtures.fields(config, "config", true, pack, 11)); PackDocument next = PackDocument.create(manifest, TestPacks.policySha1(manifest), TestPacks.CREATED, null); TestPacks.stageGeneration(storage, next); - SelectedModpackTarget target = SelectedModpackTarget.prepare(next, new SelectionIntent(Set.of("main")), new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(next, SelectionIntent.ofEnabled(Set.of("main")), SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); UpdatePlan plan = UpdateTestFixtures.plan(target, List.of(new UpdatePlan.Operation(UpdatePlan.Root.GAME_DIR, config, UpdatePlan.OperationType.INSTALL_OBJECT, pack, 11, null), new UpdatePlan.Operation(UpdatePlan.Root.PROJECTION, config, UpdatePlan.OperationType.INSTALL_OBJECT, pack, 11, null)).stream().sorted(UpdatePlan.Operation.ORDER).toList(), List.of(new UpdatePlan.ProjectedFile(UpdatePlan.Root.PROJECTION, config, true, pack, 11), new UpdatePlan.ProjectedFile(UpdatePlan.Root.GAME_DIR, config, true, pack, 11))); @@ -387,13 +387,13 @@ private static GroupManifest withOptionalGroup(String modpackId, Map groups = new TreeMap<>(); groups.put("main", group(GroupSelectionMode.REQUIRED, main)); if (!extra.isEmpty()) groups.put("extra", group(GroupSelectionMode.OPTIONAL, extra)); - return new GroupManifest(modpackId, "Test optional groups", "", "", "", "", groups); + return new GroupManifest(modpackId, "Test optional groups", "", "", "", "", Map.of(), groups); } private static GroupManifest.Group group(GroupSelectionMode mode, Map contents) { TreeMap files = new TreeMap<>(); contents.forEach((path, content) -> files.put(path, new GroupManifest.GroupFile(content.length(), false, sha1(content), null))); - return new GroupManifest.Group("", "", "General", mode, new TreeSet<>(), new TreeSet<>(), Set.of(), files); + return new GroupManifest.Group("", "", "", mode, new TreeSet<>(), Set.of(), files); } private static String sha1(String content) { @@ -406,9 +406,9 @@ private static PackDocument republished(String modpackId, String hash, long size private static PackDocument republished(String modpackId, String path, String hash, long size, Instant createdAt) { GroupManifest.GroupFile file = new GroupManifest.GroupFile(size, false, hash, null); - GroupManifest.Group group = new GroupManifest.Group("", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), + GroupManifest.Group group = new GroupManifest.Group("", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of(path, file))); - GroupManifest manifest = new GroupManifest(modpackId, "Test republished", "", "", "", "", new TreeMap<>(Map.of("main", group))); + GroupManifest manifest = new GroupManifest(modpackId, "Test republished", "", "", "", "", Map.of(), new TreeMap<>(Map.of("main", group))); return PackDocument.create(manifest, TestPacks.policySha1(manifest), createdAt, null); } @@ -508,7 +508,7 @@ void aRepublishedGenerationUnderTheSameTokenResolvesToWhatThePointerCommitted() appendEntry(storage, second); storage.writeActiveState(second); - new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, new SelectionIntent(Set.of("main"))); + new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, SelectionIntent.ofEnabled(Set.of("main"))); // The mirror now holds two generations under one token. The pointer names one of them, and the answer has to // be that one: pairing its manifest with the other entry's policy hash would be a document that never existed. @@ -562,9 +562,9 @@ void rejectsAPointerWhoseCarriedManifestIsNotItsOwnGeneration() throws Exception Path pointer = storage.stateFile(); JsonObject written = JsonParser.parseString(Files.readString(pointer, StandardCharsets.UTF_8)).getAsJsonObject(); GroupManifest.GroupFile other = new GroupManifest.GroupFile(size, false, hash, null); - GroupManifest.Group group = new GroupManifest.Group("", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), + GroupManifest.Group group = new GroupManifest.Group("", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/other.jar", other))); - written.add("manifest", ConfigTools.GSON.toJsonTree(new GroupManifest(FIRST_PACK, "Test", "", "", "", "", new TreeMap<>(Map.of("main", group))))); + written.add("manifest", ConfigTools.GSON.toJsonTree(new GroupManifest(FIRST_PACK, "Test", "", "", "", "", Map.of(), new TreeMap<>(Map.of("main", group))))); Files.writeString(pointer, written.toString(), StandardCharsets.UTF_8); assertThrows(IOException.class, storage::readActiveState); @@ -580,7 +580,7 @@ void forgetModpackDeletesOnlyTheInactivePacksRetainedState() throws Exception { ClientGenerationStore generations = new ClientGenerationStore(storage); TestPacks.stageGeneration(storage, first); TestPacks.stageGeneration(storage, second); - new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, new SelectionIntent(Set.of("main"))); + new ClientSelectionStore(storage.selectionFile()).put(FIRST_PACK, SelectionIntent.ofEnabled(Set.of("main"))); storage.writeActiveState(second); Path overlay = storage.overlayFile(FIRST_PACK, "config/options.txt"); Files.createDirectories(overlay.getParent()); @@ -617,7 +617,7 @@ void listingListsOnlyConsentedPacksAndStillFailsLoudlyOnCorruptGenerations() thr Files.delete(storage.objectFile(first.policySha1())); assertThrows(IOException.class, () -> generations.newestDocument(FIRST_PACK)); - new ClientSelectionStore(storage.selectionFile()).put(SECOND_PACK, new SelectionIntent(Set.of("main"))); + new ClientSelectionStore(storage.selectionFile()).put(SECOND_PACK, SelectionIntent.ofEnabled(Set.of("main"))); assertEquals(List.of(SECOND_PACK), new ClientGenerationStore(storage).installedPackIds()); assertEquals(second, new ClientGenerationStore(storage).newestDocument(SECOND_PACK)); } @@ -877,7 +877,7 @@ void activePointerSurvivesMirrorLineageReplacementAcrossReadsCollectionAndCompac PackDocument installed = document(FIRST_PACK, installedHash, Files.size(storage.objectFile(installedHash)), Instant.parse("2026-01-01T00:00:00Z")); TestPacks.stageGeneration(storage, installed); writeHead(storage, FIRST_PACK, installed); - storage.writeActiveState(installed, new SelectionIntent(Set.of("main"))); + storage.writeActiveState(installed, SelectionIntent.ofEnabled(Set.of("main"))); ClientGenerationStore generations = new ClientGenerationStore(storage); assertNotNull(generations.hosting(FIRST_PACK), "the matching head and pointer host the active generation"); @@ -979,17 +979,17 @@ private ClientStorage storage() throws Exception { private static PackDocument document(String modpackId, String hash, long size, Instant createdAt) { GroupManifest.GroupFile file = new GroupManifest.GroupFile(size, false, hash, null); - GroupManifest.Group group = new GroupManifest.Group("", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), + GroupManifest.Group group = new GroupManifest.Group("", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/test.jar", file))); - GroupManifest manifest = new GroupManifest(modpackId, "Test", "", "", "", "", new TreeMap<>(Map.of("main", group))); + GroupManifest manifest = new GroupManifest(modpackId, "Test", "", "", "", "", Map.of(), new TreeMap<>(Map.of("main", group))); return PackDocument.create(manifest, TestPacks.policySha1(manifest), createdAt, null); } private static PackDocument document(String modpackId, String hash, long size, Instant createdAt, PackDocument parent) { GroupManifest.GroupFile file = new GroupManifest.GroupFile(size, false, hash, null); - GroupManifest.Group group = new GroupManifest.Group("", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), + GroupManifest.Group group = new GroupManifest.Group("", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/test.jar", file))); - GroupManifest manifest = new GroupManifest(modpackId, "Test", "", "", "", "", new TreeMap<>(Map.of("main", group))); + GroupManifest manifest = new GroupManifest(modpackId, "Test", "", "", "", "", Map.of(), new TreeMap<>(Map.of("main", group))); return PackDocument.create(manifest, TestPacks.policySha1(manifest), createdAt, parent.ownershipLedger()); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/ClientObjectStoreTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/ClientObjectStoreTest.java index 2cc5bf01d..2588bbf07 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/ClientObjectStoreTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/ClientObjectStoreTest.java @@ -397,7 +397,7 @@ private static GroupManifest manifest(String hash, long size) { private static GroupManifest manifest(String modpackId, String hash, long size) { GroupManifest.GroupFile file = new GroupManifest.GroupFile(size, false, hash, null); - GroupManifest.Group group = new GroupManifest.Group("", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/test.jar", file))); - return new GroupManifest(modpackId, "", "", "", "", "", new TreeMap<>(Map.of("main", group))); + GroupManifest.Group group = new GroupManifest.Group("", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/test.jar", file))); + return new GroupManifest(modpackId, "", "", "", "", "", Map.of(), new TreeMap<>(Map.of("main", group))); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/ClientStateJournalTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/ClientStateJournalTest.java index 071e169bc..cfc91621f 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/ClientStateJournalTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/ClientStateJournalTest.java @@ -18,8 +18,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import com.google.gson.JsonParser; + import pl.skidam.automodpack_core.Environment; import pl.skidam.automodpack_core.TestEnvironment; +import pl.skidam.automodpack_core.config.ConfigTools; import pl.skidam.automodpack_core.loader.LoaderManagerService.EnvironmentType; import pl.skidam.automodpack_core.loader.LoaderManagerService.ModPlatform; import pl.skidam.automodpack_core.modpack.generation.PackDocument; @@ -99,7 +102,7 @@ void fileRestoreRefusesOwnedAndOverwrite() throws Exception { assertThrows(Exception.class, () -> StateHistory.restoreFile(storage, 1, Root.PROJECTION, "mods/player.jar")); PackDocument document = TestPacks.document(TestPacks.manifest("pack", "config/pack.txt", "pack-file")); TestPacks.stageGeneration(storage, document); - storage.writeActiveState(document, new SelectionIntent(Set.of("main"))); + storage.writeActiveState(document, SelectionIntent.ofEnabled(Set.of("main"))); storage.writeSelectedModpackId(document.manifest().modpackId()); Path restored = StateHistory.restoreFile(storage, 1, Root.GAME_DIR, "oldmods/player.jar"); assertEquals("player-mod", Files.readString(restored, StandardCharsets.UTF_8)); @@ -163,7 +166,7 @@ void removedPackCanBeRestoredUntilItsTimelineCheckpointIsForgotten() throws Exce ClientObjectStore.storeObject(storage, hash, bytes); PackDocument document = TestPacks.document(TestPacks.manifest("pack", "config/pack.txt", "restored pack file")); TestPacks.stageGeneration(storage, document); - SelectionIntent selection = new SelectionIntent(Set.of("main")); + SelectionIntent selection = SelectionIntent.ofEnabled(Set.of("main")); storage.writeActiveState(document, selection); new ClientSelectionStore(storage.selectionFile()).put(document.manifest().modpackId(), selection); InstanceTree installed = InstanceTree.of(new LiveIdentity(document.manifest().modpackId(), document.contentToken(), false, selection, List.of()), @@ -214,11 +217,11 @@ void checkoutRestoresDetachedSelectionAndReportsRestartWork() throws Exception { String hash = HashUtils.sha1(bytes); ClientObjectStore.storeObject(storage, hash, bytes); GroupManifest.GroupFile mod = new GroupManifest.GroupFile(bytes.length, false, hash, null); - GroupManifest.Group group = new GroupManifest.Group("", "test pack", "General", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Set.of(), Map.of("mods/test.jar", mod)); - GroupManifest manifest = new GroupManifest("abc1234", "test pack", "", "", "", "", Map.of("main", group)); + GroupManifest.Group group = new GroupManifest.Group("", "test pack", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of("mods/test.jar", mod)); + GroupManifest manifest = new GroupManifest("abc1234", "test pack", "", "", "", "", Map.of(), Map.of("main", group)); PackDocument document = PackDocument.create(manifest, TestPacks.policySha1(manifest), TestPacks.CREATED, null); TestPacks.stageGeneration(storage, document); - SelectionIntent selection = new SelectionIntent(Set.of("main")); + SelectionIntent selection = SelectionIntent.ofEnabled(Set.of("main")); InstanceTree target = InstanceTree.of(new LiveIdentity("abc1234", document.contentToken(), false, selection, List.of()), List.of(new TrackedFile(Root.PROJECTION, "", "mods/test.jar", hash, bytes.length))); target.write(storage); @@ -241,11 +244,11 @@ void checkoutClearsThePointerForAPreInstallSnapshotAndKeepsTheClaim() throws Exc String currentHash = HashUtils.sha1(currentBytes); ClientObjectStore.storeObject(storage, currentHash, currentBytes); GroupManifest.GroupFile mod = new GroupManifest.GroupFile(currentBytes.length, false, currentHash, null); - GroupManifest.Group group = new GroupManifest.Group("", "test pack", "General", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Set.of(), Map.of("mods/test.jar", mod)); - GroupManifest manifest = new GroupManifest("abc1234", "test pack", "", "", "", "", Map.of("main", group)); + GroupManifest.Group group = new GroupManifest.Group("", "test pack", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of("mods/test.jar", mod)); + GroupManifest manifest = new GroupManifest("abc1234", "test pack", "", "", "", "", Map.of(), Map.of("main", group)); PackDocument document = PackDocument.create(manifest, TestPacks.policySha1(manifest), TestPacks.CREATED, null); TestPacks.stageGeneration(storage, document); - SelectionIntent selection = new SelectionIntent(Set.of("main")); + SelectionIntent selection = SelectionIntent.ofEnabled(Set.of("main")); storage.writeActiveState(document, selection); storage.writeSelectedModpackId("abc1234"); new ClientSelectionStore(storage.selectionFile()).put("abc1234", selection); @@ -281,11 +284,11 @@ void checkoutDetachesWithoutOpeningTheCasObject() throws Exception { ClientObjectStore.storeObject(storage, hash, bytes); Path object = storage.objectFile(hash); GroupManifest.GroupFile mod = new GroupManifest.GroupFile(bytes.length, false, hash, null); - GroupManifest.Group group = new GroupManifest.Group("", "test pack", "General", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Set.of(), Map.of("mods/test.jar", mod)); - GroupManifest manifest = new GroupManifest("abc1234", "test pack", "", "", "", "", Map.of("main", group)); + GroupManifest.Group group = new GroupManifest.Group("", "test pack", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of("mods/test.jar", mod)); + GroupManifest manifest = new GroupManifest("abc1234", "test pack", "", "", "", "", Map.of(), Map.of("main", group)); PackDocument document = PackDocument.create(manifest, TestPacks.policySha1(manifest), TestPacks.CREATED, null); TestPacks.stageGeneration(storage, document); - SelectionIntent selection = new SelectionIntent(Set.of("main")); + SelectionIntent selection = SelectionIntent.ofEnabled(Set.of("main")); storage.writeActiveState(document, selection); storage.writeSelectedModpackId("abc1234"); Path projected = storage.activePath("mods/test.jar"); @@ -319,12 +322,12 @@ void checkoutPointsAtThePackTheSnapshotRanAndKeepsBothClaims() throws Exception PackDocument aDocument = TestPacks.document(aManifest); TestPacks.stageGeneration(storage, aDocument); GroupManifest.GroupFile bMod = new GroupManifest.GroupFile(bBytes.length, false, bHash, null); - GroupManifest.Group bGroup = new GroupManifest.Group("", "pack b", "General", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Set.of(), Map.of("mods/b.jar", bMod)); - GroupManifest bManifest = new GroupManifest("def5678", "pack b", "", "", "", "", Map.of("main", bGroup)); + GroupManifest.Group bGroup = new GroupManifest.Group("", "pack b", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of("mods/b.jar", bMod)); + GroupManifest bManifest = new GroupManifest("def5678", "pack b", "", "", "", "", Map.of(), Map.of("main", bGroup)); PackDocument bDocument = TestPacks.document(bManifest); TestPacks.stageGeneration(storage, bDocument); - SelectionIntent aSelection = new SelectionIntent(Set.of("main")); - SelectionIntent bSelection = new SelectionIntent(Set.of("main")); + SelectionIntent aSelection = SelectionIntent.ofEnabled(Set.of("main")); + SelectionIntent bSelection = SelectionIntent.ofEnabled(Set.of("main")); new ClientSelectionStore(storage.selectionFile()).put("abc1234", aSelection); new ClientSelectionStore(storage.selectionFile()).put("def5678", bSelection); storage.writeActiveState(bDocument, bSelection); @@ -363,12 +366,12 @@ void checkoutPointsAtTheOlderGenerationTheSnapshotRan() throws Exception { GroupManifest v1Manifest = TestPacks.manifest("generation one", "mods/test.jar", "one"); PackDocument v1 = TestPacks.document(v1Manifest); GroupManifest.GroupFile v2Mod = new GroupManifest.GroupFile(two.length, false, twoHash, null); - GroupManifest.Group v2Group = new GroupManifest.Group("", "generation two", "General", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Set.of(), Map.of("mods/test.jar", v2Mod)); - GroupManifest v2Manifest = new GroupManifest("abc1234", "generation two", "", "", "", "", Map.of("main", v2Group)); + GroupManifest.Group v2Group = new GroupManifest.Group("", "generation two", "", GroupSelectionMode.OPTIONAL, Set.of(), Set.of(), Map.of("mods/test.jar", v2Mod)); + GroupManifest v2Manifest = new GroupManifest("abc1234", "generation two", "", "", "", "", Map.of(), Map.of("main", v2Group)); PackDocument v2 = TestPacks.document(v2Manifest); TestPacks.stageGeneration(storage, v1); TestPacks.stageGeneration(storage, v2); - SelectionIntent selection = new SelectionIntent(Set.of("main")); + SelectionIntent selection = SelectionIntent.ofEnabled(Set.of("main")); new ClientSelectionStore(storage.selectionFile()).put("abc1234", selection); storage.writeActiveState(v2, selection); storage.writeSelectedModpackId("abc1234"); @@ -439,6 +442,32 @@ void timelinePinsReachTheReferenceSweep() throws Exception { assertTrue(ClientObjectStore.referencedHashes(storage).contains(installed)); } + /** + * rc.7 named a tree by the compact form of the selection it wrote as three legacy fields. The name is proven against + * those bytes and the selection migrates in memory, so the stored file keeps answering its snapshots. + */ + @Test + void readsARc7TreeAgainstTheHashOfTheSelectionItStored() throws Exception { + ClientStorage storage = storage(); + String file = hash("player-jar"); + String stored = "{\"activeModpackId\":\"abc1234\",\"contentToken\":\"" + hash("generation") + "\",\"detached\":false,\"requestedGroups\":[\"extras\"]," + + "\"requestedCategories\":[],\"excludedGroups\":[\"old\"],\"tombstones\":[],\"files\":[{\"root\":\"GAME_DIR\",\"overlayPackId\":\"\",\"path\":\"mods/player.jar\",\"sha1\":\"" + + file + "\",\"size\":1}]}"; + String storedName = HashUtils.sha1(stored); + Path treeFile = storage.stateHistoryTreeFile(storedName); + Files.createDirectories(treeFile.getParent()); + String onDisk = ConfigTools.GSON.toJson(JsonParser.parseString(stored)); + Files.writeString(treeFile, onDisk, StandardCharsets.UTF_8); + + InstanceTree tree = InstanceTree.read(storage, storedName); + + SelectionIntent selection = tree.identity().selection(); + assertEquals(Set.of("extras"), selection.enabled()); + assertEquals(Set.of("old"), selection.disabled()); + assertEquals(List.of(new TrackedFile(Root.GAME_DIR, "", "mods/player.jar", file, 1)), tree.files()); + assertEquals(onDisk, Files.readString(treeFile, StandardCharsets.UTF_8), "The content-addressed file keeps the bytes its name hashes"); + } + private ClientStorage storage() throws Exception { return TestDataRoot.open(temporaryDirectory.resolve("game"), temporaryDirectory.resolve("data")); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/GeneratedCopyStateCorruptionTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/GeneratedCopyStateCorruptionTest.java index c8094ea5a..d1e6f351c 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/GeneratedCopyStateCorruptionTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/GeneratedCopyStateCorruptionTest.java @@ -14,6 +14,7 @@ import pl.skidam.automodpack_core.config.ClientStorageJsons; import pl.skidam.automodpack_core.config.ConfigTools; +import pl.skidam.automodpack_core.config.SelectionJsons; import pl.skidam.automodpack_core.modpack.generation.OwnershipLedger; import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ModpackPathPolicy; @@ -67,7 +68,7 @@ void legacyPerIdentityTreeIsImportedOnceAtInitialization() throws Exception { @Test void aLegacyTreeWithTwoSelectionsKeepsTheOneTheActivePointerCommittedUnder() throws Exception { - SelectionIntent applied = new SelectionIntent(Set.of("main")); + SelectionIntent applied = SelectionIntent.ofEnabled(Set.of("main")); String appliedDigest = UpdateTransaction.digest(applied); seedLegacyTree(); Path appliedFile = tempDir.resolve("game").resolve(StoragePaths.CLIENT_GENERATED_COPIES_DIR).resolve(MODPACK_ID).resolve(CONTENT_TOKEN).resolve(appliedDigest + ".json"); @@ -78,9 +79,7 @@ void aLegacyTreeWithTwoSelectionsKeepsTheOneTheActivePointerCommittedUnder() thr state.modpackId = MODPACK_ID; state.contentToken = CONTENT_TOKEN; state.ownershipLedger = OwnershipLedger.empty(MODPACK_ID).toFields(); - state.selectedGroups = List.copyOf(applied.requestedGroups()); - state.selectedCategories = List.of(); - state.excludedGroups = List.of(); + state.selection = SelectionJsons.SelectionFields.from(applied); ConfigTools.writeAtomic(activeState, state); ClientStorage storage = TestDataRoot.open(tempDir.resolve("game"), tempDir.resolve("data")); @@ -136,11 +135,34 @@ void aLostIndexIsRebuiltForTheActiveGenerationAtBoot() throws Exception { GeneratedCopyState rebuilt = GeneratedCopyState.read(storage, target.manifest().modpackId(), target.packTarget().contentToken(), UpdateTransaction.digest(target.selection().intent())); assertEquals(List.of(new GeneratedCopyState.Entry(ModpackPathPolicy.generatedBundlePath(), HashUtils.sha1(bundleBytes), bundleBytes.length)), rebuilt.entries()); assertEquals(1, GeneratedCopyState.loadAll(storage).size(), "Only the active generation is rebuilt"); - SelectionIntent applied = new SelectionIntent(Set.of("main"), List.of(), List.of(), ClientPlatform.LINUX); + SelectionIntent applied = new SelectionIntent(Set.of("main"), Set.of(), ClientPlatform.LINUX); GeneratedCopyState read = GeneratedCopyState.read(storage, target.manifest().modpackId(), target.packTarget().contentToken(), UpdateTransaction.digest(applied)); assertEquals(rebuilt.entries(), read.entries(), "The rebuilt record answers to the selection the pointer committed under"); } + /** + * rc.7 hashed the selection differently, so its record answers no reader of this build: the generation is rebuilt from + * the installed bundle instead of being skipped as already recorded. + */ + @Test + void aRecordUnderASupersededSelectionDigestIsRebuiltAtBoot() throws Exception { + ClientStorage storage = TestDataRoot.open(tempDir.resolve("game"), tempDir.resolve("data")); + SelectedModpackTarget target = UpdateTestFixtures.target(storage, "mods/managed.jar", "mod", false, HashUtils.sha1("managed"), 1); + Path bundle = storage.gamePath(ModpackPathPolicy.generatedBundlePath()); + Files.createDirectories(bundle.getParent()); + byte[] bundleBytes = "generated-bundle".getBytes(StandardCharsets.UTF_8); + Files.write(bundle, bundleBytes); + storage.writeActiveState(target.document(), target.selection().intent()); + GeneratedCopyState.fromCopies(target.manifest().modpackId(), target.packTarget().contentToken(), HashUtils.sha1("rc7-selection"), List.of()).write(storage); + + GeneratedCopyState.rebuildActive(storage); + + GeneratedCopyState rebuilt = GeneratedCopyState.read(storage, target.manifest().modpackId(), target.packTarget().contentToken(), + UpdateTransaction.digest(target.selection().intent())); + assertEquals(List.of(new GeneratedCopyState.Entry(ModpackPathPolicy.generatedBundlePath(), HashUtils.sha1(bundleBytes), bundleBytes.length)), rebuilt.entries()); + assertEquals(1, GeneratedCopyState.loadAll(storage).size(), "The superseded record is replaced, never kept beside the rebuilt one"); + } + private void seedLegacyTree() throws IOException { Path legacy = tempDir.resolve("game").resolve(StoragePaths.CLIENT_GENERATED_COPIES_DIR).resolve(MODPACK_ID).resolve(CONTENT_TOKEN).resolve(SELECTION_DIGEST + ".json"); Files.createDirectories(legacy.getParent()); diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/OfflineRepairTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/OfflineRepairTest.java index 70fbe0518..0edecd8c7 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/OfflineRepairTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/OfflineRepairTest.java @@ -29,6 +29,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.storage.TestDataRoot; @@ -389,15 +390,14 @@ private static SelectedModpackTarget install(ClientStorage storage, FileSpec... fields.modpackId = "abc1234"; fields.modpackName = "Test"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; Map files = new LinkedHashMap<>(); for (FileSpec spec : specs) files.put(spec.path(), new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(spec.size()), spec.editable(), spec.hash(), "0")); group.files = files; - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); PackDocument document = TestPacks.document(GroupManifestValidator.validate(fields)); TestPacks.stageGeneration(storage, document); - SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); new ClientSelectionStore(storage.selectionFile()).put(document.manifest().modpackId(), target.selection().intent()); storage.writeActiveState(document); return target; diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/ProjectionStateTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/ProjectionStateTest.java index 9b9f5c59f..262dedb8c 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/ProjectionStateTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/ProjectionStateTest.java @@ -60,7 +60,7 @@ void settlingTwiceForOneTransactionDoesNotMoveTheRevision() throws Exception { void aSettledDocumentCarryingAFallbackIsInvalid() throws Exception { ClientStorage storage = UpdateTestFixtures.storage(temporaryDirectory); Files.createDirectories(storage.projectionStateFile().getParent()); - Files.writeString(storage.projectionStateFile(), "{\"version\":1,\"phase\":\"SETTLED\",\"revision\":1,\"fallback\":[{\"path\":\"a\",\"sha1\":\"" + "0".repeat(40) + "\",\"size\":1}]}"); + Files.writeString(storage.projectionStateFile(), "{\"schemaVersion\":1,\"phase\":\"SETTLED\",\"revision\":1,\"fallback\":[{\"path\":\"a\",\"sha1\":\"" + "0".repeat(40) + "\",\"size\":1}]}"); assertThrows(IOException.class, () -> ProjectionState.read(storage)); } @@ -69,7 +69,7 @@ void anUnknownEnumNameIsUnreadableInsteadOfDefaulting() throws Exception { ClientStorage storage = UpdateTestFixtures.storage(temporaryDirectory); Files.createDirectories(storage.projectionStateFile().getParent()); // Reading an effect we never wrote as RECORDED would restore a tree the document did not name. - Files.writeString(storage.projectionStateFile(), "{\"version\":1,\"phase\":\"CONVERGING\",\"revision\":1,\"fallbackSource\":\"SOMETHING_ELSE\",\"fallback\":[]}"); + Files.writeString(storage.projectionStateFile(), "{\"schemaVersion\":1,\"phase\":\"CONVERGING\",\"revision\":1,\"fallbackSource\":\"SOMETHING_ELSE\",\"fallback\":[]}"); assertThrows(ProjectionState.UnreadableException.class, () -> ProjectionState.read(storage)); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/RecordedInstalledLedgerTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/RecordedInstalledLedgerTest.java index fa28299ea..f959a27bc 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/RecordedInstalledLedgerTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/RecordedInstalledLedgerTest.java @@ -114,7 +114,7 @@ private static StagedReplacement stagedReplacement(ClientStorage storage) throws targetFields.modpackId = "def5678"; PackDocument targetDocument = TestPacks.document(GroupManifestValidator.validate(targetFields)); TestPacks.stageGeneration(storage, targetDocument); - SelectedModpackTarget target = SelectedModpackTarget.prepare(targetDocument, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(targetDocument, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); ModpackJsons.ModpackContentFields installed = ClientProjectionView.observe(storage).target(); UpdatePlan replacement = UpdatePlanner.plan(new UpdatePlanner.Input(installed, target.flatTarget(), Map.of(new UpdatePlan.FileKey(Root.GAME_DIR, preservedPath), new UpdatePlan.FileState(stagedHash, stagedBytes.length, true)), diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/RelayConsentTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/RelayConsentTest.java index 4ae9da4de..774faea68 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/RelayConsentTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/RelayConsentTest.java @@ -40,7 +40,7 @@ void forgettingAPackWithdrawsItsSharing() throws Exception { void anUnreadableConsentFileSharesNothing() throws Exception { ClientStorage storage = TestDataRoot.open(Files.createDirectory(temporaryDirectory.resolve("game")), Files.createDirectory(temporaryDirectory.resolve("data"))); Files.createDirectories(storage.relayConsentFile().getParent()); - Files.writeString(storage.relayConsentFile(), "{\"DO_NOT_CHANGE_IT\": 7, \"modpackIds\": [\"pack111\"]}"); + Files.writeString(storage.relayConsentFile(), "{\"schemaVersion\": 7, \"modpackIds\": [\"pack111\"]}"); assertFalse(RelayConsent.isRelayed(storage, "pack111")); } } diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/RepairTombstoneTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/RepairTombstoneTest.java index cd0e5ca73..1046c0060 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/RepairTombstoneTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/RepairTombstoneTest.java @@ -24,6 +24,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.storage.TestDataRoot; @@ -49,7 +50,7 @@ void repairCleansALongDeletedConfigThatUpdatesLeaveAlone() throws Exception { OwnershipLedger parent = TestPacks.document(manifest(earlier)).ownershipLedger(); PackDocument document = TestPacks.document(manifest(Map.of("config/kept.toml", kept)), parent, TestPacks.CREATED); TestPacks.stageGeneration(storage, document); - SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); new ClientSelectionStore(storage.selectionFile()).put(document.manifest().modpackId(), target.selection().intent()); storage.writeActiveState(document); write(storage.activePath("config/kept.toml"), kept); @@ -78,7 +79,7 @@ void repairNeverDeletesThroughATombstoneThatFoldsOntoAShippedPath() throws Excep OwnershipLedger parent = TestPacks.document(manifest(Map.of("config/Foo.toml", bytes))).ownershipLedger(); PackDocument document = TestPacks.document(manifest(Map.of("config/foo.toml", bytes)), parent, TestPacks.CREATED); TestPacks.stageGeneration(storage, document); - SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); new ClientSelectionStore(storage.selectionFile()).put(document.manifest().modpackId(), target.selection().intent()); storage.writeActiveState(document); write(storage.activePath("config/foo.toml"), bytes); @@ -103,7 +104,7 @@ void repairKeepsTheShippedFileAfterACaseOnlyRenameOnACaseInsensitiveDisk() throw OwnershipLedger parent = TestPacks.document(manifest(Map.of("config/Foo.toml", bytes))).ownershipLedger(); PackDocument document = TestPacks.document(manifest(Map.of("config/foo.toml", bytes)), parent, TestPacks.CREATED); TestPacks.stageGeneration(storage, document); - SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(document, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); new ClientSelectionStore(storage.selectionFile()).put(document.manifest().modpackId(), target.selection().intent()); storage.writeActiveState(document); write(storage.activePath("config/foo.toml"), bytes); @@ -123,12 +124,11 @@ private static GroupManifest manifest(Map contents) { fields.modpackId = "abc1234"; fields.modpackName = "Test"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; Map files = new LinkedHashMap<>(); contents.forEach((path, bytes) -> files.put(path, new ModpackJsons.CompleteModpackContentFields.GroupFileFields(String.valueOf(bytes.length), false, HashUtils.sha1(bytes), "0"))); group.files = files; - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return GroupManifestValidator.validate(fields); } diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/UpdateCommitTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/UpdateCommitTest.java index 1cc32789e..f02cddb64 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/UpdateCommitTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/UpdateCommitTest.java @@ -43,6 +43,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.update.UpdatePlan.Operation; @@ -98,7 +99,7 @@ void aMetadataOnlyPolicyAdvanceCommitsAgainstTheInstalledGeneration() throws Exc // The server reorganized the policy without touching the served bytes: same content token, new policy document. GroupManifest reorganized = GroupManifestValidator.validate(reorganizedFields(hash, bytes.length)); PackDocument advanced = PackDocument.create(reorganized, TestPacks.policySha1(reorganized), TestPacks.CREATED, null); - SelectedModpackTarget target = SelectedModpackTarget.prepare(advanced, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(advanced, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); assertEquals(installed.packTarget().contentToken(), target.packTarget().contentToken()); UpdatePlan plan = UpdateTestFixtures.plan(target, clientConfig(target.manifest().modpackId()), List.of(), List.of(new ProjectedFile(Root.PROJECTION, "mods/new.jar", true, hash, bytes.length))); @@ -124,7 +125,7 @@ void aPolicyOnlyAdvanceRecoversFromALaggingMirror() throws Exception { // The mirror only witnessed the generation the old policy came with; the head advanced the policy without a journal sync. GroupManifest advanced = GroupManifestValidator.validate(reorganizedFields(hash, bytes.length)); PackDocument advancedDocument = PackDocument.create(advanced, TestPacks.policySha1(advanced), TestPacks.CREATED, null); - SelectedModpackTarget target = SelectedModpackTarget.prepare(advancedDocument, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(advancedDocument, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); assertEquals(installed.packTarget().contentToken(), target.packTarget().contentToken()); UpdatePlan plan = UpdateTestFixtures.plan(target, clientConfig(target.manifest().modpackId()), List.of(), List.of(new ProjectedFile(Root.PROJECTION, "mods/new.jar", true, hash, bytes.length))); @@ -881,7 +882,7 @@ void usesPendingPlannedSelectionAsTheLogicalConfigurationBase() throws Exception fields.modpackId = "def5678"; PackDocument record = TestPacks.document(GroupManifestValidator.validate(fields)); TestPacks.stageGeneration(storage, record); - SelectedModpackTarget target = SelectedModpackTarget.prepare(record, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(record, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); UpdatePlan plan = UpdateTestFixtures.plan(target, clientConfig(target.manifest().modpackId()), List.of( new Operation(Root.PROJECTION, "mods/pending-selection.jar", OperationType.INSTALL_OBJECT, hash, bytes.length, null)), List.of(new ProjectedFile(Root.PROJECTION, "mods/pending-selection.jar", true, hash, bytes.length))); @@ -1131,7 +1132,7 @@ void preservesOwnedBytesWhileRestoringThePrePackBaseline() throws Exception { targetFields.modpackId = "def5678"; PackDocument switchedDocument = TestPacks.document(GroupManifestValidator.validate(targetFields)); TestPacks.stageGeneration(storage, switchedDocument); - SelectedModpackTarget target = SelectedModpackTarget.prepare(switchedDocument, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + SelectedModpackTarget target = SelectedModpackTarget.prepare(switchedDocument, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); Map files = Map.of( new UpdatePlan.FileKey(Root.PROJECTION, restoredPath), new UpdatePlan.FileState(serverHash, serverBytes.length, true), new UpdatePlan.FileKey(Root.GAME_DIR, restoredPath), new UpdatePlan.FileState(serverHash, serverBytes.length, true)); @@ -1302,7 +1303,7 @@ private static String legacyDocument(String contentToken, String selectionDigest private static ModpackJsons.CompleteModpackContentFields reorganizedFields(String hash, long size) { ModpackJsons.CompleteModpackContentFields fields = UpdateTestFixtures.fields("mods/new.jar", "mod", false, hash, size); - fields.categories.get("General").get("main").description = "reorganized"; + fields.groups.get("main").description = "reorganized"; return fields; } @@ -1337,13 +1338,12 @@ private static SelectedModpackTarget twoFileTarget(ClientStorage storage, String fields.modpackId = "abc1234"; fields.modpackName = "Test"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; group.files = Map.of(pathA, file(pathA, hashA, sizeA), pathB, file(pathB, hashB, sizeB)); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); PackDocument document = TestPacks.document(GroupManifestValidator.validate(fields)); TestPacks.stageGeneration(storage, document); - return SelectedModpackTarget.prepare(document, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + return SelectedModpackTarget.prepare(document, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); } private static ModpackJsons.CompleteModpackContentFields.GroupFileFields file(String path, String hash, long size) { diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/UpdatePreviewTest.java b/core/src/test/java/pl/skidam/automodpack_core/update/UpdatePreviewTest.java index e5017f2eb..0b61ea62e 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/UpdatePreviewTest.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/UpdatePreviewTest.java @@ -100,9 +100,9 @@ void presentationNamesDoNotReclassifyTheDecision() { ModpackJsons.ModpackContentFields target = manifest(item("mods/example.jar", TARGET_HASH, 9, "mod"), entry("mods/example.jar", TARGET_HASH, 9, OwnershipLedger.Status.PRESENT)); UpdatePreview preview = UpdatePreview.create(plan(target, Map.of()), null, UpdatePreview.Mode.UPDATE); - GroupManifest.Group feature = new GroupManifest.Group("Main feature", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), + GroupManifest.Group feature = new GroupManifest.Group("Main feature", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/example.jar", new GroupManifest.GroupFile(9, false, TARGET_HASH, "0")))); - GroupManifest manifest = new GroupManifest("abc1234", "", "", "", "", "", new TreeMap<>(Map.of("main", feature))); + GroupManifest manifest = new GroupManifest("abc1234", "", "", "", "", "", Map.of(), new TreeMap<>(Map.of("main", feature))); UpdatePreview named = preview.withFeatureManifest(manifest); @@ -116,9 +116,9 @@ void unnamedGroupsPresentTheirId() { ModpackJsons.ModpackContentFields target = manifest(item("mods/example.jar", TARGET_HASH, 9, "mod"), entry("mods/example.jar", TARGET_HASH, 9, OwnershipLedger.Status.PRESENT)); UpdatePreview preview = UpdatePreview.create(plan(target, Map.of()), null, UpdatePreview.Mode.UPDATE); - GroupManifest.Group feature = new GroupManifest.Group("", "", "General", GroupSelectionMode.REQUIRED, new TreeSet<>(), new TreeSet<>(), Set.of(), + GroupManifest.Group feature = new GroupManifest.Group("", "", "", GroupSelectionMode.REQUIRED, new TreeSet<>(), Set.of(), new TreeMap<>(Map.of("mods/example.jar", new GroupManifest.GroupFile(9, false, TARGET_HASH, "0")))); - GroupManifest manifest = new GroupManifest("abc1234", "", "", "", "", "", new TreeMap<>(Map.of("main", feature))); + GroupManifest manifest = new GroupManifest("abc1234", "", "", "", "", "", Map.of(), new TreeMap<>(Map.of("main", feature))); UpdatePreview named = preview.withFeatureManifest(manifest); diff --git a/core/src/test/java/pl/skidam/automodpack_core/update/UpdateTestFixtures.java b/core/src/test/java/pl/skidam/automodpack_core/update/UpdateTestFixtures.java index 4ba5f9a34..7c7243256 100644 --- a/core/src/test/java/pl/skidam/automodpack_core/update/UpdateTestFixtures.java +++ b/core/src/test/java/pl/skidam/automodpack_core/update/UpdateTestFixtures.java @@ -17,6 +17,7 @@ import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifestValidator; +import pl.skidam.automodpack_core.modpack.group.GroupSelectionMode; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; import pl.skidam.automodpack_core.storage.TestDataRoot; @@ -73,7 +74,7 @@ static UpdatePlan plan(SelectedModpackTarget target, List operations, static SelectedModpackTarget target(ClientStorage storage, String path, String type, boolean editable, String hash, long size) throws IOException { PackDocument document = TestPacks.document(GroupManifestValidator.validate(fields(path, type, editable, hash, size))); TestPacks.stageGeneration(storage, document); - return SelectedModpackTarget.prepare(document, null, new SelectionIntent(Set.of("main")), ClientPlatform.LINUX); + return SelectedModpackTarget.prepare(document, null, SelectionIntent.ofEnabled(Set.of("main")), ClientPlatform.LINUX); } static ModpackJsons.CompleteModpackContentFields fields(String path, String type, boolean editable, String hash, long size) { @@ -81,15 +82,14 @@ static ModpackJsons.CompleteModpackContentFields fields(String path, String type fields.modpackId = "abc1234"; fields.modpackName = "Test"; ModpackJsons.CompleteModpackContentFields.ModpackGroupFields group = new ModpackJsons.CompleteModpackContentFields.ModpackGroupFields(); - group.required = true; - group.defaultSelected = true; + group.selection = GroupSelectionMode.REQUIRED; ModpackJsons.CompleteModpackContentFields.GroupFileFields file = new ModpackJsons.CompleteModpackContentFields.GroupFileFields(); file.size = String.valueOf(size); file.editable = editable; file.sha1 = hash; file.murmur = "0"; group.files = Map.of(path, file); - fields.categories = Map.of("General", Map.of("main", group)); + fields.groups = Map.of("main", group); return fields; } diff --git a/docs/commands.mdx b/docs/commands.mdx index 449bdb313..47a0757b3 100644 --- a/docs/commands.mdx +++ b/docs/commands.mdx @@ -41,5 +41,6 @@ Both bootstrap exports contain trust data or a provisioning secret. Treat them l ## Groups -- `groups` - Lists every modpack group under its category, with published file counts and sizes. -- `groups ` - Shows one group's flags, dependencies, glob rules, and the files its published generation carries. +- `groups` - Lists configured categories and groups with their selection modes, dependencies, and published file counts and sizes. +- `groups ` - Shows one group's settings, category, dependencies, file rules, and published files. +- `groups import [folder]` - Creates `[groups.]` entries in `server.toml` for undeclared non-empty directories under `automodpack/host-modpack/`. Pass `folder` to import one directory. diff --git a/docs/configuration/server-config.mdx b/docs/configuration/server-config.mdx index 75d837df9..5d576b6a8 100644 --- a/docs/configuration/server-config.mdx +++ b/docs/configuration/server-config.mdx @@ -1,104 +1,91 @@ # Server configuration -`automodpack/server.toml` in the server root directory. The file is created on the first start with defaults. +AutoModpack creates `automodpack/server.toml` on the first start. Comments and formatting stay intact when AutoModpack updates the file. -The file is standard TOML: comments start with `#`, options are `key = value`, and related settings are grouped into `[tables]`. Comments, blank lines, and formatting are preserved when AutoModpack updates the file. - -## Editing the file - -Apply changes with `/automodpack config reload` or a restart. When the reload changes connection settings, run `/automodpack host restart` to apply them. A start rewrites superseded keys in the file when it can; a read-only config directory still boots and keeps the old file. +Apply edits with `/automodpack config reload` or a restart. If you change `[network]` settings, run `/automodpack host restart`. ## General -| Setting | Default | Description | +| Setting | Default | What it does | |---|---|---| -| `modpack-host` | `true` | Runs AutoModpack's built-in connection handling. When false, clients still receive connection information, which can point at a proxy or an externally handled endpoint. See [hosting](../how-it-works/hosting). | -| `generate-modpack-on-start` | `true` | Publishes a new generation on every start when the content changed. | -| `require-modpack` | `true` | When true, players without AutoModpack are kicked and modded clients sync the pack before joining. When false, the pack is optional: players without the mod join vanilla, and modded clients are asked whether to sync before they join. | -| `accepted-loaders` | current loader | Extra loaders allowed to join. The set is seeded with this server's loader on first load; this server's loader is always accepted even if you remove it. Unknown names are logged and ignored. Most mods are loader-specific, so change it with care. | -| `advertise-versions-to-sync` | `true` | Advertises the pack's version metadata (modloader, loader version, Minecraft version) to clients. When false, clients treat the pack as files-only and never switch their launcher instance's versions. See [launcher compatibility](../compatibility/launchers#version-sync-and-switching) for which launchers apply it. | -| `self-updater` | `false` | Updates AutoModpack itself from Modrinth when a new version is published. | - -## Groups +| `modpack-host` | `true` | Runs the built-in download host. Set `false` to serve through a proxy or external host. | +| `generate-modpack-on-start` | `true` | Publishes a new generation on startup when pack files changed. | +| `require-modpack` | `true` | Kicks players without AutoModpack. Set `false` to make the pack optional. | +| `accepted-loaders` | current loader | Extra modloaders allowed to join. The server's own loader is always accepted. | +| `advertise-versions-to-sync` | `true` | Sends Minecraft and loader versions so supported launchers can switch automatically. | +| `self-updater` | `false` | Updates AutoModpack on the server from Modrinth. | -The `[modpack]` section holds `name` (the display name players see), and `[modpack.groups..]` tables declare the groups under each category. The factory config contains one category, `General`, holding a single group `main`, which is required and selected by default. Extra groups become optional parts that players pick in the in-game "Group Selection" screen, listed under their categories. Group content comes from two sources: the directory `automodpack/host-modpack//` is included in full, and `from-server` pulls in files from the server root. The full picture is in [building the modpack](../pack-content). +## Modpack, categories, and groups -Both keys are identities, so treat them as permanent. The group id is the slug used by `requires` and `breaks-with`, by players' saved selections, and as the folder name under `automodpack/host-modpack//`; renaming it strands saved selections, breaks references from other groups, and requires renaming the folder. Renaming a category strands players' saved category choices. `display-name` is the always-safe rename, so keep anything volatile (versions, dates) out of ids and category names. A group with a blank `display-name` shows its id instead. +`[modpack]` holds pack-wide defaults. `[categories.]` defines optional UI sections and exclusive radio picks. `[groups.]` maps 1:1 to `automodpack/host-modpack//`. -### Categories +The file is the complete description: a key you leave out takes its documented default, and a `[groups.]` table you leave out declares no group. A config with no groups ships nothing, so generation refuses and names the repair. A fresh config always declares `[groups.main]`; if you deleted it, add it back or run `/automodpack groups import `. -Category names are player-facing display strings, not ids: they render verbatim as the section headers of the Group Selection screen. A name must be non-blank, carry no leading or trailing whitespace or control characters, and be at most 64 characters long, and names must be unique case-insensitively. An empty category or a group id declared twice is a validation error that fails `/automodpack generate` with the reasons in the log. Categories and their groups appear in the client in declared order, not alphabetically. +IDs use lowercase letters, digits, `_`, and `-` (up to 64 characters). Keep IDs stable because saved player choices, `requires`, `conflicts`, and folder names reference them. Changing `name` only changes the label in the UI. -### Rule lists +To add groups from folders you created under `automodpack/host-modpack/`, run `/automodpack groups import`. See [building the modpack](../pack-content). -Each group carries three rule lists, relative to the server root. +### Pack-wide `[modpack]` -| Setting | Factory value for `main` | Description | +| Setting | Default | What it does | |---|---|---| -| `modpack.groups...from-server` | `mods/*.jar`, `kubejs/**`, `emotes/*` | Extra paths pulled from the server root into the pack. The server root contributes only what a rule matches. | -| `modpack.groups...exclude` | `**/.*`, `**/.*/**`, `**/*.{tmp,disabled,bak}`, `kubejs/server_scripts/**` | Files kept out of the pack from every source. This is the only way to exclude something from the group directory, and it also carves exceptions out of `from-server`. These rules do not add files. | -| `modpack.groups...editable` | `options.txt`, `config/**` | Pack files that players may edit locally, mods included: editable mod jars live in the player's `mods` folder, replaceable and removable. Listing a path here does not add it to the pack. Local edits survive updates until the server changes the file; see [client updates](../how-it-works/client-updates#editable-files). | - -### Globbing wildcards - -A leading `/` is allowed and ignored. Rules are otherwise relative to the server root, with one exception: a rule may name its own group's directory under `automodpack/host-modpack//`, which is useful for excluding part of it. - -- `*` matches within a single directory, for example `mods/*.jar`. -- `**` matches recursively, for example `kubejs/**`. -- `!` negates a rule inside its own list. A path matches a list when a positive rule matches it and no `!` rule does. +| `name` | `""` | Modpack name shown to players. | +| `auto-exclude-server-side-mods` | `"METADATA"` | `DISABLED`, `METADATA`, or `PLATFORMS`. Drops dedicated-server jars on a best-effort basis. | +| `exclude` | `["**/.*", "**/.*/**", "**/*.{tmp,disabled,bak}"]` | Glob rules excluded from every group unless negated with `!`. | +| `editable` | `["options.txt", "config/**"]` | Glob rules for files where player edits survive updates until the server changes the file. | -Where the negation applies depends on the list it sits in. Inside `from-server` it skips a path from the synced set only, and the group directory may still provide it. `exclude` keeps a path from reaching clients entirely, so prefer it for exclusions and reach for a `from-server` negation only when the group-directory copy should still ship. +### Categories `[categories.]` -Read more about glob syntax on the [Globbing Wikipedia article](https://wikipedia.org/wiki/Glob_(programming)#Syntax). - -### Group fields - -| Setting | Default | Description | +| Setting | Default | What it does | |---|---|---| -| `modpack.groups...display-name` | `""` | Name shown to players in the Group Selection screen and the file browsers; blank shows the group id. The table key is the id used by rules and by `requires` and `breaks-with`. | -| `modpack.groups...description` | `""` | Short player-facing description of the group. | -| `modpack.groups...selection` | `"OPTIONAL"` | One of `REQUIRED`, `RECOMMENDED` or `OPTIONAL` (any case). `REQUIRED` is always installed and cannot be deselected; `RECOMMENDED` arrives preselected and players can opt out; `OPTIONAL` starts unchecked. The factory `main` group sets `REQUIRED`. | -| `modpack.groups...auto-exclude-server-side-mods` | `"METADATA"` | One of `DISABLED`, `METADATA` or `PLATFORMS` (any case). Best-effort drop of dedicated-server jars. `DISABLED` ships every jar. See [Dedicated-server jars](../pack-content#dedicated-server-jars). | -| `modpack.groups...requires` | `[]` | Group ids that must also be selected for this group to make sense, for example a shader config pack that needs its shader pack. | -| `modpack.groups...breaks-with` | `[]` | Group ids that cannot be selected alongside this one, for example two mods that replace the same files. | -| `modpack.groups...compatible-platforms` | `[]` | Restricts the group to matching platforms, for example a group of Windows-only mods. See platforms below. | - -### Migrating from `server.conf` or v4 JSON +| `name` | `""` | Section header in the UI. Blank uses ``. | +| `description` | `""` | Short line under the header. | +| `pick` | `"ANY"` | `ANY` (checkboxes), `AT_MOST_ONE` (radio buttons with `None`), or `EXACTLY_ONE` (radio buttons, one required). | -If `server.toml` does not exist yet, AutoModpack automatically migrates a v5-rc `server.conf` (or a v4 `automodpack-server.json` / `server-config.json`) into a fresh `server.toml`, including legacy `required`/`default-selected` group flags and pack-level `auto-exclude-server-side-mods`, and renames the old file to `.backup`. +`REQUIRED` and `AUTOMATIC` groups cannot sit in an exclusive category. -### Platforms +### Groups `[groups.]` -A platform is any short lowercase name. Clients detect `windows`, `linux`, and `macos` automatically and preselect the matching entry in the platform dropdown of the Group Selection screen. Any other name a group declares, for example `steamdeck`, is listed there too, so a player on a detected desktop OS can still opt into it. An empty `compatible-platforms` means every platform. - -When a client cannot detect a platform at all, groups without `compatible-platforms` behave as usual and platform-restricted groups stay unavailable until the player picks a platform. +| Setting | Default | What it does | +|---|---|---| +| `name` | `""` | Label in the UI. Blank uses ``. | +| `description` | `""` | Short description shown on the card. | +| `category` | `""` | Optional `[categories.]` section ID. | +| `selection` | `"OPTIONAL"` (`"REQUIRED"` on `main`) | `REQUIRED` (always installs), `RECOMMENDED` (on by default), `OPTIONAL` (off by default), or `AUTOMATIC` (installs only when required by a selected group). | +| `requires` | `[]` | Group IDs that install whenever this group is selected. | +| `conflicts` | `[]` | Group IDs that cannot install with this group. Declaring one side is enough. | +| `compatible-platforms` | `[]` | Platform names such as `windows`, `linux`, `macos`, or custom names like `steamdeck`. Empty allows all platforms. A `REQUIRED` group for other platforms is skipped. | +| `auto-exclude-server-side-mods` | inherits `[modpack]` | Optional per-group override (`DISABLED`, `METADATA`, or `PLATFORMS`). | +| `from-server` | `["mods/*.jar", "kubejs/**", "emotes/*"]` on `main` | Globs pulled from the server root into this group. | +| `exclude` | `["kubejs/server_scripts/**"]` on `main` | Extra exclusions or `!` exceptions over `modpack.exclude`. | +| `editable` | `[]` | Extra editable rules or `!` exceptions over `modpack.editable`. | + +Glob rules use `/` relative to the game root (`*` matches one folder, `**` matches recursively, `!` negates inside its own list). `exclude` and `editable` never add files on their own. ## Network and hosting -| Setting | Default | Description | +| Setting | Default | What it does | |---|---|---| -| `network.connection-mode` | `"HOLEPUNCH"` | One of `HOLEPUNCH`, `MAGIC` or `HTTP` (any case). HOLEPUNCH uses the Minecraft port. MAGIC can share it or use `network.bind-port`. HTTP uses `network.bind-port`. The modes and their port behavior are described in [hosting](../how-it-works/hosting). | -| `network.bind-address` | `""` | Local address for a dedicated listener. Empty binds to all interfaces. Used only when the selected mode starts one. | -| `network.bind-port` | `-1` | Controls built-in listeners according to `network.connection-mode`; see the [mode matrix](../how-it-works/hosting#connection-modes-and-ports). Values unused by the selected mode are preserved. | -| `network.advertised-host` | `""` | Public hostname or IP sent to clients as the download endpoint. Empty uses the hostname the player connected to. | -| `network.advertised-port` | `-1` | Public TCP port sent to clients. `-1` uses the connected port. | -| `network.bandwidth-limit` | `0` | Upload speed limit in MiB/s per client. `0` means unlimited. | -| `network.disable-internal-tls` | `false` | Skips AutoModpack's own TLS termination. Clients always start TLS, so an external terminator must forward decrypted traffic. Expert setting; see [hosting](../how-it-works/hosting#tls). | -| `network.accept-proxy-protocol` | `false` | Honors HAProxy PROXY protocol headers on dedicated listeners. Enable only behind a trusted proxy: a claimed source address feeds IP bans and audit logs, and a forged one lets a banned player past the ban. | -| `secrets.validate` | `true` | Requires a per-player secret, issued through the Minecraft login, for pack downloads. See [security](../security#download-authorization). A standalone host process has no login to provision secrets, so a fresh standalone config defaults this to `false`. | -| `secrets.lifetime-hours` | `336` | How long a download secret stays valid, in hours. 336 hours is 14 days. | -| `export-http.directory` | `""` | Non-empty: after every publish, the URL-contract tree (`head`, `journal`, `objects/`) is exported to this directory, ready to serve with any static HTTPS host. See [HTTP contract export](../how-it-works/hosting#http-contract-export). | -| `export-http.include-all` | `false` | Keeps every object in the HTTP contract export, including files Modrinth or CurseForge still serve to clients directly. Off, the platforms carry those downloads and your mirror holds no fallback for a file a platform later deletes; on, the exported tree stays complete. See [HTTP contract export](../how-it-works/hosting#http-contract-export). | - -Setting `modpack-host` to `false` turns off every built-in listener while clients keep receiving connection information. AutoModpack cannot validate external routing from the Minecraft server process, so a reverse proxy setup is your responsibility; the [proxies page](../compatibility/proxies) covers known-good setups. +| `network.connection-mode` | `"HOLEPUNCH"` | `HOLEPUNCH` (shares Minecraft port), `MAGIC` (shares port or uses `bind-port`), or `HTTP` (uses `bind-port`). See [hosting](../how-it-works/hosting). | +| `network.bind-address` | `""` | Local bind address for a dedicated listener. Empty binds all interfaces. | +| `network.bind-port` | `-1` | Dedicated listener port when the connection mode uses one. | +| `network.advertised-host` | `""` | Public host sent to clients. Empty uses the server address the player joined. | +| `network.advertised-port` | `-1` | Public port sent to clients. `-1` uses the joined port. | +| `network.bandwidth-limit` | `0` | Per-client upload cap in MiB/s. `0` is unlimited. | +| `network.disable-internal-tls` | `false` | Disables built-in TLS. Enable only behind an external TLS terminator. | +| `network.accept-proxy-protocol` | `false` | Reads HAProxy PROXY protocol headers on dedicated listeners. Enable only behind a trusted proxy. | +| `secrets.validate` | `true` | Requires a login-issued secret for pack downloads. Standalone hosts default to `false`. | +| `secrets.lifetime-hours` | `336` | Secret validity in hours (14 days). | +| `export-http.directory` | `""` | Exports the static HTTPS pack tree (`head`, `journal`, `objects/`) here after each publish. | +| `export-http.include-all` | `false` | Includes files also hosted on Modrinth or CurseForge in the static export. | ## Un-modded clients -With `require-modpack` off, players who join without AutoModpack stay in the game, and modded clients are asked whether to sync the pack when they connect. +When `require-modpack` is `false`, players without AutoModpack can join and see a chat prompt: -| Setting | Default | Description | +| Setting | Default | What it does | |---|---|---| -| `nag.enabled` | `true` | Shows a chat message to players without the mod. | -| `nag.message` | `Install the AutoModpack mod to get this server's modpack!` | The message text. | -| `nag.clickable-message` | `Click here to get the AutoModpack!` | The clickable link text. | -| `nag.clickable-link` | AutoModpack on Modrinth | The URL opened on click. | +| `nag.enabled` | `true` | Sends the chat prompt to un-modded players. | +| `nag.message` | `Install the AutoModpack mod to get this server's modpack!` | Prompt text. | +| `nag.clickable-message` | `Click here to get the AutoModpack!` | Clickable link label. | +| `nag.clickable-link` | AutoModpack on Modrinth | URL opened on click. | diff --git a/docs/faq.mdx b/docs/faq.mdx index 4b18b0129..bb074bd35 100644 --- a/docs/faq.mdx +++ b/docs/faq.mdx @@ -32,10 +32,10 @@ Usually not. The default `HOLEPUNCH` mode carries the modpack connection through Clients follow the version the server runs: they update or downgrade through Modrinth to match it. See [AutoModpack's own updates](how-it-works/client-updates#automodpacks-own-updates). ### Why does the pack live under `host-modpack/main/`? -Each group has a directory under `automodpack/host-modpack//`, and `main` is the default group. File rules live on each group in the `modpack` section of the [server config](configuration/server-config#groups). +Each group has a directory under `automodpack/host-modpack//`, and `main` is the default core group. Pack defaults live in `[modpack]` and per-group declarations live in `[groups.]` in the [server config](configuration/server-config#groups). ### What are groups? -Optional parts of a modpack, like a shader bundle or a platform-specific mod set. The server admin declares them under a category in the `modpack` section of the server config; players pick the ones they want in the in-game "Group Selection" screen, and the choice sticks across updates. They are covered in [building the modpack](pack-content#groups). +Optional parts of a modpack, like a shader bundle or a platform-specific mod set. The server admin declares groups in `[groups.]` in the server config and can organize them with optional `[categories.]` sections. Players choose groups on the "Group Selection" screen, and those choices persist across updates. See [building the modpack](pack-content#groups). ### Is my launcher supported? All standard launchers should just work, for wider compatibility check the [launcher list](compatibility/launchers). diff --git a/docs/pack-content.mdx b/docs/pack-content.mdx index aad4282e8..43033dbd2 100644 --- a/docs/pack-content.mdx +++ b/docs/pack-content.mdx @@ -1,139 +1,60 @@ # Building the modpack -The server builds a candidate generation from two sources. Both map onto the client's game directory, laid out like a `.minecraft` folder. +AutoModpack builds each group from two sources, mapped onto the client's game folder: -- The group directory `automodpack/host-modpack//` is included in full unless `exclude`d. Files go here when the server itself has no use for them, for example client-side mods or when clear separation is needed. -- The group's `from-server` rules pull files out of the server root. This is how the pack picks up the mods, configs, and scripts that already live on the server. +1. `automodpack/host-modpack//`: included in full unless matched by `exclude`. Put client-only mods, shaders, resource packs, and custom configs here. +2. `from-server`: glob rules in `server.toml` that pull files from the server root (`mods/`, `kubejs/`, etc.). -The default group id is `main`. After changing files or rules, publish a new generation with `/automodpack generate`; clients pick it up on their next connection. Publishing is described in [generations](how-it-works/generations). +When both sources contain the same path, the `host-modpack//` copy wins. After changing files or rules, run `/automodpack generate`. -The optional waiting track is `automodpack/host-modpack/waiting-music.ogg`. Drop or replace that file, then generate (or restart with `generate-modpack-on-start`). Clients stream it during downloads. On an installed pack's details screen, the music-note button plays the current advertised track without reinstalling the pack. +To stream music during downloads, place an `.ogg` file at `automodpack/host-modpack/waiting-music.ogg` and run `/automodpack generate`. ## Example -A server with this layout: - -``` -├── automodpack -│ ├── server.toml -│ └── host-modpack -│ └── main -│ ├── config -│ │ ├── my-super.conf -│ │ └── shadow.txt -│ ├── mods -│ │ ├── fabric-api.jar -│ │ └── herobrine-mod.jar -│ ├── options.txt -│ └── shaderpacks -│ └── the-ultimate-shader.zip -├── config -│ ├── ferritecore.mixin.properties -│ └── invisible-radio.json -├── kubejs -│ ├── client_scripts -│ │ └── welcome.js -│ ├── common_scripts -│ │ └── recipes.js -│ └── server_scripts -│ └── datapack_loader.js -└── mods - ├── automodpack.jar - ├── fabric-api.jar - ├── ferritecore.jar - ├── modmenu.jar - └── sodium-fabric.jar -``` - -and this group declared in `server.toml`: +Default `server.toml` setup: ```toml [modpack] name = "" +auto-exclude-server-side-mods = "METADATA" +exclude = ["**/.*", "**/.*/**", "**/*.{tmp,disabled,bak}"] +editable = ["options.txt", "config/**"] -[modpack.groups.General.main] +[groups.main] +selection = "REQUIRED" from-server = ["mods/*.jar", "kubejs/**", "emotes/*"] exclude = ["kubejs/server_scripts/**"] -editable = ["options.txt", "config/**"] ``` -produces this pack for clients: - -``` -├── config -│ ├── my-super.conf (editable) -│ └── shadow.txt (editable) -├── kubejs -│ ├── client_scripts -│ │ └── welcome.js -│ └── common_scripts -│ └── recipes.js -├── mods -│ ├── fabric-api.jar (the host-modpack copy) -│ ├── ferritecore.jar -│ ├── herobrine-mod.jar (from host-modpack) -│ ├── modmenu.jar -│ └── sodium-fabric.jar -├── options.txt (editable) -└── shaderpacks - └── the-ultimate-shader.zip -``` - -What the example shows: - -- `mods/*.jar` matches every jar in the server's `mods` folder. The AutoModpack jar itself stays out: clients update it through Modrinth to match the version the server runs, never through the pack. See [AutoModpack's own updates](how-it-works/client-updates#automodpacks-own-updates). -- Both sources contained `mods/fabric-api.jar` with different versions, and the host-modpack copy won. When the same path exists in both sources, the group directory decides. -- `kubejs/server_scripts/**` is excluded, so the server's scripts stay on the server. -- `options.txt` and everything under `config` in the pack is editable because `editable` says so. -- `config/ferritecore.mixin.properties` and `config/invisible-radio.json` exist on the server but not in the pack. `editable` marks files that are already in the pack; it does not pull files in. - -Editable files keep their copy in the game directory, mods included: a mod matched by `editable`, say `mods/customizable.jar`, materializes in the player's `mods` folder where they can edit or remove it. `/automodpack generate` warns when an `editable` rule matches active mods: a mod loaded from the standard `mods` folder needs a restart to update and sits outside AutoModpack's in-place mod management. Keep `editable` for configs and options; use it for a mod only when it breaks when loaded in place. - -## Which files reach clients? - -A file reaches clients when one of the two sources provides it: the group directory includes everything it holds, and `from-server` pulls matching files from the server root. AutoModpack does not care what a file is; the same rules move mods, configs, and everything else. - -- Keep a server file off clients: add its path to `exclude`. A dedicated-server mod, for example, is kept off with `mods/the-server-mod.jar`. Each group also has `auto-exclude-server-side-mods`, which tries to drop dedicated-server jars on a best-effort basis. See [Dedicated-server jars](#dedicated-server-jars). `DISABLED` ships every jar in that group. -- Give clients a file the server does not need: put it in the group directory, for example `automodpack/host-modpack/main/mods/`. -- Split fully: remove the mod rules from `from-server` and put every client mod into the group directory. The pack's mods then come only from `host-modpack`, and the server's `mods` folder stays server-only. - -A `!` rule inside `from-server` also skips a path, but only for the server root; the group directory can still provide the file. +- `mods/*.jar` pulls server mods into `main` (except AutoModpack itself). +- `kubejs/server_scripts/**` stays on the server. +- `options.txt` and `config/**` are marked editable only if they are already in the pack. `editable` does not pull files in. +- To split server and client mods completely, clear `from-server` and put every client file inside `automodpack/host-modpack/`. ## Dedicated-server jars -Each group has `auto-exclude-server-side-mods`. It tries to drop jars that a joining client must not run. This is best effort. It does not drop every mod that looks server-side. - -`DISABLED` ships every jar in the group. +`auto-exclude-server-side-mods` (in `[modpack]`, overridable per group) drops dedicated-server jars on a best-effort basis: -`METADATA` drops Fabric jars with `environment: server` and Forge jars with `displayTest` `IGNORE_SERVER_VERSION`. +- `DISABLED`: ships every jar. +- `METADATA`: drops Fabric jars with `environment: server` and Forge jars with `displayTest` `IGNORE_SERVER_VERSION`. +- `PLATFORMS`: applies `METADATA`, then checks Modrinth for remaining universal jars tagged `dedicated_server_only`. -`PLATFORMS` does the same, then asks Modrinth about leftover universal jars and drops those tagged `dedicated_server_only`. +If a server-only jar still ships, add it to `exclude`. -A `side` of `SERVER` on a `minecraft`, `forge`, or `neoforge` dependency is not a reason to drop the jar. That field says which side the dependency is checked on. The jar still loads on the client. If the pack leaves it out, Forge kicks joiners for a mismatched mod list. +## Editable files and deletions -If auto-exclude leaves a jar in the pack and you still do not want it on clients, add the path to `exclude`. +Player edits to editable files survive updates until the server changes the file. Keep `editable` for configs and options, because using it on a mod jar forces a restart on updates. -## File rules - -`from-server`, `exclude`, and `editable` live on each group and are documented with the [group settings](configuration/server-config#groups). All three lists speak the same glob language, described in [globbing](configuration/server-config#globbing-wildcards). - -One rule worth knowing early: the group directory is included in full, so `exclude` is the only way to keep a file there from reaching clients. Inside `from-server`, a `!` rule skips a path only for that list; the group directory may still provide it. - -## Deleting content - -Remove the file from the server, or keep it on the server and add it to `exclude`. On the next update, clients delete their copy. Updates replace files by the same rule: a file that changed on the server is replaced by the pack's new bytes, and the old copy is not kept in the game folder. The full rules are in [client updates](how-it-works/client-updates#deletions-are-measured). +To delete a file from clients, remove it from the server or add it to `exclude`. Clients remove their copy on the next update. See [client updates](how-it-works/client-updates#deletions-are-measured). ## What never ships -- AutoModpack's own jar. `/automodpack generate` never packs it and never publishes its updates: clients follow the AutoModpack version the server runs and pick the matching release up from Modrinth. To update players, update the jar on the server, restart, and clients sync to it on their next connection. The details, including `sync-automodpack-version` and `self-updater`, are in [AutoModpack's own updates](how-it-works/client-updates#automodpacks-own-updates). -- Dedicated-server jars, when a group's `auto-exclude-server-side-mods` is `METADATA` or `PLATFORMS` (default `METADATA`). This is best effort. See [Dedicated-server jars](#dedicated-server-jars). A preview reports platform verdicts but keeps the jars, so you see what a publish would drop. -- Empty, hidden, `.tmp`, `.disabled`, and `.bak` files. The default `exclude` rules carry these patterns and can be edited; the `automodpack/` namespace and Windows-reserved device names are always left out and cannot be turned back on. -- The paths `saves/`, `screenshots/`, `logs/`, and `automodpack/` can never be claimed by the pack. - -## Groups +- AutoModpack's own jar (clients update it directly from Modrinth to match the server). +- Reserved paths: `saves/`, `screenshots/`, `logs/`, `automodpack/`, and Windows-reserved names. +- Hidden and temp files matched by default `modpack.exclude` (`**/.*`, `**/*.{tmp,disabled,bak}`). -Groups split a modpack into parts. `main` is by default the required core; extra groups become optional entries that players pick in the in-game "Group Selection" screen, and the choice sticks across updates. Every group is declared under a category, whose name is the section header the group is listed under. A shader bundle or a platform-specific mod set is a typical use. +## Groups and conflicts -The [group settings](configuration/server-config#groups) document every field: display metadata, `selection`, `auto-exclude-server-side-mods`, `requires` and `breaks-with` relations, and `compatible-platforms`. +Split optional content into separate `[groups.]` blocks, each backed by `automodpack/host-modpack//`. Use `[categories.]` to group them into UI sections or enforce radio picks (`AT_MOST_ONE`, `EXACTLY_ONE`). See [group settings](configuration/server-config#modpack-categories-and-groups). -Different content under one path is allowed only between groups that can never be selected together, meaning groups that `breaks-with` each other or groups limited to different `compatible-platforms`. That is how you ship variants, for example a Windows-only file alongside a generic one. When two groups that could be selected together disagree about a path, `/automodpack generate` fails with an error naming the path and both groups, and nothing is published until you separate the paths or make the groups mutually exclusive. +Two groups can ship different files at the same path only if they cannot be selected together: inside an exclusive category, declared in `conflicts`, or on disjoint `compatible-platforms`. Otherwise `/automodpack generate` fails and prints the conflicting path and group IDs. diff --git a/gradle.properties b/gradle.properties index af31576aa..2a3b10a7e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -43,7 +43,7 @@ versionAircompressor = 2.0.3-1 versionZstdJni = 1.5.7-24 versionJzopfli = 0.0.4 versionMcholepunch = 0.1.1 -versionTomlEdit = 0.1.0 +versionTomlEdit = 0.4.1 # Loader-provided compile API floors versionLoaderGson = 2.10.1 diff --git a/src/main/java/pl/skidam/automodpack/client/autotest/AutoTestBridge.java b/src/main/java/pl/skidam/automodpack/client/autotest/AutoTestBridge.java index 73596cc34..700bba962 100644 --- a/src/main/java/pl/skidam/automodpack/client/autotest/AutoTestBridge.java +++ b/src/main/java/pl/skidam/automodpack/client/autotest/AutoTestBridge.java @@ -30,6 +30,7 @@ import pl.skidam.automodpack.client.ui.versioned.VersionedToasts; import pl.skidam.automodpack.client.ui.widget.CheckboxWidget; import pl.skidam.automodpack.client.ui.widget.Countdown; +import pl.skidam.automodpack.client.ui.widget.GroupSelectionList; import pl.skidam.automodpack.client.ui.widget.RowListWidget; import pl.skidam.automodpack.client.ui.widget.RowViewport; import pl.skidam.automodpack_core.text.L10n; @@ -673,7 +674,10 @@ private static void collectAttachedWidgets(GuiEventListener listener, LinkedHash if (listener instanceof RowViewport viewport) { rowViewports.add(viewport); if (listener instanceof ContainerEventHandler container) { - for (GuiEventListener child : container.children()) collectRowButtons(child, widgets); + viewport.syncLayout(); + int top = viewport.viewportTop(); + int bottom = viewport.viewportBottom(); + for (GuiEventListener child : container.children()) collectRowButtons(child, widgets, top, bottom); } return; } @@ -681,17 +685,27 @@ private static void collectAttachedWidgets(GuiEventListener listener, LinkedHash for (GuiEventListener child : container.children()) collectAttachedWidgets(child, widgets, rowViewports); } - private static void collectRowButtons(GuiEventListener listener, LinkedHashSet widgets) { + private static void collectRowButtons(GuiEventListener listener, LinkedHashSet widgets, int viewportTop, int viewportBottom) { if (listener instanceof ContainerEventHandler container) { - for (GuiEventListener child : container.children()) collectRowButtons(child, widgets); + for (GuiEventListener child : container.children()) collectRowButtons(child, widgets, viewportTop, viewportBottom); return; } if (!(listener instanceof AbstractWidget widget)) return; - // The row's checkbox is represented by the row element itself; exposing it again as a bare widget would duplicate every row. - if (listener instanceof CheckboxWidget) return; + // The row element stands for its primary control; a bare widget would duplicate the row. + if (listener instanceof CheckboxWidget || listener instanceof GroupSelectionList.RowPrimaryControl) return; + int y = widgetY(widget); + if (y < viewportTop || y + widget.getHeight() > viewportBottom) return; widgets.add(widget); } + private static int widgetY(AbstractWidget widget) { + /*? if >= 1.19.4 {*/ + return widget.getY(); + /*?} else {*/ + /*return widget.y; + *//*?}*/ + } + private static JsonArray elementsJson(List elements) { JsonArray a = new JsonArray(); for (GuiElement e : elements) { diff --git a/src/main/java/pl/skidam/automodpack/client/ui/screen/GroupSelectionScreen.java b/src/main/java/pl/skidam/automodpack/client/ui/screen/GroupSelectionScreen.java index 9dadec01f..6c5400b9b 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/screen/GroupSelectionScreen.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/screen/GroupSelectionScreen.java @@ -1,12 +1,10 @@ package pl.skidam.automodpack.client.ui.screen; import java.util.ArrayList; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.TreeSet; import java.util.function.Consumer; import net.minecraft.ChatFormatting; @@ -26,6 +24,7 @@ import pl.skidam.automodpack_core.change.ChangeSet; import pl.skidam.automodpack_core.client.SourceAvailability; import pl.skidam.automodpack_core.modpack.generation.PackDocument; +import pl.skidam.automodpack_core.modpack.group.CategoryPickMode; import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.GroupResolution; @@ -42,96 +41,199 @@ import pl.skidam.automodpack_core.screen.ScreenManager; import pl.skidam.automodpack_core.utils.ActionAreaLayout; -/** - * Group selection for one modpack: the player ticks optional groups per category, and the resolver turns the intent into - * the effective selection. Conflicting choices settle automatically, with a receipt line naming what was turned off. - * Changes only take effect on the next launch, because mods are loaded during preload. - */ +/** Group picker: cards under category headers, with radio buttons for exclusive categories. Selection math is in {@link GroupSelectionResolver}, submission in {@link Session}. */ public class GroupSelectionScreen extends VersionedScreen { - - /** - * The list panel's width on wide windows, shared with the other list screens (pack manager, change browser); - * narrow windows degrade to width - 24, which keeps the old 12px edge margins exactly. The panel itself centers, - * but rows keep their left-aligned labels, so content never floats mid-screen. - */ private static final int PANEL_WIDTH = 500; - /** Air between the list's last row and the footer rail: a row's checkbox needs a little more than the plain 8px widget gap. */ private static final int LIST_FOOTER_GAP = 12; - /** Vanilla checkbox geometry: the box plus the gap before its label. */ - private static final int CHECKBOX_LABEL_OFFSET = 24; + private static final int ACCENT_SELECTED = 0xFF55FF55; + private static final int ACCENT_DEFAULT = 0xFF55FFFF; + private static final int ACCENT_ERROR = 0xFFFF5555; + + interface Session { + String submitLabelKey(); + + boolean allowSubmitUnchanged(); + + default String unchangedTooltipKey() { + return null; + } + + SelectionIntent initialSelection(); + + default String origin() { + return ""; + } + + default boolean isCancelled() { + return false; + } + + default SourceAvailability sourceAvailability() { + return null; + } + + void submit(SelectionIntent intent, Runnable release); + + default void cancel() {} + } private final Screen parent; private final GroupManifest manifest; - private final String modpackId; private final String modpackName; private final Map groups; - private final InstalledModpackController controller; private final String origin; + private final Session session; private final SelectionIntent initialSelection; - private final Consumer selectionAction; - private final Runnable cancelAction; - private final ReviewConsent actions; - private final PackDocument localRecord; private final ClientPlatform detectedPlatform; - private ClientPlatform platformOverride; - // What the player has actually ticked; resolved is what that implies once required groups, - // dependencies, conflicts and platform rules are applied. - private final Set chosen = new LinkedHashSet<>(); - private final Set chosenCategories = new LinkedHashSet<>(); - private final Set excluded = new LinkedHashSet<>(); + private SelectionIntent draft; private ResolvedSelection resolution; private GroupSelectionSummary summary; private String resolutionError = ""; - // The receipt of the last auto-resolved conflict, shown in yellow until the next successful selection change. - private String conflictNotice = ""; + private String notice = ""; private boolean closed; - private boolean switchInFlight; - private boolean saveInFlight; + private boolean submitting; private AbstractWidget saveButton; + private GroupSelectionList groupList; + private double scrollAmount; private DropdownWidget platformDropdown; - private int listBottom; - public GroupSelectionScreen(Screen parent, SelectedModpackTarget target, ReviewConsent actions, Consumer selectionAction) { - this(parent, target.manifest(), new Entry(target.selection().intent(), selectionAction, () -> {}, actions, null)); + public static GroupSelectionScreen forReview(Screen parent, SelectedModpackTarget target, String origin, ReviewConsent actions, Consumer selectionAction) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(selectionAction, "selectionAction"); + String safeOrigin = origin == null ? "" : origin; + return new GroupSelectionScreen(parent, target.manifest(), new Session() { + @Override + public String submitLabelKey() { + return "automodpack.selection.preview"; + } + + @Override + public boolean allowSubmitUnchanged() { + return true; + } + + @Override + public SelectionIntent initialSelection() { + return target.selection().intent(); + } + + @Override + public String origin() { + return safeOrigin; + } + + @Override + public boolean isCancelled() { + return actions != null && actions.reviewCancelled().getAsBoolean(); + } + + @Override + public SourceAvailability sourceAvailability() { + return actions == null ? null : actions.sourceAvailability().get(); + } + + @Override + public void submit(SelectionIntent intent, Runnable release) { + try { + selectionAction.accept(intent); + } catch (RuntimeException e) { + release.run(); + ScreenManager.failure(FailureRequest.of(e, "automodpack.error.update", FailureCategory.UPDATE, FailureDestination.CURRENT_SCREEN, null)); + } + } + }); } public static GroupSelectionScreen repair(Screen parent, GroupManifest manifest, SelectionIntent savedSelection, Consumer selectionAction, Runnable cancelAction) { - return new GroupSelectionScreen(parent, manifest, new Entry(savedSelection, selectionAction, cancelAction, null, null)); - } + Objects.requireNonNull(selectionAction, "selectionAction"); + Runnable safeCancel = cancelAction == null ? () -> {} : cancelAction; + return new GroupSelectionScreen(parent, manifest, new Session() { + @Override + public String submitLabelKey() { + return "automodpack.selection.preview"; + } + + @Override + public boolean allowSubmitUnchanged() { + return true; + } + + @Override + public SelectionIntent initialSelection() { + return savedSelection; + } + + @Override + public void submit(SelectionIntent intent, Runnable release) { + try { + selectionAction.accept(intent); + } catch (RuntimeException e) { + release.run(); + ScreenManager.failure(FailureRequest.of(e, "automodpack.error.update", FailureCategory.UPDATE, FailureDestination.CURRENT_SCREEN, null)); + } + } - static GroupSelectionScreen forInstalledRecord(Screen parent, PackDocument record) { - return new GroupSelectionScreen(parent, record.manifest(), new Entry(null, null, () -> {}, null, record)); + @Override + public void cancel() { + safeCancel.run(); + } + }); } - /** What an entry point varies; the screen settles everything else itself. */ - private record Entry(SelectionIntent initialSelection, Consumer selectionAction, Runnable cancelAction, - ReviewConsent actions, PackDocument localRecord) {} + static GroupSelectionScreen forInstalled(Screen parent, InstalledModpackController controller, PackDocument record) { + Objects.requireNonNull(controller, "controller"); + Objects.requireNonNull(record, "record"); + GroupManifest manifest = record.manifest(); + return new GroupSelectionScreen(parent, manifest, new Session() { + @Override + public String submitLabelKey() { + return "automodpack.selection.save"; + } + + @Override + public boolean allowSubmitUnchanged() { + return false; + } + + @Override + public String unchangedTooltipKey() { + return "automodpack.selection.noChanges"; + } + + @Override + public SelectionIntent initialSelection() { + return controller.savedSelection(manifest.modpackId()); + } + + @Override + public String origin() { + return controller.originFor(manifest.modpackId()); + } + + @Override + public void submit(SelectionIntent intent, Runnable release) { + controller.switchSelection(record, intent, manifest.modpackName(), release); + } + }); + } - private GroupSelectionScreen(Screen parent, GroupManifest manifest, Entry entry) { + private GroupSelectionScreen(Screen parent, GroupManifest manifest, Session session) { super(VersionedText.text("automodpack.selection.title")); this.parent = parent; - this.manifest = Objects.requireNonNull(manifest); - this.modpackId = manifest.modpackId(); + this.manifest = Objects.requireNonNull(manifest, "manifest"); + this.session = Objects.requireNonNull(session, "session"); this.modpackName = manifest.modpackName(); this.groups = manifest.groups(); - this.controller = new InstalledModpackController(); - this.origin = controller.originFor(modpackId); - this.selectionAction = entry.selectionAction(); - this.cancelAction = entry.cancelAction(); - this.actions = entry.actions(); - this.localRecord = entry.localRecord(); - // The player edits the desire - what they last asked for - which may already sit ahead of what is installed. - SelectionIntent initial = entry.initialSelection() != null ? entry.initialSelection() : controller.savedSelection(modpackId); - this.initialSelection = initial == null ? GroupSelectionResolver.defaultIntent(manifest) : initial; + this.origin = session.origin(); this.detectedPlatform = ClientPlatform.current(); - this.platformOverride = initial.platform() == null || initial.platform().equals(detectedPlatform) ? null : initial.platform(); - this.chosen.addAll(initial.requestedGroups()); - this.chosenCategories.addAll(initial.requestedCategories()); - this.excluded.addAll(initial.excludedGroups()); + SelectionIntent initial = session.initialSelection(); + if (initial == null) initial = SelectionIntent.DEFAULTS; + this.initialSelection = initial; + this.draft = initial; try { - useResolved(GroupSelectionResolver.resolve(manifest, initial, effectivePlatform())); + useResolved(GroupSelectionResolver.resolve(manifest, draft, effectivePlatform())); } catch (SelectionResolutionException e) { useResolved(Objects.requireNonNull(e.resolution(), "Invalid selection did not include a partial resolution")); this.resolutionError = VersionedText.str("automodpack.selection.savedInvalid"); @@ -140,47 +242,46 @@ private GroupSelectionScreen(Screen parent, GroupManifest manifest, Entry entry) @Override protected void init() { + if (this.groupList != null) this.scrollAmount = this.groupList.preservedScrollAmount(); super.init(); int actionY = this.height - 28; - String saveLabel = selectionAction != null ? "automodpack.selection.preview" : "automodpack.selection.save"; - SelectionIntent defaults = GroupSelectionResolver.defaultIntent(manifest); ActionRow footer = actionRow(ActionAreaLayout.RowKind.FOOTER, secondaryAction(VersionedText.text("automodpack.back"), press -> back()), - optionalAction(VersionedText.text("automodpack.selection.reset"), press -> { - chosen.clear(); - chosen.addAll(defaults.requestedGroups()); - chosenCategories.clear(); - excluded.clear(); - reresolveDefault(); - }), - primaryAction(VersionedText.text(saveLabel), press -> save())); + optionalAction(VersionedText.text("automodpack.selection.reset"), press -> resetToDefaults()), + primaryAction(VersionedText.text(session.submitLabelKey()), press -> save())); List actionButtons = this.addActionArea(ActionAreaLayout.FOOTER_RAIL, actionY, footer); + actionButtons.get(1).active = !submitting && !draft.isDefaults(); this.saveButton = actionButtons.get(2); this.saveButton.active = canSave(); - if (selectionAction == null && resolutionError.isEmpty() && !this.saveButton.active) setTooltip(this.saveButton, VersionedText.text("automodpack.selection.noChanges")); - int listTop = 80; - listBottom = actionAreaTop(ActionAreaLayout.FOOTER_RAIL, actionY, footer) - LIST_FOOTER_GAP; - this.addRenderableWidget(new GroupSelectionList(this.minecraft, this.width, this.height, listWidth(), listTop, listBottom, listItems(), this::onListToggle, this::onListInspect)); - String platformLabel = platformLabel(); - int platformButtonWidth = Math.max(90, Math.min(160, this.font.width(platformLabel) + 26)); - this.platformDropdown = dropdownWidget(listLeft() + listWidth() - platformButtonWidth, 24, platformButtonWidth, 20, VersionedText.literal(platformLabel)); - setTooltip(this.platformDropdown, VersionedText.text("automodpack.selection.platformTooltip")); - List choices = platformChoices(); - // The saved platform may no longer be declared by a refreshed manifest; the detected platform is always a choice. - int selected = choices.indexOf(effectivePlatform()); - if (selected < 0) selected = choices.indexOf(detectedPlatform); - this.platformDropdown.setOptions(platformOptions(choices), selected, listBottom, index -> pickPlatform(choices.get(index))); - } - - /** The detectable platforms plus every platform the loaded manifest declares, so a declared-only group stays reachable by explicit choice. */ + String unchangedTooltip = session.unchangedTooltipKey(); + if (unchangedTooltip != null && !submitting && resolutionError.isEmpty() && !this.saveButton.active) setTooltip(this.saveButton, VersionedText.text(unchangedTooltip)); + + int listTop = 78; + int listBottom = actionAreaTop(ActionAreaLayout.FOOTER_RAIL, actionY, footer) - LIST_FOOTER_GAP; + this.groupList = this.addRenderableWidget( + new GroupSelectionList(this.minecraft, this.width, this.height, panelWidth(PANEL_WIDTH), listTop, listBottom, listItems(), this::onListToggle, this::onListInspect)); + if (this.scrollAmount > 0) this.groupList.restoreScrollAmount(this.scrollAmount); + + this.platformDropdown = null; + if (manifest.hasDeclaredPlatforms()) { + String platformLabel = platformLabel(); + int platformButtonWidth = Math.max(90, Math.min(160, this.font.width(platformLabel) + 26)); + this.platformDropdown = dropdownWidget(panelLeft(PANEL_WIDTH) + panelWidth(PANEL_WIDTH) - platformButtonWidth, 24, platformButtonWidth, 20, VersionedText.literal(platformLabel)); + setTooltip(this.platformDropdown, VersionedText.text("automodpack.selection.platformTooltip")); + List choices = platformChoices(); + int selected = choices.indexOf(effectivePlatform()); + if (selected < 0 && detectedPlatform != null) selected = choices.indexOf(detectedPlatform); + this.platformDropdown.setOptions(platformOptions(choices), Math.max(0, selected), listBottom, index -> pickPlatform(choices.get(index))); + } + } + private List platformChoices() { List choices = new ArrayList<>(ClientPlatform.builtIns()); for (ClientPlatform platform : manifest.declaredPlatforms()) if (!choices.contains(platform)) choices.add(platform); return choices; } - /** The OS dropdown options: every platform choice, with the detected one marked in the list. */ private List platformOptions(List choices) { List options = new ArrayList<>(choices.size()); for (ClientPlatform platform : choices) @@ -190,392 +291,299 @@ private List platformOptions(List choices) { return options; } - /** Every group sits in a category, so the list is always sectioned: a header row, then that category's groups in declared order. */ private List listItems() { List items = new ArrayList<>(); - String section = null; - for (var entry : groups.entrySet()) { - if (!entry.getValue().category().equals(section)) { - section = entry.getValue().category(); - items.add(headerItem(section)); + + for (var catEntry : manifest.categories().entrySet()) { + String catId = catEntry.getKey(); + GroupManifest.Category cat = catEntry.getValue(); + List members = new ArrayList<>(); + for (String groupId : manifest.groupsOf(catId)) if (groups.get(groupId).selection().choosable()) members.add(groupId); + if (members.isEmpty()) continue; + + items.add(categoryHeaderItem(catId, cat)); + boolean exclusive = cat.pick().isExclusive(); + if (cat.pick() == CategoryPickMode.AT_MOST_ONE) items.add(noneRadioItem(catId, members)); + for (String groupId : members) items.add(groupItem(groupId, exclusive)); + } + + List uncategorized = new ArrayList<>(); + for (String groupId : manifest.groupsOf("")) if (groups.get(groupId).selection().choosable()) uncategorized.add(groupId); + if (!uncategorized.isEmpty()) { + if (!manifest.categories().isEmpty()) { + items.add(GroupSelectionList.Item.header("", VersionedText.text("automodpack.selection.otherCategory").withStyle(ChatFormatting.BOLD), VersionedText.literal(""), "")); } - items.add(groupItem(entry.getKey())); + for (String groupId : uncategorized) items.add(groupItem(groupId, false)); + } + + List included = new ArrayList<>(); + for (var entry : groups.entrySet()) { + if (entry.getValue().selection().choosable() || !resolution.selectedGroups().contains(entry.getKey())) continue; + included.add(entry.getKey()); + } + if (!included.isEmpty()) { + items.add(GroupSelectionList.Item.header("", VersionedText.text("automodpack.selection.includedAutomatically").withStyle(ChatFormatting.BOLD, ChatFormatting.WHITE), VersionedText.literal(""), "")); + for (String groupId : included) items.add(includedGroupItem(groupId)); } return List.copyOf(items); } - private GroupSelectionList.Item headerItem(String category) { - return new GroupSelectionList.Item(GroupSelectionList.Kind.HEADER, category, headerLabel(category), headerTooltip(category, hasOptionalCategoryGroups(category)), - categoryFullySelected(category), hasOptionalCategoryGroups(category), categoryPartiallySelected(category), headerCounter(category)); + private GroupSelectionList.Item includedGroupItem(String groupId) { + GroupManifest.Group group = groups.get(groupId); + GroupResolution explanation = resolution.resolution(groupId); + Component title = VersionedText.literal(manifest.displayName(groupId)); + Component badge = VersionedText.literal(UiFormat.plural(group.files().size(), "automodpack.selection.metrics", UiFormat.formatSize(groupBytes(group))).getString()); + Component subtitle = includedSubtitle(explanation); + Component tooltip = cardTooltip(groupId, group, explanation, subtitle); + return GroupSelectionList.Item.included(groupId, group.category(), title, subtitle, badge, tooltip); } - private GroupSelectionList.Item groupItem(String groupId) { - GroupManifest.Group group = groups.get(groupId); - boolean togglable = group != null && canToggle(groupId, group); - return new GroupSelectionList.Item(GroupSelectionList.Kind.GROUP, groupId, rowLabel(groupId, group), rowTooltip(groupId, group), resolution.selectedGroups().contains(groupId), togglable, false, ""); + private Component includedSubtitle(GroupResolution explanation) { + if (explanation != null && !explanation.relatedGroups().isEmpty()) return VersionedText.text("automodpack.selection.dependencyNamed", names(explanation.relatedGroups())); + return VersionedText.text("automodpack.selection.required"); } - private void onListToggle(GroupSelectionList.Item item) { - if (item.kind() == GroupSelectionList.Kind.HEADER) { - toggleCategory(item.id()); - return; + private GroupSelectionList.Item categoryHeaderItem(String catId, GroupManifest.Category cat) { + String actionLabel = ""; + if (!cat.pick().isExclusive()) { + List toggleable = GroupSelectionResolver.bulkToggleTargets(manifest, resolution, catId, effectivePlatform()); + if (toggleable.size() >= 2) { + boolean allSelected = toggleable.stream().allMatch(resolution.selectedGroups()::contains); + actionLabel = VersionedText.str(allSelected ? "automodpack.selection.clearCategory" : "automodpack.selection.selectAll"); + } } - toggle(item.id()); + MutableComponent title = VersionedText.literal(manifest.categoryDisplayName(catId)).withStyle(ChatFormatting.BOLD, ChatFormatting.WHITE); + String subtitleText = headerSubtitle(cat); + return GroupSelectionList.Item.header(catId, title, subtitleText.isBlank() ? VersionedText.literal("") : VersionedText.literal(subtitleText), actionLabel); } - private void onListInspect(GroupSelectionList.Item item) { - if (item.kind() == GroupSelectionList.Kind.GROUP) inspect(item.id()); + private static String headerSubtitle(GroupManifest.Category cat) { + String pickHint = cat.pick() == CategoryPickMode.EXACTLY_ONE + ? VersionedText.str("automodpack.selection.pickOne") + : cat.pick() == CategoryPickMode.AT_MOST_ONE ? VersionedText.str("automodpack.selection.pickAtMostOne") : ""; + if (cat.description().isBlank()) return pickHint; + if (pickHint.isBlank()) return cat.description(); + return pickHint + " · " + cat.description(); } - /** The Files button on a group row opens the pack's file browser pre-filtered to that group - the row tooltip already carries the group's metadata. */ - private void inspect(String groupId) { - if (!groups.containsKey(groupId)) return; - ScreenImpl.setScreen(new ChangeBrowserScreen(this, VersionedText.literal(displayName(groupId)), - VersionedText.text("automodpack.browser.groupDescription"), ChangeSet.catalogue(manifest), InstalledModpackController.groupNames(manifest), null, List.of(), 0, groupId)); + private GroupSelectionList.Item noneRadioItem(String catId, List members) { + boolean noneSelected = members.stream().noneMatch(resolution.selectedGroups()::contains); + boolean locked = members.stream().anyMatch(id -> resolution.selectedGroups().contains(id) && resolution.requiredGroups().contains(id)); + return GroupSelectionList.Item.radio("", catId, + VersionedText.text("automodpack.selection.noneOption").withStyle(noneSelected ? ChatFormatting.WHITE : ChatFormatting.GRAY), VersionedText.text("automodpack.selection.noneSubtitle"), + VersionedText.literal(""), null, noneSelected, !locked, noneSelected ? ACCENT_SELECTED : 0); } - @Override - public void tick() { - super.tick(); - if (actions == null) return; - if (actions.reviewCancelled().getAsBoolean()) ScreenImpl.multiplayer(); + private GroupSelectionList.Item groupItem(String groupId, boolean radio) { + GroupManifest.Group group = groups.get(groupId); + boolean selected = resolution.selectedGroups().contains(groupId); + boolean canToggle = canToggle(groupId, group); + GroupResolution explanation = resolution.resolution(groupId); + ChatFormatting color = rowColor(groupId, group, explanation); + MutableComponent title = VersionedText.literal(manifest.displayName(groupId)).withStyle(color); + MutableComponent badge = VersionedText.literal(UiFormat.plural(group.files().size(), "automodpack.selection.metrics", UiFormat.formatSize(groupBytes(group))).getString()) + .withStyle(ChatFormatting.GRAY); + Component subtitle = cardSubtitle(groupId, group, explanation); + Component tooltip = cardTooltip(groupId, group, explanation, subtitle); + int accent = accentColor(groupId, selected, explanation); + return radio + ? GroupSelectionList.Item.radio(groupId, group.category(), title, subtitle, badge, tooltip, selected, canToggle, accent) + : GroupSelectionList.Item.checkable(groupId, group.category(), title, subtitle, badge, tooltip, selected, canToggle, accent); + } + + private Component cardSubtitle(String groupId, GroupManifest.Group group, GroupResolution explanation) { + if (explanation != null && explanation.status() == GroupResolution.Status.CONFLICT && !explanation.relatedGroups().isEmpty()) { + return VersionedText.text("automodpack.selection.conflictsWith", names(explanation.relatedGroups())).withStyle(ChatFormatting.RED); + } + if (explanation != null && explanation.status() == GroupResolution.Status.UNAVAILABLE) { + return VersionedText.text("automodpack.selection.unavailableOn", platformDisplay(effectivePlatform())).withStyle(ChatFormatting.RED); + } + if (explanation != null && explanation.status() == GroupResolution.Status.BLOCKED) { + String text = explanation.relatedGroups().isEmpty() + ? VersionedText.str("automodpack.selection.status.dependencyUnavailable") + : VersionedText.str("automodpack.selection.blockedBy", names(explanation.relatedGroups())); + return VersionedText.literal(text).withStyle(ChatFormatting.RED); + } + if (resolution.requiredGroups().contains(groupId)) { + return VersionedText.text("automodpack.selection.includedWithCore").withStyle(ChatFormatting.AQUA); + } + if (resolution.dependencyGroups().contains(groupId) && explanation != null && !explanation.relatedGroups().isEmpty()) { + return VersionedText.text("automodpack.selection.dependencyNamed", names(explanation.relatedGroups())).withStyle(ChatFormatting.AQUA); + } + if (!group.description().isBlank()) return VersionedText.literal(group.description()); + return VersionedText.literal(""); + } + + private Component cardTooltip(String groupId, GroupManifest.Group group, GroupResolution explanation, Component subtitle) { + List lines = new ArrayList<>(); + if (!group.description().isBlank()) lines.add(group.description()); + if (!group.requires().isEmpty()) lines.add(VersionedText.str("automodpack.selection.requires", names(group.requires()))); + Set conflicts = manifest.conflictsOf(groupId); + if (!conflicts.isEmpty()) lines.add(VersionedText.str("automodpack.selection.conflictsWith", names(conflicts))); + if (explanation != null && !explanation.relatedGroups().isEmpty() && explanation.reasons().contains(GroupResolution.Reason.DEPENDENCY)) { + lines.add(VersionedText.str("automodpack.selection.dependencyNamed", names(explanation.relatedGroups()))); + } + if (!group.compatiblePlatforms().isEmpty()) { + List platforms = group.compatiblePlatforms().stream().map(this::platformDisplay).toList(); + lines.add(VersionedText.str("automodpack.selection.onlyFor", String.join(", ", platforms))); + } + if (explanation != null && explanation.status() == GroupResolution.Status.BLOCKED) { + lines.add(explanation.relatedGroups().isEmpty() + ? VersionedText.str("automodpack.selection.status.dependencyUnavailable") + : VersionedText.str("automodpack.selection.blockedBy", names(explanation.relatedGroups()))); + } else if (!group.supports(effectivePlatform())) { + lines.add(VersionedText.str("automodpack.selection.unavailableOn", platformDisplay(effectivePlatform()))); + } + if (lines.isEmpty()) return null; + String subtitleText = subtitle == null ? "" : subtitle.getString(); + if (lines.size() == 1 && lines.get(0).equals(subtitleText) && this.font.width(subtitleText) <= GroupSelectionList.cardTextWidth(panelWidth(PANEL_WIDTH))) { + return null; + } + return VersionedText.literal(String.join("\n", lines)).withStyle(ChatFormatting.GRAY); } - private boolean canToggle(String groupId, GroupManifest.Group group) { - if (group.alwaysInstalled()) return false; - GroupResolution explanation = resolution.resolution(groupId); - if (explanation == null) return group.supports(effectivePlatform()); - if (explanation.selected() && (resolution.requiredGroups().contains(groupId) || resolution.forcedGroups().contains(groupId) - || resolution.dependencyGroups().contains(groupId))) - return false; - return group.supports(effectivePlatform()) || excluded.contains(groupId); + private int accentColor(String groupId, boolean selected, GroupResolution explanation) { + if (isUnavailableOrConflicting(explanation)) return ACCENT_ERROR; + if (!selected) return 0; + if (draft.enabled().contains(groupId)) return ACCENT_SELECTED; + return ACCENT_DEFAULT; } - /** Toggling a category requests or removes its optional groups through the persisted group intent. */ - private void toggleCategory(String category) { - SelectionIntent previous = currentIntent(); - // Direction mirrors the header glyph: when every optional group is already in, the click excludes them all. - SelectionIntent resolved = categoryFullySelected(category) - ? GroupSelectionResolver.excludeCategory(manifest, previous, category, effectivePlatform()) - : GroupSelectionResolver.preferCategory(manifest, previous, category, effectivePlatform()); - SelectionIntent next = resolved.withPlatform(override()); - Set preferred = next.requestedCategories().contains(category) ? categoryGroups(category) : Set.of(); - applySelectionChange(next, preferred, category); + private ChatFormatting rowColor(String groupId, GroupManifest.Group group, GroupResolution explanation) { + if (isUnavailableOrConflicting(explanation)) return ChatFormatting.RED; + if (resolution.selectedGroups().contains(groupId)) { + if (draft.enabled().contains(groupId)) return ChatFormatting.GREEN; + return ChatFormatting.AQUA; + } + return ChatFormatting.WHITE; } - private boolean categoryFullySelected(String category) { - long optional = optionalGroupCount(category); - return optional > 0 && selectedOptionalGroupCount(category) == optional; + private static boolean isUnavailableOrConflicting(GroupResolution explanation) { + return explanation != null && (explanation.status() == GroupResolution.Status.UNAVAILABLE || explanation.status() == GroupResolution.Status.BLOCKED + || explanation.status() == GroupResolution.Status.CONFLICT || explanation.reasons().contains(GroupResolution.Reason.EXPLICIT_ENABLE_UNAVAILABLE)); } - /** - * A group inside a selected category becomes an explicit exclusion when it is not otherwise required. - * Direct choices remain in the intent when they conflict, so the player can remove either choice explicitly. - */ - private void toggle(String groupId) { - GroupManifest.Group group = groups.get(groupId); - if (group == null) return; - if (group.alwaysInstalled()) return; - SelectionIntent previous = currentIntent(); - SelectionIntent next = GroupSelectionResolver.prefer(manifest, previous, groupId, effectivePlatform()).withPlatform(override()); - Set preferred = resolution.selectedGroups().contains(groupId) ? Set.of() : Set.of(groupId); - applySelectionChange(next, preferred, displayName(groupId)); - } - - private void applySelectionChange(SelectionIntent next, Set preferredGroups, String preferredName) { - InstalledModpackController.SelectionChange change = controller.planSelectionChange(manifest, next, preferredGroups, preferredName, effectivePlatform()); - if (change.resolution() != null) { - applyResolved(change.intent(), change.resolution()); + private void onListToggle(GroupSelectionList.Item item) { + if (item.kind() == GroupSelectionList.Kind.HEADER) { + List toggleable = GroupSelectionResolver.bulkToggleTargets(manifest, resolution, item.categoryId(), effectivePlatform()); + boolean allSelected = toggleable.stream().allMatch(resolution.selectedGroups()::contains); + applyUpdate(GroupSelectionResolver.setCategoryAll(manifest, draft, item.categoryId(), !allSelected, effectivePlatform())); return; } - if (change.conflict() != null) resolveConflict(change.conflict(), preferredName); - else { - resolutionError = change.failure(); - rebuild(); + if (item.kind() == GroupSelectionList.Kind.RADIO_GROUP) { + if (carriesUninstalledAsk(item.id())) { + // A radio pick this platform cannot install has no choice to re-pick; clicking it forgets the ask. + applyUpdate(GroupSelectionResolver.toggleGroup(manifest, draft, item.id(), effectivePlatform())); + return; + } + String chosen = item.id().isEmpty() ? null : item.id(); + applyUpdate(GroupSelectionResolver.pickInCategory(manifest, draft, item.categoryId(), chosen, effectivePlatform())); + return; } + applyUpdate(GroupSelectionResolver.toggleGroup(manifest, draft, item.id(), effectivePlatform())); } - /** - * A conflict no longer asks: the resolver's replacement applies immediately, and the receipt line names what it turned - * off and which preferred choice caused it. If even the replacement cannot resolve, the failure line explains why and - * the selection stays unchanged. The notice survives failed changes; the next successful selection change clears it. - */ - private void resolveConflict(GroupSelectionResolver.ConflictReplacement replacement, String preferredName) { - Set previousSelection = Set.copyOf(resolution.selectedGroups()); - InstalledModpackController.SelectionChange settled = controller.planSelectionChange(manifest, replacement.intent().withPlatform(override()), Set.of(), preferredName, effectivePlatform()); - if (settled.resolution() == null) { - resolutionError = settled.failure(); + /** An ask for a group that is not selected here: its platform or a blocked dependency keeps it from installing, so the click can only forget it. */ + private boolean carriesUninstalledAsk(String groupId) { + return !groupId.isEmpty() && draft.enabled().contains(groupId) && !resolution.selectedGroups().contains(groupId); + } + + private void applyUpdate(GroupSelectionResolver.SelectionUpdate update) { + if (!update.ok()) { + this.resolutionError = update.error(); rebuild(); return; } - applyResolved(settled.intent(), settled.resolution()); - // Set after applyResolved: the next successful change clears the notice, and applying IS that change. - conflictNotice = turnedOffNotice(previousSelection, settled.resolution(), preferredName); + this.draft = update.intent(); + useResolved(update.resolution()); + this.resolutionError = ""; + String noticeKey = update.turnedOffByConflict() ? "automodpack.selection.conflictTurnedOff" : "automodpack.selection.cascadeTurnedOff"; + this.notice = update.turnedOff().isEmpty() ? "" : UiFormat.plural(update.turnedOff().size(), noticeKey, names(update.turnedOff())).getString(); + rebuild(); } - /** The groups the replacement deselected, as a plural-aware warning naming the preferred choice that caused it. */ - private String turnedOffNotice(Set previousSelection, ResolvedSelection resolved, String preferredName) { - Set turnedOff = new TreeSet<>(previousSelection); - turnedOff.removeAll(resolved.selectedGroups()); - if (turnedOff.isEmpty()) return ""; - return UiFormat.plural(turnedOff.size(), "automodpack.selection.conflictTurnedOff", names(turnedOff), preferredName).getString(); + private void resetToDefaults() { + SelectionIntent reset = SelectionIntent.DEFAULTS.withPlatform(override()); + try { + ResolvedSelection resolved = GroupSelectionResolver.resolve(manifest, reset, effectivePlatform()); + this.draft = reset; + useResolved(resolved); + this.resolutionError = ""; + this.notice = ""; + rebuild(); + } catch (SelectionResolutionException e) { + this.resolutionError = String.join("; ", e.errors()); + rebuild(); + } } - private Set categoryGroups(String category) { - Set result = new TreeSet<>(); - for (var entry : groups.entrySet()) if (category.equals(entry.getValue().category()) && !entry.getValue().alwaysInstalled() && entry.getValue().supports(effectivePlatform())) result.add(entry.getKey()); - return Set.copyOf(result); + private void onListInspect(GroupSelectionList.Item item) { + if (item.kind() != GroupSelectionList.Kind.HEADER && !item.id().isEmpty()) inspect(item.id()); } - private void applyResolved(SelectionIntent intent, ResolvedSelection resolved) { - applyIntent(intent); - useResolved(resolved); - resolutionError = ""; - conflictNotice = ""; - rebuild(); + private void inspect(String groupId) { + if (!groups.containsKey(groupId)) return; + ScreenImpl.setScreen(new ChangeBrowserScreen(this, VersionedText.literal(manifest.displayName(groupId)), + VersionedText.text("automodpack.browser.groupDescription"), ChangeSet.catalogue(manifest), InstalledModpackController.groupNames(manifest), null, List.of(), 0, groupId)); } - private void applyIntent(SelectionIntent intent) { - chosen.clear(); - chosen.addAll(intent.requestedGroups()); - chosenCategories.clear(); - chosenCategories.addAll(intent.requestedCategories()); - excluded.clear(); - excluded.addAll(intent.excludedGroups()); + @Override + public void tick() { + super.tick(); + if (session.isCancelled()) ScreenImpl.multiplayer(); } - private void reresolveDefault() { - useResolved(GroupSelectionResolver.resolveDefault(manifest, effectivePlatform())); - resolutionError = ""; - conflictNotice = ""; - rebuild(); + private boolean canToggle(String groupId, GroupManifest.Group group) { + if (group == null || !group.selection().choosable()) return false; + if (resolution.requiredGroups().contains(groupId)) return false; + GroupManifest.Category cat = manifest.categoryOf(groupId); + if (cat != null && cat.pick() == CategoryPickMode.EXACTLY_ONE && resolution.selectedGroups().contains(groupId)) return false; + GroupResolution explanation = resolution.resolution(groupId); + if (explanation != null && explanation.status() == GroupResolution.Status.BLOCKED && !resolution.selectedGroups().contains(groupId) && !draft.enabled().contains(groupId)) return false; + return group.supports(effectivePlatform()) || draft.enabled().contains(groupId); } - /** Every answer of the resolver is rendered from this one place, so the summary never lags the selection. */ private void useResolved(ResolvedSelection resolved) { this.resolution = Objects.requireNonNull(resolved, "resolution"); this.summary = GroupSelectionSummary.of(manifest, resolved.selectedGroups()); } private void save() { - SelectionIntent target = currentIntent(); - if (!resolutionError.isEmpty()) return; - if (selectionAction != null) { - if (saveInFlight) return; - saveInFlight = true; - try { - selectionAction.accept(target); - } catch (RuntimeException e) { - saveInFlight = false; - ScreenManager.failure(FailureRequest.of(e, "automodpack.error.update", FailureCategory.UPDATE, FailureDestination.CURRENT_SCREEN, null)); - } - return; - } - startCachedSwitch(target); + if (!canSave()) return; + submitting = true; + if (saveButton != null) saveButton.active = false; + session.submit(draft, this::releaseSubmit); } - private void startCachedSwitch(SelectionIntent targetIntent) { - if (switchInFlight) return; - switchInFlight = true; - controller.switchSelection(localRecord, targetIntent, modpackName, () -> switchInFlight = false); + private void releaseSubmit() { + Runnable finish = () -> { + submitting = false; + if (!closed) rebuild(); + }; + if (this.minecraft != null) this.minecraft.execute(finish); + else finish.run(); } private void back() { if (closed) return; closed = true; - cancelAction.run(); + session.cancel(); ScreenImpl.setScreen(parent); } - /** The header glyph names what the next click does: full = exclude all, empty = include all, partial = include the rest. */ - private MutableComponent headerLabel(String category) { - long optional = optionalGroupCount(category); - long selected = selectedOptionalGroupCount(category); - boolean allSelected = optional > 0 && selected == optional; - return VersionedText.literal(VersionedText.str("automodpack.selection.category", category)) - .withStyle(ChatFormatting.BOLD, allSelected ? ChatFormatting.GREEN : selected == 0 ? ChatFormatting.GRAY : ChatFormatting.YELLOW); - } - - private boolean categoryPartiallySelected(String category) { - long optional = optionalGroupCount(category); - long selected = selectedOptionalGroupCount(category); - return selected > 0 && selected < optional; - } - - private String headerCounter(String category) { - long optional = optionalGroupCount(category); - return optional == 0 ? "" : selectedOptionalGroupCount(category) + "/" + optional; - } - - private Component headerTooltip(String category, boolean canToggle) { - if (!canToggle) return null; - StringBuilder tooltip = new StringBuilder(VersionedText.str("automodpack.selection.categoryTooltip")); - if (categoryPartiallySelected(category)) - tooltip.append("\n").append(VersionedText.str("automodpack.selection.categoryPart", selectedOptionalGroupCount(category), optionalGroupCount(category))); - return VersionedText.literal(tooltip.toString()).withStyle(ChatFormatting.GRAY); - } - - private long optionalGroupCount(String category) { - return groups.values().stream().filter(group -> category.equals(group.category()) && !group.alwaysInstalled()).count(); - } - - private long selectedOptionalGroupCount(String category) { - return groups.entrySet().stream().filter(entry -> category.equals(entry.getValue().category()) && !entry.getValue().alwaysInstalled() && resolution.selectedGroups().contains(entry.getKey())).count(); - } - - /** The group's metadata and the resolver explanation, shown on hover. */ - private MutableComponent rowTooltip(String groupId, GroupManifest.Group group) { - if (group == null) return null; - StringBuilder tooltip = new StringBuilder(); - if (!group.description().isBlank()) { - tooltip.append(group.description()); - // The description is the server's words; the attribution keeps them from reading as client-authored copy. - appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.serverDescription")); - } - GroupResolution explanation = resolution.resolution(groupId); - if (explanation != null) appendTooltipLine(tooltip, resolutionText(explanation)); - appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.category", group.category())); - // The resolution text already carries "Required: always included" whenever it exists; only fall back to it here. - if (group.alwaysInstalled() && explanation == null) appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.requiredAlways")); - if (group.arrivesSelected()) appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.defaultSelected")); - if (resolution.forcedGroups().contains(groupId)) appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.forced")); - if (!group.requires().isEmpty()) appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.requires", names(group.requires()))); - if (!group.breaksWith().isEmpty()) appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.conflicts", names(group.breaksWith()))); - appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.files", group.files().size(), UiFormat.formatSize(groupBytes(group)))); - if (!group.supports(effectivePlatform())) appendTooltipLine(tooltip, VersionedText.str("automodpack.selection.unavailableOn", effectivePlatform().id())); - return VersionedText.literal(tooltip.toString()).withStyle(ChatFormatting.GRAY); - } - - private String resolutionText(GroupResolution groupResolution) { - return switch (groupResolution.status()) { - case SELECTED -> selectedResolutionText(groupResolution); - case AVAILABLE -> VersionedText.str("automodpack.selection.status.available"); - case UNAVAILABLE -> VersionedText.str("automodpack.selection.unavailableOn", effectivePlatform().id()); - case BLOCKED -> groupResolution.relatedGroups().isEmpty() - ? VersionedText.str("automodpack.selection.status.dependencyUnavailable") - : VersionedText.str("automodpack.selection.blockedBy", names(groupResolution.relatedGroups())); - case EXCLUDED -> VersionedText.str("automodpack.selection.status.excluded"); - case CONFLICT -> VersionedText.str("automodpack.selection.conflictsWith", names(groupResolution.relatedGroups())); - }; - } - - private String selectedResolutionText(GroupResolution groupResolution) { - if (groupResolution.reasons().contains(GroupResolution.Reason.REQUIRED)) return VersionedText.str("automodpack.selection.requiredAlways"); - if (groupResolution.reasons().contains(GroupResolution.Reason.FORCED)) return VersionedText.str("automodpack.selection.forced"); - if (groupResolution.reasons().contains(GroupResolution.Reason.DEPENDENCY)) return VersionedText.str("automodpack.selection.dependencyNamed", names(groupResolution.relatedGroups())); - if (groupResolution.reasons().contains(GroupResolution.Reason.DEFAULT_SELECTED)) return VersionedText.str("automodpack.selection.defaultSelected"); - return VersionedText.str("automodpack.selection.status.selected"); - } - - private static void appendTooltipLine(StringBuilder tooltip, String line) { - if (tooltip.length() > 0) tooltip.append('\n'); - tooltip.append(line); - } - - private MutableComponent rowLabel(String groupId, GroupManifest.Group group) { - if (group == null) return VersionedText.text("automodpack.browser.unknownGroup"); - - GroupResolution explanation = resolution.resolution(groupId); - String status = statusWord(explanation); - int maxWidth = groupLabelWidth(); - int textWidth = status.isEmpty() ? maxWidth : Math.max(1, maxWidth - this.font.width(" " + status)); - String name = displayName(groupId); - String metrics = UiFormat.plural(group.files().size(), "automodpack.selection.metrics", UiFormat.formatSize(groupBytes(group))).getString(); - MutableComponent label = VersionedText.literal(truncateToWidth(this.font, name + " " + metrics, textWidth)).withStyle(rowColor(groupId, group, explanation)); - if (!status.isEmpty()) label.append(VersionedText.literal(" " + status).withStyle(ChatFormatting.GRAY)); - return label; - } - - /** The color is the load-bearing row state; the wording lives in the status word and the hover tooltip. */ - private ChatFormatting rowColor(String groupId, GroupManifest.Group group, GroupResolution explanation) { - if (group.alwaysInstalled()) return ChatFormatting.GRAY; - if (explanation != null && (explanation.reasons().contains(GroupResolution.Reason.EXPLICIT_REQUEST_UNAVAILABLE) || explanation.status() == GroupResolution.Status.UNAVAILABLE - || explanation.status() == GroupResolution.Status.BLOCKED || explanation.status() == GroupResolution.Status.CONFLICT)) - return ChatFormatting.RED; - if (excluded.contains(groupId)) return ChatFormatting.YELLOW; - if (resolution.selectedGroups().contains(groupId)) { - // A dependency lock is the load-bearing fact: the row cannot be unchecked while its dependent needs it. - if (resolution.dependencyGroups().contains(groupId)) return ChatFormatting.AQUA; - if (chosen.contains(groupId)) return ChatFormatting.GREEN; - return ChatFormatting.AQUA; - } - if (resolution.forcedGroups().contains(groupId)) return ChatFormatting.AQUA; - return group.arrivesSelected() ? ChatFormatting.YELLOW : ChatFormatting.GRAY; - } - - /** The row's state word in the surviving status keys; statuses whose explanation is a full sentence stay hover-only. */ - private String statusWord(GroupResolution explanation) { - if (explanation == null) return ""; - return switch (explanation.status()) { - case SELECTED -> explanation.reasons().contains(GroupResolution.Reason.REQUIRED) || explanation.reasons().contains(GroupResolution.Reason.FORCED) - || explanation.reasons().contains(GroupResolution.Reason.DEPENDENCY) || explanation.reasons().contains(GroupResolution.Reason.DEFAULT_SELECTED) - ? "" - : VersionedText.str("automodpack.selection.status.selected"); - case AVAILABLE -> VersionedText.str("automodpack.selection.status.available"); - case BLOCKED -> explanation.relatedGroups().isEmpty() ? VersionedText.str("automodpack.selection.status.dependencyUnavailable") : ""; - case EXCLUDED -> VersionedText.str("automodpack.selection.status.excluded"); - default -> ""; - }; - } - - private int groupLabelWidth() { - return Math.max(1, listWidth() - CHECKBOX_LABEL_OFFSET - GroupSelectionList.filesButtonWidth() - ActionAreaLayout.SEAM - 4); - } - - /** The group list sits on the same centered panel as every other list screen. */ - private int listWidth() { - return panelWidth(PANEL_WIDTH); - } - - private int listLeft() { - return panelLeft(PANEL_WIDTH); - } - - private static long groupBytes(GroupManifest.Group group) { - long total = 0; - for (GroupManifest.GroupFile file : group.files().values()) total = Math.addExact(total, file.size()); - return total; - } - - private String names(Iterable values) { - StringBuilder result = new StringBuilder(); - for (String value : values) { - if (result.length() > 0) result.append(", "); - GroupManifest.Group related = groups.get(value); - if (related == null) result.append(VersionedText.str("automodpack.browser.unknownGroup")); - else result.append(related.displayName().isBlank() ? value : related.displayName()); - } - return result.length() == 0 ? VersionedText.str("automodpack.ui.none") : result.toString(); - } - - /** A group without a display name shows its id, so an unnamed group is never mistaken for a broken reference. */ - private String displayName(String groupId) { - GroupManifest.Group group = groups.get(groupId); - if (group == null) return VersionedText.str("automodpack.browser.unknownGroup"); - return group.displayName().isBlank() ? groupId : group.displayName(); - } - - private boolean hasOptionalCategoryGroups(String category) { - return groups.values().stream().anyMatch(group -> category.equals(group.category()) && !group.alwaysInstalled()); - } - - private SelectionIntent currentIntent() { - return new SelectionIntent(chosen, chosenCategories, excluded, override()); - } - private ClientPlatform override() { - return Objects.equals(detectedPlatform, platformOverride) ? null : platformOverride; + ClientPlatform current = draft.platform(); + return Objects.equals(detectedPlatform, current) ? null : current; } private ClientPlatform effectivePlatform() { - return ClientPlatform.effective(currentIntent()); + return ClientPlatform.effective(draft); } private String platformLabel() { return VersionedText.str("automodpack.selection.platformButton", platformDisplay(effectivePlatform())); } - /** The display name of a platform choice; nothing is known about the platform when none is detected or chosen. */ private String platformDisplay(ClientPlatform platform) { if (platform == null) return VersionedText.str("automodpack.selection.platformUndetected"); if (platform.equals(ClientPlatform.WINDOWS)) return "Windows"; @@ -585,24 +593,53 @@ private String platformDisplay(ClientPlatform platform) { } private void pickPlatform(ClientPlatform platform) { - platformOverride = platform.equals(detectedPlatform) ? null : platform; - applySelectionChange(currentIntent(), Set.of(), null); + ClientPlatform nextOverride = Objects.equals(detectedPlatform, platform) ? null : platform; + ClientPlatform effective = nextOverride != null ? nextOverride : detectedPlatform; + applyUpdate(GroupSelectionResolver.withPlatform(manifest, draft, nextOverride, effective)); } private boolean canSave() { - ClientPlatform savedPlatform = initialSelection.platform(); - ClientPlatform currentPlatform = currentIntent().platform(); - boolean platformChanged = currentPlatform != null ? !currentPlatform.equals(savedPlatform) : savedPlatform != null && !savedPlatform.equals(detectedPlatform); - return resolutionError.isEmpty() - && (selectionAction != null || !initialSelection.equals(currentIntent()) || platformChanged); + boolean platformChanged = !Objects.equals(ClientPlatform.effective(initialSelection), effectivePlatform()); + return !submitting && resolutionError.isEmpty() && (session.allowSubmitUnchanged() || !initialSelection.equals(draft) || platformChanged); + } + + private static long groupBytes(GroupManifest.Group group) { + long total = 0; + for (GroupManifest.GroupFile file : group.files().values()) total = Math.addExact(total, file.size()); + return total; + } + + private String names(Iterable ids) { + List list = new ArrayList<>(); + for (String id : ids) list.add(groups.containsKey(id) ? manifest.displayName(id) : VersionedText.str("automodpack.browser.unknownGroup")); + return list.isEmpty() ? VersionedText.str("automodpack.ui.none") : String.join(", ", list); } - /** The estimated download size of the current selection: unique paths across the selected groups, shared files counted once. */ - private long selectionBytes() { - return summary == null ? 0 : summary.byteCount(); + private String summaryText() { + int coreCount = 0; + int optionalSelected = 0; + int optionalTotal = 0; + ClientPlatform platform = effectivePlatform(); + for (var entry : groups.entrySet()) { + GroupManifest.Group group = entry.getValue(); + boolean selected = resolution.selectedGroups().contains(entry.getKey()); + if (group.selection().choosable()) { + if (group.supports(platform)) { + optionalTotal++; + if (selected) optionalSelected++; + } + } else if (selected) { + coreCount++; + } + } + String counts = optionalTotal > 0 + ? VersionedText.str("automodpack.selection.countsWithOptional", coreCount, optionalSelected, optionalTotal) + : VersionedText.str("automodpack.selection.countsCoreOnly", coreCount); + String size = UiFormat.formatSize(summary == null ? 0 : summary.byteCount()); + if (!manifest.hasDeclaredPlatforms()) return VersionedText.str("automodpack.selection.summary", counts, size); + return VersionedText.str("automodpack.selection.summaryPlatform", platformDisplay(platform), counts, size); } - // Per-frame cache: the rail wrap only changes when the window resizes. private List wrappedDescription = List.of(); private int wrappedDescriptionWidth = -1; @@ -616,56 +653,48 @@ private List wrappedDescription(int width, String description) { @Override public void versionedRender(VersionedMatrices matrices, int mouseX, int mouseY, float delta) { - // Header names the modpack when the server set one, so the player knows which pack they are editing. - MutableComponent header = modpackName.isBlank() - ? VersionedText.text("automodpack.selection.title") - : VersionedText.literal(modpackName); + MutableComponent header = modpackName.isBlank() ? VersionedText.text("automodpack.selection.title") : VersionedText.literal(modpackName); drawCenteredTextWithShadow(matrices, this.font, VersionedText.literal(truncateToWidth(this.font, header.getString(), this.width - 20)).withStyle(ChatFormatting.BOLD), this.width / 2, 11, TextColors.WHITE); MutableComponent description = VersionedText.text("automodpack.selection.description"); - // The header stack shares the rail with the platform dropdown (y 24..44), so the description - // wraps inside the space left of it and the summary waits until that zone ends. The origin - // takes the first rail line when it is known, so the pack name always sits next to its server. - int railLeft = listLeft(); - int railWidth = listWidth(); + int railLeft = panelLeft(PANEL_WIDTH); + int railWidth = panelWidth(PANEL_WIDTH); int railY = 22; if (!origin.isBlank()) { drawTextWithShadow(matrices, this.font, VersionedText.text("automodpack.packDetails.server", origin).withStyle(ChatFormatting.GRAY), railLeft, railY, TextColors.WHITE); railY += 11; } - List descriptionLines = wrappedDescription(railWidth - platformDropdown.getWidth() - 8, description.getString()); - // The description shares the rail with the summary line at y=44, so it may only use the rows above it. + int dropdownReserve = platformDropdown != null ? platformDropdown.getWidth() + 8 : 0; + List descriptionLines = wrappedDescription(railWidth - dropdownReserve, description.getString()); int maxDescriptionLines = Math.max(1, (44 - railY) / 11); if (descriptionLines.size() > maxDescriptionLines) descriptionLines = descriptionLines.subList(0, maxDescriptionLines); for (int index = 0; index < descriptionLines.size(); index++) drawTextWithShadow(matrices, this.font, VersionedText.literal(descriptionLines.get(index)).withStyle(ChatFormatting.GRAY), railLeft, railY + index * 11, TextColors.WHITE); + drawTextWithShadow(matrices, this.font, - VersionedText.text("automodpack.selection.platformSummary", platformDisplay(effectivePlatform()), resolution.selectedGroups().size(), UiFormat.formatSize(selectionBytes())) - .withStyle(platformOverride == null ? ChatFormatting.GRAY : ChatFormatting.YELLOW), + VersionedText.literal(summaryText()).withStyle(override() == null ? ChatFormatting.GRAY : ChatFormatting.YELLOW), railLeft, 44, TextColors.WHITE); - // Status lines are load-bearing sentences: they wrap, they never hard-truncate mid-sentence. + if (!resolutionError.isEmpty()) { drawWrappedStatus(matrices, VersionedText.literal(resolutionError).withStyle(ChatFormatting.RED)); - } else if (!conflictNotice.isEmpty()) { - drawWrappedStatus(matrices, VersionedText.literal(conflictNotice).withStyle(ChatFormatting.YELLOW)); - } else if (actions == null || actions.sourceAvailability().get().totalFiles() == 0) { - if (!groups.isEmpty()) drawWrappedStatus(matrices, VersionedText.text("automodpack.selection.categoryExplanation").withStyle(ChatFormatting.GRAY)); + } else if (!notice.isEmpty()) { + drawWrappedStatus(matrices, VersionedText.literal(notice).withStyle(ChatFormatting.YELLOW)); } else { - SourceAvailability availability = actions.sourceAvailability().get(); - String sourceStatus = VersionedText.str(availability.cancelled() - ? "automodpack.selection.sourcesCancelled" - : !availability.complete() - ? "automodpack.selection.sourcesResolving" - : "automodpack.selection.sourcesResolved", - availability.resolvedFiles(), availability.totalFiles()); - drawWrappedStatus(matrices, VersionedText.literal(sourceStatus).withStyle(ChatFormatting.GRAY)); + SourceAvailability availability = session.sourceAvailability(); + if (availability != null && availability.totalFiles() > 0) { + String sourceStatus = VersionedText.str(availability.cancelled() + ? "automodpack.selection.sourcesCancelled" + : !availability.complete() + ? "automodpack.selection.sourcesResolving" + : "automodpack.selection.sourcesResolved", + availability.resolvedFiles(), availability.totalFiles()); + drawWrappedStatus(matrices, VersionedText.literal(sourceStatus).withStyle(ChatFormatting.GRAY)); + } } } - /** Draws one status line centered below the header stack; two wrapped lines fit between it and the first row. */ private void drawWrappedStatus(VersionedMatrices matrices, MutableComponent text) { - - List lines = wrapToWidth(this.font, text.getString(), listWidth(), 2); + List lines = wrapToWidth(this.font, text.getString(), panelWidth(PANEL_WIDTH), 2); int firstY = lines.size() > 1 ? 55 : 60; for (String line : lines) { drawCenteredTextWithShadow(matrices, this.font, VersionedText.literal(line).withStyle(text.getStyle()), this.width / 2, firstY, TextColors.WHITE); @@ -678,5 +707,4 @@ public void onClose() { if (closeOpenMenus()) return; back(); } - } diff --git a/src/main/java/pl/skidam/automodpack/client/ui/screen/InstalledModpackController.java b/src/main/java/pl/skidam/automodpack/client/ui/screen/InstalledModpackController.java index 0beac91d6..ee6dffe5e 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/screen/InstalledModpackController.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/screen/InstalledModpackController.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.function.Consumer; @@ -41,11 +42,8 @@ import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.ClientSelectionStore; import pl.skidam.automodpack_core.modpack.group.GroupManifest; -import pl.skidam.automodpack_core.modpack.group.GroupSelectionResolver; -import pl.skidam.automodpack_core.modpack.group.ResolvedSelection; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.modpack.group.SelectionIntent; -import pl.skidam.automodpack_core.modpack.group.SelectionResolutionException; import pl.skidam.automodpack_core.screen.FailureCategory; import pl.skidam.automodpack_core.screen.FailureDestination; import pl.skidam.automodpack_core.screen.FailureRequest; @@ -100,25 +98,6 @@ private SelectionIntent appliedSelection(String modpackId) throws IOException { return new ClientGenerationStore(storage).appliedSelection(modpackId).orElse(null); } - /** One applied selection change, the conflict the player must settle first, or the player-facing reason the change cannot apply. */ - record SelectionChange(SelectionIntent intent, ResolvedSelection resolution, GroupSelectionResolver.ConflictReplacement conflict, String failure) {} - - /** - * The outcome of applying one selection change: the resolver's answer when it holds, otherwise the conflict offer that - * can settle it, otherwise the reason it cannot. Screens route between the outcomes; the resolver policy stays here. - */ - SelectionChange planSelectionChange(GroupManifest manifest, SelectionIntent next, Set preferredGroups, String preferredName, ClientPlatform platform) { - try { - return new SelectionChange(next, GroupSelectionResolver.resolve(manifest, next, platform), null, null); - } catch (SelectionResolutionException exception) { - GroupSelectionResolver.ConflictReplacement replacement = GroupSelectionResolver.replaceConflicts(manifest, next, preferredGroups, platform, exception.resolution()).orElse(null); - if (replacement != null) return new SelectionChange(next, null, replacement, null); - return new SelectionChange(next, null, null, preferredGroups.isEmpty() - ? VersionedText.str("automodpack.selection.changeInvalid") - : VersionedText.str("automodpack.selection.cannotSelect", preferredName)); - } - } - boolean relayed(InstalledPacks.Pack pack) { try { return RelayConsent.isRelayed(storage, pack.modpackId()); @@ -320,7 +299,9 @@ void openStateHistory(Screen parent, Runnable released) { boolean pendingGroupChanges(InstalledPacks.Pack pack) { try { SelectionIntent desired = new ClientSelectionStore(storage.selectionFile()).get(pack.modpackId()).orElse(null); - return desired != null && !desired.equals(appliedSelection(pack.modpackId())); + if (desired == null) return false; + SelectionIntent applied = appliedSelection(pack.modpackId()); + return !desired.equals(applied) || !Objects.equals(ClientPlatform.effective(desired), ClientPlatform.effective(applied)); } catch (IOException | RuntimeException e) { return false; } @@ -399,7 +380,7 @@ void repair(Screen parent, InstalledPacks.Pack pack, Consumer completed void activate(InstalledPacks.Pack pack, Runnable released) { try { SelectionIntent desired = new ClientSelectionStore(storage.selectionFile()).get(pack.modpackId()).orElse(null); - SelectionIntent targetSelection = desired == null ? GroupSelectionResolver.defaultIntent(pack.record().manifest()) : desired; + SelectionIntent targetSelection = desired == null ? SelectionIntent.DEFAULTS : desired; SwitchFlow.start(storage, pack.record(), appliedSelection(pack.modpackId()), targetSelection, pack.name(), released, LoaderServices.modpackLoader()); } catch (IOException | RuntimeException e) { released.run(); @@ -460,8 +441,7 @@ Map activeGroupNames() { /** A group id to display-name map for a manifest; unnamed groups fall back to their id. */ static Map groupNames(GroupManifest manifest) { Map names = new TreeMap<>(); - manifest.groups().forEach((groupId, group) -> names.put(groupId, - group.displayName().isBlank() ? groupId : group.displayName())); + manifest.groups().forEach((groupId, group) -> names.put(groupId, manifest.displayName(groupId))); return Map.copyOf(names); } diff --git a/src/main/java/pl/skidam/automodpack/client/ui/screen/ModpackSettingsScreen.java b/src/main/java/pl/skidam/automodpack/client/ui/screen/ModpackSettingsScreen.java index d06523161..89a278535 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/screen/ModpackSettingsScreen.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/screen/ModpackSettingsScreen.java @@ -69,7 +69,7 @@ protected void init() { super.init(); actionButtons.clear(); buildHeaderLines(); - launchWritesCheckbox = new CheckboxWidget(this.font, panelLeft(PANEL_WIDTH), generationY() + LINE_GAP, panelWidth(PANEL_WIDTH), PackConfirmCopy.launchWritesLabel(), launchWrites, value -> { + launchWritesCheckbox = new CheckboxWidget(this.font, panelLeft(PANEL_WIDTH), generationY() + LINE_GAP + 4, panelWidth(PANEL_WIDTH), PackConfirmCopy.launchWritesLabel(), launchWrites, value -> { launchWrites = value; controller.setLaunchWritesUnverified(pack, value); }); @@ -82,7 +82,7 @@ protected void init() { actions.add(pack.detached() ? new Action("automodpack.management.resumeSyncing", this::resumeSyncing, VersionedText.text("automodpack.management.resumeSyncingTooltip")) : new Action("automodpack.management.stopSyncing", this::stopSyncing, VersionedText.text("automodpack.management.stopSyncingTooltip"))); - actions.add(new Action("automodpack.management.groups", this::openGroups)); + if (pack.record().manifest().hasChoosableGroups()) actions.add(new Action("automodpack.management.groups", this::openGroups)); actions.add(new Action("automodpack.management.packFiles", this::openFiles)); actions.add(new Action("automodpack.management.history", this::openHistory)); boolean shared = controller.relayed(pack); @@ -169,7 +169,7 @@ private void repair() { private void openGroups() { if (busy) return; - ScreenImpl.setScreen(GroupSelectionScreen.forInstalledRecord(this, pack.record())); + ScreenImpl.setScreen(GroupSelectionScreen.forInstalled(this, controller, pack.record())); } private void openHistory() { @@ -253,7 +253,7 @@ private void updateActions() { /** The generation line's y - the end of the header stack the render walks - so the action grid derives from one layout. */ private int generationY() { - int y = HEADER_TOP + STATE_LINE_GAP + IDENTITY_LINE_GAP + LINE_GAP + LINE_GAP; + int y = HEADER_TOP + STATE_LINE_GAP + IDENTITY_LINE_GAP + LINE_GAP * 3; if (pack.connectionDetail() != null) y += LINE_GAP; return y; } @@ -285,8 +285,11 @@ private void buildHeaderLines() { GroupManifest manifest = pack.record().manifest(); versionLine = VersionedText.str("automodpack.packDetails.identity", manifest.loader(), manifest.loaderVersion(), manifest.mcVersion()); idLine = VersionedText.str("automodpack.packDetails.id", pack.modpackId()); - contentsLine = VersionedText.str("automodpack.packDetails.contents", UiFormat.plural(pack.groupCount(), "automodpack.confirm.groupCount").getString(), - UiFormat.plural(pack.fileCount(), "automodpack.confirm.fileCount").getString(), UiFormat.formatSize(pack.fileBytes())); + contentsLine = manifest.hasChoosableGroups() + ? VersionedText.str("automodpack.packDetails.contents", UiFormat.plural(pack.groupCount(), "automodpack.confirm.groupCount").getString(), + UiFormat.plural(pack.fileCount(), "automodpack.confirm.fileCount").getString(), UiFormat.formatSize(pack.fileBytes())) + : VersionedText.str("automodpack.packDetails.contentsNoGroups", + UiFormat.plural(pack.fileCount(), "automodpack.confirm.fileCount").getString(), UiFormat.formatSize(pack.fileBytes())); connectionLine = pack.connectionDetail() == null ? null : VersionedText.str("automodpack.packDetails.connection", pack.connectionOrigin(), pack.connectionDetail()); String contentToken = pack.record().contentToken(); Instant createdAt = pack.record().createdAt(); diff --git a/src/main/java/pl/skidam/automodpack/client/ui/screen/PackConfirmCopy.java b/src/main/java/pl/skidam/automodpack/client/ui/screen/PackConfirmCopy.java index 592449a2f..800afca31 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/screen/PackConfirmCopy.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/screen/PackConfirmCopy.java @@ -10,6 +10,7 @@ import pl.skidam.automodpack.client.ui.UiFormat; import pl.skidam.automodpack.client.ui.versioned.VersionedText; +import pl.skidam.automodpack_core.modpack.group.ClientPlatform; import pl.skidam.automodpack_core.modpack.group.GroupManifest; import pl.skidam.automodpack_core.modpack.group.SelectedModpackTarget; import pl.skidam.automodpack_core.screen.SourceCounts; @@ -76,8 +77,8 @@ static long selectedJarSize(SelectedModpackTarget target, String path) { } static String requestedGroups(SelectedModpackTarget target) { - if (target.selection().intent().requestedGroups().isEmpty()) return ""; - return VersionedText.str("automodpack.firstConnect.requestedGroups", groupNames(target.manifest(), target.selection().intent().requestedGroups())); + if (target.selection().intent().enabled().isEmpty()) return ""; + return VersionedText.str("automodpack.firstConnect.requestedGroups", groupNames(target.manifest(), target.selection().intent().enabled())); } static String includedGroups(SelectedModpackTarget target) { @@ -91,8 +92,8 @@ static String requestedUnavailableGroups(SelectedModpackTarget target) { } static String staleRequestedGroups(SelectedModpackTarget target) { - if (target.selection().staleRequestedGroups().isEmpty()) return ""; - return VersionedText.str("automodpack.firstConnect.unavailableOldChoices", groupNames(target.manifest(), target.selection().staleRequestedGroups())); + if (target.selection().staleGroups().isEmpty()) return ""; + return VersionedText.str("automodpack.firstConnect.unavailableOldChoices", groupNames(target.manifest(), target.selection().staleGroups())); } static String existingMods(boolean keep, int count) { @@ -102,10 +103,7 @@ static String existingMods(boolean keep, int count) { private static String groupNames(GroupManifest manifest, Iterable ids) { List names = new ArrayList<>(); - for (String id : ids) { - GroupManifest.Group group = manifest.groups().get(id); - names.add(group == null || group.displayName().isBlank() ? id : group.displayName()); - } + for (String id : ids) names.add(manifest.displayName(id)); return String.join(", ", names); } @@ -147,7 +145,9 @@ static Map groupNames(GroupManifest manifest) { } static boolean canCustomize(GroupManifest manifest) { - return manifest.groups().values().stream().anyMatch(group -> !group.alwaysInstalled()); + if (manifest.hasChoosableGroups()) return true; + // Without a detected platform the player picks the OS in the group screen. + return ClientPlatform.current() == null && manifest.hasDeclaredPlatforms(); } static Component leftoverLabel(int count) { diff --git a/src/main/java/pl/skidam/automodpack/client/ui/screen/PackConfirmScreen.java b/src/main/java/pl/skidam/automodpack/client/ui/screen/PackConfirmScreen.java index c06efbc28..d4679b9ee 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/screen/PackConfirmScreen.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/screen/PackConfirmScreen.java @@ -406,7 +406,7 @@ private void customize() { ScreenManager.failure(FailureRequest.of(e, "automodpack.error.update", FailureCategory.UPDATE, FailureDestination.MULTIPLAYER, null)); } }; - ScreenImpl.setScreen(new GroupSelectionScreen(this, target(), actions, action)); + ScreenImpl.setScreen(GroupSelectionScreen.forReview(this, target(), originFull.isBlank() ? "" : PackConfirmCopy.displayOrigin(originFull), actions, action)); } private void retryVerification() { diff --git a/src/main/java/pl/skidam/automodpack/client/ui/screen/UpdatePreviewScreen.java b/src/main/java/pl/skidam/automodpack/client/ui/screen/UpdatePreviewScreen.java index caf394a70..21565c7b0 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/screen/UpdatePreviewScreen.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/screen/UpdatePreviewScreen.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Objects; import java.util.function.Consumer; +import java.util.stream.Collectors; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.components.AbstractWidget; @@ -155,7 +156,11 @@ private List buildBodyLines() { } UpdatePreview.GroupConsequences groups = preview.groupConsequences(); if (!groups.staleGroups().isEmpty()) lines.add(VersionedText.text("automodpack.update.staleSelection").withStyle(ChatFormatting.RED)); - else lines.add(UiFormat.plural(groups.resolvedGroups().size(), "automodpack.update.groupsSelected").withStyle(ChatFormatting.GREEN)); + else if (target == null || target.manifest().hasChoosableGroups()) lines.add(UiFormat.plural(groups.resolvedGroups().size(), "automodpack.update.groupsSelected").withStyle(ChatFormatting.GREEN)); + if (!groups.newGroups().isEmpty()) { + String names = groups.newGroups().stream().map(id -> preview.featureNames().getOrDefault(id, id)).collect(Collectors.joining(", ")); + lines.addAll(wrapParagraph(this.font, UiFormat.plural(groups.newGroups().size(), "automodpack.update.newGroups", names).getString(), wrapWidth, ChatFormatting.AQUA)); + } if (!preview.conflicts().isEmpty()) lines.add(UiFormat.plural(preview.conflicts().size(), "automodpack.browser.conflicts").withStyle(ChatFormatting.RED)); if (unverifiedPlanJarCount > 0) lines.addAll(wrapParagraph(this.font, UiFormat.plural(unverifiedPlanJarCount, "automodpack.update.unverifiedTrusted").getString(), wrapWidth, ChatFormatting.YELLOW)); @@ -197,7 +202,7 @@ private void customize() { ScreenManager.failure(FailureRequest.of(e, "automodpack.error.update", FailureCategory.UPDATE, FailureDestination.MULTIPLAYER, null)); } }; - ScreenImpl.setScreen(new GroupSelectionScreen(this, target, actions, action)); + ScreenImpl.setScreen(GroupSelectionScreen.forReview(this, target, origin, actions, action)); } private void openFiles() { diff --git a/src/main/java/pl/skidam/automodpack/client/ui/versioned/VersionedIconButton.java b/src/main/java/pl/skidam/automodpack/client/ui/versioned/VersionedIconButton.java index 28fac4212..b8a133a77 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/versioned/VersionedIconButton.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/versioned/VersionedIconButton.java @@ -84,10 +84,15 @@ public void renderButton(PoseStack matrices, int mouseX, int mouseY, float delta } *//*?}*/ - private Identifier texture() { + /** Icons come from the mod's own assets, never a sprite a server pack could replace. */ + public static Identifier spriteTexture(String sprite) { return Common.id("textures/gui/sprites/" + sprite + ".png"); } + private Identifier texture() { + return spriteTexture(sprite); + } + // Positions are read live: lists build rows at 0,0 and move the widgets during layout. private int iconLeft() { /*? if >=1.19.4 {*/ diff --git a/src/main/java/pl/skidam/automodpack/client/ui/widget/CategoryHeaderRow.java b/src/main/java/pl/skidam/automodpack/client/ui/widget/CategoryHeaderRow.java deleted file mode 100644 index 62ccf72b1..000000000 --- a/src/main/java/pl/skidam/automodpack/client/ui/widget/CategoryHeaderRow.java +++ /dev/null @@ -1,33 +0,0 @@ -package pl.skidam.automodpack.client.ui.widget; - -import net.minecraft.ChatFormatting; -import net.minecraft.client.gui.Font; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; - -import pl.skidam.automodpack.client.ui.TextColors; -import pl.skidam.automodpack.client.ui.versioned.VersionedMatrices; -import pl.skidam.automodpack.client.ui.versioned.VersionedScreen; -import pl.skidam.automodpack.client.ui.versioned.VersionedText; - -/** - * A category header over its group rows: the tri-state box telling the truth about the children - * (all in, some in, none in), the category's bold state-colored label, and the selected-of-total - * count right-aligned. Clicking still includes/excludes the whole category; the resolution owns the state. - */ -public final class CategoryHeaderRow extends CheckboxWidget { - private final Font font; - private final MutableComponent counterLine; - - public CategoryHeaderRow(Font font, int x, int y, int maxWidth, Component message, State state, String counter, Runnable onToggle) { - super(font, x, y, maxWidth, message, state, selected -> onToggle.run(), font.width(counter)); - this.font = font; - this.counterLine = VersionedText.literal(counter).withStyle(ChatFormatting.GRAY); - } - - @Override - protected void versionedRender(VersionedMatrices matrices) { - super.versionedRender(matrices); - VersionedScreen.drawTextWithShadow(matrices, font, counterLine, left() + getWidth() - font.width(counterLine), top() + BOX_SIZE / 2 - font.lineHeight / 2, TextColors.WHITE); - } -} diff --git a/src/main/java/pl/skidam/automodpack/client/ui/widget/GroupSelectionList.java b/src/main/java/pl/skidam/automodpack/client/ui/widget/GroupSelectionList.java index cbd681e92..1be61effd 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/widget/GroupSelectionList.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/widget/GroupSelectionList.java @@ -5,19 +5,29 @@ import java.util.function.Consumer; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.components.AbstractButton; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.ContainerObjectSelectionList; import net.minecraft.client.gui.components.events.GuiEventListener; +import net.minecraft.client.gui.narration.NarratedElementType; import net.minecraft.client.gui.narration.NarratableEntry; +import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import pl.skidam.automodpack.client.ui.TextColors; import pl.skidam.automodpack.client.ui.versioned.VersionedMatrices; import pl.skidam.automodpack.client.ui.versioned.VersionedScissor; +import pl.skidam.automodpack.client.ui.versioned.VersionedIconButton; import pl.skidam.automodpack.client.ui.versioned.VersionedScreen; import pl.skidam.automodpack.client.ui.versioned.VersionedText; import pl.skidam.automodpack_core.utils.ActionAreaLayout; +/*? if >=1.21.10 {*/ +import net.minecraft.client.input.InputWithModifiers; +/*?}*/ /*? if >=26.1 {*/ import net.minecraft.client.gui.GuiGraphicsExtractor; /*?} elif >=1.20 {*/ @@ -26,15 +36,32 @@ /*import com.mojang.blaze3d.vertex.PoseStack; *//*?}*/ -/** Scrolling group rows: every togglable row is a vanilla checkbox, so the bridge and screen readers see the whole list. */ +/** Scrolling list of group cards and section headers. */ public final class GroupSelectionList extends ContainerObjectSelectionList implements RowViewport { - private static final int ROW_HEIGHT = 24; + private static final int ROW_HEIGHT = 34; + private static final int CARD_HEIGHT = 32; + private static final int CHILD_INDENT = 8; + private static final int RADIO_SIZE = 13; + private static final int ACTION_BUTTON_HEIGHT = 16; + private static final int ICON_SIZE = 16; + /** Text column shared by every card, past the checkbox, radio and padlock. */ + private static final int CARD_TEXT_INSET = 26; + private static final int PADLOCK_WIDTH = 8; + private static final int PADLOCK_HEIGHT = 10; + private static final int FILES_BUTTON_WIDTH = CARD_HEIGHT; + private static final int HEADER_DIVIDER = 0x30FFFFFF; + private static final int RADIO_BORDER = 0xFF909090; + private static final int RADIO_BORDER_ACTIVE = 0xFFFFFFFF; + private static final int RADIO_BORDER_DISABLED = 0xFF606060; + private static final int RADIO_INNER_BG = 0xFF141414; + + /** Marks a row's primary control so AutoTestBridge does not emit it twice. */ + public interface RowPrimaryControl {} private static Component filesLabel() { return VersionedText.text("automodpack.selection.groupFiles"); } - /** Group rows span the whole list like the shared UniformList lists do; vanilla caps the row width, which squashed every row into the center. */ @Override public int getRowWidth() { return this.contentWidth; @@ -47,9 +74,13 @@ protected int getScrollbarPosition() { } *//*?}*/ - /** Width of a group row's square Files icon button; the screen uses the same value so row labels stop short of the button. */ public static int filesButtonWidth() { - return ActionAreaLayout.BUTTON_HEIGHT; + return FILES_BUTTON_WIDTH; + } + + public static int cardTextWidth(int rowWidth) { + int cardWidth = Math.max(1, rowWidth - CHILD_INDENT - filesButtonWidth() - ActionAreaLayout.SEAM); + return Math.max(1, cardWidth - 32); } private final int contentWidth; @@ -63,9 +94,6 @@ public GroupSelectionList(Minecraft client, int width, int height, int contentWi /*?}*/ this.contentWidth = Math.max(1, contentWidth); this.centerListVertically = false; - // This list cannot sit on the UniformList base - it needs ContainerObjectSelectionList for its interactive - // rows - so it strips vanilla chrome and draws the ListChrome look itself. Every number the shared lists pin - // reads from ListChrome, which is what keeps the two in step. /*? if <1.21.1 {*/ /*this.setRenderBackground(false); this.setRenderTopAndBottom(false); @@ -76,6 +104,7 @@ public GroupSelectionList(Minecraft client, int width, int height, int contentWi Consumer toggle = Objects.requireNonNull(onToggle, "onToggle"); Consumer inspect = Objects.requireNonNull(onInspect, "onInspect"); for (Item item : Objects.requireNonNull(items, "items")) this.addEntry(new Entry(item, toggle, inspect)); + this.syncLayout(); } /*? if >=1.21.10 {*/ @@ -138,7 +167,6 @@ protected void renderSelection(GuiGraphics guiGraphics, int y, int entryWidth, i public void render(PoseStack matrices, int mouseX, int mouseY, float delta) { VersionedMatrices chrome = new VersionedMatrices(); ListChrome.drawBackdrop(chrome, x0, y0, x1, y1); - // Separators precede super.render so the scrollbar paints over them, like vanilla's bands before its scrollbar. ListChrome.drawSeparators(chrome, x0, y0, x1, y1); VersionedScissor.enable(minecraft, x0, y0, x1, y1); super.render(matrices, mouseX, mouseY, delta); @@ -149,7 +177,6 @@ public void render(PoseStack matrices, int mouseX, int mouseY, float delta) { public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { VersionedMatrices chrome = new VersionedMatrices(graphics); ListChrome.drawBackdrop(chrome, x0, y0, x1, y1); - // Separators precede super.render so the scrollbar paints over them, like vanilla's bands before its scrollbar. ListChrome.drawSeparators(chrome, x0, y0, x1, y1); VersionedScissor.enable(minecraft, x0, y0, x1, y1); super.render(graphics, mouseX, mouseY, delta); @@ -168,11 +195,56 @@ public void revealRow(int index) { entry.layoutRow(this.getRowLeft(), this.getRowTop(index), this.getRowWidth()); } + @Override + public void syncLayout() { + int left = this.getRowLeft(); + int width = this.getRowWidth(); + List entries = this.children(); + for (int i = 0; i < entries.size(); i++) entries.get(i).layoutRow(left, this.getRowTop(i), width); + } + + @Override + public int viewportTop() { + /*? if <1.20.3 {*/ + /*return this.y0; + *//*?} else {*/ + return this.getY(); + /*?}*/ + } + + @Override + public int viewportBottom() { + /*? if <1.20.3 {*/ + /*return this.y1; + *//*?} else {*/ + return this.getY() + this.getHeight(); + /*?}*/ + } + + public double preservedScrollAmount() { + /*? if >=1.21.4 {*/ + return this.scrollAmount(); + /*?} else {*/ + /*return this.getScrollAmount(); + *//*?}*/ + } + + public void restoreScrollAmount(double amount) { + this.setScrollAmount(amount); + this.syncLayout(); + } + @Override public RowView rowView(int index) { Item item = this.children().get(index).item(); - String text = item.counter().isBlank() ? item.label().getString() : item.label().getString() + " " + item.counter(); - return new RowView(text, item.canToggle(), item.selected(), item.partial()); + StringBuilder text = new StringBuilder(item.title().getString()); + String badge = item.badge().getString(); + if (!badge.isBlank()) text.append(' ').append(badge); + String subtitle = item.subtitle().getString(); + if (!subtitle.isBlank()) text.append(" | ").append(subtitle); + if (item.kind() == Kind.HEADER) return new RowView(text.toString(), !item.actionLabel().isBlank(), null, false); + if (item.kind() == Kind.INCLUDED_GROUP) return new RowView(text.toString(), false, null, false); + return new RowView(text.toString(), item.canToggle(), item.selected(), false); } public int rowCount() { @@ -195,57 +267,98 @@ public int rowHeight() { return ROW_HEIGHT; } - public record Item(Kind kind, String id, Component label, Component tooltip, boolean selected, boolean canToggle, boolean partial, String counter) { + public record Item( + Kind kind, + String id, + String categoryId, + Component title, + Component subtitle, + Component badge, + Component tooltip, + boolean selected, + boolean canToggle, + boolean showFilesButton, + String actionLabel, + int accentColor) { public Item { Objects.requireNonNull(kind, "kind"); id = id == null ? "" : id; - label = Objects.requireNonNull(label, "label"); - counter = counter == null ? "" : counter; + categoryId = categoryId == null ? "" : categoryId; + title = Objects.requireNonNull(title, "title"); + subtitle = subtitle == null ? VersionedText.literal("") : subtitle; + badge = badge == null ? VersionedText.literal("") : badge; + actionLabel = actionLabel == null ? "" : actionLabel; + } + + public static Item header(String categoryId, Component title, Component subtitle, String actionLabel) { + String label = actionLabel == null ? "" : actionLabel; + return new Item(Kind.HEADER, categoryId, categoryId, title, subtitle, VersionedText.literal(""), null, false, !label.isBlank(), false, label, 0); + } + + public static Item checkable(String id, String categoryId, Component title, Component subtitle, Component badge, Component tooltip, boolean selected, boolean canToggle, int accentColor) { + return new Item(Kind.CHECKBOX_GROUP, id, categoryId, title, subtitle, badge, tooltip, selected, canToggle, true, "", accentColor); + } + + /** The None option names no group, so it is the one radio row without a files control. */ + public static Item radio(String id, String categoryId, Component title, Component subtitle, Component badge, Component tooltip, boolean selected, boolean canToggle, int accentColor) { + String rowId = id == null ? "" : id; + return new Item(Kind.RADIO_GROUP, rowId, categoryId, title, subtitle, badge, tooltip, selected, canToggle, !rowId.isEmpty(), "", accentColor); + } + + public static Item included(String id, String categoryId, Component title, Component subtitle, Component badge, Component tooltip) { + return new Item(Kind.INCLUDED_GROUP, id, categoryId, title, subtitle, badge, tooltip, true, false, true, "", 0); } } public enum Kind { HEADER, - GROUP - } - - /** Group rows step right of their category header; the same step the change browser uses for nested rows. */ - private static final int CHILD_INDENT = 12; - - private static CheckboxWidget.State state(Item item) { - return item.partial() ? CheckboxWidget.State.PARTIAL : item.selected() ? CheckboxWidget.State.CHECKED : CheckboxWidget.State.UNCHECKED; + CHECKBOX_GROUP, + RADIO_GROUP, + INCLUDED_GROUP } public final class Entry extends ContainerObjectSelectionList.Entry { private final Item item; - private final AbstractWidget row; + private final AbstractWidget primaryControl; + private final AbstractWidget actionButton; private final AbstractWidget filesButton; private final List children; private Entry(Item item, Consumer onToggle, Consumer onInspect) { this.item = item; int rowWidth = GroupSelectionList.this.getRowWidth(); - int indent = item.kind() == Kind.GROUP ? CHILD_INDENT : 0; - int filesWidth = item.kind() == Kind.GROUP ? filesButtonWidth() : 0; - int mainWidth = item.kind() == Kind.GROUP ? Math.max(1, rowWidth - indent - filesWidth - ActionAreaLayout.SEAM) : rowWidth; - AbstractWidget checkbox = item.kind() == Kind.HEADER - ? new CategoryHeaderRow(minecraft.font, 0, 0, mainWidth, item.label(), state(item), item.counter(), () -> onToggle.accept(item)) - : new CheckboxWidget(minecraft.font, 0, 0, mainWidth, item.label(), item.selected(), value -> { - if (value != item.selected()) onToggle.accept(item); - }); - // Locked rows and inert headers still show their state, but the box is dead: the resolution owns it. - checkbox.active = item.canToggle(); - if (item.tooltip() != null) VersionedScreen.setTooltip(checkbox, item.tooltip()); - this.row = checkbox; - if (item.kind() == Kind.GROUP) { - // The narration keeps the "Files" label so screen readers and the tooling bridge still name the action. - Button files = VersionedScreen.iconButtonWidget(0, 0, filesWidth, 16, button -> onInspect.accept(item), "folder", filesLabel()); - if (item.tooltip() != null) VersionedScreen.setTooltip(files, item.tooltip()); + if (item.kind() == Kind.HEADER) { + this.primaryControl = null; + this.filesButton = null; + if (!item.actionLabel().isBlank()) { + int buttonWidth = Math.max(48, minecraft.font.width(item.actionLabel()) + 18); + Button action = new GroupActionButton(minecraft.font, 0, 0, buttonWidth, ACTION_BUTTON_HEIGHT, VersionedText.literal(item.actionLabel()), button -> onToggle.accept(item)); + if (item.tooltip() != null) VersionedScreen.setTooltip(action, item.tooltip()); + this.actionButton = action; + this.children = List.of(action); + } else { + this.actionButton = null; + this.children = List.of(); + } + return; + } + + int filesWidth = filesButtonWidth(); + int cardWidth = Math.max(1, rowWidth - CHILD_INDENT - filesWidth - ActionAreaLayout.SEAM); + GroupCardButton card = new GroupCardButton(minecraft.font, 0, 0, cardWidth, CARD_HEIGHT, item, () -> onToggle.accept(item)); + card.active = item.canToggle(); + if (item.tooltip() != null) VersionedScreen.setTooltip(card, item.tooltip()); + this.primaryControl = card; + this.actionButton = null; + if (item.showFilesButton()) { + Button files = new GroupFilesButton(0, 0, filesWidth, CARD_HEIGHT, filesLabel(), button -> onInspect.accept(item)); + VersionedScreen.setTooltip(files, filesLabel()); this.filesButton = files; + this.children = List.of(card, files); } else { this.filesButton = null; + this.children = List.of(card); } - this.children = this.filesButton == null ? List.of(this.row) : List.of(this.row, this.filesButton); } public Item item() { @@ -289,12 +402,37 @@ public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWi *//*?}*/ private void versionedRender(VersionedMatrices matrices, int x, int y, int entryWidth, int mouseX, int mouseY, float tickDelta) { + if (item.kind() == Kind.HEADER) { + renderHeader(matrices, x, y, entryWidth); + if (actionButton != null) renderWidget(actionButton, matrices, mouseX, mouseY, tickDelta); + return; + } + if (primaryControl != null) renderWidget(primaryControl, matrices, mouseX, mouseY, tickDelta); + if (filesButton != null) renderWidget(filesButton, matrices, mouseX, mouseY, tickDelta); + } + + private void renderHeader(VersionedMatrices matrices, int x, int y, int entryWidth) { + int rightReserve = actionButton == null ? 0 : actionButton.getWidth() + ActionAreaLayout.SEAM; + int maxTextWidth = Math.max(1, entryWidth - rightReserve - 4); + Font font = minecraft.font; + boolean hasSubtitle = !item.subtitle().getString().isBlank(); + int titleY = hasSubtitle ? y + 6 : y + ROW_HEIGHT - font.lineHeight - 7; + MutableComponent title = item.title() instanceof MutableComponent mutable + ? VersionedText.literal(VersionedScreen.truncateToWidth(font, mutable.getString(), maxTextWidth)).withStyle(mutable.getStyle()) + : VersionedText.literal(VersionedScreen.truncateToWidth(font, item.title().getString(), maxTextWidth)); + VersionedScreen.drawTextWithShadow(matrices, font, title, x + 2, titleY, TextColors.WHITE); + if (hasSubtitle) { + String sub = VersionedScreen.truncateToWidth(font, item.subtitle().getString(), maxTextWidth); + VersionedScreen.drawTextWithShadow(matrices, font, VersionedText.literal(sub), x + 2, y + 18, TextColors.LIGHT_GRAY); + } + matrices.fill(x, y + ROW_HEIGHT - 2, x + entryWidth, y + ROW_HEIGHT - 1, HEADER_DIVIDER); + } + + private void renderWidget(AbstractWidget widget, VersionedMatrices matrices, int mouseX, int mouseY, float tickDelta) { /*? if >=26.1 {*/ - row.extractRenderState(matrices.getContext(), mouseX, mouseY, tickDelta); - if (filesButton != null) filesButton.extractRenderState(matrices.getContext(), mouseX, mouseY, tickDelta); + widget.extractRenderState(matrices.getContext(), mouseX, mouseY, tickDelta); /*?} else {*/ - /*row.render(matrices.getContext(), mouseX, mouseY, tickDelta); - if (filesButton != null) filesButton.render(matrices.getContext(), mouseX, mouseY, tickDelta); + /*widget.render(matrices.getContext(), mouseX, mouseY, tickDelta); *//*?}*/ } @@ -306,8 +444,10 @@ private void layoutRow(int x, int y, int entryWidth) { this.setWidth(entryWidth); this.setHeight(ROW_HEIGHT); /*?}*/ - positionWidget(row, x + (item.kind() == Kind.GROUP ? CHILD_INDENT : 0), y); - if (filesButton != null) positionWidget(filesButton, x + GroupSelectionList.this.getRowWidth() - filesButton.getWidth(), y); + int rowWidth = GroupSelectionList.this.getRowWidth(); + if (actionButton != null) positionWidget(actionButton, x + rowWidth - actionButton.getWidth(), y + (ROW_HEIGHT - actionButton.getHeight()) / 2); + if (primaryControl != null) positionWidget(primaryControl, x + CHILD_INDENT, y); + if (filesButton != null) positionWidget(filesButton, x + rowWidth - filesButton.getWidth(), y); } private static void positionWidget(AbstractWidget widget, int x, int y) { @@ -320,4 +460,183 @@ private static void positionWidget(AbstractWidget widget, int x, int y) { *//*?}*/ } } + + /** Compact {@code Select all} / {@code Clear} control. */ + private static final class GroupActionButton extends ListControlButton { + private final Font font; + + private GroupActionButton(Font font, int x, int y, int width, int height, Component message, OnPress onPress) { + super(x, y, width, height, message, onPress); + this.font = font; + } + + @Override + protected void drawContent(VersionedMatrices matrices, int left, int top, int width, int height, boolean highlighted) { + String label = VersionedScreen.truncateToWidth(font, getMessage().getString(), Math.max(1, width - 6)); + int color = highlighted ? TextColors.WHITE : active ? TextColors.LIGHT_GRAY : ListChrome.TEXT_MUTED; + VersionedScreen.drawTextWithShadow(matrices, font, VersionedText.literal(label), left + (width - font.width(label)) / 2, top + (height - font.lineHeight + 1) / 2, color); + } + } + + /** The row's folder control, on a full-height plate matching the card. */ + private static final class GroupFilesButton extends ListControlButton { + private GroupFilesButton(int x, int y, int width, int height, Component message, OnPress onPress) { + super(x, y, width, height, message, onPress); + } + + @Override + protected void drawContent(VersionedMatrices matrices, int left, int top, int width, int height, boolean highlighted) { + VersionedScreen.drawTexture(VersionedIconButton.spriteTexture("folder"), matrices, left + (width - ICON_SIZE) / 2, top + (height - ICON_SIZE) / 2, 0, 0, ICON_SIZE, + ICON_SIZE, ICON_SIZE, ICON_SIZE); + } + } + + private static final class GroupCardButton extends AbstractButton implements RowPrimaryControl { + private final Font font; + private final Item item; + private final Runnable onPressAction; + + private GroupCardButton(Font font, int x, int y, int width, int height, Item item, Runnable onPressAction) { + super(x, y, Math.max(1, width), Math.max(1, height), item.title()); + this.font = font; + this.item = item; + this.onPressAction = onPressAction; + } + + /*? if >=1.21.10 {*/ + @Override + public void onPress(InputWithModifiers input) { + onPressAction.run(); + } + /*?} else {*/ + /*@Override + public void onPress() { + onPressAction.run(); + } + *//*?}*/ + + /*? if <1.19.4 {*/ + /*@Override + public void updateNarration(NarrationElementOutput output) { + output.add(NarratedElementType.TITLE, getMessage()); + } + *//*?} else {*/ + @Override + public void updateWidgetNarration(NarrationElementOutput output) { + output.add(NarratedElementType.TITLE, getMessage()); + } + /*?}*/ + + /*? if >=26.1 {*/ + @Override + protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float delta) { + renderCard(new VersionedMatrices(graphics), mouseX, mouseY); + } + /*?} elif >=1.21.11 {*/ + /*@Override + public void renderContents(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + renderCard(new VersionedMatrices(graphics), mouseX, mouseY); + } + *//*?} elif >=1.20 {*/ + /*@Override + protected void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + renderCard(new VersionedMatrices(graphics), mouseX, mouseY); + } + *//*?} else {*/ + /*@Override + public void renderButton(PoseStack matrices, int mouseX, int mouseY, float delta) { + renderCard(new VersionedMatrices(), mouseX, mouseY); + } + *//*?}*/ + + private void renderCard(VersionedMatrices matrices, int mouseX, int mouseY) { + int left = cardLeft(); + int top = cardTop(); + int width = getWidth(); + int height = getHeight(); + boolean hovered = mouseX >= left && mouseX < left + width && mouseY >= top && mouseY < top + height; + + if (item.kind() == Kind.INCLUDED_GROUP) { + renderReadOnlyCard(matrices, left, top, width, height); + return; + } + + ListChrome.drawRow(matrices, left, top, width, height, item.selected(), this.active && (hovered || isFocused()), this.active); + if (item.accentColor() != 0) matrices.fill(left, top, left + 2, top + height, item.accentColor()); + + if (item.kind() == Kind.RADIO_GROUP) { + drawRadioCircle(matrices, left + 6, top + (height - RADIO_SIZE) / 2, item.selected(), this.active, hovered); + } else { + CheckboxWidget.drawBox(matrices, left + 4, top + (height - CheckboxWidget.BOX_SIZE) / 2, + item.selected() ? CheckboxWidget.State.CHECKED : CheckboxWidget.State.UNCHECKED); + } + + drawRowText(matrices, left, top, width, height, TextColors.WHITE, TextColors.LIGHT_GRAY, TextColors.LIGHT_GRAY); + } + + /** A locked group: framed row with a padlock and muted text. */ + private void renderReadOnlyCard(VersionedMatrices matrices, int left, int top, int width, int height) { + ListChrome.drawReadOnlyRow(matrices, left, top, width, height); + ListChrome.drawPadlock(matrices, left + 8, top + (height - PADLOCK_HEIGHT) / 2, ListChrome.TEXT_MUTED, RADIO_INNER_BG); + drawRowText(matrices, left, top, width, height, ListChrome.TEXT_READONLY_TITLE, ListChrome.TEXT_MUTED, ListChrome.TEXT_READONLY_SUBTITLE); + } + + /** Title, badge and subtitle of one card, truncated into the column shared by every row kind. */ + private void drawRowText(VersionedMatrices matrices, int left, int top, int width, int height, int titleColor, int badgeColor, int subtitleColor) { + int textLeft = left + CARD_TEXT_INSET; + int textRight = left + width - 6; + String badgeText = item.badge().getString(); + int badgeWidth = badgeText.isBlank() ? 0 : font.width(badgeText); + int titleMaxWidth = Math.max(1, textRight - textLeft - (badgeWidth > 0 ? badgeWidth + 6 : 0)); + String subtitleText = item.subtitle().getString(); + boolean hasSubtitle = !subtitleText.isBlank(); + int titleY = hasSubtitle ? top + 6 : top + (height - font.lineHeight + 1) / 2; + VersionedScreen.drawTextWithShadow(matrices, font, styledCopy(item.title(), VersionedScreen.truncateToWidth(font, item.title().getString(), titleMaxWidth)), textLeft, titleY, titleColor); + if (badgeWidth > 0) VersionedScreen.drawTextWithShadow(matrices, font, styledCopy(item.badge(), badgeText), textRight - badgeWidth, titleY, badgeColor); + if (hasSubtitle) { + VersionedScreen.drawTextWithShadow(matrices, font, styledCopy(item.subtitle(), VersionedScreen.truncateToWidth(font, subtitleText, Math.max(1, textRight - textLeft))), textLeft, top + 18, + subtitleColor); + } + } + + private static MutableComponent styledCopy(Component original, String truncatedText) { + MutableComponent copy = VersionedText.literal(truncatedText); + return original instanceof MutableComponent mutable ? copy.withStyle(mutable.getStyle()) : copy; + } + + private static void drawRadioCircle(VersionedMatrices matrices, int x, int y, boolean selected, boolean active, boolean hovered) { + int border = !active ? RADIO_BORDER_DISABLED : selected || hovered ? RADIO_BORDER_ACTIVE : RADIO_BORDER; + // 13x13 crisp circular outline via row spans + int[] insets = { 4, 2, 1, 1, 0, 0, 0, 0, 0, 1, 1, 2, 4 }; + for (int row = 0; row < RADIO_SIZE; row++) { + int inset = insets[row]; + matrices.fill(x + inset, y + row, x + RADIO_SIZE - inset, y + row + 1, border); + int innerInset = row == 0 || row == RADIO_SIZE - 1 ? RADIO_SIZE : insets[row] + 1; + if (innerInset < RADIO_SIZE - innerInset) { + matrices.fill(x + innerInset, y + row, x + RADIO_SIZE - innerInset, y + row + 1, RADIO_INNER_BG); + } + } + if (selected) { + int dotColor = active ? RADIO_BORDER_ACTIVE : RADIO_BORDER; + matrices.fill(x + 4, y + 3, x + 9, y + 10, dotColor); + matrices.fill(x + 3, y + 4, x + 10, y + 9, dotColor); + } + } + + private int cardLeft() { + /*? if >=1.19.4 {*/ + return getX(); + /*?} else {*/ + /*return x; + *//*?}*/ + } + + private int cardTop() { + /*? if >=1.19.4 {*/ + return getY(); + /*?} else {*/ + /*return y; + *//*?}*/ + } + } } diff --git a/src/main/java/pl/skidam/automodpack/client/ui/widget/ListChrome.java b/src/main/java/pl/skidam/automodpack/client/ui/widget/ListChrome.java index e30a48d7c..1e54f8d5f 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/widget/ListChrome.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/widget/ListChrome.java @@ -2,13 +2,7 @@ import pl.skidam.automodpack.client.ui.versioned.VersionedMatrices; -/** - * The one list look, drawn identically on every version; every color is vanilla's own, measured from its sprites. The - * window geometry the shared lists pin also lives here, so the numbers that make a list's rows land where the caller - * asked have one home: {@link #listHeight} and {@link #windowTop} shift the vanilla window onto the rows, - * {@link #scrollbarPosition} anchors the scrollbar in absolute screen coordinates, and {@link #scrollRange} is the exact - * overflow once that shift is applied. The lists differ only in which vanilla base class they extend. - */ +/** Shared list look: vanilla colors plus a neutral wash, and the window geometry ({@link #listHeight}, {@link #windowTop}, {@link #scrollbarPosition}, {@link #scrollRange}) the lists share. */ public final class ListChrome { /** vanilla menu_list_background.png: flat black at 112/255 alpha. */ public static final int BACKDROP = 0x70000000; @@ -21,6 +15,18 @@ public final class ListChrome { public static final int SELECTION_INNER = 0xFF000000; /** The hovered-row wash reads as "you can click this" without ever lightening the backdrop. */ public static final int HOVER = 0x33000000; + /** Neutral translucent row chrome. */ + public static final int ROW_FILL = 0x24000000; + public static final int ROW_FILL_SELECTED = 0x42000000; + public static final int ROW_FILL_HOVER = 0x52000000; + public static final int ROW_FILL_DISABLED = 0x16000000; + public static final int ROW_FILL_READONLY = 0x18000000; + public static final int ROW_BORDER = 0x33FFFFFF; + public static final int ROW_BORDER_HOVER = 0x99FFFFFF; + public static final int ROW_BORDER_DISABLED = 0x1EFFFFFF; + public static final int TEXT_MUTED = 0xFF9E9E9E; + public static final int TEXT_READONLY_TITLE = 0xFFC8C8C8; + public static final int TEXT_READONLY_SUBTITLE = 0xFF8E8E8E; /** Vanilla renders the first row this far below the list's top edge; the window is shifted up so rows land where the caller asked. */ /*? if >=1.21.10 {*/ @@ -70,4 +76,42 @@ public static void drawSelection(VersionedMatrices matrices, int x, int y, int w public static void drawHover(VersionedMatrices matrices, int x, int y, int width, int height) { matrices.fill(x, y, x + width, y + height, HOVER); } + + /** One row; brighter when selected or hovered, dimmer when inactive. */ + public static void drawRow(VersionedMatrices matrices, int x, int y, int width, int height, boolean selected, boolean highlighted, boolean active) { + int fill = !active ? ROW_FILL_DISABLED : highlighted ? ROW_FILL_HOVER : selected ? ROW_FILL_SELECTED : ROW_FILL; + int border = !active ? ROW_BORDER_DISABLED : highlighted ? ROW_BORDER_HOVER : ROW_BORDER; + matrices.fill(x, y, x + width, y + height, fill); + drawOutline(matrices, x, y, width, height, border); + } + + /** A read-only row: recessed wash in a hairline frame. */ + public static void drawReadOnlyRow(VersionedMatrices matrices, int x, int y, int width, int height) { + matrices.fill(x, y, x + width, y + height, ROW_FILL_READONLY); + drawOutline(matrices, x, y, width, height, ROW_BORDER_DISABLED); + } + + /** A control beside a row, in the same neutral glass. */ + public static void drawControl(VersionedMatrices matrices, int x, int y, int width, int height, boolean highlighted, boolean active) { + int fill = !active ? ROW_FILL_DISABLED : highlighted ? ROW_FILL_HOVER : ROW_FILL; + int border = !active ? ROW_BORDER_DISABLED : highlighted ? ROW_BORDER_HOVER : ROW_BORDER; + matrices.fill(x, y, x + width, y + height, fill); + drawOutline(matrices, x, y, width, height, border); + } + + /** An 8x10 padlock. */ + public static void drawPadlock(VersionedMatrices matrices, int x, int y, int color, int keyholeColor) { + matrices.fill(x + 2, y, x + 6, y + 1, color); + matrices.fill(x + 1, y + 1, x + 2, y + 4, color); + matrices.fill(x + 6, y + 1, x + 7, y + 4, color); + matrices.fill(x, y + 4, x + 8, y + 10, color); + matrices.fill(x + 3, y + 6, x + 5, y + 8, keyholeColor); + } + + private static void drawOutline(VersionedMatrices matrices, int x, int y, int width, int height, int border) { + matrices.fill(x, y, x + width, y + 1, border); + matrices.fill(x, y + height - 1, x + width, y + height, border); + matrices.fill(x, y + 1, x + 1, y + height - 1, border); + matrices.fill(x + width - 1, y + 1, x + width, y + height - 1, border); + } } diff --git a/src/main/java/pl/skidam/automodpack/client/ui/widget/ListControlButton.java b/src/main/java/pl/skidam/automodpack/client/ui/widget/ListControlButton.java new file mode 100644 index 000000000..bd9f332ae --- /dev/null +++ b/src/main/java/pl/skidam/automodpack/client/ui/widget/ListControlButton.java @@ -0,0 +1,78 @@ +package pl.skidam.automodpack.client.ui.widget; + +import net.minecraft.client.gui.components.Button; +import net.minecraft.network.chat.Component; + +import pl.skidam.automodpack.client.ui.versioned.VersionedMatrices; + +/*? if >=26.1 {*/ +import net.minecraft.client.gui.GuiGraphicsExtractor; +/*?} elif >=1.20 {*/ +/*import net.minecraft.client.gui.GuiGraphics; +*//*?} else {*/ +/*import com.mojang.blaze3d.vertex.PoseStack; +*//*?}*/ + +/** A list control in the same neutral glass as its rows. */ +abstract class ListControlButton extends Button { + protected ListControlButton(int x, int y, int width, int height, Component message, OnPress onPress) { + /*? if <1.19.3 {*/ + /*super(x, y, width, height, message, onPress); + *//*?} else {*/ + super(x, y, width, height, message, onPress, DEFAULT_NARRATION); + /*?}*/ + } + + /*? if >=26.1 {*/ + @Override + protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float delta) { + renderControl(new VersionedMatrices(graphics), mouseX, mouseY); + } + /*?} elif >=1.21.11 {*/ + /*@Override + public void renderContents(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + renderControl(new VersionedMatrices(graphics), mouseX, mouseY); + } + *//*?} elif >=1.20 {*/ + /*@Override + protected void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + renderControl(new VersionedMatrices(graphics), mouseX, mouseY); + } + *//*?} else {*/ + /*@Override + public void renderButton(PoseStack matrices, int mouseX, int mouseY, float delta) { + renderControl(new VersionedMatrices(), mouseX, mouseY); + } + *//*?}*/ + + /** Draws the control's content over the glass. */ + protected abstract void drawContent(VersionedMatrices matrices, int left, int top, int width, int height, boolean highlighted); + + private void renderControl(VersionedMatrices matrices, int mouseX, int mouseY) { + int left = left(); + int top = top(); + int width = getWidth(); + int height = getHeight(); + boolean hovered = mouseX >= left && mouseX < left + width && mouseY >= top && mouseY < top + height; + boolean highlighted = this.active && (hovered || isFocused()); + ListChrome.drawControl(matrices, left, top, width, height, highlighted, this.active); + drawContent(matrices, left, top, width, height, highlighted); + } + + // Positions are read live: lists build rows at 0,0 and move the widgets during layout. + protected int left() { + /*? if >=1.19.4 {*/ + return getX(); + /*?} else {*/ + /*return this.x; + *//*?}*/ + } + + protected int top() { + /*? if >=1.19.4 {*/ + return getY(); + /*?} else {*/ + /*return this.y; + *//*?}*/ + } +} diff --git a/src/main/java/pl/skidam/automodpack/client/ui/widget/RowViewport.java b/src/main/java/pl/skidam/automodpack/client/ui/widget/RowViewport.java index 0def91307..1859cbfca 100644 --- a/src/main/java/pl/skidam/automodpack/client/ui/widget/RowViewport.java +++ b/src/main/java/pl/skidam/automodpack/client/ui/widget/RowViewport.java @@ -18,5 +18,15 @@ public interface RowViewport { int rowHeight(); + default void syncLayout() {} + + default int viewportTop() { + return 0; + } + + default int viewportBottom() { + return Integer.MAX_VALUE; + } + record RowView(String text, boolean enabled, Boolean checked, boolean partial) {} } diff --git a/src/main/java/pl/skidam/automodpack/modpack/Commands.java b/src/main/java/pl/skidam/automodpack/modpack/Commands.java index 68eeb5123..4689f78fc 100644 --- a/src/main/java/pl/skidam/automodpack/modpack/Commands.java +++ b/src/main/java/pl/skidam/automodpack/modpack/Commands.java @@ -186,6 +186,12 @@ public static void register(CommandDispatcher dispatcher) { .then(literal("groups") .requires((source) -> source.permissions().hasPermission(new Permission.HasCommandLevel(PermissionLevel.byId(3)))) .executes(Commands::modpackGroups) + .then(literal("import") + .executes(Commands::modpackGroupsImportAll) + .then(argument("folder", StringArgumentType.word()) + .executes(Commands::modpackGroupsImportOne) + ) + ) .then(argument("group-id", StringArgumentType.word()) .executes(Commands::modpackGroupDetail) ) @@ -798,7 +804,7 @@ private static int modpackGroups(CommandContext context) { runAsync(context, "Group overview", () -> { try { Optional published = Hosting.role().currentDocument(); - for (String line : GroupInspector.overview(ServerConfigStore.current().modpack.categories, published.map(PackDocument::manifest).orElse(null))) + for (String line : GroupInspector.overview(ServerConfigStore.current().modpack, published.map(PackDocument::manifest).orElse(null))) send(context, line, ChatFormatting.WHITE, false); } catch (IOException e) { send(context, "Failed to read the published modpack: " + e.getMessage(), ChatFormatting.RED, true); @@ -812,7 +818,7 @@ private static int modpackGroupDetail(CommandContext context runAsync(context, "Group detail", () -> { try { Optional published = Hosting.role().currentDocument(); - Optional> lines = GroupInspector.detail(ServerConfigStore.current().modpack.categories, groupId, published.map(PackDocument::manifest).orElse(null)); + Optional> lines = GroupInspector.detail(ServerConfigStore.current().modpack, groupId, published.map(PackDocument::manifest).orElse(null)); if (lines.isEmpty()) { send(context, "Unknown group id: " + groupId + ". Run /automodpack groups for the list.", ChatFormatting.RED, false); return; @@ -825,6 +831,35 @@ private static int modpackGroupDetail(CommandContext context return Command.SINGLE_SUCCESS; } + private static int modpackGroupsImportAll(CommandContext context) { + return importGroups(context, null); + } + + private static int modpackGroupsImportOne(CommandContext context) { + return importGroups(context, StringArgumentType.getString(context, "folder")); + } + + private static int importGroups(CommandContext context, String folder) { + runAsync(context, "Import groups", () -> { + try { + GroupInspector.ImportResult result = GroupInspector.importFolders(StoragePaths.SERVER_CONFIG_FILE, + GameDirectory.current().resolve(StoragePaths.HOST_MODPACK_DIR), ServerConfigStore.current().modpack, folder); + if (!result.imported().isEmpty()) { + ConfigUtils.reloadServerConfig(); + send(context, "Imported group(s) into server.toml: " + String.join(", ", result.imported()), ChatFormatting.GREEN, false); + send(context, "Run /automodpack generate to publish the updated group list.", ChatFormatting.GRAY, false); + } + if (!result.skipped().isEmpty()) send(context, "Skipped: " + String.join(", ", result.skipped()), ChatFormatting.YELLOW, false); + for (String warning : result.warnings()) send(context, warning, ChatFormatting.RED, false); + if (result.imported().isEmpty() && result.skipped().isEmpty() && result.warnings().isEmpty()) + send(context, "No undeclared non-empty group folders found under host-modpack/.", ChatFormatting.YELLOW, false); + } catch (Exception e) { + send(context, "Failed to import group folders: " + e.getMessage(), ChatFormatting.RED, true); + } + }); + return Command.SINGLE_SUCCESS; + } + private static int generationStorage(CommandContext context) { try { GenerationStore.StorageReport report = Hosting.executor().storageReport(); diff --git a/src/main/resources/assets/automodpack/lang/en_us.json b/src/main/resources/assets/automodpack/lang/en_us.json index 685e3948b..df1ef47fa 100644 --- a/src/main/resources/assets/automodpack/lang/en_us.json +++ b/src/main/resources/assets/automodpack/lang/en_us.json @@ -10,7 +10,7 @@ "automodpack.restart.toast.title": "Restart might fix this", "automodpack.restart.toast.description": "The modpack's current mods may not be loaded. Restart the game and join again.", "automodpack.selection.title": "Group Selection", - "automodpack.selection.description": "Choose which optional parts of the modpack you want.", + "automodpack.selection.description": "Choose which optional groups to include.", "automodpack.selection.saved": "Your selection was saved.", "automodpack.selection.restartRequired": "Restart the game to apply your changes.", "automodpack.selection.updateOnLaunchDisabled": "\"Update modpack on launch\" is disabled. Enable it or start a manual update to apply this selection.", @@ -18,7 +18,6 @@ "automodpack.selection.save": "Save", "automodpack.selection.reset": "Defaults", "automodpack.selection.preview": "Continue", - "automodpack.selection.categoryExplanation": "Category buttons select their groups. AutoModpack saves category choices separately from individual groups.", "automodpack.firstConnect.title": "Set up this modpack", "automodpack.firstConnect.description": "Review the default content before downloading.", "automodpack.firstConnect.requestedGroups": "Requested groups: %s", @@ -84,6 +83,7 @@ "automodpack.packDetails.identity": "%s %s | Minecraft %s", "automodpack.packDetails.id": "ID: %s", "automodpack.packDetails.contents": "%s | %s | %s", + "automodpack.packDetails.contentsNoGroups": "%s | %s", "automodpack.packDetails.server": "Server: %s", "automodpack.packDetails.connection": "Server %s | %s", "automodpack.packDetails.generation": "Generation %s | %s", @@ -255,35 +255,40 @@ "automodpack.firstConnect.downloadSummary": "%s to download | %s new content", "automodpack.firstConnect.includedGroups": "Included groups: %s", "automodpack.firstConnect.unavailableOldChoices": "Previously selected groups that are no longer available: %s", - "automodpack.selection.platformSummary": "Platform: %s Selected groups: %s Download: %s", + "automodpack.selection.summary": "Included: %s | %s", + "automodpack.selection.summaryPlatform": "%s | Included: %s | %s", + "automodpack.selection.countsWithOptional": "%s core, %s/%s optional", + "automodpack.selection.countsCoreOnly": "%s core", "automodpack.selection.platformTooltip": "Chooses the platform used to resolve optional groups. Only change it when automatic detection got your system wrong. Picking the detected platform follows detection again.", "automodpack.selection.platformButton": "OS: %s", "automodpack.selection.platformDetected": "%s (detected)", "automodpack.selection.platformUndetected": "no platform detected", - "automodpack.selection.category": "Category: %s", - "automodpack.selection.requiredAlways": "Required: always included", - "automodpack.selection.defaultSelected": "Default: selected unless you remove it", - "automodpack.selection.forced": "Forced: selected by the server", + "automodpack.selection.otherCategory": "Optional", + "automodpack.selection.selectAll": "Select all", + "automodpack.selection.clearCategory": "Clear", + "automodpack.selection.pickOne": "Choose one", + "automodpack.selection.pickAtMostOne": "Choose at most one", + "automodpack.selection.noneOption": "None", + "automodpack.selection.noneSubtitle": "Leave every option in this category unselected", + "automodpack.selection.includedWithCore": "Included with Core", + "automodpack.selection.includedAutomatically": "Included automatically", + "automodpack.selection.required": "Required", + "automodpack.selection.conflictsWith": "Conflicts with: %s", "automodpack.selection.dependencyNamed": "Required by: %s", "automodpack.selection.requires": "Requires: %s", - "automodpack.selection.conflicts": "Conflicts: %s", - "automodpack.selection.serverDescription": "Description provided by the server", + "automodpack.selection.onlyFor": "Only for: %s", "automodpack.selection.files": "Files: %s (%s)", "automodpack.selection.groupFiles": "Files", "automodpack.selection.unavailableOn": "Not available on %s", "automodpack.selection.metrics.one": "(%s file, %s)", "automodpack.selection.metrics.other": "(%s files, %s)", "automodpack.selection.status.dependencyUnavailable": "(dependency unavailable)", - "automodpack.selection.status.available": "Available", "automodpack.selection.blockedBy": "Unavailable because this group requires %s", - "automodpack.selection.conflictsWith": "Conflicts with %s", - "automodpack.selection.conflictTurnedOff.one": "Turned off %2$s - conflicts with %3$s", - "automodpack.selection.conflictTurnedOff.other": "Turned off %2$s - conflict with %3$s", + "automodpack.selection.cascadeTurnedOff.one": "Turned off %s because its dependency was unselected.", + "automodpack.selection.cascadeTurnedOff.other": "Turned off %s because their dependencies were unselected.", + "automodpack.selection.conflictTurnedOff.one": "Turned off %s because it conflicts with your selection.", + "automodpack.selection.conflictTurnedOff.other": "Turned off %s because they conflict with your selection.", "automodpack.selection.savedInvalid": "Some saved group choices are incompatible. Change the highlighted choices to continue.", - "automodpack.selection.changeInvalid": "That group change is not available.", - "automodpack.selection.cannotSelect": "%s cannot be selected with this modpack configuration.", - "automodpack.selection.status.excluded": "(excluded)", - "automodpack.selection.status.selected": "(selected)", "automodpack.selection.sourcesCancelled": "Third-party sources: lookup canceled. Server download remains available", "automodpack.selection.sourcesResolving": "Third-party sources: resolving (%s / %s files matched)", "automodpack.selection.sourcesResolved": "Third-party sources: %s / %s files matched. Unmatched files use the server", @@ -377,6 +382,8 @@ "automodpack.update.rollbackApply": "Restore", "automodpack.update.rollbackDetaches": "Restoring this version also stops syncing this modpack until you resume syncing.", "automodpack.update.staleSelection": "Some previously selected content is no longer available.", + "automodpack.update.newGroups.one": "New optional group available: %s", + "automodpack.update.newGroups.other": "New optional groups available: %s", "automodpack.update.groupsSelected.one": "%s group selected", "automodpack.update.groupsSelected.other": "%s groups selected", "automodpack.update.unverifiedTrusted.one": "Includes %s mod not on CurseForge or Modrinth (allowed by this pack's trust setting).", @@ -419,8 +426,6 @@ "automodpack.management.preservedFilesCount": "%s kept files", "automodpack.restart.preservedFiles": "%s of your files were kept. They are on the instance timeline.", "automodpack.restart.removeStale": "Remove packs this origin no longer serves", - "automodpack.selection.categoryPart": "%s of %s selected", - "automodpack.selection.categoryTooltip": "Click to include every optional group in this category. Click again to exclude them all.", "automodpack.management.deactivateTooltip": "Turns the modpack off. Its files stay, so you can activate it again.", "automodpack.management.stopSyncingTooltip": "Keeps every file exactly as it is and stops applying server updates until you resume.", "automodpack.management.resumeSyncingTooltip": "Syncs this pack to the server's current generation.",