diff --git a/CHANGELOG.md b/CHANGELOG.md index 8576f20c..d3af18c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,8 +5,14 @@ User-facing changes only. The release workflow publishes the matching ## [Unreleased] +### Added + +- Game switcher for Team Fortress 2 and Deadlock, with Deadlock install detection, write lock while Deadlock runs, Launch Deadlock, and a per-game accent colour and dot backdrop. +- Deadlock profiles: switch setups, manage `pak01_dir.vpk`–`pak99_dir.vpk` addons with slot priority and file-overlap detection, browse and install single or multiple files from Deadlock GameBanana listings (and reopen `Files…` on installed cards or pick specific `.vpk` entries inside multi-mod archives), manage `gameinfo.gi` search paths with `PGIVersion` checks, edit Steam launch options (`1422450`), inspect live `.vcfg`/`video.txt` and `citadel_*.cfg` files read-only, and edit and lint user `.cfg` files. + ### Fixed +- Linux on Hyprland no longer shows a duplicate GTK titlebar beneath the compositor's window bar. - Crosshair and Sounds: when another pack replaces the same files, Show in Mods now opens Custom packs with that pack marked, instead of only opening Mods. - HUD and Viewmodels: importing something that belongs in Mods now says so and offers Open Mods, diff --git a/apps/desktop/src-tauri/core/src/deadlock/gameinfo.rs b/apps/desktop/src-tauri/core/src/deadlock/gameinfo.rs new file mode 100644 index 00000000..9ff4f60a --- /dev/null +++ b/apps/desktop/src-tauri/core/src/deadlock/gameinfo.rs @@ -0,0 +1,486 @@ +//! Safe reading, patching, stock snapshotting, and `PGIVersion` checking for +//! Deadlock's `game/citadel/gameinfo.gi`. + +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use crate::hash::{read_small_text_bounded, sha256_hex, validate_file_within, write_atomic_within}; +use crate::profile::ProfileError; + +pub const MAX_GAMEINFO_BYTES: usize = 2 * 1024 * 1024; +pub const PGI_MISMATCH_PREFIX: &str = "Deadlock updated gameinfo.gi (PGIVersion changed)"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GameInfoMode { + #[default] + StockManaged, + Custom, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GameInfoCheck { + pub mode: GameInfoMode, + pub live_pgi_version: Option, + pub profile_pgi_version: Option, + pub pgi_mismatch: bool, + pub addons_enabled: bool, + pub live_is_custom: bool, +} + +fn strip_line_comment(line: &str) -> &str { + let mut in_quotes = false; + let mut prev_slash = false; + for (idx, ch) in line.char_indices() { + if ch == '"' { + in_quotes = !in_quotes; + prev_slash = false; + continue; + } + if !in_quotes && ch == '/' { + if prev_slash { + return &line[..idx - 1]; + } + prev_slash = true; + } else { + prev_slash = false; + } + } + line +} + +fn split_kv_pair(code: &str) -> Option<(String, String)> { + let trimmed = code.trim(); + if trimmed.is_empty() { + return None; + } + let mut parts = Vec::new(); + let mut chars = trimmed.char_indices().peekable(); + while let Some(&(_, ch)) = chars.peek() { + if ch.is_whitespace() { + chars.next(); + continue; + } + if ch == '"' { + chars.next(); + let mut val = String::new(); + for (_, c) in chars.by_ref() { + if c == '"' { + break; + } + val.push(c); + } + parts.push(val); + } else { + let mut val = String::new(); + while let Some(&(_, c)) = chars.peek() { + if c.is_whitespace() { + break; + } + val.push(c); + chars.next(); + } + parts.push(val); + } + if parts.len() == 2 { + break; + } + } + if parts.len() == 2 { + Some((parts[0].clone(), parts[1].clone())) + } else { + None + } +} + +/// Extract `PGIVersion ""` outside line comments. +pub fn parse_pgi_version(text: &str) -> Option { + for line in text.lines() { + let code = strip_line_comment(line); + if let Some((k, v)) = split_kv_pair(code) { + if k.eq_ignore_ascii_case("pgiversion") && !v.trim().is_empty() { + return Some(v.trim().to_string()); + } + } + } + None +} + +fn find_search_paths_span(text: &str) -> Option<(usize, usize)> { + let bytes = text.as_bytes(); + let mut line_start = 0usize; + let mut looking_for_open = false; + let mut block_body_start = None; + let mut depth = 0i32; + + for raw_line in text.split_inclusive('\n') { + let line_len = raw_line.len(); + let line_no_nl = raw_line.trim_end_matches(['\r', '\n']); + let code = strip_line_comment(line_no_nl); + let trimmed = code.trim(); + + if let Some(start) = block_body_start { + for (rel_idx, ch) in code.char_indices() { + match ch { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + return Some((start, line_start + rel_idx)); + } + } + _ => {} + } + } + } else if looking_for_open { + if let Some(open_rel) = code.find('{') { + block_body_start = Some(line_start + open_rel + 1); + depth = 1; + for (rel_idx, ch) in code[open_rel + 1..].char_indices() { + match ch { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + return Some(( + line_start + open_rel + 1, + line_start + open_rel + 1 + rel_idx, + )); + } + } + _ => {} + } + } + looking_for_open = false; + } + } else if trimmed.eq_ignore_ascii_case("searchpaths") + || trimmed.eq_ignore_ascii_case("\"searchpaths\"") + { + looking_for_open = true; + } else if bytes[line_start..line_start + line_len] + .windows(11) + .any(|w| w.eq_ignore_ascii_case(b"searchpaths")) + && trimmed.to_ascii_lowercase().starts_with("searchpaths") + && code.contains('{') + { + if let Some(open_rel) = code.find('{') { + block_body_start = Some(line_start + open_rel + 1); + depth = 1; + } + } + + line_start += line_len; + } + + None +} + +fn normalized_search_entry(code: &str) -> Option<(String, String)> { + let (k, v) = split_kv_pair(code)?; + Some(( + k.to_ascii_lowercase(), + v.trim().replace('\\', "/").to_ascii_lowercase(), + )) +} + +/// Whether `SearchPaths { ... }` mounts `citadel/addons`. +pub fn has_addons_search_path(text: &str) -> bool { + let Some((start, end)) = find_search_paths_span(text) else { + return false; + }; + for line in text[start..end].lines() { + let code = strip_line_comment(line); + if let Some((k, v)) = normalized_search_entry(code) { + if k == "game" && v == "citadel/addons" { + return true; + } + } + } + false +} + +/// Best-effort heuristic (optionally refined by comparing against a saved stock +/// baseline) telling whether `gameinfo.gi` carries customizations beyond +/// mounting `citadel/addons`. +pub fn is_custom_gameinfo(text: &str) -> bool { + is_custom_gameinfo_against(text, None) +} + +pub fn is_custom_gameinfo_against(text: &str, stock_baseline: Option<&str>) -> bool { + if let Some(stock) = stock_baseline { + if let (Ok(norm_live), Ok(norm_stock)) = ( + patch_addons_search_path(text, false), + patch_addons_search_path(stock, false), + ) { + return canonical_whitespace(&norm_live) != canonical_whitespace(&norm_stock); + } + } + let lower = text.to_ascii_lowercase(); + if lower.contains("deadlockconfig") + || lower.contains("complock") + || lower.contains("deadlock mod manager") + { + return true; + } + if let Some((start, end)) = find_search_paths_span(text) { + for line in text[start..end].lines() { + let code = strip_line_comment(line); + if let Some((k, v)) = normalized_search_entry(code) { + let allowed = matches!( + (k.as_str(), v.as_str()), + ("game_uilanguage", "citadel_*language*") + | ("game_lowviolence", "citadel_lv") + | ("mod", "citadel") + | ("write", "citadel") + | ("game", "citadel/addons") + | ("game", "citadel") + | ("game", "core") + ); + if !allowed { + return true; + } + } + } + } + false +} + +fn canonical_whitespace(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// Enable or disable `citadel/addons` inside `FileSystem { SearchPaths { ... } }`, +/// preserving the rest of `gameinfo.gi` byte-for-byte. +pub fn patch_addons_search_path(text: &str, enable: bool) -> Result { + let Some((start, end)) = find_search_paths_span(text) else { + return Err(ProfileError::Io( + "Deadlock's gameinfo.gi has no SearchPaths block.".into(), + )); + }; + + let nl = if text.contains("\r\n") { "\r\n" } else { "\n" }; + let block = &text[start..end]; + let mut lines: Vec = Vec::new(); + let mut has_mod_citadel = false; + let mut has_write_citadel = false; + let mut has_addons = false; + let mut game_citadel_idx: Option = None; + + for raw_line in block.split_inclusive('\n') { + let stripped = raw_line.trim_end_matches(['\r', '\n']); + let code = strip_line_comment(stripped); + let entry = normalized_search_entry(code); + + if enable { + if let Some((ref k, ref v)) = entry { + match (k.as_str(), v.as_str()) { + ("mod", "citadel") => has_mod_citadel = true, + ("write", "citadel") => has_write_citadel = true, + ("game", "citadel/addons") => has_addons = true, + ("game", "citadel") if game_citadel_idx.is_none() => { + game_citadel_idx = Some(lines.len()); + } + _ => {} + } + } + lines.push(raw_line.to_string()); + } else { + let remove = matches!( + entry.as_ref().map(|(k, v)| (k.as_str(), v.as_str())), + Some(("mod", "citadel") | ("write", "citadel") | ("game", "citadel/addons")) + ); + if !remove { + lines.push(raw_line.to_string()); + } + } + } + + if enable && !has_addons { + let idx = game_citadel_idx.ok_or_else(|| { + ProfileError::Io( + "Deadlock's gameinfo.gi SearchPaths block has no Game citadel entry.".into(), + ) + })?; + let indent: String = lines[idx] + .chars() + .take_while(|ch| ch.is_whitespace() && *ch != '\r' && *ch != '\n') + .collect(); + let mut insert = Vec::new(); + if !has_mod_citadel { + insert.push(format!("{indent}Mod\t\t\t\tcitadel{nl}")); + } + if !has_write_citadel { + insert.push(format!("{indent}Write\t\t\t\tcitadel{nl}")); + } + insert.push(format!("{indent}Game\t\t\t\tcitadel/addons{nl}")); + for (offset, item) in insert.into_iter().enumerate() { + lines.insert(idx + offset, item); + } + } else if !enable + && !block.split_inclusive('\n').any(|l| { + let code = strip_line_comment(l.trim_end_matches(['\r', '\n'])); + matches!( + normalized_search_entry(code) + .as_ref() + .map(|(k, v)| (k.as_str(), v.as_str())), + Some(("game", "citadel")) + ) + }) + { + return Err(ProfileError::Io( + "Deadlock's gameinfo.gi SearchPaths block has no Game citadel entry.".into(), + )); + } + + let mut out = String::with_capacity(text.len() + 64); + out.push_str(&text[..start]); + for line in lines { + out.push_str(&line); + } + out.push_str(&text[end..]); + Ok(out) +} + +/// Snapshot a clean stock copy (addons SearchPath stripped) under +/// `/.gi` when `text` appears stock. +pub fn snapshot_stock_gameinfo( + stock_dir: &Path, + text: &str, +) -> Result, ProfileError> { + let Some(pgi) = parse_pgi_version(text) else { + return Ok(None); + }; + if is_custom_gameinfo(text) { + return Ok(None); + } + if !pgi + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + { + return Ok(None); + } + let clean = patch_addons_search_path(text, false)?; + let dest = stock_dir.join(format!("{pgi}.gi")); + if !dest.exists() { + write_atomic_within(stock_dir, &dest, clean.as_bytes()) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + Ok(Some(pgi)) +} + +pub fn load_stock_snapshot(stock_dir: &Path, pgi: &str) -> Option { + if !pgi + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + { + return None; + } + let path = stock_dir.join(format!("{pgi}.gi")); + validate_file_within(stock_dir, &path).ok()?; + read_small_text_bounded(&path, MAX_GAMEINFO_BYTES).ok() +} + +pub fn verify_custom_gameinfo_pgi(live_text: &str, profile_text: &str) -> Result<(), ProfileError> { + if let (Some(live_pgi), Some(profile_pgi)) = ( + parse_pgi_version(live_text), + parse_pgi_version(profile_text), + ) { + if live_pgi != profile_pgi { + return Err(ProfileError::Io(format!( + "{PGI_MISMATCH_PREFIX}: installed is {live_pgi}, profile expects {profile_pgi}. Update gameinfo.gi to match the new Deadlock patch or switch this profile back to stock SearchPaths." + ))); + } + } + Ok(()) +} + +pub fn text_digest(text: &str) -> String { + sha256_hex(text.as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn sample_stock_gi(nl: &str, pgi: &str) -> String { + [ + "\"GameInfo\"", + "{", + "\tgame\t\t\"citadel\"", + &format!("\tPGIVersion \"{pgi}\""), + "\tFileSystem", + "\t{", + "\t\tSearchPaths", + "\t\t{", + "\t\t\tGame_UILanguage\t\tcitadel_*LANGUAGE*", + "\t\t\tGame_LowViolence\tcitadel_lv", + "", + "\t\t\tGame\t\t\t\tcitadel", + "\t\t\tGame\t\t\t\tcore", + "\t\t}", + "\t}", + "\tConVars", + "\t{", + "\t\t\"fps_max\" \"400\"", + "\t}", + "}", + "", + ] + .join(nl) + } + + #[test] + fn parses_pgi_version_and_ignores_comments() { + let text = "// PGIVersion \"OLD\"\n\"GameInfo\" {\n\tPGIVersion \"48C04ECA\"\n}"; + assert_eq!(parse_pgi_version(text).as_deref(), Some("48C04ECA")); + } + + #[test] + fn patches_addons_round_trip_preserving_line_endings() { + for nl in ["\n", "\r\n"] { + let stock = sample_stock_gi(nl, "48C04ECA"); + assert!(!has_addons_search_path(&stock)); + assert!(!is_custom_gameinfo(&stock)); + + let enabled = patch_addons_search_path(&stock, true).unwrap(); + assert!(has_addons_search_path(&enabled)); + assert!(enabled.contains(nl)); + assert!(enabled.contains(&format!("\t\t\tGame\t\t\t\tcitadel/addons{nl}"))); + + let disabled = patch_addons_search_path(&enabled, false).unwrap(); + assert_eq!(disabled, stock); + } + } + + #[test] + fn detects_custom_complock_gameinfo_and_refuses_pgi_mismatch() { + let custom = format!( + "// deadlockconfig.com - by jcStani and HoppCX\n{}", + sample_stock_gi("\n", "OLDHASH") + ); + let custom_enabled = patch_addons_search_path(&custom, true).unwrap(); + assert!(is_custom_gameinfo(&custom_enabled)); + + let live_patched = sample_stock_gi("\n", "NEWHASH"); + let err = verify_custom_gameinfo_pgi(&live_patched, &custom_enabled).unwrap_err(); + assert!(err.message().contains(PGI_MISMATCH_PREFIX)); + + let live_same = sample_stock_gi("\n", "OLDHASH"); + verify_custom_gameinfo_pgi(&live_same, &custom_enabled).unwrap(); + } + + #[test] + fn snapshots_and_reloads_stock_baseline() { + let dir = crate::test_temp_dir(); + let enabled = patch_addons_search_path(&sample_stock_gi("\n", "HASH1"), true).unwrap(); + let saved_pgi = snapshot_stock_gameinfo(&dir, &enabled).unwrap(); + assert_eq!(saved_pgi.as_deref(), Some("HASH1")); + let loaded = load_stock_snapshot(&dir, "HASH1").unwrap(); + assert!(!has_addons_search_path(&loaded)); + assert!(!is_custom_gameinfo_against(&enabled, Some(&loaded))); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/apps/desktop/src-tauri/core/src/deadlock/mod.rs b/apps/desktop/src-tauri/core/src/deadlock/mod.rs new file mode 100644 index 00000000..403f3521 --- /dev/null +++ b/apps/desktop/src-tauri/core/src/deadlock/mod.rs @@ -0,0 +1,83 @@ +//! Deadlock profile library, `gameinfo.gi` handling, addon VPK metadata, +//! launch options, and user `.cfg` projection. + +pub mod gameinfo; +pub mod profiles; +pub mod vpk_meta; + +use std::path::{Path, PathBuf}; + +use crate::game::GameId; +use crate::profile::ProfileError; +use crate::settings::{execs_data_dir, try_execs_data_dir}; + +pub use gameinfo::{ + has_addons_search_path, is_custom_gameinfo, parse_pgi_version, patch_addons_search_path, + snapshot_stock_gameinfo, verify_custom_gameinfo_pgi, GameInfoCheck, GameInfoMode, +}; +pub use profiles::{ + adopt_deadlock_live_gameinfo, adopt_deadlock_live_gameinfo_in, + adopt_deadlock_steam_launch_options, adopt_deadlock_steam_launch_options_in, + capture_deadlock_profile, capture_deadlock_profile_in, create_deadlock_profile, + create_deadlock_profile_in, deadlock_launch_sync_status, deadlock_launch_sync_status_in, + delete_deadlock_cfg_file, delete_deadlock_cfg_file_in, delete_deadlock_profile, + delete_deadlock_profile_in, inspect_deadlock_mod_payload, install_deadlock_mod_bytes, + install_deadlock_mod_bytes_in, install_deadlock_staged_vpks, install_deadlock_staged_vpks_in, + load_deadlock_library, load_deadlock_library_in, load_deadlock_profile_detail, + load_deadlock_profile_detail_in, read_deadlock_cfg_files, read_deadlock_cfg_files_in, + remove_deadlock_mod, remove_deadlock_mod_in, rename_deadlock_profile, + rename_deadlock_profile_in, reorder_deadlock_mods, reorder_deadlock_mods_in, + reset_deadlock_profile_gameinfo_to_stock, reset_deadlock_profile_gameinfo_to_stock_in, + save_deadlock_cfg_file, save_deadlock_cfg_file_in, set_deadlock_launch_options, + set_deadlock_launch_options_in, set_deadlock_mod_enabled, set_deadlock_mod_enabled_in, + switch_deadlock_profile, switch_deadlock_profile_in, DeadlockArchiveVpkEntry, DeadlockCfgFile, + DeadlockLaunchSyncStatus, DeadlockLibrary, DeadlockModRecord, DeadlockModSource, + DeadlockModView, DeadlockProfileDetail, DeadlockProfileSummary, DeadlockSetLaunchResult, + DeadlockStagedVpk, +}; +pub use vpk_meta::{ + compute_mod_conflicts, inspect_vpk_bytes, parse_mods_txt_titles, DeadlockModConflict, + DeadlockVpkInfo, +}; + +/// Base storage folder for Deadlock (`/deadlock`). +pub fn deadlock_data_dir(data_dir: &Path) -> PathBuf { + GameId::Deadlock.data_dir(data_dir) +} + +/// Default Deadlock data folder under the active user's execs data dir. +pub fn default_deadlock_data_dir() -> PathBuf { + execs_data_dir() +} + +pub fn try_default_deadlock_data_dir() -> Result { + try_execs_data_dir().map_err(ProfileError::Io) +} + +pub fn deadlock_profiles_dir(data_dir: &Path) -> PathBuf { + deadlock_data_dir(data_dir).join("profiles") +} + +pub fn deadlock_blobs_dir(data_dir: &Path) -> PathBuf { + deadlock_data_dir(data_dir).join("blobs") +} + +pub fn deadlock_gameinfo_stock_dir(data_dir: &Path) -> PathBuf { + deadlock_data_dir(data_dir).join("gameinfo-stock") +} + +pub fn citadel_dir(root: &Path) -> PathBuf { + root.join("game").join("citadel") +} + +pub fn live_gameinfo_path(root: &Path) -> PathBuf { + citadel_dir(root).join("gameinfo.gi") +} + +pub fn live_addons_dir(root: &Path) -> PathBuf { + citadel_dir(root).join("addons") +} + +pub fn live_cfg_dir(root: &Path) -> PathBuf { + citadel_dir(root).join("cfg") +} diff --git a/apps/desktop/src-tauri/core/src/deadlock/profiles.rs b/apps/desktop/src-tauri/core/src/deadlock/profiles.rs new file mode 100644 index 00000000..6bee24dc --- /dev/null +++ b/apps/desktop/src-tauri/core/src/deadlock/profiles.rs @@ -0,0 +1,2718 @@ +//! Deadlock profile storage, live projection (`pakNN_dir.vpk`, `gameinfo.gi`, +//! user `.cfg` files), mod library actions, and launch option sync. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Component, Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::archive::{extract_archive, ArchiveLimits, MAX_IMPORTED_CFG_BYTES}; +use crate::finder::{discover_steam_roots, normalize_deadlock_root, read_deadlock_client_version}; +use crate::game::GameId; +use crate::hash::{ + create_dir_all_within, metadata_is_link, read_small_file_bounded, read_small_text_bounded, + remove_file_force_within, remove_tree_within, sha256_file, sha256_hex, validate_dir_within, + validate_file_within, write_atomic_within, +}; +use crate::launch::{ + pick_steam_account_for_app_from, read_steam_launch_options_for_app_from, + sanitize_deadlock_launch_options, write_steam_launch_options_for_app_from, LaunchWriteReason, + DEADLOCK_APP, +}; +use crate::mods::MAX_MOD_BYTES; +use crate::process_lock::{live_process_names, refuse_if_game_running_among, steam_running_among}; +use crate::profile::ProfileError; + +const PROFILE_NAME_MAX: usize = 80; + +use super::gameinfo::{ + has_addons_search_path, is_custom_gameinfo_against, load_stock_snapshot, parse_pgi_version, + patch_addons_search_path, snapshot_stock_gameinfo, verify_custom_gameinfo_pgi, GameInfoCheck, + GameInfoMode, MAX_GAMEINFO_BYTES, PGI_MISMATCH_PREFIX, +}; +use super::vpk_meta::{ + compute_mod_conflicts, inspect_vpk_bytes, parse_mods_txt_titles, DeadlockModConflict, + DeadlockVpkInfo, +}; +use super::{ + deadlock_blobs_dir, deadlock_gameinfo_stock_dir, deadlock_profiles_dir, live_addons_dir, + live_cfg_dir, live_gameinfo_path, try_default_deadlock_data_dir, +}; + +const SCHEMA_VERSION: u32 = 1; +const MAX_ADDON_SLOTS: usize = 99; +const MAX_CFG_FILES_PER_PROFILE: usize = 64; +const MAX_READONLY_GAME_CFGS: usize = 64; +const LIVE_DEADLOCK_SETTINGS_FILES: &[&str] = &[ + "user_convars_0_slot0.vcfg", + "user_keys_0_slot0.vcfg", + "machine_convars.vcfg", + "video.txt", +]; +const MAX_MANIFEST_BYTES: usize = 4 * 1024 * 1024; +const MAX_INDEX_BYTES: usize = 16 * 1024 * 1024; +const VPK_MAGIC: [u8; 4] = [0x34, 0x12, 0xAA, 0x55]; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum DeadlockModSource { + External, + Local { + #[serde(rename = "fileName")] + file_name: String, + }, + GameBanana { + id: u64, + section: String, + #[serde(rename = "fileId")] + file_id: u64, + #[serde(rename = "fileName")] + file_name: String, + #[serde(rename = "pageUrl")] + page_url: String, + author: Option, + version: Option, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockModRecord { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub author: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub built_for_client: Option, + pub source: DeadlockModSource, + pub enabled: bool, + pub blob_sha256: String, + pub bytes: u64, + pub files_count: usize, + pub original_name: String, + pub installed_at: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockModView { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub author: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub built_for_client: Option, + pub source: DeadlockModSource, + pub enabled: bool, + pub blob_sha256: String, + pub bytes: u64, + pub files_count: usize, + pub original_name: String, + pub installed_at: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub slot: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pak_name: Option, + pub client_mismatch: bool, + pub conflict_count: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockArchiveVpkEntry { + pub archive_path: String, + pub title: String, + pub bytes: u64, + pub files_count: usize, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub built_for_client: Option, +} + +#[derive(Debug, Clone)] +pub struct DeadlockStagedVpk { + pub entry: DeadlockArchiveVpkEntry, + pub vpk_bytes: Vec, + pub info: DeadlockVpkInfo, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockCfgFile { + pub path: String, + pub text: String, + pub read_only: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockProfileSummary { + pub id: String, + pub name: String, + pub mod_count: usize, + pub enabled_mod_count: usize, + pub gameinfo_mode: GameInfoMode, + pub created_at: i64, + pub updated_at: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockLibrary { + pub deadlock_root: String, + pub active_profile_id: Option, + pub profiles: Vec, + pub client_version: Option, + pub gameinfo: GameInfoCheck, + pub live_addon_count: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockProfileDetail { + pub id: String, + pub name: String, + pub gameinfo_mode: GameInfoMode, + pub gameinfo_pgi: Option, + pub gameinfo_check: GameInfoCheck, + pub launch_options: String, + pub mods: Vec, + pub conflicts: Vec, + pub cfg_files: Vec, + pub client_version: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockLaunchSyncStatus { + pub profile_options: String, + pub steam_options: Option, + pub in_sync: bool, + pub steam_running: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockSetLaunchResult { + pub launch_options: String, + pub steam_write: LaunchWriteReason, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct DeadlockIndex { + version: u32, + deadlock_root: String, + active_profile_id: Option, + profiles: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct DeadlockProfileMeta { + id: String, + name: String, + created_at: i64, + updated_at: i64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct DeadlockManifest { + version: u32, + id: String, + name: String, + gameinfo_mode: GameInfoMode, + gameinfo_pgi: Option, + #[serde(default)] + has_custom_gameinfo: bool, + #[serde(default)] + launch_options: String, + #[serde(default)] + mods: Vec, + #[serde(default)] + cfg_files: Vec, +} + +fn now_millis() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +fn is_valid_token(id: &str) -> bool { + !id.is_empty() + && id.len() <= 128 + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +fn validate_profile_id(id: &str) -> Result<(), ProfileError> { + if is_valid_token(id) { + Ok(()) + } else { + Err(ProfileError::Io( + "Invalid Deadlock profile identifier.".into(), + )) + } +} + +fn normalize_root(root: &Path) -> Result { + normalize_deadlock_root(root).map_err(|err| ProfileError::Io(err.message())) +} + +fn validate_profile_name(raw: &str) -> Result { + let trimmed = raw.trim(); + if trimmed.is_empty() + || trimmed.chars().count() > PROFILE_NAME_MAX + || trimmed.chars().any(char::is_control) + { + return Err(ProfileError::Io( + "Enter a profile name up to 80 characters without control characters.".into(), + )); + } + Ok(trimmed.to_string()) +} + +fn is_pak_slot_name(name: &str) -> Option { + let lower = name.to_ascii_lowercase(); + let num = lower.strip_prefix("pak")?.strip_suffix("_dir.vpk")?; + if num.len() != 2 || !num.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let slot: u8 = num.parse().ok()?; + (1..=MAX_ADDON_SLOTS as u8).contains(&slot).then_some(slot) +} + +pub fn format_pak_slot_name(slot: u8) -> String { + format!("pak{slot:02}_dir.vpk") +} + +/// Only editable plain user `.cfg` files belong to profiles; Valve's own +/// shipped configs (`citadel_*.cfg`, `.vcfg`, `.lst`, `.vdf`, `video.txt`) +/// are always left untouched. +pub fn is_protected_deadlock_cfg_path(rel: &str) -> bool { + let lower = rel.trim().replace('\\', "/").to_ascii_lowercase(); + let file_name = lower.rsplit('/').next().unwrap_or(&lower); + !file_name.ends_with(".cfg") + || file_name.starts_with("citadel_") + || file_name.contains(".vcfg") + || file_name == "video.txt" +} + +pub fn normalize_deadlock_cfg_path(raw: &str) -> Result { + let trimmed = raw.trim().replace('\\', "/"); + let stripped = trimmed.trim_start_matches('/'); + if stripped.is_empty() + || stripped.len() > 160 + || stripped.contains('\0') + || stripped.chars().any(char::is_control) + { + return Err(ProfileError::Io("Invalid cfg file path.".into())); + } + let path = Path::new(stripped); + let mut parts = Vec::new(); + for component in path.components() { + match component { + Component::Normal(seg) => { + let s = seg + .to_str() + .ok_or_else(|| ProfileError::Io("Invalid UTF-8 cfg path.".into()))?; + if s.contains(':') || s.starts_with('.') { + return Err(ProfileError::Io("Invalid cfg file name.".into())); + } + parts.push(s.to_string()); + } + _ => return Err(ProfileError::Io("Cfg path must be relative.".into())), + } + } + if parts.is_empty() || parts.len() > 6 { + return Err(ProfileError::Io("Cfg path depth is unsupported.".into())); + } + let normalized = parts.join("/"); + if is_protected_deadlock_cfg_path(&normalized) { + return Err(ProfileError::Io( + "Only user .cfg files can be edited here; shipped Valve configs are protected.".into(), + )); + } + Ok(normalized) +} + +fn ensure_store_dirs(data_dir: &Path) -> Result<(), ProfileError> { + for dir in [ + deadlock_profiles_dir(data_dir), + deadlock_blobs_dir(data_dir), + deadlock_gameinfo_stock_dir(data_dir), + ] { + fs::create_dir_all(&dir).map_err(|err| ProfileError::Io(err.to_string()))?; + } + Ok(()) +} + +fn load_index(data_dir: &Path) -> Result { + let profiles_dir = deadlock_profiles_dir(data_dir); + let path = profiles_dir.join("index.json"); + if !path.exists() { + return Ok(DeadlockIndex { + version: SCHEMA_VERSION, + ..Default::default() + }); + } + validate_file_within(&profiles_dir, &path).map_err(|err| ProfileError::Io(err.to_string()))?; + let text = read_small_text_bounded(&path, MAX_MANIFEST_BYTES) + .map_err(|err| ProfileError::Io(err.to_string()))?; + serde_json::from_str(&text) + .map_err(|err| ProfileError::Io(format!("Invalid Deadlock profile index: {err}"))) +} + +fn save_index(data_dir: &Path, index: &DeadlockIndex) -> Result<(), ProfileError> { + let profiles_dir = deadlock_profiles_dir(data_dir); + let bytes = + serde_json::to_vec_pretty(index).map_err(|err| ProfileError::Io(err.to_string()))?; + write_atomic_within(&profiles_dir, &profiles_dir.join("index.json"), &bytes) + .map_err(|err| ProfileError::Io(err.to_string())) +} + +fn profile_dir(data_dir: &Path, profile_id: &str) -> Result { + validate_profile_id(profile_id)?; + Ok(deadlock_profiles_dir(data_dir).join(profile_id)) +} + +fn load_manifest(data_dir: &Path, profile_id: &str) -> Result { + let dir = profile_dir(data_dir, profile_id)?; + let path = dir.join("manifest.json"); + validate_file_within(&dir, &path).map_err(|err| ProfileError::Io(err.to_string()))?; + let text = read_small_text_bounded(&path, MAX_MANIFEST_BYTES) + .map_err(|err| ProfileError::Io(err.to_string()))?; + serde_json::from_str(&text) + .map_err(|err| ProfileError::Io(format!("Invalid Deadlock profile manifest: {err}"))) +} + +fn save_manifest(data_dir: &Path, manifest: &DeadlockManifest) -> Result<(), ProfileError> { + let dir = profile_dir(data_dir, &manifest.id)?; + create_dir_all_within(&deadlock_profiles_dir(data_dir), &dir) + .map_err(|err| ProfileError::Io(err.to_string()))?; + let bytes = + serde_json::to_vec_pretty(manifest).map_err(|err| ProfileError::Io(err.to_string()))?; + write_atomic_within(&dir, &dir.join("manifest.json"), &bytes) + .map_err(|err| ProfileError::Io(err.to_string())) +} + +fn store_blob_and_index( + data_dir: &Path, + vpk_bytes: &[u8], + entry_paths: &[String], +) -> Result { + let blobs_dir = deadlock_blobs_dir(data_dir); + fs::create_dir_all(&blobs_dir).map_err(|err| ProfileError::Io(err.to_string()))?; + let sha = sha256_hex(vpk_bytes); + let blob_path = blobs_dir.join(format!("{sha}.vpk")); + if !blob_path.exists() { + write_atomic_within(&blobs_dir, &blob_path, vpk_bytes) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + let idx_path = blobs_dir.join(format!("{sha}.index.json")); + if !idx_path.exists() { + let json = + serde_json::to_vec(entry_paths).map_err(|err| ProfileError::Io(err.to_string()))?; + write_atomic_within(&blobs_dir, &idx_path, &json) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + Ok(sha) +} + +fn load_blob_entry_paths(data_dir: &Path, sha: &str) -> Result, ProfileError> { + if !is_valid_token(sha) { + return Err(ProfileError::Io("Invalid blob digest.".into())); + } + let blobs_dir = deadlock_blobs_dir(data_dir); + let idx_path = blobs_dir.join(format!("{sha}.index.json")); + if idx_path.exists() { + validate_file_within(&blobs_dir, &idx_path) + .map_err(|err| ProfileError::Io(err.to_string()))?; + let text = read_small_text_bounded(&idx_path, MAX_INDEX_BYTES) + .map_err(|err| ProfileError::Io(err.to_string()))?; + if let Ok(paths) = serde_json::from_str::>(&text) { + return Ok(paths); + } + } + let blob_path = blobs_dir.join(format!("{sha}.vpk")); + validate_file_within(&blobs_dir, &blob_path) + .map_err(|err| ProfileError::Io(err.to_string()))?; + let bytes = fs::read(&blob_path).map_err(|err| ProfileError::Io(err.to_string()))?; + let info = inspect_vpk_bytes(&bytes)?; + let _ = serde_json::to_vec(&info.entry_paths).map(|json| { + let _ = write_atomic_within(&blobs_dir, &idx_path, &json); + }); + Ok(info.entry_paths) +} + +fn prune_unused_blobs(data_dir: &Path, index: &DeadlockIndex) { + let blobs_dir = deadlock_blobs_dir(data_dir); + if !blobs_dir.is_dir() { + return; + } + let mut keep = BTreeSet::new(); + for meta in &index.profiles { + if let Ok(manifest) = load_manifest(data_dir, &meta.id) { + for m in manifest.mods { + keep.insert(m.blob_sha256); + } + } + } + let Ok(entries) = fs::read_dir(&blobs_dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().to_string(); + let stem = name + .strip_suffix(".vpk") + .or_else(|| name.strip_suffix(".index.json")); + if let Some(sha) = stem { + if !keep.contains(sha) { + let _ = remove_file_force_within(&blobs_dir, &path); + } + } + } +} + +fn read_live_gameinfo(root: &Path) -> Result { + let path = live_gameinfo_path(root); + validate_file_within(root, &path).map_err(|err| ProfileError::Io(err.to_string()))?; + read_small_text_bounded(&path, MAX_GAMEINFO_BYTES) + .map_err(|err| ProfileError::Io(err.to_string())) +} + +fn read_profile_gameinfo( + data_dir: &Path, + profile_id: &str, +) -> Result, ProfileError> { + let dir = profile_dir(data_dir, profile_id)?; + let path = dir.join("gameinfo.gi"); + if !path.exists() { + return Ok(None); + } + validate_file_within(&dir, &path).map_err(|err| ProfileError::Io(err.to_string()))?; + read_small_text_bounded(&path, MAX_GAMEINFO_BYTES) + .map(Some) + .map_err(|err| ProfileError::Io(err.to_string())) +} + +fn check_gameinfo_status( + data_dir: &Path, + root: &Path, + manifest: Option<&DeadlockManifest>, +) -> GameInfoCheck { + let live_text = read_live_gameinfo(root).ok(); + let live_pgi_version = live_text.as_deref().and_then(parse_pgi_version); + let addons_enabled = live_text.as_deref().is_some_and(has_addons_search_path); + let stock_baseline = live_pgi_version + .as_deref() + .and_then(|pgi| load_stock_snapshot(&deadlock_gameinfo_stock_dir(data_dir), pgi)); + let live_is_custom = live_text + .as_deref() + .is_some_and(|text| is_custom_gameinfo_against(text, stock_baseline.as_deref())); + + match manifest { + Some(m) => { + let profile_pgi_version = m.gameinfo_pgi.clone(); + let pgi_mismatch = match ( + m.gameinfo_mode, + live_pgi_version.as_deref(), + profile_pgi_version.as_deref(), + ) { + (GameInfoMode::Custom, Some(live), Some(prof)) => live != prof, + _ => false, + }; + GameInfoCheck { + mode: m.gameinfo_mode, + live_pgi_version, + profile_pgi_version, + pgi_mismatch, + addons_enabled, + live_is_custom, + } + } + None => GameInfoCheck { + mode: if live_is_custom { + GameInfoMode::Custom + } else { + GameInfoMode::StockManaged + }, + live_pgi_version, + profile_pgi_version: None, + pgi_mismatch: false, + addons_enabled, + live_is_custom, + }, + } +} + +fn scan_live_addon_slots(root: &Path) -> Result, ProfileError> { + let addons = live_addons_dir(root); + if !addons.exists() { + return Ok(Vec::new()); + } + validate_dir_within(root, &addons).map_err(|err| ProfileError::Io(err.to_string()))?; + let mut items = Vec::new(); + let entries = fs::read_dir(&addons).map_err(|err| ProfileError::Io(err.to_string()))?; + for entry in entries { + let entry = entry.map_err(|err| ProfileError::Io(err.to_string()))?; + let path = entry.path(); + let meta = fs::symlink_metadata(&path).map_err(|err| ProfileError::Io(err.to_string()))?; + if metadata_is_link(&meta) || !meta.is_file() { + continue; + } + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(slot) = is_pak_slot_name(&name) { + items.push((slot, name, path)); + } + } + items.sort_by_key(|(slot, _, _)| *slot); + Ok(items) +} + +fn scan_user_cfg_files(root: &Path) -> Result, ProfileError> { + let cfg_dir = live_cfg_dir(root); + if !cfg_dir.exists() { + return Ok(Vec::new()); + } + validate_dir_within(root, &cfg_dir).map_err(|err| ProfileError::Io(err.to_string()))?; + let mut found = Vec::new(); + collect_user_cfgs_recursive(&cfg_dir, &cfg_dir, 0, &mut found)?; + found.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(found) +} + +fn collect_user_cfgs_recursive( + cfg_root: &Path, + dir: &Path, + depth: usize, + out: &mut Vec<(String, String)>, +) -> Result<(), ProfileError> { + if depth > 6 { + return Ok(()); + } + let entries = fs::read_dir(dir).map_err(|err| ProfileError::Io(err.to_string()))?; + for entry in entries { + let entry = entry.map_err(|err| ProfileError::Io(err.to_string()))?; + let path = entry.path(); + let meta = fs::symlink_metadata(&path).map_err(|err| ProfileError::Io(err.to_string()))?; + if metadata_is_link(&meta) { + continue; + } + if meta.is_dir() { + collect_user_cfgs_recursive(cfg_root, &path, depth + 1, out)?; + } else if meta.is_file() { + let rel = path + .strip_prefix(cfg_root) + .unwrap_or(&path) + .to_string_lossy() + .replace('\\', "/"); + if is_protected_deadlock_cfg_path(&rel) { + continue; + } + if let Ok(rel_norm) = normalize_deadlock_cfg_path(&rel) { + let text = read_small_text_bounded(&path, MAX_IMPORTED_CFG_BYTES) + .map_err(|err| ProfileError::Io(err.to_string()))?; + out.push((rel_norm, text)); + if out.len() >= MAX_CFG_FILES_PER_PROFILE { + break; + } + } + } + } + Ok(()) +} + +fn touch_profile_updated(data_dir: &Path, profile_id: &str) -> Result<(), ProfileError> { + let mut index = load_index(data_dir)?; + if let Some(meta) = index.profiles.iter_mut().find(|p| p.id == profile_id) { + meta.updated_at = now_millis(); + } + save_index(data_dir, &index) +} + +fn resolve_target_gameinfo_text( + data_dir: &Path, + root: &Path, + manifest: &DeadlockManifest, +) -> Result { + let live_text = read_live_gameinfo(root)?; + let enable_addons = manifest.mods.iter().any(|m| m.enabled); + match manifest.gameinfo_mode { + GameInfoMode::StockManaged => { + let _ = snapshot_stock_gameinfo(&deadlock_gameinfo_stock_dir(data_dir), &live_text)?; + let stock_dir = deadlock_gameinfo_stock_dir(data_dir); + let baseline = if let Some(pgi) = parse_pgi_version(&live_text) { + if let Some(stock) = load_stock_snapshot(&stock_dir, &pgi) { + stock + } else { + live_text + } + } else { + live_text + }; + patch_addons_search_path(&baseline, enable_addons) + } + GameInfoMode::Custom => { + let profile_text = read_profile_gameinfo(data_dir, &manifest.id)?.ok_or_else(|| { + ProfileError::Io( + "This profile's custom gameinfo.gi file is missing. Reset it to stock or recapture from live." + .into(), + ) + })?; + verify_custom_gameinfo_pgi(&live_text, &profile_text)?; + patch_addons_search_path(&profile_text, enable_addons) + } + } +} + +fn project_live_deadlock_with( + data_dir: &Path, + root: &Path, + previous_manifest: Option<&DeadlockManifest>, + target: &DeadlockManifest, + process_names: I, +) -> Result<(), ProfileError> +where + I: IntoIterator, + S: AsRef, +{ + let root = normalize_root(root)?; + refuse_if_game_running_among(GameId::Deadlock, process_names) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let enabled_mods: Vec<&DeadlockModRecord> = target.mods.iter().filter(|m| m.enabled).collect(); + if enabled_mods.len() > MAX_ADDON_SLOTS { + return Err(ProfileError::Io(format!( + "Deadlock supports at most {MAX_ADDON_SLOTS} enabled addon VPKs at once." + ))); + } + + let blobs_dir = deadlock_blobs_dir(data_dir); + let mut staged_blobs: Vec<(u8, String, PathBuf)> = Vec::with_capacity(enabled_mods.len()); + for (idx, record) in enabled_mods.iter().enumerate() { + if !is_valid_token(&record.blob_sha256) { + return Err(ProfileError::Io(format!( + "Mod {} has an invalid stored digest.", + record.name + ))); + } + let blob_path = blobs_dir.join(format!("{}.vpk", record.blob_sha256)); + validate_file_within(&blobs_dir, &blob_path) + .map_err(|err| ProfileError::Io(err.to_string()))?; + let actual_sha = + sha256_file(&blob_path).map_err(|err| ProfileError::Io(err.to_string()))?; + if actual_sha != record.blob_sha256 { + return Err(ProfileError::Io(format!( + "Stored blob for mod {} failed checksum verification.", + record.name + ))); + } + let slot = (idx + 1) as u8; + staged_blobs.push((slot, record.blob_sha256.clone(), blob_path)); + } + + // Verify custom/stock gameinfo.gi and PGIVersion BEFORE touching live files. + let target_gameinfo = resolve_target_gameinfo_text(data_dir, &root, target)?; + + // Validate & read all target user cfgs before mutating live cfg/ folder. + let prof_dir = profile_dir(data_dir, &target.id)?; + let prof_cfg_root = prof_dir.join("cfg"); + let mut target_cfgs: Vec<(String, Vec)> = Vec::with_capacity(target.cfg_files.len()); + for rel in &target.cfg_files { + let norm = normalize_deadlock_cfg_path(rel)?; + let src = prof_cfg_root.join(&norm); + validate_file_within(&prof_cfg_root, &src) + .map_err(|err| ProfileError::Io(err.to_string()))?; + let bytes = read_small_file_bounded(&src, MAX_IMPORTED_CFG_BYTES) + .map_err(|err| ProfileError::Io(err.to_string()))?; + target_cfgs.push((norm, bytes)); + } + + // Project addons/pak01_dir.vpk..pakNN_dir.vpk. + let citadel = citadel_dir_validated(&root)?; + let addons = citadel.join("addons"); + create_dir_all_within(&root, &addons).map_err(|err| ProfileError::Io(err.to_string()))?; + + let expected_slots: BTreeSet = staged_blobs + .iter() + .map(|(slot, _, _)| format_pak_slot_name(*slot)) + .collect(); + + for (slot, sha, blob_path) in staged_blobs { + let dest = addons.join(format_pak_slot_name(slot)); + let unchanged = dest.exists() + && validate_file_within(&root, &dest).is_ok() + && sha256_file(&dest).ok().as_deref() == Some(sha.as_str()); + if !unchanged { + let bytes = fs::read(&blob_path).map_err(|err| ProfileError::Io(err.to_string()))?; + write_atomic_within(&root, &dest, &bytes) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + } + + // Remove only stale pakNN_dir.vpk files beyond our enabled slots. + if let Ok(entries) = fs::read_dir(&addons) { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if is_pak_slot_name(&name).is_some() + && !expected_slots.contains(&name.to_ascii_lowercase()) + { + let _ = remove_file_force_within(&root, &entry.path()); + } + } + } + + // Write gameinfo.gi if its bytes changed. + let current_gi = read_live_gameinfo(&root)?; + if current_gi != target_gameinfo { + write_atomic_within( + &root, + &live_gameinfo_path(&root), + target_gameinfo.as_bytes(), + ) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + + // Project managed user .cfg files inside game/citadel/cfg/. + let live_cfg = citadel.join("cfg"); + create_dir_all_within(&root, &live_cfg).map_err(|err| ProfileError::Io(err.to_string()))?; + let target_cfg_set: BTreeSet = target_cfgs.iter().map(|(p, _)| p.clone()).collect(); + if let Some(prev) = previous_manifest { + for old_rel in &prev.cfg_files { + if let Ok(norm) = normalize_deadlock_cfg_path(old_rel) { + if !target_cfg_set.contains(&norm) { + let _ = remove_file_force_within(&root, &live_cfg.join(&norm)); + } + } + } + } + for (rel, bytes) in target_cfgs { + let dest = live_cfg.join(&rel); + if let Some(parent) = dest.parent() { + create_dir_all_within(&root, parent) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + write_atomic_within(&root, &dest, &bytes) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + + Ok(()) +} + +fn citadel_dir_validated(root: &Path) -> Result { + let citadel = super::citadel_dir(root); + validate_dir_within(root, &citadel).map_err(|err| ProfileError::Io(err.to_string()))?; + Ok(citadel) +} + +fn load_summary( + data_dir: &Path, + meta: &DeadlockProfileMeta, +) -> Result { + let manifest = load_manifest(data_dir, &meta.id)?; + let enabled_mod_count = manifest.mods.iter().filter(|m| m.enabled).count(); + Ok(DeadlockProfileSummary { + id: manifest.id, + name: manifest.name, + mod_count: manifest.mods.len(), + enabled_mod_count, + gameinfo_mode: manifest.gameinfo_mode, + created_at: meta.created_at, + updated_at: meta.updated_at, + }) +} + +pub fn load_deadlock_library(root: &Path) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + load_deadlock_library_in(&data_dir, root) +} + +pub fn load_deadlock_library_in( + data_dir: &Path, + root: &Path, +) -> Result { + let root = normalize_root(root)?; + ensure_store_dirs(data_dir)?; + let index = load_index(data_dir)?; + let client_version = read_deadlock_client_version(&root); + + let mut summaries = Vec::with_capacity(index.profiles.len()); + for meta in &index.profiles { + summaries.push(load_summary(data_dir, meta)?); + } + + let active_manifest = index + .active_profile_id + .as_deref() + .and_then(|id| load_manifest(data_dir, id).ok()); + let gameinfo = check_gameinfo_status(data_dir, &root, active_manifest.as_ref()); + let live_addon_count = scan_live_addon_slots(&root).map(|v| v.len()).unwrap_or(0); + + Ok(DeadlockLibrary { + deadlock_root: root.to_string_lossy().to_string(), + active_profile_id: index.active_profile_id, + profiles: summaries, + client_version, + gameinfo, + live_addon_count, + }) +} + +pub fn load_deadlock_profile_detail( + root: &Path, + profile_id: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + load_deadlock_profile_detail_in(&data_dir, root, profile_id) +} + +pub fn load_deadlock_profile_detail_in( + data_dir: &Path, + root: &Path, + profile_id: &str, +) -> Result { + let root = normalize_root(root)?; + ensure_store_dirs(data_dir)?; + let manifest = load_manifest(data_dir, profile_id)?; + let client_version = read_deadlock_client_version(&root); + let gameinfo_check = check_gameinfo_status(data_dir, &root, Some(&manifest)); + + let mut enabled_inputs: Vec<(String, String, u8, Vec)> = Vec::new(); + let mut slot_by_id: BTreeMap = BTreeMap::new(); + let mut next_slot = 1u8; + for record in &manifest.mods { + if record.enabled { + slot_by_id.insert(record.id.clone(), next_slot); + let paths = load_blob_entry_paths(data_dir, &record.blob_sha256).unwrap_or_default(); + enabled_inputs.push((record.id.clone(), record.name.clone(), next_slot, paths)); + next_slot = next_slot.saturating_add(1); + } + } + + let conflicts = compute_mod_conflicts(&enabled_inputs); + let mut conflict_counts: BTreeMap = BTreeMap::new(); + for c in &conflicts { + *conflict_counts.entry(c.winner_id.clone()).or_default() += c.shared_count; + *conflict_counts.entry(c.loser_id.clone()).or_default() += c.shared_count; + } + + let mods = manifest + .mods + .iter() + .map(|record| { + let slot = slot_by_id.get(&record.id).copied(); + let pak_name = slot.map(format_pak_slot_name); + let client_mismatch = match ( + record.built_for_client.as_deref(), + client_version.as_deref(), + ) { + (Some(built), Some(live)) => built != live, + _ => false, + }; + let conflict_count = conflict_counts.get(&record.id).copied().unwrap_or(0); + DeadlockModView { + id: record.id.clone(), + name: record.name.clone(), + author: record.author.clone(), + version: record.version.clone(), + built_for_client: record.built_for_client.clone(), + source: record.source.clone(), + enabled: record.enabled, + blob_sha256: record.blob_sha256.clone(), + bytes: record.bytes, + files_count: record.files_count, + original_name: record.original_name.clone(), + installed_at: record.installed_at, + slot, + pak_name, + client_mismatch, + conflict_count, + } + }) + .collect(); + + let cfg_files = + read_deadlock_cfg_files_in(data_dir, &root, profile_id, &discover_steam_roots())?; + + Ok(DeadlockProfileDetail { + id: manifest.id, + name: manifest.name, + gameinfo_mode: manifest.gameinfo_mode, + gameinfo_pgi: manifest.gameinfo_pgi, + gameinfo_check, + launch_options: manifest.launch_options, + mods, + conflicts, + cfg_files, + client_version, + }) +} + +pub fn capture_deadlock_profile(root: &Path, name: &str) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + capture_deadlock_profile_in(&data_dir, root, &discover_steam_roots(), name) +} + +pub fn capture_deadlock_profile_in( + data_dir: &Path, + root: &Path, + steam_roots: &[PathBuf], + name: &str, +) -> Result { + let root = normalize_root(root)?; + ensure_store_dirs(data_dir)?; + let profile_name = validate_profile_name(name)?; + + let live_gi = read_live_gameinfo(&root)?; + let _ = snapshot_stock_gameinfo(&deadlock_gameinfo_stock_dir(data_dir), &live_gi)?; + let pgi = parse_pgi_version(&live_gi); + let stock_baseline = pgi + .as_deref() + .and_then(|hash| load_stock_snapshot(&deadlock_gameinfo_stock_dir(data_dir), hash)); + let is_custom = is_custom_gameinfo_against(&live_gi, stock_baseline.as_deref()); + let gameinfo_mode = if is_custom { + GameInfoMode::Custom + } else { + GameInfoMode::StockManaged + }; + + let mods_txt_path = live_addons_dir(&root).join("mods.txt"); + let mods_txt_titles = + if mods_txt_path.exists() && validate_file_within(&root, &mods_txt_path).is_ok() { + read_small_text_bounded(&mods_txt_path, 256 * 1024) + .map(|text| parse_mods_txt_titles(&text)) + .unwrap_or_default() + } else { + BTreeMap::new() + }; + + let slots = scan_live_addon_slots(&root)?; + let installed_at = now_millis() / 1000; + let mut mods = Vec::with_capacity(slots.len()); + for (_, file_name, path) in slots { + let meta = fs::metadata(&path).map_err(|err| ProfileError::Io(err.to_string()))?; + if meta.len() > MAX_MOD_BYTES { + return Err(ProfileError::Io(format!( + "{file_name} exceeds the {} MiB mod size limit.", + MAX_MOD_BYTES / (1024 * 1024) + ))); + } + let bytes = fs::read(&path).map_err(|err| ProfileError::Io(err.to_string()))?; + let info = inspect_vpk_bytes(&bytes)?; + let sha = store_blob_and_index(data_dir, &bytes, &info.entry_paths)?; + let title = info + .title + .or_else(|| { + mods_txt_titles + .get(&file_name.to_ascii_lowercase()) + .cloned() + }) + .unwrap_or_else(|| { + file_name + .strip_suffix(".vpk") + .unwrap_or(&file_name) + .to_string() + }); + mods.push(DeadlockModRecord { + id: Uuid::new_v4().to_string(), + name: title, + author: info.author, + version: info.version, + built_for_client: info.built_for_client, + source: DeadlockModSource::External, + enabled: true, + blob_sha256: sha, + bytes: bytes.len() as u64, + files_count: info.entry_count, + original_name: file_name, + installed_at, + }); + } + + let profile_id = Uuid::new_v4().to_string(); + let prof_dir = profile_dir(data_dir, &profile_id)?; + create_dir_all_within(&deadlock_profiles_dir(data_dir), &prof_dir) + .map_err(|err| ProfileError::Io(err.to_string()))?; + + if gameinfo_mode == GameInfoMode::Custom { + write_atomic_within(&prof_dir, &prof_dir.join("gameinfo.gi"), live_gi.as_bytes()) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + + let user_cfgs = scan_user_cfg_files(&root)?; + let prof_cfg_dir = prof_dir.join("cfg"); + create_dir_all_within(&prof_dir, &prof_cfg_dir) + .map_err(|err| ProfileError::Io(err.to_string()))?; + let mut cfg_paths = Vec::with_capacity(user_cfgs.len()); + for (rel, text) in user_cfgs { + let dest = prof_cfg_dir.join(&rel); + if let Some(parent) = dest.parent() { + create_dir_all_within(&prof_cfg_dir, parent) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + write_atomic_within(&prof_cfg_dir, &dest, text.as_bytes()) + .map_err(|err| ProfileError::Io(err.to_string()))?; + cfg_paths.push(rel); + } + + let launch_options = + read_steam_launch_options_for_app_from(DEADLOCK_APP, steam_roots).unwrap_or_default(); + + let manifest = DeadlockManifest { + version: SCHEMA_VERSION, + id: profile_id.clone(), + name: profile_name.clone(), + gameinfo_mode, + gameinfo_pgi: pgi, + has_custom_gameinfo: gameinfo_mode == GameInfoMode::Custom, + launch_options, + mods, + cfg_files: cfg_paths, + }; + save_manifest(data_dir, &manifest)?; + + let mut index = load_index(data_dir)?; + index.version = SCHEMA_VERSION; + index.deadlock_root = root.to_string_lossy().to_string(); + let ts = now_millis(); + index.profiles.push(DeadlockProfileMeta { + id: profile_id.clone(), + name: profile_name, + created_at: ts, + updated_at: ts, + }); + index.active_profile_id = Some(profile_id); + save_index(data_dir, &index)?; + + load_deadlock_library_in(data_dir, &root) +} + +pub fn create_deadlock_profile( + root: &Path, + name: &str, + activate: bool, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + create_deadlock_profile_in(&data_dir, root, name, activate, live_process_names()) +} + +pub fn create_deadlock_profile_in( + data_dir: &Path, + root: &Path, + name: &str, + activate: bool, + process_names: I, +) -> Result +where + I: IntoIterator, + S: AsRef, +{ + let root = normalize_root(root)?; + ensure_store_dirs(data_dir)?; + let profile_name = validate_profile_name(name)?; + + let live_gi = read_live_gameinfo(&root)?; + let _ = snapshot_stock_gameinfo(&deadlock_gameinfo_stock_dir(data_dir), &live_gi)?; + let pgi = parse_pgi_version(&live_gi); + + let profile_id = Uuid::new_v4().to_string(); + let manifest = DeadlockManifest { + version: SCHEMA_VERSION, + id: profile_id.clone(), + name: profile_name.clone(), + gameinfo_mode: GameInfoMode::StockManaged, + gameinfo_pgi: pgi, + has_custom_gameinfo: false, + launch_options: String::new(), + mods: Vec::new(), + cfg_files: Vec::new(), + }; + save_manifest(data_dir, &manifest)?; + + let mut index = load_index(data_dir)?; + index.version = SCHEMA_VERSION; + index.deadlock_root = root.to_string_lossy().to_string(); + let ts = now_millis(); + index.profiles.push(DeadlockProfileMeta { + id: profile_id.clone(), + name: profile_name, + created_at: ts, + updated_at: ts, + }); + + if activate { + let prev = index + .active_profile_id + .as_deref() + .and_then(|id| load_manifest(data_dir, id).ok()); + project_live_deadlock_with(data_dir, &root, prev.as_ref(), &manifest, process_names)?; + index.active_profile_id = Some(profile_id); + } + save_index(data_dir, &index)?; + load_deadlock_library_in(data_dir, &root) +} + +pub fn switch_deadlock_profile( + root: &Path, + profile_id: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + switch_deadlock_profile_in(&data_dir, root, profile_id, live_process_names()) +} + +pub fn switch_deadlock_profile_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + process_names: I, +) -> Result +where + I: IntoIterator, + S: AsRef, +{ + let root = normalize_root(root)?; + ensure_store_dirs(data_dir)?; + let mut index = load_index(data_dir)?; + if !index.profiles.iter().any(|p| p.id == profile_id) { + return Err(ProfileError::Io("Deadlock profile not found.".into())); + } + let target = load_manifest(data_dir, profile_id)?; + let prev = index + .active_profile_id + .as_deref() + .filter(|id| *id != profile_id) + .and_then(|id| load_manifest(data_dir, id).ok()); + + project_live_deadlock_with(data_dir, &root, prev.as_ref(), &target, process_names)?; + + index.deadlock_root = root.to_string_lossy().to_string(); + index.active_profile_id = Some(profile_id.to_string()); + save_index(data_dir, &index)?; + load_deadlock_library_in(data_dir, &root) +} + +pub fn rename_deadlock_profile( + root: &Path, + profile_id: &str, + new_name: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + rename_deadlock_profile_in(&data_dir, root, profile_id, new_name) +} + +pub fn rename_deadlock_profile_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + new_name: &str, +) -> Result { + let root = normalize_root(root)?; + ensure_store_dirs(data_dir)?; + let trimmed = validate_profile_name(new_name)?; + let mut index = load_index(data_dir)?; + let Some(meta) = index.profiles.iter_mut().find(|p| p.id == profile_id) else { + return Err(ProfileError::Io("Deadlock profile not found.".into())); + }; + meta.name = trimmed.to_string(); + meta.updated_at = now_millis(); + + let mut manifest = load_manifest(data_dir, profile_id)?; + manifest.name = trimmed.to_string(); + save_manifest(data_dir, &manifest)?; + save_index(data_dir, &index)?; + load_deadlock_library_in(data_dir, &root) +} + +pub fn delete_deadlock_profile( + root: &Path, + profile_id: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + delete_deadlock_profile_in(&data_dir, root, profile_id) +} + +pub fn delete_deadlock_profile_in( + data_dir: &Path, + root: &Path, + profile_id: &str, +) -> Result { + let root = normalize_root(root)?; + ensure_store_dirs(data_dir)?; + let mut index = load_index(data_dir)?; + let before = index.profiles.len(); + index.profiles.retain(|p| p.id != profile_id); + if index.profiles.len() == before { + return Err(ProfileError::Io("Deadlock profile not found.".into())); + } + if index.active_profile_id.as_deref() == Some(profile_id) { + index.active_profile_id = None; + } + save_index(data_dir, &index)?; + + let dir = profile_dir(data_dir, profile_id)?; + if dir.exists() { + let _ = remove_tree_within(&deadlock_profiles_dir(data_dir), &dir); + } + prune_unused_blobs(data_dir, &index); + load_deadlock_library_in(data_dir, &root) +} + +pub fn adopt_deadlock_live_gameinfo( + root: &Path, + profile_id: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + adopt_deadlock_live_gameinfo_in(&data_dir, root, profile_id, live_process_names()) +} + +pub fn adopt_deadlock_live_gameinfo_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + process_names: I, +) -> Result +where + I: IntoIterator, + S: AsRef, +{ + let root = normalize_root(root)?; + refuse_if_game_running_among(GameId::Deadlock, process_names) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let live_gi = read_live_gameinfo(&root)?; + let pgi = parse_pgi_version(&live_gi); + let _ = snapshot_stock_gameinfo(&deadlock_gameinfo_stock_dir(data_dir), &live_gi)?; + let stock_baseline = pgi + .as_deref() + .and_then(|hash| load_stock_snapshot(&deadlock_gameinfo_stock_dir(data_dir), hash)); + let is_custom = is_custom_gameinfo_against(&live_gi, stock_baseline.as_deref()); + + let mut manifest = load_manifest(data_dir, profile_id)?; + manifest.gameinfo_pgi = pgi; + if is_custom { + manifest.gameinfo_mode = GameInfoMode::Custom; + manifest.has_custom_gameinfo = true; + let dir = profile_dir(data_dir, profile_id)?; + write_atomic_within(&dir, &dir.join("gameinfo.gi"), live_gi.as_bytes()) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } else { + manifest.gameinfo_mode = GameInfoMode::StockManaged; + manifest.has_custom_gameinfo = false; + } + save_manifest(data_dir, &manifest)?; + touch_profile_updated(data_dir, profile_id)?; + + let index = load_index(data_dir)?; + if index.active_profile_id.as_deref() == Some(profile_id) { + let patched = patch_addons_search_path(&live_gi, manifest.mods.iter().any(|m| m.enabled))?; + if patched != live_gi { + write_atomic_within(&root, &live_gameinfo_path(&root), patched.as_bytes()) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + } + + load_deadlock_profile_detail_in(data_dir, &root, profile_id) +} + +pub fn reset_deadlock_profile_gameinfo_to_stock( + root: &Path, + profile_id: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + reset_deadlock_profile_gameinfo_to_stock_in(&data_dir, root, profile_id, live_process_names()) +} + +pub fn reset_deadlock_profile_gameinfo_to_stock_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + process_names: I, +) -> Result +where + I: IntoIterator, + S: AsRef, +{ + let root = normalize_root(root)?; + refuse_if_game_running_among(GameId::Deadlock, process_names) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let live_gi = read_live_gameinfo(&root)?; + let live_pgi = parse_pgi_version(&live_gi); + let mut manifest = load_manifest(data_dir, profile_id)?; + manifest.gameinfo_mode = GameInfoMode::StockManaged; + manifest.has_custom_gameinfo = false; + manifest.gameinfo_pgi = live_pgi.clone(); + save_manifest(data_dir, &manifest)?; + let gi_copy = profile_dir(data_dir, profile_id)?.join("gameinfo.gi"); + if gi_copy.exists() { + let _ = remove_file_force_within(&deadlock_profiles_dir(data_dir), &gi_copy); + } + touch_profile_updated(data_dir, profile_id)?; + + let index = load_index(data_dir)?; + if index.active_profile_id.as_deref() == Some(profile_id) { + let enable = manifest.mods.iter().any(|m| m.enabled); + let base = live_pgi + .as_deref() + .and_then(|pgi| load_stock_snapshot(&deadlock_gameinfo_stock_dir(data_dir), pgi)) + .unwrap_or(live_gi); + let target = patch_addons_search_path(&base, enable)?; + write_atomic_within(&root, &live_gameinfo_path(&root), target.as_bytes()) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + load_deadlock_profile_detail_in(data_dir, &root, profile_id) +} + +fn is_split_vpk_chunk_name(file_name: &str) -> bool { + let lower = file_name.to_ascii_lowercase(); + let Some(stem) = lower.strip_suffix(".vpk") else { + return false; + }; + let Some((_, tail)) = stem.rsplit_once('_') else { + return false; + }; + tail.len() == 3 && tail.bytes().all(|b| b.is_ascii_digit()) +} + +fn normalize_archive_vpk_path(raw: &str) -> Option { + let normalized = raw.trim().replace('\\', "/"); + let stripped = normalized.trim_start_matches('/'); + if stripped.is_empty() + || stripped + .split('/') + .any(|seg| seg.is_empty() || seg == "." || seg == "..") + { + return None; + } + Some(stripped.to_string()) +} + +fn is_generic_pak_stem(stem: &str) -> bool { + let lower = stem.trim().to_ascii_lowercase(); + let digits = lower + .strip_prefix("pak") + .map(|rest| rest.strip_suffix("_dir").unwrap_or(rest)); + digits.is_some_and(|d| d.len() == 2 && d.bytes().all(|b| b.is_ascii_digit())) +} + +fn strip_vpk_suffix(name: &str) -> &str { + if name.len() >= 4 && name[name.len() - 4..].eq_ignore_ascii_case(".vpk") { + &name[..name.len() - 4] + } else { + name + } +} + +fn strip_mod_extension(file_name: &str) -> &str { + let leaf = Path::new(file_name) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(file_name) + .trim(); + for ext in [".vpk", ".zip", ".7z", ".rar"] { + if leaf.len() > ext.len() && leaf[leaf.len() - ext.len()..].eq_ignore_ascii_case(ext) { + return &leaf[..leaf.len() - ext.len()]; + } + } + leaf +} + +fn clean_variant_label(variant_label: Option<&str>, listing_name: Option<&str>) -> Option { + let raw = variant_label?; + let first_line = raw.lines().map(str::trim).find(|line| !line.is_empty())?; + let truncated: String = first_line.chars().take(60).collect(); + let label = truncated.trim().to_string(); + if label.is_empty() { + return None; + } + if listing_name.is_some_and(|listing| listing.trim().eq_ignore_ascii_case(&label)) { + return None; + } + Some(label) +} + +fn derive_entry_hint(archive_path: &str) -> Option { + let segments: Vec<&str> = archive_path.split('/').filter(|s| !s.is_empty()).collect(); + let leaf = segments.last().copied().unwrap_or(archive_path); + let stem = strip_vpk_suffix(leaf).trim(); + if !stem.is_empty() && !is_generic_pak_stem(stem) { + return Some(stem.to_string()); + } + for &dir in segments[..segments.len().saturating_sub(1)].iter().rev() { + let trimmed = dir.trim(); + let lower = trimmed.to_ascii_lowercase(); + if !trimmed.is_empty() && !matches!(lower.as_str(), "addons" | "citadel" | "game") { + return Some(trimmed.to_string()); + } + } + None +} + +pub fn derive_deadlock_mod_title( + info_title: Option<&str>, + archive_path: &str, + archive_file_name: &str, + listing_name: Option<&str>, + variant_label: Option<&str>, + total_vpks: usize, +) -> String { + if let Some(title) = info_title.map(str::trim).filter(|t| !t.is_empty()) { + if !is_generic_pak_stem(strip_vpk_suffix(title)) { + return title.to_string(); + } + } + + let entry_hint = derive_entry_hint(archive_path); + let clean_listing = listing_name.map(str::trim).filter(|s| !s.is_empty()); + let clean_variant = clean_variant_label(variant_label, clean_listing); + + if let Some(listing) = clean_listing { + return match (clean_variant, entry_hint) { + (Some(variant), Some(hint)) + if total_vpks > 1 + && !variant + .to_ascii_lowercase() + .contains(&hint.to_ascii_lowercase()) => + { + format!("{listing} — {variant} ({hint})") + } + (Some(variant), _) => format!("{listing} — {variant}"), + (None, Some(hint)) + if !listing + .to_ascii_lowercase() + .contains(&hint.to_ascii_lowercase()) => + { + format!("{listing} — {hint}") + } + (None, _) => listing.to_string(), + }; + } + + let archive_stem = strip_mod_extension(archive_file_name).trim(); + let is_bare_vpk = archive_file_name + .trim() + .to_ascii_lowercase() + .ends_with(".vpk"); + if is_bare_vpk { + if let Some(hint) = entry_hint { + return hint; + } + } + match ( + !archive_stem.is_empty() && !is_generic_pak_stem(archive_stem), + entry_hint, + ) { + (true, Some(hint)) if total_vpks > 1 || !archive_stem.eq_ignore_ascii_case(&hint) => { + format!("{archive_stem} — {hint}") + } + (true, _) => archive_stem.to_string(), + (false, Some(hint)) => hint, + (false, None) => { + let leaf = Path::new(archive_path) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("mod.vpk"); + strip_vpk_suffix(leaf).to_string() + } + } +} + +fn extract_vpks_from_payload( + file_name: &str, + bytes: &[u8], +) -> Result)>, ProfileError> { + if bytes.len() as u64 > MAX_MOD_BYTES { + return Err(ProfileError::Io(format!( + "{file_name} is larger than {} MiB.", + MAX_MOD_BYTES / (1024 * 1024) + ))); + } + if bytes.starts_with(&VPK_MAGIC) { + let leaf = Path::new(file_name) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("mod.vpk") + .to_string(); + return Ok(vec![(leaf, bytes.to_vec())]); + } + + let limits = ArchiveLimits::new(20_000, MAX_MOD_BYTES, 2 * MAX_MOD_BYTES); + let members = extract_archive(bytes, limits)?; + let mut vpks = Vec::new(); + for (rel, body) in members { + let lower = rel.to_ascii_lowercase(); + if lower.ends_with(".vpk") && !is_split_vpk_chunk_name(&rel) { + let norm = normalize_archive_vpk_path(&rel).ok_or_else(|| { + ProfileError::Io("Archive contains an invalid .vpk member path.".into()) + })?; + vpks.push((norm, body)); + } + } + if vpks.is_empty() { + return Err(ProfileError::Io( + "No .vpk mod files were found inside that archive.".into(), + )); + } + vpks.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(vpks) +} + +pub fn inspect_deadlock_mod_payload( + file_name: &str, + bytes: &[u8], + listing_name: Option<&str>, + variant_label: Option<&str>, +) -> Result, ProfileError> { + let vpks = extract_vpks_from_payload(file_name, bytes)?; + let total_vpks = vpks.len(); + let mut staged = Vec::with_capacity(total_vpks); + for (archive_path, vpk_bytes) in vpks { + let info = inspect_vpk_bytes(&vpk_bytes)?; + let title = derive_deadlock_mod_title( + info.title.as_deref(), + &archive_path, + file_name, + listing_name, + variant_label, + total_vpks, + ); + staged.push(DeadlockStagedVpk { + entry: DeadlockArchiveVpkEntry { + archive_path, + title, + bytes: vpk_bytes.len() as u64, + files_count: info.entry_count, + built_for_client: info.built_for_client.clone(), + }, + vpk_bytes, + info, + }); + } + Ok(staged) +} + +pub fn install_deadlock_staged_vpks( + root: &Path, + profile_id: &str, + staged: &[DeadlockStagedVpk], + selected_paths: &[String], + source: DeadlockModSource, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + install_deadlock_staged_vpks_in( + &data_dir, + root, + profile_id, + staged, + selected_paths, + source, + live_process_names(), + ) +} + +pub fn install_deadlock_staged_vpks_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + staged: &[DeadlockStagedVpk], + selected_paths: &[String], + source: DeadlockModSource, + process_names: I, +) -> Result +where + I: IntoIterator + Clone, + S: AsRef, +{ + let root = normalize_root(root)?; + ensure_store_dirs(data_dir)?; + refuse_if_game_running_among(GameId::Deadlock, process_names.clone()) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + if selected_paths.is_empty() { + return Err(ProfileError::Io( + "Select at least one .vpk to install.".into(), + )); + } + let chosen: BTreeSet<&str> = selected_paths.iter().map(String::as_str).collect(); + for path in &chosen { + if !staged.iter().any(|s| s.entry.archive_path == *path) { + return Err(ProfileError::Io(format!( + "Selected .vpk is not in the staged archive: {path}" + ))); + } + } + let selected: Vec<&DeadlockStagedVpk> = staged + .iter() + .filter(|s| chosen.contains(s.entry.archive_path.as_str())) + .collect(); + + let mut manifest = load_manifest(data_dir, profile_id)?; + let current_enabled = manifest.mods.iter().filter(|m| m.enabled).count(); + if current_enabled + selected.len() > MAX_ADDON_SLOTS { + return Err(ProfileError::Io(format!( + "Installing {} mod(s) would exceed Deadlock's {MAX_ADDON_SLOTS}-addon limit.", + selected.len() + ))); + } + + let installed_at = now_millis() / 1000; + for item in selected { + let sha = store_blob_and_index(data_dir, &item.vpk_bytes, &item.info.entry_paths)?; + let (author, version) = match &source { + DeadlockModSource::GameBanana { + author: gb_author, + version: gb_ver, + .. + } => ( + item.info.author.clone().or_else(|| gb_author.clone()), + item.info.version.clone().or_else(|| gb_ver.clone()), + ), + _ => (item.info.author.clone(), item.info.version.clone()), + }; + let original_name = Path::new(&item.entry.archive_path) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("mod.vpk") + .to_string(); + manifest.mods.push(DeadlockModRecord { + id: Uuid::new_v4().to_string(), + name: item.entry.title.clone(), + author, + version, + built_for_client: item.info.built_for_client.clone(), + source: source.clone(), + enabled: true, + blob_sha256: sha, + bytes: item.entry.bytes, + files_count: item.entry.files_count, + original_name, + installed_at, + }); + } + + save_manifest(data_dir, &manifest)?; + touch_profile_updated(data_dir, profile_id)?; + + let index = load_index(data_dir)?; + if index.active_profile_id.as_deref() == Some(profile_id) { + project_live_deadlock_with(data_dir, &root, Some(&manifest), &manifest, process_names)?; + } + + load_deadlock_profile_detail_in(data_dir, &root, profile_id) +} + +pub fn install_deadlock_mod_bytes( + root: &Path, + profile_id: &str, + file_name: &str, + bytes: &[u8], + source: DeadlockModSource, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + install_deadlock_mod_bytes_in( + &data_dir, + root, + profile_id, + file_name, + bytes, + source, + live_process_names(), + ) +} + +pub fn install_deadlock_mod_bytes_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + file_name: &str, + bytes: &[u8], + source: DeadlockModSource, + process_names: I, +) -> Result +where + I: IntoIterator + Clone, + S: AsRef, +{ + let staged = inspect_deadlock_mod_payload(file_name, bytes, None, None)?; + let all_paths: Vec = staged + .iter() + .map(|item| item.entry.archive_path.clone()) + .collect(); + install_deadlock_staged_vpks_in( + data_dir, + root, + profile_id, + &staged, + &all_paths, + source, + process_names, + ) +} + +pub fn set_deadlock_mod_enabled( + root: &Path, + profile_id: &str, + mod_id: &str, + enabled: bool, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + set_deadlock_mod_enabled_in( + &data_dir, + root, + profile_id, + mod_id, + enabled, + live_process_names(), + ) +} + +pub fn set_deadlock_mod_enabled_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + mod_id: &str, + enabled: bool, + process_names: I, +) -> Result +where + I: IntoIterator + Clone, + S: AsRef, +{ + let root = normalize_root(root)?; + refuse_if_game_running_among(GameId::Deadlock, process_names.clone()) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let mut manifest = load_manifest(data_dir, profile_id)?; + let target_exists = manifest.mods.iter().any(|m| m.id == mod_id); + if !target_exists { + return Err(ProfileError::Io("Deadlock mod not found.".into())); + } + if enabled { + let already = manifest + .mods + .iter() + .filter(|m| m.enabled && m.id != mod_id) + .count(); + if already + 1 > MAX_ADDON_SLOTS { + return Err(ProfileError::Io(format!( + "Deadlock supports at most {MAX_ADDON_SLOTS} enabled addons." + ))); + } + } + for m in &mut manifest.mods { + if m.id == mod_id { + m.enabled = enabled; + } + } + save_manifest(data_dir, &manifest)?; + touch_profile_updated(data_dir, profile_id)?; + + let index = load_index(data_dir)?; + if index.active_profile_id.as_deref() == Some(profile_id) { + project_live_deadlock_with(data_dir, &root, Some(&manifest), &manifest, process_names)?; + } + + load_deadlock_profile_detail_in(data_dir, &root, profile_id) +} + +pub fn reorder_deadlock_mods( + root: &Path, + profile_id: &str, + ordered_ids: &[String], +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + reorder_deadlock_mods_in( + &data_dir, + root, + profile_id, + ordered_ids, + live_process_names(), + ) +} + +pub fn reorder_deadlock_mods_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + ordered_ids: &[String], + process_names: I, +) -> Result +where + I: IntoIterator + Clone, + S: AsRef, +{ + let root = normalize_root(root)?; + refuse_if_game_running_among(GameId::Deadlock, process_names.clone()) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let mut manifest = load_manifest(data_dir, profile_id)?; + let current_set: BTreeSet<&str> = manifest.mods.iter().map(|m| m.id.as_str()).collect(); + let given_set: BTreeSet<&str> = ordered_ids.iter().map(String::as_str).collect(); + if ordered_ids.len() != manifest.mods.len() || current_set != given_set { + return Err(ProfileError::Io( + "Reorder list must contain every mod in the profile exactly once.".into(), + )); + } + + let mut by_id: BTreeMap = + manifest.mods.drain(..).map(|m| (m.id.clone(), m)).collect(); + for id in ordered_ids { + if let Some(m) = by_id.remove(id) { + manifest.mods.push(m); + } + } + save_manifest(data_dir, &manifest)?; + touch_profile_updated(data_dir, profile_id)?; + + let index = load_index(data_dir)?; + if index.active_profile_id.as_deref() == Some(profile_id) { + project_live_deadlock_with(data_dir, &root, Some(&manifest), &manifest, process_names)?; + } + + load_deadlock_profile_detail_in(data_dir, &root, profile_id) +} + +pub fn remove_deadlock_mod( + root: &Path, + profile_id: &str, + mod_id: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + remove_deadlock_mod_in(&data_dir, root, profile_id, mod_id, live_process_names()) +} + +pub fn remove_deadlock_mod_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + mod_id: &str, + process_names: I, +) -> Result +where + I: IntoIterator + Clone, + S: AsRef, +{ + let root = normalize_root(root)?; + refuse_if_game_running_among(GameId::Deadlock, process_names.clone()) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let mut manifest = load_manifest(data_dir, profile_id)?; + let before = manifest.mods.len(); + manifest.mods.retain(|m| m.id != mod_id); + if manifest.mods.len() == before { + return Err(ProfileError::Io("Deadlock mod not found.".into())); + } + save_manifest(data_dir, &manifest)?; + touch_profile_updated(data_dir, profile_id)?; + + let index = load_index(data_dir)?; + if index.active_profile_id.as_deref() == Some(profile_id) { + project_live_deadlock_with(data_dir, &root, Some(&manifest), &manifest, process_names)?; + } + prune_unused_blobs(data_dir, &index); + + load_deadlock_profile_detail_in(data_dir, &root, profile_id) +} + +fn read_regular_text_within(base: &Path, path: &Path) -> Option { + let meta = fs::symlink_metadata(path).ok()?; + if metadata_is_link(&meta) || !meta.is_file() { + return None; + } + validate_file_within(base, path).ok()?; + read_small_text_bounded(path, MAX_IMPORTED_CFG_BYTES).ok() +} + +fn read_live_readonly_deadlock_cfgs(root: &Path, steam_roots: &[PathBuf]) -> Vec { + let mut files = Vec::new(); + let live_cfg = live_cfg_dir(root); + let steam_cfg_dir = pick_steam_account_for_app_from(steam_roots, DEADLOCK_APP).map(|account| { + let dir = account + .steam_root + .join("userdata") + .join(&account.account_id) + .join(DEADLOCK_APP) + .join("local") + .join("cfg"); + (account.steam_root, dir) + }); + + for &name in LIVE_DEADLOCK_SETTINGS_FILES { + let steam_text = steam_cfg_dir + .as_ref() + .and_then(|(steam_root, dir)| read_regular_text_within(steam_root, &dir.join(name))); + let text = steam_text.or_else(|| read_regular_text_within(root, &live_cfg.join(name))); + if let Some(text) = text { + files.push(DeadlockCfgFile { + path: name.to_string(), + text, + read_only: true, + }); + } + } + + if live_cfg.is_dir() && validate_dir_within(root, &live_cfg).is_ok() { + if let Ok(entries) = fs::read_dir(&live_cfg) { + let mut valve_cfgs: Vec<(String, PathBuf)> = Vec::new(); + for entry in entries.flatten() { + let path = entry.path(); + let Ok(meta) = fs::symlink_metadata(&path) else { + continue; + }; + if metadata_is_link(&meta) || !meta.is_file() { + continue; + } + let name = entry.file_name().to_string_lossy().to_string(); + let lower = name.to_ascii_lowercase(); + if lower.starts_with("citadel_") && lower.ends_with(".cfg") { + valve_cfgs.push((name, path)); + } + } + valve_cfgs.sort_by(|a, b| a.0.cmp(&b.0)); + for (name, path) in valve_cfgs.into_iter().take(MAX_READONLY_GAME_CFGS) { + if let Some(text) = read_regular_text_within(root, &path) { + files.push(DeadlockCfgFile { + path: name, + text, + read_only: true, + }); + } + } + } + } + + files +} + +pub fn read_deadlock_cfg_files( + root: &Path, + profile_id: &str, +) -> Result, ProfileError> { + let data_dir = try_default_deadlock_data_dir()?; + read_deadlock_cfg_files_in(&data_dir, root, profile_id, &discover_steam_roots()) +} + +pub fn read_deadlock_cfg_files_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + steam_roots: &[PathBuf], +) -> Result, ProfileError> { + let root = normalize_root(root)?; + let manifest = load_manifest(data_dir, profile_id)?; + let prof_dir = profile_dir(data_dir, profile_id)?; + let cfg_root = prof_dir.join("cfg"); + let mut files = Vec::with_capacity(manifest.cfg_files.len()); + for rel in &manifest.cfg_files { + let norm = normalize_deadlock_cfg_path(rel)?; + let path = cfg_root.join(&norm); + if path.exists() { + validate_file_within(&cfg_root, &path) + .map_err(|err| ProfileError::Io(err.to_string()))?; + let text = read_small_text_bounded(&path, MAX_IMPORTED_CFG_BYTES) + .map_err(|err| ProfileError::Io(err.to_string()))?; + files.push(DeadlockCfgFile { + path: norm, + text, + read_only: false, + }); + } + } + files.sort_by(|a, b| a.path.cmp(&b.path)); + files.extend(read_live_readonly_deadlock_cfgs(&root, steam_roots)); + Ok(files) +} + +pub fn save_deadlock_cfg_file( + root: &Path, + profile_id: &str, + rel_path: &str, + text: &str, +) -> Result, ProfileError> { + let data_dir = try_default_deadlock_data_dir()?; + save_deadlock_cfg_file_in( + &data_dir, + root, + profile_id, + rel_path, + text, + live_process_names(), + ) +} + +pub fn save_deadlock_cfg_file_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + rel_path: &str, + text: &str, + process_names: I, +) -> Result, ProfileError> +where + I: IntoIterator, + S: AsRef, +{ + let root = normalize_root(root)?; + refuse_if_game_running_among(GameId::Deadlock, process_names) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let norm = normalize_deadlock_cfg_path(rel_path)?; + if text.len() > MAX_IMPORTED_CFG_BYTES { + return Err(ProfileError::Io("Cfg file exceeds maximum size.".into())); + } + + let mut manifest = load_manifest(data_dir, profile_id)?; + if !manifest.cfg_files.contains(&norm) && manifest.cfg_files.len() >= MAX_CFG_FILES_PER_PROFILE + { + return Err(ProfileError::Io(format!( + "A Deadlock profile supports up to {MAX_CFG_FILES_PER_PROFILE} user .cfg files." + ))); + } + + let prof_dir = profile_dir(data_dir, profile_id)?; + let cfg_root = prof_dir.join("cfg"); + create_dir_all_within(&prof_dir, &cfg_root).map_err(|err| ProfileError::Io(err.to_string()))?; + let lib_dest = cfg_root.join(&norm); + if let Some(parent) = lib_dest.parent() { + create_dir_all_within(&cfg_root, parent) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + write_atomic_within(&cfg_root, &lib_dest, text.as_bytes()) + .map_err(|err| ProfileError::Io(err.to_string()))?; + + if !manifest.cfg_files.contains(&norm) { + manifest.cfg_files.push(norm.clone()); + manifest.cfg_files.sort(); + save_manifest(data_dir, &manifest)?; + } + touch_profile_updated(data_dir, profile_id)?; + + let index = load_index(data_dir)?; + if index.active_profile_id.as_deref() == Some(profile_id) { + let live_cfg = citadel_dir_validated(&root)?.join("cfg"); + create_dir_all_within(&root, &live_cfg).map_err(|err| ProfileError::Io(err.to_string()))?; + let live_dest = live_cfg.join(&norm); + if let Some(parent) = live_dest.parent() { + create_dir_all_within(&root, parent) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + write_atomic_within(&root, &live_dest, text.as_bytes()) + .map_err(|err| ProfileError::Io(err.to_string()))?; + } + + read_deadlock_cfg_files_in(data_dir, &root, profile_id, &discover_steam_roots()) +} + +pub fn delete_deadlock_cfg_file( + root: &Path, + profile_id: &str, + rel_path: &str, +) -> Result, ProfileError> { + let data_dir = try_default_deadlock_data_dir()?; + delete_deadlock_cfg_file_in(&data_dir, root, profile_id, rel_path, live_process_names()) +} + +pub fn delete_deadlock_cfg_file_in( + data_dir: &Path, + root: &Path, + profile_id: &str, + rel_path: &str, + process_names: I, +) -> Result, ProfileError> +where + I: IntoIterator, + S: AsRef, +{ + let root = normalize_root(root)?; + refuse_if_game_running_among(GameId::Deadlock, process_names) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let norm = normalize_deadlock_cfg_path(rel_path)?; + let mut manifest = load_manifest(data_dir, profile_id)?; + let before = manifest.cfg_files.len(); + manifest.cfg_files.retain(|p| p != &norm); + if manifest.cfg_files.len() == before { + return Err(ProfileError::Io("Cfg file not found in profile.".into())); + } + save_manifest(data_dir, &manifest)?; + touch_profile_updated(data_dir, profile_id)?; + + let cfg_root = profile_dir(data_dir, profile_id)?.join("cfg"); + let lib_file = cfg_root.join(&norm); + if lib_file.exists() { + let _ = remove_file_force_within(&cfg_root, &lib_file); + } + + let index = load_index(data_dir)?; + if index.active_profile_id.as_deref() == Some(profile_id) { + let live_file = live_cfg_dir(&root).join(&norm); + if live_file.exists() { + let _ = remove_file_force_within(&root, &live_file); + } + } + + read_deadlock_cfg_files_in(data_dir, &root, profile_id, &discover_steam_roots()) +} + +pub fn deadlock_launch_sync_status( + profile_id: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + deadlock_launch_sync_status_in( + &data_dir, + profile_id, + &discover_steam_roots(), + live_process_names(), + ) +} + +pub fn deadlock_launch_sync_status_in( + data_dir: &Path, + profile_id: &str, + steam_roots: &[PathBuf], + process_names: I, +) -> Result +where + I: IntoIterator, + S: AsRef, +{ + let manifest = load_manifest(data_dir, profile_id)?; + let steam_options = read_steam_launch_options_for_app_from(DEADLOCK_APP, steam_roots); + let in_sync = steam_options + .as_deref() + .is_some_and(|steam| steam == manifest.launch_options); + Ok(DeadlockLaunchSyncStatus { + profile_options: manifest.launch_options, + steam_options, + in_sync, + steam_running: steam_running_among(process_names), + }) +} + +pub fn set_deadlock_launch_options( + profile_id: &str, + options: &str, + write_steam: bool, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + set_deadlock_launch_options_in( + &data_dir, + profile_id, + options, + write_steam, + &discover_steam_roots(), + live_process_names(), + ) +} + +pub fn set_deadlock_launch_options_in( + data_dir: &Path, + profile_id: &str, + options: &str, + write_steam: bool, + steam_roots: &[PathBuf], + process_names: I, +) -> Result +where + I: IntoIterator + Clone, + S: AsRef, +{ + refuse_if_game_running_among(GameId::Deadlock, process_names.clone()) + .map_err(|err| ProfileError::Io(err.message().to_string()))?; + + let sanitized = sanitize_deadlock_launch_options(options); + let mut manifest = load_manifest(data_dir, profile_id)?; + manifest.launch_options = sanitized.clone(); + save_manifest(data_dir, &manifest)?; + touch_profile_updated(data_dir, profile_id)?; + + let steam_write = if write_steam { + match write_steam_launch_options_for_app_from( + DEADLOCK_APP, + steam_roots, + &sanitized, + process_names, + ) { + Ok(res) => res.reason, + Err(_) => LaunchWriteReason::WriteFailed, + } + } else { + LaunchWriteReason::NotRequested + }; + + Ok(DeadlockSetLaunchResult { + launch_options: sanitized, + steam_write, + }) +} + +pub fn adopt_deadlock_steam_launch_options( + profile_id: &str, +) -> Result { + let data_dir = try_default_deadlock_data_dir()?; + adopt_deadlock_steam_launch_options_in(&data_dir, profile_id, &discover_steam_roots()) +} + +pub fn adopt_deadlock_steam_launch_options_in( + data_dir: &Path, + profile_id: &str, + steam_roots: &[PathBuf], +) -> Result { + let steam_options = + read_steam_launch_options_for_app_from(DEADLOCK_APP, steam_roots).unwrap_or_default(); + let mut manifest = load_manifest(data_dir, profile_id)?; + manifest.launch_options = steam_options.clone(); + save_manifest(data_dir, &manifest)?; + touch_profile_updated(data_dir, profile_id)?; + Ok(DeadlockSetLaunchResult { + launch_options: steam_options, + steam_write: LaunchWriteReason::Written, + }) +} + +pub fn is_pgi_mismatch_error(err: &ProfileError) -> bool { + matches!(err, ProfileError::Io(msg) if msg.starts_with(PGI_MISMATCH_PREFIX)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::vpk::write_vpk_v2; + use std::io::Write; + use zip::write::SimpleFileOptions; + + fn setup_deadlock_fixture(dir: &Path, pgi: &str, complock: bool) -> PathBuf { + let root = dir.join("Deadlock"); + let citadel = root.join("game/citadel"); + fs::create_dir_all(citadel.join("addons")).unwrap(); + fs::create_dir_all(citadel.join("cfg")).unwrap(); + fs::write( + citadel.join("steam.inf"), + "appID=1422450\nProductName=citadel\nClientVersion=6895\n", + ) + .unwrap(); + let banner = if complock { + "// deadlockconfig.com - by jcStani\n" + } else { + "" + }; + let gi = format!( + "{banner}\"GameInfo\"\n{{\n\tgame\t\"citadel\"\n\tPGIVersion \"{pgi}\"\n\tFileSystem\n\t{{\n\t\tSearchPaths\n\t\t{{\n\t\t\tGame\t\t\t\tcitadel\n\t\t\tGame\t\t\t\tcore\n\t\t}}\n\t}}\n}}\n" + ); + fs::write(citadel.join("gameinfo.gi"), gi).unwrap(); + fs::write(citadel.join("cfg/citadel_server.cfg"), "// shipped valve\n").unwrap(); + root + } + + fn make_vpk(title: &str, asset_path: &str, asset_body: &[u8], client: &str) -> Vec { + let mut files = BTreeMap::new(); + files.insert( + "modinfo.json".into(), + format!(r#"{{"title":"{title}","author":"Tester","version":"1.0"}}"#).into_bytes(), + ); + files.insert( + "addoninfo.txt".into(), + format!("\"AddonInfo\"\n{{\n\tbuiltforclient \"{client}\"\n}}\n").into_bytes(), + ); + files.insert(asset_path.into(), asset_body.to_vec()); + write_vpk_v2(&files) + } + + #[test] + fn captures_switches_and_projects_addons_gameinfo_and_user_cfgs() { + let dir = crate::test_temp_dir(); + let data_dir = dir.join("data"); + let root = setup_deadlock_fixture(&dir, "PGI_A", true); + + let vpk1 = make_vpk("HUD++", "panorama/styles/top.vcss_c", b"v1", "6895"); + let vpk2 = make_vpk("Old Hud", "panorama/styles/top.vcss_c", b"v2", "6800"); + fs::write(root.join("game/citadel/addons/pak01_dir.vpk"), &vpk1).unwrap(); + fs::write(root.join("game/citadel/addons/pak02_dir.vpk"), &vpk2).unwrap(); + fs::write(root.join("game/citadel/addons/mods.txt"), "note").unwrap(); + fs::write(root.join("game/citadel/cfg/autoexec.cfg"), "fps_max 240\n").unwrap(); + + let lib = capture_deadlock_profile_in(&data_dir, &root, &[], "CompLock").unwrap(); + assert_eq!(lib.profiles.len(), 1); + let complock_id = lib.active_profile_id.clone().unwrap(); + assert_eq!(lib.gameinfo.mode, GameInfoMode::Custom); + + let detail = load_deadlock_profile_detail_in(&data_dir, &root, &complock_id).unwrap(); + assert_eq!(detail.mods.len(), 2); + assert_eq!(detail.mods[0].slot, Some(1)); + assert!(!detail.mods[0].client_mismatch); + assert!(detail.mods[1].client_mismatch); + assert_eq!(detail.conflicts.len(), 1); + assert_eq!(detail.conflicts[0].winner_name, "HUD++"); + assert_eq!(detail.cfg_files.len(), 2); + assert_eq!(detail.cfg_files[0].path, "autoexec.cfg"); + assert!(!detail.cfg_files[0].read_only); + assert_eq!(detail.cfg_files[1].path, "citadel_server.cfg"); + assert!(detail.cfg_files[1].read_only); + + // Create and activate a clean Vanilla profile. + let lib2 = + create_deadlock_profile_in(&data_dir, &root, "Vanilla", true, Vec::::new()) + .unwrap(); + assert_eq!(lib2.profiles.len(), 2); + assert!(!root.join("game/citadel/addons/pak01_dir.vpk").exists()); + assert!(!root.join("game/citadel/addons/pak02_dir.vpk").exists()); + assert!(root.join("game/citadel/addons/mods.txt").exists()); + assert!(!root.join("game/citadel/cfg/autoexec.cfg").exists()); + assert!(root.join("game/citadel/cfg/citadel_server.cfg").exists()); + + // Switch back to CompLock -> mods and autoexec return. + switch_deadlock_profile_in(&data_dir, &root, &complock_id, Vec::::new()).unwrap(); + assert!(root.join("game/citadel/addons/pak01_dir.vpk").is_file()); + assert!(root.join("game/citadel/addons/pak02_dir.vpk").is_file()); + assert!(root.join("game/citadel/cfg/autoexec.cfg").is_file()); + + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn refuses_writes_while_deadlock_is_running_and_handles_pgi_mismatch() { + let dir = crate::test_temp_dir(); + let data_dir = dir.join("data"); + let root = setup_deadlock_fixture(&dir, "PGI_1", true); + let lib = capture_deadlock_profile_in(&data_dir, &root, &[], "Custom").unwrap(); + let custom_id = lib.active_profile_id.unwrap(); + create_deadlock_profile_in(&data_dir, &root, "Stock", true, Vec::::new()).unwrap(); + + // While deadlock.exe runs, switch/install/cfg save refuse. + assert!( + switch_deadlock_profile_in(&data_dir, &root, &custom_id, ["deadlock.exe"]).is_err() + ); + + // Simulate Deadlock patch bumping PGIVersion in live gameinfo.gi. + let new_live = + "\"GameInfo\"\n{\n\tgame\t\"citadel\"\n\tPGIVersion \"PGI_2\"\n\tFileSystem\n\t{\n\t\tSearchPaths\n\t\t{\n\t\t\tGame\t\t\t\tcitadel\n\t\t\tGame\t\t\t\tcore\n\t\t}\n\t}}\n"; + fs::write(root.join("game/citadel/gameinfo.gi"), new_live).unwrap(); + + let err = switch_deadlock_profile_in(&data_dir, &root, &custom_id, Vec::::new()) + .unwrap_err(); + assert!(is_pgi_mismatch_error(&err)); + + // Reset custom profile to stock allows switching safely. + reset_deadlock_profile_gameinfo_to_stock_in( + &data_dir, + &root, + &custom_id, + Vec::::new(), + ) + .unwrap(); + switch_deadlock_profile_in(&data_dir, &root, &custom_id, Vec::::new()).unwrap(); + + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn installs_from_zip_reorders_slots_and_protects_valve_cfgs() { + let dir = crate::test_temp_dir(); + let data_dir = dir.join("data"); + let root = setup_deadlock_fixture(&dir, "PGI_1", false); + let lib = create_deadlock_profile_in(&data_dir, &root, "Main", true, Vec::::new()) + .unwrap(); + let id = lib.active_profile_id.unwrap(); + + let vpk_a = make_vpk("Mod A", "models/hero.vmdl_c", b"A", "6895"); + let vpk_b = make_vpk("Mod B", "models/hero.vmdl_c", b"B", "6895"); + + let mut zip_buf = std::io::Cursor::new(Vec::new()); + { + let mut zw = zip::ZipWriter::new(&mut zip_buf); + zw.start_file("nested/mod_a.vpk", SimpleFileOptions::default()) + .unwrap(); + zw.write_all(&vpk_a).unwrap(); + zw.start_file("nested/mod_b.vpk", SimpleFileOptions::default()) + .unwrap(); + zw.write_all(&vpk_b).unwrap(); + zw.finish().unwrap(); + } + + let detail = install_deadlock_mod_bytes_in( + &data_dir, + &root, + &id, + "bundle.zip", + zip_buf.get_ref(), + DeadlockModSource::Local { + file_name: "bundle.zip".into(), + }, + Vec::::new(), + ) + .unwrap(); + assert_eq!(detail.mods.len(), 2); + assert_eq!(detail.mods[0].slot, Some(1)); + assert_eq!(detail.conflicts[0].winner_id, detail.mods[0].id); + + // Reorder Mod B before Mod A -> Mod B becomes pak01 and conflict winner. + let reordered = reorder_deadlock_mods_in( + &data_dir, + &root, + &id, + &[detail.mods[1].id.clone(), detail.mods[0].id.clone()], + Vec::::new(), + ) + .unwrap(); + assert_eq!(reordered.conflicts[0].winner_id, detail.mods[1].id); + assert_eq!( + fs::read(root.join("game/citadel/addons/pak01_dir.vpk")).unwrap(), + vpk_b + ); + + // User cfg writes work, Valve citadel_*.cfg writes are refused. + assert!(save_deadlock_cfg_file_in( + &data_dir, + &root, + &id, + "citadel_server.cfg", + "sv_cheats 1", + Vec::::new() + ) + .is_err()); + let cfgs = save_deadlock_cfg_file_in( + &data_dir, + &root, + &id, + "autoexec.cfg", + "fps_max 300\n", + Vec::::new(), + ) + .unwrap(); + assert_eq!(cfgs.len(), 2); + assert_eq!(cfgs[0].path, "autoexec.cfg"); + assert!(!cfgs[0].read_only); + assert_eq!(cfgs[1].path, "citadel_server.cfg"); + assert!(cfgs[1].read_only); + assert_eq!( + fs::read_to_string(root.join("game/citadel/cfg/autoexec.cfg")).unwrap(), + "fps_max 300\n" + ); + + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn reads_steam_userdata_settings_with_game_fallback_and_ignores_symlinks() { + let dir = crate::test_temp_dir(); + let data_dir = dir.join("data"); + let root = setup_deadlock_fixture(&dir, "PGI_1", false); + let steam_root = dir.join("Steam"); + let userdata_cfg = steam_root.join("userdata/12345/1422450/local/cfg"); + fs::create_dir_all(steam_root.join("userdata/12345/config")).unwrap(); + fs::create_dir_all(&userdata_cfg).unwrap(); + fs::write( + steam_root.join("userdata/12345/config/localconfig.vdf"), + "\"UserLocalConfigStore\" { \"Software\" { \"Valve\" { \"Steam\" { \"apps\" { \"1422450\" {} } } } } }\n", + ) + .unwrap(); + + fs::write( + root.join("game/citadel/cfg/user_convars_0_slot0.vcfg"), + "older-game-copy\n", + ) + .unwrap(); + fs::write( + userdata_cfg.join("user_convars_0_slot0.vcfg"), + "newer-cloud-copy\n", + ) + .unwrap(); + fs::write(root.join("game/citadel/cfg/video.txt"), "game-video\n").unwrap(); + + let outside = dir.join("secret.cfg"); + fs::write(&outside, "secret").unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&outside, root.join("game/citadel/cfg/citadel_symlink.cfg")) + .unwrap(); + + let lib = create_deadlock_profile_in(&data_dir, &root, "Main", true, Vec::::new()) + .unwrap(); + let id = lib.active_profile_id.unwrap(); + + let files = read_deadlock_cfg_files_in(&data_dir, &root, &id, &[steam_root]).unwrap(); + let convars = files + .iter() + .find(|f| f.path == "user_convars_0_slot0.vcfg") + .unwrap(); + assert_eq!(convars.text, "newer-cloud-copy\n"); + assert!(convars.read_only); + + let video = files.iter().find(|f| f.path == "video.txt").unwrap(); + assert_eq!(video.text, "game-video\n"); + assert!(video.read_only); + + let server = files + .iter() + .find(|f| f.path == "citadel_server.cfg") + .unwrap(); + assert!(server.read_only); + + assert!(!files.iter().any(|f| f.path == "citadel_symlink.cfg")); + + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn derives_readable_deadlock_mod_titles_without_generic_pak_names() { + assert_eq!( + derive_deadlock_mod_title( + None, + "pak37_dir.vpk", + "engineer_as_mcginnis_blue_50392.rar", + Some("Engineer as McGinnis [FIX VIOLET]"), + Some("Only Blue"), + 1, + ), + "Engineer as McGinnis [FIX VIOLET] — Only Blue" + ); + assert_eq!( + derive_deadlock_mod_title( + Some("pak37_dir"), + "addons/pak37_dir.vpk", + "voicelines.rar", + Some("Engineer as McGinnis [FIX VIOLET]"), + Some("VOICELINES"), + 1, + ), + "Engineer as McGinnis [FIX VIOLET] — VOICELINES" + ); + assert_eq!( + derive_deadlock_mod_title( + Some("Custom Embedded Title"), + "pak37_dir.vpk", + "mod.zip", + Some("Listing Title"), + Some("Blue"), + 1, + ), + "Custom Embedded Title" + ); + assert_eq!( + derive_deadlock_mod_title( + None, + "Blue/pak01_dir.vpk", + "bundle.zip", + Some("Hero Rework"), + None, + 2, + ), + "Hero Rework — Blue" + ); + assert_eq!( + derive_deadlock_mod_title(None, "pak01_dir.vpk", "Local Cool Mod.zip", None, None, 1), + "Local Cool Mod" + ); + assert_eq!( + derive_deadlock_mod_title(None, "custom_sound.vpk", "custom_sound.vpk", None, None, 1), + "custom_sound" + ); + } + + #[test] + fn inspects_and_installs_selected_subset_from_multi_vpk_archive() { + let dir = crate::test_temp_dir(); + let data_dir = dir.join("data"); + let root = setup_deadlock_fixture(&dir, "PGI_1", false); + let lib = create_deadlock_profile_in(&data_dir, &root, "Main", true, Vec::::new()) + .unwrap(); + let id = lib.active_profile_id.unwrap(); + + let vpk_blue = write_vpk_v2(&BTreeMap::from([( + "models/blue.vmdl_c".to_string(), + b"B".to_vec(), + )])); + let vpk_red = write_vpk_v2(&BTreeMap::from([( + "models/red.vmdl_c".to_string(), + b"R".to_vec(), + )])); + let vpk_voice = write_vpk_v2(&BTreeMap::from([( + "sounds/voice.vsnd_c".to_string(), + b"V".to_vec(), + )])); + + let mut zip_buf = std::io::Cursor::new(Vec::new()); + { + let mut zw = zip::ZipWriter::new(&mut zip_buf); + zw.start_file("Blue/pak01_dir.vpk", SimpleFileOptions::default()) + .unwrap(); + zw.write_all(&vpk_blue).unwrap(); + zw.start_file("Red/pak01_dir.vpk", SimpleFileOptions::default()) + .unwrap(); + zw.write_all(&vpk_red).unwrap(); + zw.start_file("Voicelines/pak02_dir.vpk", SimpleFileOptions::default()) + .unwrap(); + zw.write_all(&vpk_voice).unwrap(); + zw.finish().unwrap(); + } + + let staged = inspect_deadlock_mod_payload( + "mcginnis_bundle.zip", + zip_buf.get_ref(), + Some("Engineer as McGinnis"), + Some("All Variants"), + ) + .unwrap(); + assert_eq!(staged.len(), 3); + assert_eq!(staged[0].entry.archive_path, "Blue/pak01_dir.vpk"); + assert_eq!( + staged[0].entry.title, + "Engineer as McGinnis — All Variants (Blue)" + ); + + let selected = vec![ + "Blue/pak01_dir.vpk".to_string(), + "Voicelines/pak02_dir.vpk".to_string(), + ]; + let detail = install_deadlock_staged_vpks_in( + &data_dir, + &root, + &id, + &staged, + &selected, + DeadlockModSource::GameBanana { + id: 670908, + section: "mod".into(), + file_id: 1861274, + file_name: "mcginnis_bundle.zip".into(), + page_url: "https://gamebanana.com/mods/670908".into(), + author: Some("Marbix".into()), + version: None, + }, + Vec::::new(), + ) + .unwrap(); + assert_eq!(detail.mods.len(), 2); + assert_eq!( + detail.mods[0].name, + "Engineer as McGinnis — All Variants (Blue)" + ); + assert_eq!(detail.mods[0].author.as_deref(), Some("Marbix")); + assert_eq!( + detail.mods[1].name, + "Engineer as McGinnis — All Variants (Voicelines)" + ); + assert_eq!( + fs::read(root.join("game/citadel/addons/pak01_dir.vpk")).unwrap(), + vpk_blue + ); + assert_eq!( + fs::read(root.join("game/citadel/addons/pak02_dir.vpk")).unwrap(), + vpk_voice + ); + assert!(!root.join("game/citadel/addons/pak03_dir.vpk").exists()); + + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/apps/desktop/src-tauri/core/src/deadlock/vpk_meta.rs b/apps/desktop/src-tauri/core/src/deadlock/vpk_meta.rs new file mode 100644 index 00000000..e2442211 --- /dev/null +++ b/apps/desktop/src-tauri/core/src/deadlock/vpk_meta.rs @@ -0,0 +1,330 @@ +//! Read-only inspection of Deadlock addon VPKs (`modinfo.json`, +//! `addoninfo.txt`, `mods.txt`) and slot-priority conflict computation. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use crate::profile::ProfileError; +use crate::vpk::{read_vpk_dir_bytes_filtered, validate_vpk_dir_bytes_with_paths}; + +const MAX_CONFLICT_SAMPLE_PATHS: usize = 25; + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct DeadlockVpkInfo { + pub title: Option, + pub author: Option, + pub version: Option, + pub built_for_client: Option, + pub entry_paths: Vec, + pub entry_count: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeadlockModConflict { + pub winner_id: String, + pub winner_name: String, + pub winner_slot: u8, + pub loser_id: String, + pub loser_name: String, + pub loser_slot: u8, + pub shared_count: usize, + pub sample_paths: Vec, +} + +#[derive(Debug, Deserialize)] +struct ModInfoJson { + title: Option, + author: Option, + version: Option, +} + +fn is_meta_entry(path: &str) -> bool { + path.eq_ignore_ascii_case("modinfo.json") || path.eq_ignore_ascii_case("addoninfo.txt") +} + +/// Inspect a single-file Deadlock addon VPK from raw bytes, validating the +/// directory header, collecting normalized entry paths, and extracting +/// `modinfo.json` and `addoninfo.txt` if present. +pub fn inspect_vpk_bytes(bytes: &[u8]) -> Result { + let mut entry_paths = Vec::new(); + validate_vpk_dir_bytes_with_paths(bytes, &mut |rel| { + if !is_meta_entry(rel) { + entry_paths.push(rel.to_string()); + } + Ok(()) + }) + .map_err(|err| ProfileError::Io(err.message()))?; + + let meta_archive = read_vpk_dir_bytes_filtered(bytes, &|rel| is_meta_entry(rel)) + .map_err(|err| ProfileError::Io(err.message()))?; + + let mut info = DeadlockVpkInfo { + entry_count: entry_paths.len(), + entry_paths, + ..Default::default() + }; + + if let Some((_, raw)) = meta_archive + .files + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case("addoninfo.txt")) + { + if let Ok(text) = std::str::from_utf8(raw) { + parse_addoninfo(text, &mut info); + } + } + + if let Some((_, raw)) = meta_archive + .files + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case("modinfo.json")) + { + if let Ok(parsed) = serde_json::from_slice::(raw) { + if let Some(title) = parsed.title.filter(|s| !s.trim().is_empty()) { + info.title = Some(title.trim().to_string()); + } + if let Some(author) = parsed.author.filter(|s| !s.trim().is_empty()) { + info.author = Some(author.trim().to_string()); + } + if let Some(version) = parsed.version.filter(|s| !s.trim().is_empty()) { + info.version = Some(version.trim().to_string()); + } + } + } + + Ok(info) +} + +fn parse_addoninfo(text: &str, info: &mut DeadlockVpkInfo) { + for raw_line in text.lines() { + let trimmed = raw_line.trim(); + if trimmed.is_empty() || trimmed.starts_with("//") { + continue; + } + let tokens = tokenize_kv_line(trimmed); + if tokens.len() < 2 { + continue; + } + let key = tokens[0].trim().to_ascii_lowercase(); + let val = tokens[1].trim().to_string(); + if val.is_empty() { + continue; + } + match key.as_str() { + "addontitle" | "title" => { + if info.title.is_none() { + info.title = Some(val); + } + } + "addonauthor" | "author" => { + if info.author.is_none() { + info.author = Some(val); + } + } + "addonversion" | "version" => { + if info.version.is_none() { + info.version = Some(val); + } + } + "builtforclient" if val.chars().all(|c| c.is_ascii_digit()) => { + info.built_for_client = Some(val); + } + _ => {} + } + } +} + +fn tokenize_kv_line(line: &str) -> Vec { + let mut out = Vec::new(); + let mut chars = line.char_indices().peekable(); + while let Some(&(_, ch)) = chars.peek() { + if ch.is_whitespace() { + chars.next(); + continue; + } + if ch == '/' && line[chars.peek().unwrap().0..].starts_with("//") { + break; + } + if ch == '"' { + chars.next(); + let mut val = String::new(); + for (_, c) in chars.by_ref() { + if c == '"' { + break; + } + val.push(c); + } + out.push(val); + } else { + let mut val = String::new(); + while let Some(&(_, c)) = chars.peek() { + if c.is_whitespace() { + break; + } + val.push(c); + chars.next(); + } + out.push(val); + } + if out.len() == 2 { + break; + } + } + out +} + +/// Parse optional `addons/mods.txt` lines (e.g. `pak01_dir.vpk HUD++ (hud.vpk)`) +/// as display titles keyed by lowercase VPK file name. +pub fn parse_mods_txt_titles(text: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + for line in text.lines() { + let trimmed = line.trim(); + let Some((pak, rest)) = trimmed.split_once(char::is_whitespace) else { + continue; + }; + let pak_lower = pak.trim().to_ascii_lowercase(); + if !(pak_lower.starts_with("pak") && pak_lower.ends_with("_dir.vpk")) { + continue; + } + let rest = rest.trim(); + if rest.is_empty() { + continue; + } + let title = rest + .rfind(" (") + .or_else(|| rest.rfind(" (")) + .map(|idx| rest[..idx].trim()) + .unwrap_or(rest); + if !title.is_empty() { + out.insert(pak_lower, title.to_string()); + } + } + out +} + +/// Compute pairwise asset collisions across enabled Deadlock mods ordered by +/// slot ascending (`pak01` overrides `pak02`, so slot 1 wins over slot 2). +pub fn compute_mod_conflicts( + enabled_mods: &[(String, String, u8, Vec)], +) -> Vec { + let mut path_owners: BTreeMap> = BTreeMap::new(); + for (idx, (_, _, _, paths)) in enabled_mods.iter().enumerate() { + let unique: BTreeSet = paths + .iter() + .filter(|p| !is_meta_entry(p)) + .map(|p| p.to_ascii_lowercase()) + .collect(); + for rel in unique { + path_owners.entry(rel).or_default().push(idx); + } + } + + let mut pairs: BTreeMap<(usize, usize), Vec> = BTreeMap::new(); + for (rel, mut owners) in path_owners { + if owners.len() < 2 { + continue; + } + owners.sort_by_key(|&idx| enabled_mods[idx].2); + let winner = owners[0]; + for &loser in &owners[1..] { + pairs.entry((winner, loser)).or_default().push(rel.clone()); + } + } + + pairs + .into_iter() + .map(|((winner, loser), paths)| { + let shared_count = paths.len(); + let sample_paths = paths.into_iter().take(MAX_CONFLICT_SAMPLE_PATHS).collect(); + DeadlockModConflict { + winner_id: enabled_mods[winner].0.clone(), + winner_name: enabled_mods[winner].1.clone(), + winner_slot: enabled_mods[winner].2, + loser_id: enabled_mods[loser].0.clone(), + loser_name: enabled_mods[loser].1.clone(), + loser_slot: enabled_mods[loser].2, + shared_count, + sample_paths, + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::vpk::write_vpk_v2; + + #[test] + fn inspects_modinfo_and_addoninfo_excluding_meta_from_entries() { + let mut files = BTreeMap::new(); + files.insert( + "modinfo.json".into(), + br#"{"title":"HUD++","author":"HoppCX","version":"1.2"}"#.to_vec(), + ); + files.insert( + "addoninfo.txt".into(), + b"\"AddonInfo\"\n{\n\taddontitle \"Fallback\"\n\tbuiltforclient \"6895\"\n}\n".to_vec(), + ); + files.insert("panorama/styles/hud.vcss_c".into(), b"css".to_vec()); + let bytes = write_vpk_v2(&files); + + let info = inspect_vpk_bytes(&bytes).unwrap(); + assert_eq!(info.title.as_deref(), Some("HUD++")); + assert_eq!(info.author.as_deref(), Some("HoppCX")); + assert_eq!(info.version.as_deref(), Some("1.2")); + assert_eq!(info.built_for_client.as_deref(), Some("6895")); + assert_eq!(info.entry_paths, vec!["panorama/styles/hud.vcss_c"]); + assert_eq!(info.entry_count, 1); + } + + #[test] + fn computes_slot_ordered_conflicts_without_counting_metadata() { + let mods = vec![ + ( + "m1".into(), + "HUD++".into(), + 1u8, + vec![ + "modinfo.json".into(), + "panorama/styles/top_bar.vcss_c".into(), + "models/hero.vmdl_c".into(), + ], + ), + ( + "m2".into(), + "Minimal Topbar".into(), + 2u8, + vec![ + "addoninfo.txt".into(), + "panorama/styles/top_bar.vcss_c".into(), + "sounds/ping.vsnd_c".into(), + ], + ), + ]; + let conflicts = compute_mod_conflicts(&mods); + assert_eq!(conflicts.len(), 1); + assert_eq!(conflicts[0].winner_slot, 1); + assert_eq!(conflicts[0].winner_name, "HUD++"); + assert_eq!(conflicts[0].loser_slot, 2); + assert_eq!(conflicts[0].shared_count, 1); + assert_eq!( + conflicts[0].sample_paths, + vec!["panorama/styles/top_bar.vcss_c"] + ); + } + + #[test] + fn parses_mods_txt_titles() { + let map = parse_mods_txt_titles( + "pak01_dir.vpk HUD++ (hud.vpk)\npak06_dir.vpk Low detail map (low.vpk)\n", + ); + assert_eq!(map.get("pak01_dir.vpk").map(String::as_str), Some("HUD++")); + assert_eq!( + map.get("pak06_dir.vpk").map(String::as_str), + Some("Low detail map") + ); + } +} diff --git a/apps/desktop/src-tauri/core/src/finder.rs b/apps/desktop/src-tauri/core/src/finder.rs index 0404706a..8a13b742 100644 --- a/apps/desktop/src-tauri/core/src/finder.rs +++ b/apps/desktop/src-tauri/core/src/finder.rs @@ -7,11 +7,13 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use crate::hash::{metadata_is_link, read_small_text_bounded}; -use crate::steam_inf::steam_inf_app_id; +use crate::steam_inf::{steam_inf_app_id, steam_inf_client_version}; use crate::vdf::{installdir_from_acf, parse_vdf, steam_libraries, SteamLibrary}; const DEFAULT_INSTALLDIR: &str = "Team Fortress 2"; const TF2_APP: &str = "440"; +const DEFAULT_DEADLOCK_INSTALLDIR: &str = "Deadlock"; +const DEADLOCK_APP: &str = "1422450"; const MAX_STEAM_INF_BYTES: usize = 64 * 1024; const MAX_LIBRARYFOLDERS_BYTES: usize = 16 * 1024 * 1024; const MAX_APPMANIFEST_BYTES: usize = 1024 * 1024; @@ -21,6 +23,17 @@ pub struct Tf2Install { pub path: String, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeadlockInstall { + pub path: String, + #[serde( + rename = "clientVersion", + default, + skip_serializing_if = "Option::is_none" + )] + pub client_version: Option, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Tf2RootError { MissingSteamInf, @@ -55,6 +68,40 @@ impl Tf2RootError { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeadlockRootError { + MissingSteamInf, + WrongApp { app_id: String }, + InvalidPath { reason: String }, + Io(String), +} + +impl DeadlockRootError { + pub fn code(&self) -> &'static str { + match self { + Self::MissingSteamInf => "MissingSteamInf", + Self::WrongApp { .. } => "WrongApp", + Self::InvalidPath { .. } => "InvalidPath", + Self::Io(_) => "Io", + } + } + + pub fn message(&self) -> String { + match self { + Self::MissingSteamInf => { + "That folder doesn't look like a Deadlock install. Pick the Deadlock folder (it contains game/citadel), game, or game/citadel itself.".into() + } + Self::WrongApp { app_id } => { + format!("That install is not Deadlock (steam.inf app {app_id}, expected 1422450).") + } + Self::InvalidPath { reason } => { + format!("That Deadlock folder cannot be used safely: {reason}") + } + Self::Io(err) => format!("Could not write settings: {err}"), + } + } +} + pub fn existing_canonical(path: &Path) -> Option { if !path.exists() { return None; @@ -178,10 +225,107 @@ pub fn normalize_tf2_root(picked: &Path) -> Result { } } +/// Accept a Deadlock root, `game/`, or `game/citadel/`. Folder name alone is never enough. +pub fn normalize_deadlock_root(picked: &Path) -> Result { + let root_inf = picked.join("game").join("citadel").join("steam.inf"); + let game_inf = picked.join("citadel").join("steam.inf"); + let picked_inf = picked.join("steam.inf"); + + let (root, inf_path) = if root_inf.is_file() { + (picked.to_path_buf(), root_inf) + } else if game_inf.is_file() { + let parent = picked.parent().ok_or(DeadlockRootError::MissingSteamInf)?; + (parent.to_path_buf(), game_inf) + } else if picked_inf.is_file() { + let game_dir = picked.parent().ok_or(DeadlockRootError::MissingSteamInf)?; + let parent = game_dir + .parent() + .ok_or(DeadlockRootError::MissingSteamInf)?; + (parent.to_path_buf(), picked_inf) + } else { + return Err(DeadlockRootError::MissingSteamInf); + }; + + let canonical_root = fs::canonicalize(&root).map_err(|_| DeadlockRootError::MissingSteamInf)?; + let game_path = canonical_root.join("game"); + if fs::symlink_metadata(&game_path).is_ok_and(|meta| metadata_is_link(&meta)) { + return Err(DeadlockRootError::InvalidPath { + reason: "its game directory is a link or junction".into(), + }); + } + let canonical_game = + fs::canonicalize(&game_path).map_err(|_| DeadlockRootError::MissingSteamInf)?; + if canonical_game.parent() != Some(canonical_root.as_path()) { + return Err(DeadlockRootError::InvalidPath { + reason: "its game directory resolves outside the selected folder".into(), + }); + } + let citadel_path = canonical_game.join("citadel"); + if fs::symlink_metadata(&citadel_path).is_ok_and(|meta| metadata_is_link(&meta)) { + return Err(DeadlockRootError::InvalidPath { + reason: "its game/citadel directory is a link or junction".into(), + }); + } + let canonical_citadel = + fs::canonicalize(&citadel_path).map_err(|_| DeadlockRootError::MissingSteamInf)?; + if canonical_citadel.parent() != Some(canonical_game.as_path()) { + return Err(DeadlockRootError::InvalidPath { + reason: "its game/citadel directory resolves outside the game folder".into(), + }); + } + if fs::symlink_metadata(&inf_path).is_ok_and(|meta| metadata_is_link(&meta)) { + return Err(DeadlockRootError::InvalidPath { + reason: "game/citadel/steam.inf is a link".into(), + }); + } + let canonical_inf = + fs::canonicalize(&inf_path).map_err(|_| DeadlockRootError::MissingSteamInf)?; + if canonical_inf.parent() != Some(canonical_citadel.as_path()) { + return Err(DeadlockRootError::InvalidPath { + reason: "game/citadel/steam.inf resolves outside game/citadel".into(), + }); + } + if canonical_root.to_str().is_none() { + return Err(DeadlockRootError::InvalidPath { + reason: "its path is not valid Unicode".into(), + }); + } + + let text = read_small_text_bounded(&canonical_inf, MAX_STEAM_INF_BYTES).map_err(|err| { + if err.kind() == std::io::ErrorKind::NotFound { + DeadlockRootError::MissingSteamInf + } else { + DeadlockRootError::InvalidPath { + reason: format!("game/citadel/steam.inf cannot be read safely ({err})"), + } + } + })?; + match steam_inf_app_id(&text) { + Some(id) if id == DEADLOCK_APP => Ok(user_path(&canonical_root)), + Some(id) => Err(DeadlockRootError::WrongApp { app_id: id }), + None => Err(DeadlockRootError::WrongApp { + app_id: "missing".into(), + }), + } +} + +pub fn read_deadlock_client_version(root: &Path) -> Option { + let inf_path = root.join("game").join("citadel").join("steam.inf"); + if fs::symlink_metadata(&inf_path).is_ok_and(|meta| metadata_is_link(&meta)) { + return None; + } + let text = read_small_text_bounded(&inf_path, MAX_STEAM_INF_BYTES).ok()?; + steam_inf_client_version(&text) +} + pub fn scan_tf2_installs() -> Vec { scan_tf2_installs_in(&discover_steam_roots()) } +pub fn scan_deadlock_installs() -> Vec { + scan_deadlock_installs_in(&discover_steam_roots()) +} + pub fn scan_tf2_installs_in(steam_roots: &[PathBuf]) -> Vec { let mut seen = HashSet::new(); let mut out = Vec::new(); @@ -215,6 +359,43 @@ pub fn scan_tf2_installs_in(steam_roots: &[PathBuf]) -> Vec { out } +pub fn scan_deadlock_installs_in(steam_roots: &[PathBuf]) -> Vec { + let mut seen = HashSet::new(); + let mut out = Vec::new(); + + for steam in steam_roots { + let Some(steam) = existing_canonical(steam) else { + continue; + }; + for lib in libraries_for_steam(&steam) { + let Some(lib_path) = existing_canonical(Path::new(&lib.path)) else { + continue; + }; + if !library_has_app(&lib, &lib_path, DEADLOCK_APP) { + continue; + } + let installdir = read_installdir_for(&lib_path, DEADLOCK_APP) + .unwrap_or_else(|| DEFAULT_DEADLOCK_INSTALLDIR.into()); + let root = lib_path.join("steamapps").join("common").join(installdir); + if let Ok(valid) = normalize_deadlock_root(&root) { + let Some(key) = valid.to_str().map(str::to_owned) else { + continue; + }; + if seen.insert(key.clone()) { + let client_version = read_deadlock_client_version(&valid); + out.push(DeadlockInstall { + path: key, + client_version, + }); + } + } + } + } + + out.sort_by(|a, b| a.path.cmp(&b.path)); + out +} + /// The machine's real Steam installs. Unit tests never see them: a test that /// switched a fixture profile through a default `None` Steam root once wrote /// its `config.cfg` fixture (`bind w +forward`) into the developer's real @@ -259,19 +440,29 @@ fn libraries_for_steam(steam: &Path) -> Vec { libs } -fn library_has_tf2(parsed: &SteamLibrary, lib_path: &Path) -> bool { - parsed.apps.iter().any(|app| app == TF2_APP) +fn library_has_app(parsed: &SteamLibrary, lib_path: &Path, app_id: &str) -> bool { + parsed.apps.iter().any(|app| app == app_id) || lib_path .join("steamapps") - .join("appmanifest_440.acf") + .join(format!("appmanifest_{app_id}.acf")) .is_file() } -fn read_installdir(lib_path: &Path) -> Option { - let acf = lib_path.join("steamapps").join("appmanifest_440.acf"); +fn library_has_tf2(parsed: &SteamLibrary, lib_path: &Path) -> bool { + library_has_app(parsed, lib_path, TF2_APP) +} + +fn read_installdir_for(lib_path: &Path, app_id: &str) -> Option { + let acf = lib_path + .join("steamapps") + .join(format!("appmanifest_{app_id}.acf")); installdir_from_acf(&read_small_text_bounded(&acf, MAX_APPMANIFEST_BYTES).ok()?) } +fn read_installdir(lib_path: &Path) -> Option { + read_installdir_for(lib_path, TF2_APP) +} + #[cfg(windows)] fn windows_registry_steam() -> Vec { use winreg::enums::*; @@ -380,13 +571,17 @@ mod tests { #[cfg(windows)] fn link_dir(target: &Path, link: &Path) { - let status = std::process::Command::new("cmd") + let output = std::process::Command::new("cmd") .args(["/d", "/c", "mklink", "/j"]) .arg(link) .arg(target) - .status() + .output() .unwrap(); - assert!(status.success(), "could not create test junction"); + assert!( + output.status.success(), + "could not create test junction: {}", + String::from_utf8_lossy(&output.stderr) + ); } #[test] @@ -567,4 +762,112 @@ mod tests { assert_eq!(read_installdir(&steam), None); cleanup(&dir); } + + fn deadlock_tree(root: &Path, app_id: &str, client_version: Option<&str>) { + let mut text = format!("ProductName=citadel\nappID={app_id}\n"); + if let Some(version) = client_version { + text = format!("ClientVersion={version}\n{text}"); + } + write_file(&root.join("game/citadel/steam.inf"), &text); + } + + #[test] + fn normalizes_deadlock_root_game_and_citadel_folders() { + let dir = crate::test_temp_dir(); + let root = dir.join("Deadlock"); + deadlock_tree(&root, "1422450", Some("6895")); + + let from_root = normalize_deadlock_root(&root).unwrap(); + let from_game = normalize_deadlock_root(&root.join("game")).unwrap(); + let from_citadel = normalize_deadlock_root(&root.join("game/citadel")).unwrap(); + assert_eq!(from_root, from_game); + assert_eq!(from_root, from_citadel); + assert!(from_root.ends_with("Deadlock")); + assert_eq!( + read_deadlock_client_version(&from_root).as_deref(), + Some("6895") + ); + cleanup(&dir); + } + + #[test] + fn rejects_deadlock_wrong_app_missing_and_oversized_inf() { + let dir = crate::test_temp_dir(); + let tf2 = dir.join("TF2"); + deadlock_tree(&tf2, "440", None); + match normalize_deadlock_root(&tf2) { + Err(DeadlockRootError::WrongApp { app_id }) => assert_eq!(app_id, "440"), + other => panic!("expected WrongApp, got {other:?}"), + } + assert_eq!( + normalize_deadlock_root(&dir), + Err(DeadlockRootError::MissingSteamInf) + ); + + let oversized = dir.join("Oversized"); + let inf = oversized.join("game/citadel/steam.inf"); + fs::create_dir_all(inf.parent().unwrap()).unwrap(); + fs::File::create(&inf) + .unwrap() + .set_len(MAX_STEAM_INF_BYTES as u64 + 1) + .unwrap(); + assert!(matches!( + normalize_deadlock_root(&oversized), + Err(DeadlockRootError::InvalidPath { .. }) + )); + cleanup(&dir); + } + + #[test] + fn rejects_symlinked_deadlock_boundaries() { + let dir = crate::test_temp_dir(); + let real = dir.join("real"); + deadlock_tree(&real, "1422450", Some("6895")); + + let linked_game = dir.join("linked-game"); + fs::create_dir_all(&linked_game).unwrap(); + link_dir(&real.join("game"), &linked_game.join("game")); + assert!(matches!( + normalize_deadlock_root(&linked_game), + Err(DeadlockRootError::InvalidPath { .. }) + )); + + let linked_citadel = dir.join("linked-citadel"); + fs::create_dir_all(linked_citadel.join("game")).unwrap(); + link_dir( + &real.join("game").join("citadel"), + &linked_citadel.join("game").join("citadel"), + ); + assert!(matches!( + normalize_deadlock_root(&linked_citadel), + Err(DeadlockRootError::InvalidPath { .. }) + )); + cleanup(&dir); + } + + #[test] + fn scan_deadlock_finds_listed_library_and_reads_client_version() { + let dir = crate::test_temp_dir(); + let steam = dir.join("Steam"); + let extra = dir.join("FastLib"); + let deadlock_root = extra.join("steamapps/common/Deadlock"); + deadlock_tree(&deadlock_root, "1422450", Some("6895")); + write_file( + &extra.join("steamapps/appmanifest_1422450.acf"), + "\"AppState\"\n{\n\t\"appid\"\t\t\"1422450\"\n\t\"installdir\"\t\t\"Deadlock\"\n}\n", + ); + write_file( + &steam.join("steamapps/libraryfolders.vdf"), + &format!( + "\"libraryfolders\"\n{{\n\t\"0\"\n\t{{\n\t\t\"path\"\t\t\"{}\"\n\t\t\"apps\"\n\t\t{{\n\t\t\t\"1422450\"\t\t\"1\"\n\t\t}}\n\t}}\n}}\n", + vdf_path(&extra) + ), + ); + + let found = scan_deadlock_installs_in(&[steam]); + assert_eq!(found.len(), 1); + assert!(found[0].path.contains("Deadlock")); + assert_eq!(found[0].client_version.as_deref(), Some("6895")); + cleanup(&dir); + } } diff --git a/apps/desktop/src-tauri/core/src/game.rs b/apps/desktop/src-tauri/core/src/game.rs new file mode 100644 index 00000000..55319004 --- /dev/null +++ b/apps/desktop/src-tauri/core/src/game.rs @@ -0,0 +1,124 @@ +//! Supported games managed by execs. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum GameId { + #[default] + Tf2, + Deadlock, +} + +impl GameId { + pub const ALL: [GameId; 2] = [GameId::Tf2, GameId::Deadlock]; + + pub fn as_str(self) -> &'static str { + match self { + Self::Tf2 => "tf2", + Self::Deadlock => "deadlock", + } + } + + pub fn display_name(self) -> &'static str { + match self { + Self::Tf2 => "Team Fortress 2", + Self::Deadlock => "Deadlock", + } + } + + pub fn short_name(self) -> &'static str { + match self { + Self::Tf2 => "TF2", + Self::Deadlock => "Deadlock", + } + } + + pub fn steam_app_id(self) -> &'static str { + match self { + Self::Tf2 => "440", + Self::Deadlock => "1422450", + } + } + + pub fn gamebanana_game_id(self) -> u64 { + match self { + Self::Tf2 => 297, + Self::Deadlock => 20948, + } + } + + pub fn default_install_dir(self) -> &'static str { + match self { + Self::Tf2 => "Team Fortress 2", + Self::Deadlock => "Deadlock", + } + } + + pub fn steam_rungame_url(self) -> &'static str { + match self { + Self::Tf2 => "steam://rungameid/440", + Self::Deadlock => "steam://rungameid/1422450", + } + } + + /// Root data directory for a game. TF2 keeps the top-level data dir so + /// existing profiles, restore points, and caches require no migration. + pub fn data_dir(self, base: &Path) -> PathBuf { + match self { + Self::Tf2 => base.to_path_buf(), + Self::Deadlock => base.join("deadlock"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_is_tf2_and_serde_uses_lowercase_ids() { + assert_eq!(GameId::default(), GameId::Tf2); + assert_eq!(serde_json::to_string(&GameId::Tf2).unwrap(), "\"tf2\""); + assert_eq!( + serde_json::to_string(&GameId::Deadlock).unwrap(), + "\"deadlock\"" + ); + assert_eq!( + serde_json::from_str::("\"tf2\"").unwrap(), + GameId::Tf2 + ); + assert_eq!( + serde_json::from_str::("\"deadlock\"").unwrap(), + GameId::Deadlock + ); + } + + #[test] + fn metadata_and_data_dirs_match_spec() { + assert_eq!(GameId::Tf2.as_str(), "tf2"); + assert_eq!(GameId::Tf2.display_name(), "Team Fortress 2"); + assert_eq!(GameId::Tf2.short_name(), "TF2"); + assert_eq!(GameId::Tf2.steam_app_id(), "440"); + assert_eq!(GameId::Tf2.gamebanana_game_id(), 297); + assert_eq!(GameId::Tf2.default_install_dir(), "Team Fortress 2"); + assert_eq!(GameId::Tf2.steam_rungame_url(), "steam://rungameid/440"); + + assert_eq!(GameId::Deadlock.as_str(), "deadlock"); + assert_eq!(GameId::Deadlock.display_name(), "Deadlock"); + assert_eq!(GameId::Deadlock.short_name(), "Deadlock"); + assert_eq!(GameId::Deadlock.steam_app_id(), "1422450"); + assert_eq!(GameId::Deadlock.gamebanana_game_id(), 20948); + assert_eq!(GameId::Deadlock.default_install_dir(), "Deadlock"); + assert_eq!( + GameId::Deadlock.steam_rungame_url(), + "steam://rungameid/1422450" + ); + + let base = Path::new("/data/execs"); + assert_eq!(GameId::Tf2.data_dir(base), base); + assert_eq!(GameId::Deadlock.data_dir(base), base.join("deadlock")); + } +} diff --git a/apps/desktop/src-tauri/core/src/launch.rs b/apps/desktop/src-tauri/core/src/launch.rs index 12fd0710..5cf37c9c 100644 --- a/apps/desktop/src-tauri/core/src/launch.rs +++ b/apps/desktop/src-tauri/core/src/launch.rs @@ -16,24 +16,12 @@ use crate::profile::{load_library_from, load_manifest, profiles_dir, ProfileErro use crate::vdf::{parse_vdf, serialize_vdf, VdfMap, VdfValue}; const TF2_APP: &str = "440"; +pub const DEADLOCK_APP: &str = "1422450"; const STEAM_ID64_BASE: u64 = 76561197960265728; const RECOMMENDED_LAUNCH_OPTIONS: &str = "-novid -nojoy -nosteamcontroller -nohltv -particles 1"; const MAX_LOCALCONFIG_BYTES: usize = 16 * 1024 * 1024; const MAX_LOGINUSERS_BYTES: usize = 1024 * 1024; -const LAUNCH_OPTIONS_PATH: &[&str] = &[ - "UserLocalConfigStore", - "Software", - "Valve", - "Steam", - "apps", - "440", - "LaunchOptions", -]; - -const LAUNCH_OPTIONS_PATH_FROM_STORE: &[&str] = - &["Software", "Valve", "Steam", "apps", "440", "LaunchOptions"]; - #[derive(Debug, Clone, PartialEq, Eq)] pub struct SteamAccount { pub steam_root: PathBuf, @@ -71,12 +59,62 @@ pub fn read_launch_options_from(steam_roots: &[PathBuf]) -> String { /// Steam's saved TF2 launch options, or `None` when no account has a readable /// `localconfig.vdf`. An account without TF2 options reads as empty. fn read_steam_launch_options_from(steam_roots: &[PathBuf]) -> Option { - let account = pick_steam_account_from(steam_roots)?; + read_steam_launch_options_for_app_from(TF2_APP, steam_roots) +} + +/// Steam's saved launch options for any app id (`"440"`, `"1422450"`, etc.), +/// or `None` when no account has a readable `localconfig.vdf`. +pub fn read_steam_launch_options_for_app_from( + app_id: &str, + steam_roots: &[PathBuf], +) -> Option { + let account = pick_steam_account_for_app_from(steam_roots, app_id)?; let text = read_small_text_bounded(&account.localconfig(), MAX_LOCALCONFIG_BYTES).ok()?; let vdf = parse_vdf(&text).ok()?; - Some(sanitize_launch_options( - &launch_options_from_localconfig(&vdf).unwrap_or_default(), - )) + let raw = launch_options_from_localconfig_for_app(&vdf, app_id).unwrap_or_default(); + Some(sanitize_launch_options_for_app(app_id, &raw)) +} + +pub fn write_steam_launch_options_for_app_from( + app_id: &str, + steam_roots: &[PathBuf], + options: &str, + process_names: I, +) -> Result +where + I: IntoIterator, + S: AsRef, +{ + let steam_running = steam_running_among(process_names); + if steam_running { + return Ok(LaunchWriteResult { + written: false, + reason: LaunchWriteReason::SteamOpen, + }); + } + let Some(account) = pick_steam_account_for_app_from(steam_roots, app_id) else { + return Ok(LaunchWriteResult { + written: false, + reason: LaunchWriteReason::NoAccount, + }); + }; + let sanitized = sanitize_launch_options_for_app(app_id, options); + let prepared = prepare_localconfig_update_for_app(account, app_id, &sanitized)?; + backup_localconfig_once( + &prepared.account.steam_root, + &prepared.path, + prepared.original.as_bytes(), + )?; + write_atomic_within( + &prepared.account.steam_root, + &prepared.path, + prepared.serialized.as_bytes(), + ) + .map_err(|err| ProfileError::Io(err.to_string()))?; + Ok(LaunchWriteResult { + written: true, + reason: LaunchWriteReason::Written, + }) } /// Official mastercomfig recommended set. Same on Windows and Linux (no `gamemoderun`). @@ -196,6 +234,14 @@ struct PreparedLocalconfigUpdate { fn prepare_localconfig_update( account: SteamAccount, options: &str, +) -> Result { + prepare_localconfig_update_for_app(account, TF2_APP, &sanitize_launch_options(options)) +} + +fn prepare_localconfig_update_for_app( + account: SteamAccount, + app_id: &str, + options: &str, ) -> Result { let path = account.localconfig(); validate_existing_file_within(&account.steam_root, &path)?; @@ -207,7 +253,7 @@ fn prepare_localconfig_update( "Refusing to rewrite localconfig.vdf: its Steam settings root is missing.".into(), )); } - set_launch_options_in_vdf(&mut vdf, &sanitize_launch_options(options)); + set_launch_options_in_vdf_for_app(&mut vdf, app_id, options); let serialized = serialize_vdf(&vdf); // We re-emit the whole file through our own writer, so anything our parser // does not model would be silently corrupted. Read our own output back and @@ -590,20 +636,37 @@ fn ensure_library_usable(profiles_dir: &Path, tf2_root: &Path) -> Result<(), Pro Ok(()) } -fn set_launch_options_in_vdf(vdf: &mut VdfMap, options: &str) { +fn set_launch_options_in_vdf_for_app(vdf: &mut VdfMap, app_id: &str, options: &str) { + let full_path = [ + "UserLocalConfigStore", + "Software", + "Valve", + "Steam", + "apps", + app_id, + "LaunchOptions", + ]; + let store_path = [ + "Software", + "Valve", + "Steam", + "apps", + app_id, + "LaunchOptions", + ]; if vdf .get("UserLocalConfigStore") .and_then(VdfValue::as_obj) .is_some() { - vdf.set_path(LAUNCH_OPTIONS_PATH, options); + vdf.set_path(&full_path, options); return; } if vdf.get("Software").and_then(VdfValue::as_obj).is_some() { - vdf.set_path(LAUNCH_OPTIONS_PATH_FROM_STORE, options); + vdf.set_path(&store_path, options); return; } - vdf.set_path(LAUNCH_OPTIONS_PATH, options); + vdf.set_path(&full_path, options); } pub fn find_cloud_config() -> Option { @@ -642,6 +705,13 @@ fn cloud_parent_is_safe(account: &SteamAccount) -> bool { } pub fn pick_steam_account_from(steam_roots: &[PathBuf]) -> Option { + pick_steam_account_for_app_from(steam_roots, TF2_APP) +} + +pub fn pick_steam_account_for_app_from( + steam_roots: &[PathBuf], + app_id: &str, +) -> Option { let mut candidates = Vec::new(); for steam_root in steam_roots { let userdata = steam_root.join("userdata"); @@ -691,13 +761,13 @@ pub fn pick_steam_account_from(steam_roots: &[PathBuf]) -> Option } // `MostRecent` describes the account Steam actually selected. Consult it - // before the TF2-directory heuristic: a newly logged-in account may not - // have created userdata//440 yet, while an older account has. + // before the app-directory heuristic: a newly logged-in account may not + // have created userdata// yet, while an older account has. if let Some(preferred) = prefer_most_recent(steam_roots, &candidates) { return Some(preferred); } - let with_440: Vec = candidates + let with_app: Vec = candidates .iter() .filter(|account| { validate_dir_within( @@ -706,21 +776,21 @@ pub fn pick_steam_account_from(steam_roots: &[PathBuf]) -> Option .steam_root .join("userdata") .join(&account.account_id) - .join(TF2_APP), + .join(app_id), ) .is_ok() }) .cloned() .collect(); - let pool = if with_440.is_empty() { + let pool = if with_app.is_empty() { &candidates } else { - &with_440 + &with_app }; pool.iter() - .filter(|account| localconfig_mentions_440(&account.localconfig())) + .filter(|account| localconfig_mentions_app(&account.localconfig(), app_id)) .max_by_key(|account| localconfig_mtime(&account.localconfig())) .cloned() .or_else(|| { @@ -736,22 +806,37 @@ pub fn pick_steam_account_from(steam_roots: &[PathBuf]) -> Option /// and including `%command%` is kept exactly as written, and only the TF2 /// arguments after it are checked. Dropping `%command%` while keeping its /// wrapper would turn the wrapper into TF2 arguments and break the launch. +/// Remove destructive launch flags that a Deadlock profile should not persist, +/// preserving `%command%` Steam wrappers verbatim. +pub fn sanitize_deadlock_launch_options(raw: &str) -> String { + let cleaned: String = raw.chars().filter(|ch| !ch.is_control()).collect(); + rebuild_launch_options_for_app(&cleaned, true, true) +} + +fn sanitize_launch_options_for_app(app_id: &str, raw: &str) -> String { + if app_id == DEADLOCK_APP { + sanitize_deadlock_launch_options(raw) + } else { + sanitize_launch_options(raw) + } +} + pub fn sanitize_launch_options(raw: &str) -> String { - rebuild_launch_options(raw, true) + rebuild_launch_options_for_app(raw, true, false) } /// The same layout `sanitize_launch_options` produces, without removing /// anything, so a caller can tell whether sanitizing would change a string. fn normalize_launch_options(raw: &str) -> String { - rebuild_launch_options(raw, false) + rebuild_launch_options_for_app(raw, false, false) } -fn rebuild_launch_options(raw: &str, drop_forbidden: bool) -> String { +fn rebuild_launch_options_for_app(raw: &str, drop_forbidden: bool, is_deadlock: bool) -> String { let (wrapper, arguments) = split_steam_wrapper(raw.trim()); let arguments = split_launch_commands(arguments) .into_iter() .filter_map(|command| { - let sanitized = sanitize_launch_command(&command, drop_forbidden); + let sanitized = sanitize_launch_command(&command, drop_forbidden, is_deadlock); (!sanitized.is_empty()).then_some(sanitized) }) .collect::>() @@ -801,7 +886,7 @@ fn split_steam_wrapper(raw: &str) -> (Option<&str>, &str) { const STEAM_COMMAND_TOKEN: &str = "%command%"; -fn sanitize_launch_command(raw: &str, drop_forbidden: bool) -> String { +fn sanitize_launch_command(raw: &str, drop_forbidden: bool, is_deadlock: bool) -> String { let tokens = tokenize_launch_options(raw); if !drop_forbidden { return tokens @@ -814,7 +899,7 @@ fn sanitize_launch_command(raw: &str, drop_forbidden: bool) -> String { let mut i = 0; while i < tokens.len() { let normalized = normalized_launch_token(&tokens[i].value); - if normalized == "-dxlevel" || normalized.starts_with("-dxlevel") { + if !is_deadlock && (normalized == "-dxlevel" || normalized.starts_with("-dxlevel")) { if normalized == "-dxlevel" && i + 1 < tokens.len() && !normalized_launch_token(&tokens[i + 1].value).starts_with('-') @@ -826,16 +911,23 @@ fn sanitize_launch_command(raw: &str, drop_forbidden: bool) -> String { i += 1; continue; } - if launch_token_is_forbidden(&normalized) { + let is_forbidden = |tok: &str| { + if is_deadlock { + deadlock_token_is_forbidden(tok) + } else { + launch_token_is_forbidden(tok) + } + }; + if is_forbidden(&normalized) { i += 1; continue; } // A quoted shell fragment can contain multiple effective words. Drop // the whole fragment if any one is forbidden; leaving `bash -c` behind - // is safer than persisting a hidden destructive TF2 option. + // is safer than persisting a hidden destructive option. if normalized .split(|ch: char| ch.is_whitespace() || ch == ';') - .any(launch_token_is_forbidden) + .any(is_forbidden) { i += 1; continue; @@ -963,6 +1055,10 @@ fn launch_token_is_forbidden(token: &str) -> bool { || token.contains(STEAM_COMMAND_TOKEN) } +fn deadlock_token_is_forbidden(token: &str) -> bool { + matches!(token, "-autoconfig" | "-default" | "+quit") || token.contains(STEAM_COMMAND_TOKEN) +} + fn prefer_most_recent(steam_roots: &[PathBuf], pool: &[SteamAccount]) -> Option { for steam_root in steam_roots { let loginusers = steam_root.join("config").join("loginusers.vdf"); @@ -1011,35 +1107,39 @@ fn steamid64_to_account(id: &str) -> Option { n.checked_sub(STEAM_ID64_BASE).map(|id| id.to_string()) } -fn launch_options_from_localconfig(vdf: &VdfMap) -> Option { +fn launch_options_from_localconfig_for_app(vdf: &VdfMap, app_id: &str) -> Option { let store = vdf .get("UserLocalConfigStore") .and_then(VdfValue::as_obj) .unwrap_or(vdf); let apps = vdf_get_obj(store, &["Software", "Valve", "Steam", "apps"])?; - let app = apps.get(TF2_APP)?.as_obj()?; + let app = apps.get(app_id)?.as_obj()?; app.get("LaunchOptions") .and_then(VdfValue::as_str) .map(str::to_string) } -fn localconfig_mentions_440(path: &Path) -> bool { +fn launch_options_from_localconfig(vdf: &VdfMap) -> Option { + launch_options_from_localconfig_for_app(vdf, TF2_APP) +} + +fn localconfig_mentions_app(path: &Path, app_id: &str) -> bool { let Ok(text) = read_small_text_bounded(path, MAX_LOCALCONFIG_BYTES) else { return false; }; let Ok(vdf) = parse_vdf(&text) else { return false; }; - launch_options_from_localconfig(&vdf).is_some() || vdf_has_app_440(&vdf) + launch_options_from_localconfig_for_app(&vdf, app_id).is_some() || vdf_has_app(&vdf, app_id) } -fn vdf_has_app_440(vdf: &VdfMap) -> bool { +fn vdf_has_app(vdf: &VdfMap, app_id: &str) -> bool { let store = vdf .get("UserLocalConfigStore") .and_then(VdfValue::as_obj) .unwrap_or(vdf); vdf_get_obj(store, &["Software", "Valve", "Steam", "apps"]) - .and_then(|apps| apps.get(TF2_APP)) + .and_then(|apps| apps.get(app_id)) .is_some() } @@ -2115,4 +2215,43 @@ mod tests { ); cleanup(&dir); } + + #[test] + fn deadlock_app_launch_options_round_trip_without_touching_tf2() { + let dir = crate::test_temp_dir(); + let steam = dir.join("Steam"); + write_account(&steam, "111", "-novid -nojoy"); + let roots = [steam.clone()]; + + assert_eq!( + sanitize_deadlock_launch_options("gamemoderun %command% -novid -autoconfig +quit -dev"), + "gamemoderun %command% -novid -dev" + ); + + let steam_res = write_steam_launch_options_for_app_from( + DEADLOCK_APP, + &roots, + "-console -vulkan", + ["steam.exe", "steam"], + ) + .unwrap(); + assert!(!steam_res.written); + assert_eq!(steam_res.reason, LaunchWriteReason::SteamOpen); + + let res = write_steam_launch_options_for_app_from( + DEADLOCK_APP, + &roots, + "mangohud %command% -novid -autoconfig +citadel_hud_visible 1", + Vec::::new(), + ) + .unwrap(); + assert!(res.written); + assert_eq!( + read_steam_launch_options_for_app_from(DEADLOCK_APP, &roots).as_deref(), + Some("mangohud %command% -novid +citadel_hud_visible 1") + ); + // App 440 stays untouched. + assert_eq!(read_launch_options_from(&roots), "-novid -nojoy"); + cleanup(&dir); + } } diff --git a/apps/desktop/src-tauri/core/src/lib.rs b/apps/desktop/src-tauri/core/src/lib.rs index 5102b0e5..52c1e228 100644 --- a/apps/desktop/src-tauri/core/src/lib.rs +++ b/apps/desktop/src-tauri/core/src/lib.rs @@ -11,10 +11,12 @@ pub mod comfig; pub mod content_index; pub mod crosshair; pub mod custom_folders; +pub mod deadlock; pub mod disk_space; pub mod files_workspace; pub mod finder; pub mod first_run; +pub mod game; pub mod game_resolution; pub mod hash; pub mod health; @@ -95,11 +97,26 @@ pub use crosshair::{ apply_crosshairs, extract_stock_crosshair_sprites, remove_crosshairs, stored_pack_crosshair, CrosshairAsset, CrosshairAssetFormat, StockCrosshairSprite, }; +pub use deadlock::{ + adopt_deadlock_live_gameinfo, adopt_deadlock_steam_launch_options, capture_deadlock_profile, + create_deadlock_profile, deadlock_launch_sync_status, delete_deadlock_cfg_file, + delete_deadlock_profile, inspect_deadlock_mod_payload, install_deadlock_mod_bytes, + install_deadlock_staged_vpks, load_deadlock_library, load_deadlock_profile_detail, + read_deadlock_cfg_files, remove_deadlock_mod, rename_deadlock_profile, reorder_deadlock_mods, + reset_deadlock_profile_gameinfo_to_stock, save_deadlock_cfg_file, set_deadlock_launch_options, + set_deadlock_mod_enabled, switch_deadlock_profile, DeadlockArchiveVpkEntry, DeadlockCfgFile, + DeadlockLaunchSyncStatus, DeadlockLibrary, DeadlockModConflict, DeadlockModRecord, + DeadlockModSource, DeadlockModView, DeadlockProfileDetail, DeadlockProfileSummary, + DeadlockSetLaunchResult, DeadlockStagedVpk, GameInfoCheck, GameInfoMode, +}; pub use finder::{ - discover_steam_roots, normalize_tf2_root, scan_tf2_installs, scan_tf2_installs_in, Tf2Install, + discover_steam_roots, normalize_deadlock_root, normalize_tf2_root, + read_deadlock_client_version, scan_deadlock_installs, scan_deadlock_installs_in, + scan_tf2_installs, scan_tf2_installs_in, DeadlockInstall, DeadlockRootError, Tf2Install, Tf2RootError, }; pub use first_run::{classify_first_run, FirstRunClass, FirstRunKind}; +pub use game::GameId; pub use hitsound::{ apply_hitsounds, clamp_boost_db, extract_stock_hitsounds, inspect_wav, prepare_hitsound_wav, prepare_hitsound_wav_boosted, preview_wav, remove_hitsounds, stored_hitsound, HitsoundChange, @@ -129,8 +146,9 @@ pub use mods::{ ModContent, ModRecord, ModSource, ParticleSource, }; pub use process_lock::{ - is_tf2_running, os_description, refuse_if_running, refuse_if_running_among, write_lock_status, - WriteLock, WriteLockError, + is_deadlock_running, is_game_running, is_tf2_running, os_description, + refuse_if_deadlock_running, refuse_if_game_running, refuse_if_running, refuse_if_running_among, + write_lock_status, write_lock_status_for, WriteLock, WriteLockError, }; pub use profile::{ init_library, load_library, load_manifest, profile_mutation_status_to, profiles_dir, @@ -140,9 +158,11 @@ pub use profile::{ ViewmodelRecord, ViewmodelSource, ViewmodelSourceFingerprint, VIEWMODEL_BUILD_RECIPE_SCHEMA, }; pub use settings::{ - execs_data_dir, remember_tf2_root, remember_tf2_root_to, remembered_tf2_root, - remembered_tf2_root_from, settings_file, try_execs_data_dir, unavailable_tf2_root, - unavailable_tf2_root_from, Settings, + active_game_from, execs_data_dir, remember_deadlock_root, remember_deadlock_root_to, + remember_tf2_root, remember_tf2_root_to, remembered_deadlock_root, + remembered_deadlock_root_from, remembered_tf2_root, remembered_tf2_root_from, + set_active_game_to, settings_file, try_execs_data_dir, unavailable_deadlock_root, + unavailable_deadlock_root_from, unavailable_tf2_root, unavailable_tf2_root_from, Settings, }; pub use surface::{inventory_live_surface, CfgLayer, LiveInventory}; pub use switch::{switch_profile, switch_profile_with_progress, SwitchProgress, SwitchStep}; diff --git a/apps/desktop/src-tauri/core/src/process_lock.rs b/apps/desktop/src-tauri/core/src/process_lock.rs index af74d139..061cad29 100644 --- a/apps/desktop/src-tauri/core/src/process_lock.rs +++ b/apps/desktop/src-tauri/core/src/process_lock.rs @@ -1,8 +1,10 @@ -//! Refuse live-surface / profile-library writes while TF2 is running. +//! Refuse live-surface / profile-library writes while the active game is running. use serde::Serialize; use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System}; +use crate::game::GameId; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ProcessOs { Windows, @@ -18,6 +20,7 @@ pub struct WriteLock { #[derive(Debug, Clone, PartialEq, Eq)] pub enum WriteLockError { GameRunning, + DeadlockRunning, } impl WriteLockError { @@ -26,7 +29,12 @@ impl WriteLockError { } pub fn message(&self) -> &'static str { - "TF2 is running — execs is read-only until the game quits." + match self { + Self::GameRunning => "TF2 is running — execs is read-only until the game quits.", + Self::DeadlockRunning => { + "Deadlock is running — execs is read-only until the game quits." + } + } } } @@ -53,6 +61,34 @@ pub fn process_name_is_tf2(name: &str) -> bool { process_name_is_tf2_for(current_process_os(), name) } +pub fn process_name_is_deadlock_for(os: ProcessOs, name: &str) -> bool { + let base = name.rsplit(['/', '\\']).next().unwrap_or(name); + let lower = base.to_ascii_lowercase(); + match os { + ProcessOs::Windows => { + matches!( + lower.as_str(), + "deadlock.exe" | "deadlock" | "project8.exe" | "project8" + ) + } + // Proton runs `deadlock.exe` (or legacy `project8.exe`); also match `deadlock` for any native build. + ProcessOs::Linux => { + matches!(lower.as_str(), "deadlock.exe" | "project8.exe" | "deadlock") + } + } +} + +pub fn process_name_is_deadlock(name: &str) -> bool { + process_name_is_deadlock_for(current_process_os(), name) +} + +pub fn process_name_is_game_for(game: GameId, os: ProcessOs, name: &str) -> bool { + match game { + GameId::Tf2 => process_name_is_tf2_for(os, name), + GameId::Deadlock => process_name_is_deadlock_for(os, name), + } +} + /// Steam main client only. `steamwebhelper` is not enough to block `localconfig.vdf`. pub fn process_name_is_steam_for(os: ProcessOs, name: &str) -> bool { let base = name.rsplit(['/', '\\']).next().unwrap_or(name); @@ -103,6 +139,24 @@ where tf2_running_among_for(current_process_os(), names) } +pub fn deadlock_running_among_for(os: ProcessOs, names: I) -> bool +where + I: IntoIterator, + S: AsRef, +{ + names + .into_iter() + .any(|name| process_name_is_deadlock_for(os, name.as_ref())) +} + +pub fn deadlock_running_among(names: I) -> bool +where + I: IntoIterator, + S: AsRef, +{ + deadlock_running_among_for(current_process_os(), names) +} + pub fn live_process_names() -> Vec { let mut sys = System::new(); // Only `name()` is read. The default refresh pulls cmdline, environment, @@ -119,6 +173,17 @@ pub fn is_tf2_running() -> bool { tf2_running_among(live_process_names()) } +pub fn is_deadlock_running() -> bool { + deadlock_running_among(live_process_names()) +} + +pub fn is_game_running(game: GameId) -> bool { + match game { + GameId::Tf2 => is_tf2_running(), + GameId::Deadlock => is_deadlock_running(), + } +} + /// "Windows 11 (10.0.26200) x86_64" style line for bug reports. pub fn os_description() -> String { let name = System::long_os_version().unwrap_or_else(|| std::env::consts::OS.to_string()); @@ -136,12 +201,26 @@ pub fn write_lock_status() -> WriteLock { } } +pub fn write_lock_status_for(game: GameId) -> WriteLock { + WriteLock { + running: is_game_running(game), + } +} + /// Wraps every live-surface / profile-library write. Confirming the TF2 root /// is an app-data settings write and must not call this. pub fn refuse_if_running() -> Result<(), WriteLockError> { refuse_if_running_among(live_process_names()) } +pub fn refuse_if_deadlock_running() -> Result<(), WriteLockError> { + refuse_if_game_running_among(GameId::Deadlock, live_process_names()) +} + +pub fn refuse_if_game_running(game: GameId) -> Result<(), WriteLockError> { + refuse_if_game_running_among(game, live_process_names()) +} + pub fn refuse_if_running_among(names: I) -> Result<(), WriteLockError> where I: IntoIterator, @@ -155,10 +234,41 @@ where I: IntoIterator, S: AsRef, { - if tf2_running_among_for(os, names) { - Err(WriteLockError::GameRunning) - } else { - Ok(()) + refuse_if_game_running_among_for(GameId::Tf2, os, names) +} + +pub fn refuse_if_game_running_among(game: GameId, names: I) -> Result<(), WriteLockError> +where + I: IntoIterator, + S: AsRef, +{ + refuse_if_game_running_among_for(game, current_process_os(), names) +} + +pub fn refuse_if_game_running_among_for( + game: GameId, + os: ProcessOs, + names: I, +) -> Result<(), WriteLockError> +where + I: IntoIterator, + S: AsRef, +{ + match game { + GameId::Tf2 => { + if tf2_running_among_for(os, names) { + Err(WriteLockError::GameRunning) + } else { + Ok(()) + } + } + GameId::Deadlock => { + if deadlock_running_among_for(os, names) { + Err(WriteLockError::DeadlockRunning) + } else { + Ok(()) + } + } } } @@ -241,4 +351,40 @@ mod tests { assert!(refuse_if_running_among_for(ProcessOs::Windows, ["steam.exe"]).is_ok()); assert!(refuse_if_running_among_for(ProcessOs::Windows, ["tf_win64.exe"]).is_err()); } + + #[test] + fn matches_deadlock_process_names_only() { + for os in [ProcessOs::Windows, ProcessOs::Linux] { + for name in [ + "deadlock.exe", + "DEADLOCK.EXE", + r"C:\Steam\Deadlock\game\bin\win64\deadlock.exe", + "/mnt/fast/SteamLibrary/steamapps/common/Deadlock/game/bin/win64/deadlock.exe", + "project8.exe", + "deadlock", + ] { + assert!(process_name_is_deadlock_for(os, name), "{os:?}: {name}"); + assert!(process_name_is_game_for(GameId::Deadlock, os, name)); + let err = + refuse_if_game_running_among_for(GameId::Deadlock, os, [name]).unwrap_err(); + assert_eq!(err, WriteLockError::DeadlockRunning); + assert_eq!(err.code(), "GameRunning"); + } + for non_match in [ + "vconsole2.exe", + "deadlock.exe.bak", + "mydeadlock.exe", + "steam", + "tf_win64.exe", + ] { + assert!( + !process_name_is_deadlock_for(os, non_match), + "{os:?}: {non_match}" + ); + assert!( + refuse_if_game_running_among_for(GameId::Deadlock, os, [non_match]).is_ok() + ); + } + } + } } diff --git a/apps/desktop/src-tauri/core/src/settings.rs b/apps/desktop/src-tauri/core/src/settings.rs index e3ab2ee5..545a7504 100644 --- a/apps/desktop/src-tauri/core/src/settings.rs +++ b/apps/desktop/src-tauri/core/src/settings.rs @@ -6,7 +6,10 @@ use std::sync::Mutex; use serde::{Deserialize, Serialize}; use crate::archive::read_regular_file_bounded_within; -use crate::finder::{normalize_tf2_root, user_path_string, Tf2RootError}; +use crate::finder::{ + normalize_deadlock_root, normalize_tf2_root, user_path_string, DeadlockRootError, Tf2RootError, +}; +use crate::game::GameId; use crate::hash::{validate_dir_within, write_atomic_within}; use crate::profile::ProfileError; @@ -41,13 +44,29 @@ impl Default for AppPreferences { } } +fn is_default_active_game(game: &GameId) -> bool { + *game == GameId::default() +} + /// Settings files written by earlier versions may carry keys this struct does /// not have, such as `inheritBinds`. Unknown keys are ignored, so they load. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Settings { pub schema: u32, + #[serde( + rename = "activeGame", + default, + skip_serializing_if = "is_default_active_game" + )] + pub active_game: GameId, #[serde(rename = "tf2Root", default)] pub tf2_root: String, + #[serde( + rename = "deadlockRoot", + default, + skip_serializing_if = "String::is_empty" + )] + pub deadlock_root: String, #[serde(default)] pub preferences: AppPreferences, /// Where the main window was when execs last closed. Additive: older @@ -90,7 +109,9 @@ impl Default for Settings { fn default() -> Self { Self { schema: SETTINGS_SCHEMA, + active_game: GameId::default(), tf2_root: String::new(), + deadlock_root: String::new(), preferences: AppPreferences::default(), window: None, } @@ -330,6 +351,20 @@ pub fn remember_tf2_root_to(file: &Path, root: &Path) -> Result Result { + Ok(read_settings_from(file)?.unwrap_or_default().active_game) +} + +pub fn set_active_game_to(file: &Path, game: GameId) -> Result { + let _guard = SETTINGS_WRITES + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut settings = read_settings_from(file)?.unwrap_or_default(); + settings.active_game = game; + save_settings_to(file, &settings)?; + Ok(settings.active_game) +} + pub fn remembered_tf2_root() -> Option { remembered_tf2_root_from(&settings_file()) } @@ -338,6 +373,53 @@ pub fn remember_tf2_root(root: &Path) -> Result { remember_tf2_root_to(&settings_file(), root) } +/// Re-validates `game/citadel/steam.inf`. A moved or non-1422450 root is treated as unconfirmed. +pub fn remembered_deadlock_root_from(file: &Path) -> Option { + let _guard = SETTINGS_WRITES + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut settings = load_settings_from(file)?; + let valid = normalize_deadlock_root(Path::new(&settings.deadlock_root)).ok()?; + let cleaned = user_path_string(&valid); + if settings.deadlock_root != cleaned { + settings.deadlock_root = cleaned; + let _ = save_settings_to(file, &settings); + } + Some(valid) +} + +pub fn unavailable_deadlock_root() -> Option { + unavailable_deadlock_root_from(&settings_file()) +} + +pub fn unavailable_deadlock_root_from(file: &Path) -> Option { + let settings = load_settings_from(file)?; + let saved = settings.deadlock_root.trim(); + (!saved.is_empty() && normalize_deadlock_root(Path::new(saved)).is_err()) + .then(|| saved.to_string()) +} + +pub fn remember_deadlock_root_to(file: &Path, root: &Path) -> Result { + let valid = normalize_deadlock_root(root)?; + let _guard = SETTINGS_WRITES + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut settings = read_settings_from(file) + .map_err(DeadlockRootError::Io)? + .unwrap_or_default(); + settings.deadlock_root = user_path_string(&valid); + save_settings_to(file, &settings).map_err(DeadlockRootError::Io)?; + Ok(valid) +} + +pub fn remembered_deadlock_root() -> Option { + remembered_deadlock_root_from(&settings_file()) +} + +pub fn remember_deadlock_root(root: &Path) -> Result { + remember_deadlock_root_to(&settings_file(), root) +} + #[cfg(test)] mod tests { use super::*; @@ -745,4 +827,53 @@ mod tests { assert!(!fs::read_to_string(&file).unwrap().contains(r"\\?\")); let _ = fs::remove_dir_all(&dir); } + + fn write_deadlock(root: &Path) { + let inf = root.join("game/citadel/steam.inf"); + fs::create_dir_all(inf.parent().unwrap()).unwrap(); + let mut file = fs::File::create(inf).unwrap(); + file.write_all(b"ClientVersion=6895\nProductName=citadel\nappID=1422450\n") + .unwrap(); + } + + #[test] + fn legacy_settings_default_active_game_to_tf2_and_deadlock_root_round_trips() { + let dir = crate::test_temp_dir(); + let file = dir.join("execs").join("settings.json"); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(&file, br#"{"schema":1,"tf2Root":"D:/tf2"}"#).unwrap(); + assert_eq!(active_game_from(&file).unwrap(), GameId::Tf2); + assert!(load_settings_from(&file).unwrap().deadlock_root.is_empty()); + + // TF2-only preference updates preserve the legacy settings shape with no extra keys. + set_app_preferences_to(&file, AppPreferences::default()).unwrap(); + let tf2_json = fs::read_to_string(&file).unwrap(); + assert!(!tf2_json.contains("activeGame")); + assert!(!tf2_json.contains("deadlockRoot")); + + let deadlock = dir.join("Deadlock"); + write_deadlock(&deadlock); + let stored = remember_deadlock_root_to(&file, &deadlock).unwrap(); + assert_eq!( + remembered_deadlock_root_from(&file).as_deref(), + Some(stored.as_path()) + ); + assert_eq!( + set_active_game_to(&file, GameId::Deadlock).unwrap(), + GameId::Deadlock + ); + let saved = load_settings_from(&file).unwrap(); + assert_eq!(saved.active_game, GameId::Deadlock); + assert_eq!(saved.tf2_root, "D:/tf2"); + assert!(saved.deadlock_root.contains("Deadlock")); + + assert_eq!(unavailable_deadlock_root_from(&file), None); + fs::remove_file(deadlock.join("game/citadel/steam.inf")).unwrap(); + assert_eq!(remembered_deadlock_root_from(&file), None); + assert_eq!( + unavailable_deadlock_root_from(&file), + Some(saved.deadlock_root) + ); + let _ = fs::remove_dir_all(&dir); + } } diff --git a/apps/desktop/src-tauri/core/src/steam_inf.rs b/apps/desktop/src-tauri/core/src/steam_inf.rs index a1a80061..73d37e5f 100644 --- a/apps/desktop/src-tauri/core/src/steam_inf.rs +++ b/apps/desktop/src-tauri/core/src/steam_inf.rs @@ -1,4 +1,4 @@ -//! Valve `steam.inf` reader. Confirm TF2 with app 440 — never write this file. +//! Valve `steam.inf` reader. Confirm TF2 (440) or Deadlock (1422450) — never write this file. use std::collections::HashMap; @@ -21,15 +21,27 @@ pub fn steam_inf_app_id(text: &str) -> Option { parse_steam_inf(text).get("appid").cloned() } +pub fn steam_inf_client_version(text: &str) -> Option { + parse_steam_inf(text) + .get("clientversion") + .filter(|value| !value.is_empty()) + .cloned() +} + pub fn is_tf2_steam_inf(text: &str) -> bool { steam_inf_app_id(text).as_deref() == Some("440") } +pub fn is_deadlock_steam_inf(text: &str) -> bool { + steam_inf_app_id(text).as_deref() == Some("1422450") +} + #[cfg(test)] mod tests { use super::*; const VALVE: &str = "PatchVersion=105.0.0\nProductName=tf\nappID=440\nServerAppID=232250\n"; + const DEADLOCK: &str = "ClientVersion=6895\nServerVersion=6895\nProductName=citadel\nappID=1422450\nServerAppID=1422460\n"; #[test] fn accepts_tf2_app_id_any_case() { @@ -38,10 +50,22 @@ mod tests { assert!(is_tf2_steam_inf("AppID=440\n")); } + #[test] + fn accepts_deadlock_steam_inf_and_reads_client_version() { + assert!(is_deadlock_steam_inf(DEADLOCK)); + assert!(!is_tf2_steam_inf(DEADLOCK)); + assert_eq!(steam_inf_app_id(DEADLOCK).as_deref(), Some("1422450")); + assert_eq!(steam_inf_client_version(DEADLOCK).as_deref(), Some("6895")); + assert_eq!(steam_inf_client_version("ClientVersion=\n"), None); + } + #[test] fn rejects_other_apps_and_missing_id() { assert!(!is_tf2_steam_inf("appID=730\n")); + assert!(!is_deadlock_steam_inf("appID=440\n")); assert!(!is_tf2_steam_inf("ProductName=tf\n")); + assert!(!is_deadlock_steam_inf("ProductName=citadel\n")); assert!(!is_tf2_steam_inf("")); + assert!(!is_deadlock_steam_inf("")); } } diff --git a/apps/desktop/src-tauri/core/src/storage.rs b/apps/desktop/src-tauri/core/src/storage.rs index 105cc413..352e20b6 100644 --- a/apps/desktop/src-tauri/core/src/storage.rs +++ b/apps/desktop/src-tauri/core/src/storage.rs @@ -120,11 +120,15 @@ fn classify(data_dir: &Path, path: &Path) -> StorageGroupId { | "preloader/gameinfo.original.txt" | "preloader/state.json" => StorageGroupId::Protected, _ if name == format!("preloader/mods-{MODS_RELEASE}.zip") => StorageGroupId::Protected, + "deadlock/profiles" | "deadlock/blobs" => StorageGroupId::Profiles, + "deadlock/restore-points" => StorageGroupId::RestorePoints, + "deadlock/caches" => StorageGroupId::Downloads, + "deadlock/gameinfo-stock" => StorageGroupId::Protected, _ => StorageGroupId::Other, } } -/// The entries to classify: top-level items, with the two mixed folders split. +/// The entries to classify: top-level items, with mixed folders split. fn entries(data_dir: &Path) -> io::Result> { let mut out = Vec::new(); for entry in fs::read_dir(data_dir)? { @@ -136,7 +140,7 @@ fn entries(data_dir: &Path) -> io::Result> { let is_dir = fs::symlink_metadata(&path) .map(|meta| meta.is_dir() && !metadata_is_link(&meta)) .unwrap_or(false); - if is_dir && (name == "preloader" || name == "hitsound-cache") { + if is_dir && (name == "preloader" || name == "hitsound-cache" || name == "deadlock") { match fs::read_dir(&path) { Ok(children) => { for child in children.flatten() { @@ -408,4 +412,32 @@ mod tests { fs::remove_dir_all(dir).unwrap(); fs::remove_dir_all(outside).unwrap(); } + + #[test] + fn classifies_and_clears_deadlock_storage() { + let dir = crate::test_temp_dir(); + write(&dir, "deadlock/profiles/a/manifest.json", 120); + write(&dir, "deadlock/blobs/abc.vpk", 80); + write(&dir, "deadlock/restore-points/0123.zip", 45); + write(&dir, "deadlock/caches/gamebanana.json", 80); + write(&dir, "deadlock/gameinfo-stock/6895.gi", 30); + write(&dir, "deadlock/unknown.bin", 15); + + let report = inspect_storage(&dir).unwrap(); + assert_eq!(group(&report, StorageGroupId::Profiles).bytes, 200); + assert_eq!(group(&report, StorageGroupId::RestorePoints).bytes, 45); + assert_eq!(group(&report, StorageGroupId::Downloads).bytes, 80); + assert_eq!(group(&report, StorageGroupId::Protected).bytes, 30); + assert_eq!(group(&report, StorageGroupId::Other).bytes, 15); + + let cleared = clear_download_caches(&dir).unwrap(); + assert_eq!(cleared.freed_bytes, 80); + assert!(!dir.join("deadlock/caches").exists()); + assert!(dir.join("deadlock/profiles/a/manifest.json").is_file()); + assert!(dir.join("deadlock/blobs/abc.vpk").is_file()); + assert!(dir.join("deadlock/restore-points/0123.zip").is_file()); + assert!(dir.join("deadlock/gameinfo-stock/6895.gi").is_file()); + assert!(dir.join("deadlock/unknown.bin").is_file()); + fs::remove_dir_all(dir).unwrap(); + } } diff --git a/apps/desktop/src-tauri/src/commands/app_settings.rs b/apps/desktop/src-tauri/src/commands/app_settings.rs index 94b1b07b..95547ad9 100644 --- a/apps/desktop/src-tauri/src/commands/app_settings.rs +++ b/apps/desktop/src-tauri/src/commands/app_settings.rs @@ -1,6 +1,9 @@ //! Global app-data preferences, independent of profiles and the TF2 write lock. -use execs_core::settings::{app_preferences_from, set_app_preferences_to, AppPreferences}; +use execs_core::settings::{ + read_settings_from, set_active_game_to, set_app_preferences_to, AppPreferences, +}; +use execs_core::GameId; use serde::Serialize; use super::shared::{blocking, with_root, RootContext}; @@ -13,18 +16,26 @@ use tauri_plugin_dialog::DialogExt; pub struct AppSettingsPayload { preferences: AppPreferences, data_directory: String, + active_game: GameId, +} + +fn load_payload(data_dir: &std::path::Path) -> Result { + let settings_path = data_dir.join("settings.json"); + let settings = read_settings_from(&settings_path) + .map_err(|err| CommandError::new("AppSettingsRead", err))? + .unwrap_or_default(); + Ok(AppSettingsPayload { + preferences: settings.preferences, + data_directory: execs_core::finder::user_path_string(data_dir), + active_game: settings.active_game, + }) } #[tauri::command] pub async fn get_app_settings() -> Result { blocking(|| { let data_dir = execs_core::try_execs_data_dir().map_err(CommandError::unknown)?; - let preferences = app_preferences_from(&data_dir.join("settings.json")) - .map_err(|err| CommandError::new("AppSettingsRead", err))?; - Ok(AppSettingsPayload { - preferences, - data_directory: execs_core::finder::user_path_string(&data_dir), - }) + load_payload(&data_dir) }) .await } @@ -39,12 +50,24 @@ pub async fn set_app_preferences( let _guard = gate.writes.lock().await; blocking(move || { let data_dir = execs_core::try_execs_data_dir().map_err(CommandError::unknown)?; - let preferences = set_app_preferences_to(&data_dir.join("settings.json"), preferences) + let _ = set_app_preferences_to(&data_dir.join("settings.json"), preferences) + .map_err(|err| CommandError::new("AppSettingsWrite", err))?; + load_payload(&data_dir) + }) + .await +} + +#[tauri::command] +pub async fn set_active_game( + gate: tauri::State<'_, WriteGate>, + game: GameId, +) -> Result { + let _guard = gate.writes.lock().await; + blocking(move || { + let data_dir = execs_core::try_execs_data_dir().map_err(CommandError::unknown)?; + set_active_game_to(&data_dir.join("settings.json"), game) .map_err(|err| CommandError::new("AppSettingsWrite", err))?; - Ok(AppSettingsPayload { - preferences, - data_directory: execs_core::finder::user_path_string(&data_dir), - }) + load_payload(&data_dir) }) .await } diff --git a/apps/desktop/src-tauri/src/commands/deadlock.rs b/apps/desktop/src-tauri/src/commands/deadlock.rs new file mode 100644 index 00000000..b2fa92e1 --- /dev/null +++ b/apps/desktop/src-tauri/src/commands/deadlock.rs @@ -0,0 +1,609 @@ +//! Deadlock profile, `gameinfo.gi`, mod addon, launch-option, and cfg IPC commands. + +use std::collections::VecDeque; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use execs_core::mods::MAX_MOD_BYTES; +use execs_core::{ + DeadlockArchiveVpkEntry, DeadlockCfgFile, DeadlockLaunchSyncStatus, DeadlockLibrary, + DeadlockModSource, DeadlockProfileDetail, DeadlockSetLaunchResult, DeadlockStagedVpk, + ProfileError, +}; +use serde::Serialize; +use tauri::AppHandle; +use tauri_plugin_dialog::DialogExt; + +use super::shared::blocking; +use crate::error::CommandError; +use crate::gamebanana::{self, FileUse, GameBananaSection}; +use crate::WriteGate; + +const MAX_STAGED_ARCHIVES: usize = 4; + +#[derive(Default)] +pub struct PendingDeadlockModInstall(Mutex>); + +struct StagedDeadlockArchive { + root: PathBuf, + profile_id: String, + source: DeadlockModSource, + entries: Vec, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum DeadlockModInstallOutcome { + Installed { + detail: DeadlockProfileDetail, + }, + ChooseVpks { + #[serde(rename = "stagingId")] + staging_id: String, + #[serde(rename = "archiveName")] + archive_name: String, + #[serde(rename = "displayName")] + display_name: String, + entries: Vec, + }, +} + +fn push_staged_archive( + pending: &PendingDeadlockModInstall, + staged: StagedDeadlockArchive, +) -> String { + let staging_id = execs_core::hash::random_token(); + let mut queue = pending + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + while queue.len() >= MAX_STAGED_ARCHIVES { + queue.pop_front(); + } + queue.push_back((staging_id.clone(), staged)); + staging_id +} + +fn take_staged_archive( + pending: &PendingDeadlockModInstall, + staging_id: &str, +) -> Option { + let mut queue = pending + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let idx = queue.iter().position(|(id, _)| id == staging_id)?; + queue.remove(idx).map(|(_, item)| item) +} + +fn confirmed_deadlock_root() -> Result { + execs_core::remembered_deadlock_root().ok_or_else(|| { + CommandError::new( + "NoConfirmedRoot", + "Confirm a Deadlock install folder first.", + ) + }) +} + +fn active_deadlock_profile_id(root: &Path) -> Result { + let lib = execs_core::load_deadlock_library(root).map_err(map_deadlock_err)?; + lib.active_profile_id + .ok_or_else(|| CommandError::unknown("Save or switch to a Deadlock profile first.")) +} + +fn map_deadlock_err(err: ProfileError) -> CommandError { + if execs_core::deadlock::profiles::is_pgi_mismatch_error(&err) { + CommandError::new("GameInfoVersionMismatch", err.message()) + } else { + err.into() + } +} + +#[tauri::command] +pub async fn get_deadlock_library() -> Result { + blocking(|| { + let root = confirmed_deadlock_root()?; + execs_core::load_deadlock_library(&root).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn get_deadlock_profile_detail() -> Result, CommandError> { + blocking(|| { + let root = confirmed_deadlock_root()?; + let lib = execs_core::load_deadlock_library(&root).map_err(map_deadlock_err)?; + let Some(active_id) = lib.active_profile_id else { + return Ok(None); + }; + execs_core::load_deadlock_profile_detail(&root, &active_id) + .map(Some) + .map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn capture_deadlock_profile( + gate: tauri::State<'_, WriteGate>, + name: String, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + execs_core::capture_deadlock_profile(&root, &name).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn create_deadlock_profile( + gate: tauri::State<'_, WriteGate>, + name: String, + activate: bool, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + execs_core::create_deadlock_profile(&root, &name, activate).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn switch_deadlock_profile( + gate: tauri::State<'_, WriteGate>, + id: String, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + execs_core::switch_deadlock_profile(&root, &id).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn rename_deadlock_profile( + gate: tauri::State<'_, WriteGate>, + id: String, + name: String, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + execs_core::rename_deadlock_profile(&root, &id, &name).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn delete_deadlock_profile( + gate: tauri::State<'_, WriteGate>, + id: String, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + execs_core::delete_deadlock_profile(&root, &id).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn adopt_deadlock_live_gameinfo( + gate: tauri::State<'_, WriteGate>, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(|| { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::adopt_deadlock_live_gameinfo(&root, &profile_id).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn reset_deadlock_profile_gameinfo_to_stock( + gate: tauri::State<'_, WriteGate>, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(|| { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::reset_deadlock_profile_gameinfo_to_stock(&root, &profile_id) + .map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn install_deadlock_gamebanana_mod( + gate: tauri::State<'_, WriteGate>, + pending: tauri::State<'_, PendingDeadlockModInstall>, + id: u64, + file_id: u64, + section: Option, +) -> Result { + let section = GameBananaSection::parse(section.as_deref())?; + let (started_root, started_profile) = blocking(|| { + execs_core::refuse_if_deadlock_running()?; + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + Ok((root, profile_id)) + }) + .await?; + + let (profile, pick, bytes) = blocking(move || { + let profile = + gamebanana::submission_profile_for_game(gamebanana::DEADLOCK_GAME_ID, section, id)?; + let pick = gamebanana::download_file_in(section, id, file_id, FileUse::Pack)?; + let bytes = gamebanana::download_pick(&pick)?; + Ok((profile, pick, bytes)) + }) + .await?; + + let _guard = gate.lock_for_write().await?; + let pending_ref = pending.inner(); + let file_name = pick.file_name.clone(); + let display_name = profile.name.clone(); + let section_name = match section { + GameBananaSection::Mod => "mod", + GameBananaSection::Sound => "sound", + } + .to_string(); + let source = DeadlockModSource::GameBanana { + id, + section: section_name, + file_id, + file_name: file_name.clone(), + page_url: profile.url, + author: profile.author, + version: None, + }; + + let staged = blocking(move || { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + if root != started_root || profile_id != started_profile { + return Err(CommandError::new( + "ProfileChanged", + "The active Deadlock profile changed while that download was running. Try again.", + )); + } + let variant_label = (!pick.description.is_empty()).then_some(pick.description.as_str()); + let entries = execs_core::inspect_deadlock_mod_payload( + &file_name, + &bytes, + Some(&profile.name), + variant_label, + ) + .map_err(map_deadlock_err)?; + Ok((root, profile_id, file_name, entries)) + }) + .await?; + + let (root, profile_id, file_name, entries) = staged; + if entries.len() == 1 { + let title = entries[0].entry.title.clone(); + let selected_paths = vec![entries[0].entry.archive_path.clone()]; + let detail = blocking(move || { + execs_core::install_deadlock_staged_vpks( + &root, + &profile_id, + &entries, + &selected_paths, + source, + ) + .map_err(map_deadlock_err) + }) + .await?; + execs_core::activity_log::record("done", &format!("Installed Deadlock mod {title}")); + return Ok(DeadlockModInstallOutcome::Installed { detail }); + } + + let public_entries: Vec = + entries.iter().map(|item| item.entry.clone()).collect(); + let staging_id = push_staged_archive( + pending_ref, + StagedDeadlockArchive { + root, + profile_id, + source, + entries, + }, + ); + Ok(DeadlockModInstallOutcome::ChooseVpks { + staging_id, + archive_name: file_name, + display_name, + entries: public_entries, + }) +} + +#[tauri::command] +pub async fn import_deadlock_mod_dialog( + app: AppHandle, + gate: tauri::State<'_, WriteGate>, + pending: tauri::State<'_, PendingDeadlockModInstall>, +) -> Result, CommandError> { + let (started_root, started_profile) = blocking(|| { + execs_core::refuse_if_deadlock_running()?; + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + Ok((root, profile_id)) + }) + .await?; + + let picked = tauri::async_runtime::spawn_blocking(move || { + app.dialog() + .file() + .set_title("Import Deadlock mod") + .add_filter("Deadlock mods", &["vpk", "zip", "7z", "rar"]) + .blocking_pick_file() + }) + .await + .map_err(|err| CommandError::unknown(err.to_string()))?; + + let Some(picked) = picked else { + return Ok(None); + }; + let path = picked + .into_path() + .map_err(|err| CommandError::unknown(err.to_string()))?; + + let _guard = gate.lock_for_write().await?; + let pending_ref = pending.inner(); + let (root, profile_id, file_name, entries) = blocking(move || { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + if root != started_root || profile_id != started_profile { + return Err(CommandError::new( + "ProfileChanged", + "The active Deadlock profile changed while choosing that file. Try again.", + )); + } + let meta = + std::fs::metadata(&path).map_err(|err| CommandError::unknown(err.to_string()))?; + if meta.len() > MAX_MOD_BYTES { + return Err(CommandError::unknown( + execs_core::mods::oversized_mod_message(Some(meta.len())), + )); + } + let file_name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("mod.vpk") + .to_string(); + let bytes = std::fs::read(&path).map_err(|err| CommandError::unknown(err.to_string()))?; + let entries = execs_core::inspect_deadlock_mod_payload(&file_name, &bytes, None, None) + .map_err(map_deadlock_err)?; + Ok((root, profile_id, file_name, entries)) + }) + .await?; + + let source = DeadlockModSource::Local { + file_name: file_name.clone(), + }; + if entries.len() == 1 { + let title = entries[0].entry.title.clone(); + let selected_paths = vec![entries[0].entry.archive_path.clone()]; + let detail = blocking(move || { + execs_core::install_deadlock_staged_vpks( + &root, + &profile_id, + &entries, + &selected_paths, + source, + ) + .map_err(map_deadlock_err) + }) + .await?; + execs_core::activity_log::record("done", &format!("Imported Deadlock mod {title}")); + return Ok(Some(DeadlockModInstallOutcome::Installed { detail })); + } + + let public_entries: Vec = + entries.iter().map(|item| item.entry.clone()).collect(); + let display_name = Path::new(&file_name) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or(&file_name) + .to_string(); + let staging_id = push_staged_archive( + pending_ref, + StagedDeadlockArchive { + root, + profile_id, + source, + entries, + }, + ); + Ok(Some(DeadlockModInstallOutcome::ChooseVpks { + staging_id, + archive_name: file_name, + display_name, + entries: public_entries, + })) +} + +#[tauri::command] +pub async fn confirm_deadlock_staged_mod( + gate: tauri::State<'_, WriteGate>, + pending: tauri::State<'_, PendingDeadlockModInstall>, + staging_id: String, + selected_paths: Vec, +) -> Result { + if selected_paths.is_empty() { + return Err(CommandError::unknown( + "Select at least one .vpk to install.", + )); + } + let _guard = gate.lock_for_write().await?; + let Some(staged) = take_staged_archive(pending.inner(), &staging_id) else { + return Err(CommandError::new( + "ImportReviewExpired", + "That mod selection expired. Download or import the archive again.", + )); + }; + let count = selected_paths.len(); + let detail = blocking(move || { + execs_core::refuse_if_deadlock_running()?; + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + if root != staged.root || profile_id != staged.profile_id { + return Err(CommandError::new( + "ProfileChanged", + "The active Deadlock profile changed before those files were installed. Try again.", + )); + } + execs_core::install_deadlock_staged_vpks( + &root, + &profile_id, + &staged.entries, + &selected_paths, + staged.source, + ) + .map_err(map_deadlock_err) + }) + .await?; + execs_core::activity_log::record( + "done", + &format!("Installed {count} Deadlock mod(s) from archive"), + ); + Ok(detail) +} + +#[tauri::command] +pub async fn cancel_deadlock_staged_mod( + pending: tauri::State<'_, PendingDeadlockModInstall>, + staging_id: String, +) -> Result<(), CommandError> { + let _ = take_staged_archive(pending.inner(), &staging_id); + Ok(()) +} + +#[tauri::command] +pub async fn set_deadlock_mod_enabled( + gate: tauri::State<'_, WriteGate>, + mod_id: String, + enabled: bool, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::set_deadlock_mod_enabled(&root, &profile_id, &mod_id, enabled) + .map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn reorder_deadlock_mods( + gate: tauri::State<'_, WriteGate>, + mod_ids: Vec, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::reorder_deadlock_mods(&root, &profile_id, &mod_ids).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn remove_deadlock_mod( + gate: tauri::State<'_, WriteGate>, + mod_id: String, +) -> Result { + let _guard = gate.lock_for_write().await?; + let detail = blocking(move || { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::remove_deadlock_mod(&root, &profile_id, &mod_id).map_err(map_deadlock_err) + }) + .await?; + execs_core::activity_log::record("done", "Removed Deadlock mod"); + Ok(detail) +} + +#[tauri::command] +pub async fn get_deadlock_launch_sync_status() -> Result { + blocking(|| { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::deadlock_launch_sync_status(&profile_id).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn set_deadlock_launch_options( + gate: tauri::State<'_, WriteGate>, + options: String, + write_steam: bool, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::set_deadlock_launch_options(&profile_id, &options, write_steam) + .map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn adopt_deadlock_steam_launch_options( + gate: tauri::State<'_, WriteGate>, +) -> Result { + let _guard = gate.lock_for_write().await?; + blocking(|| { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::adopt_deadlock_steam_launch_options(&profile_id).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn get_deadlock_cfg_files() -> Result, CommandError> { + blocking(|| { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::read_deadlock_cfg_files(&root, &profile_id).map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn save_deadlock_cfg_file( + gate: tauri::State<'_, WriteGate>, + path: String, + text: String, +) -> Result, CommandError> { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::save_deadlock_cfg_file(&root, &profile_id, &path, &text) + .map_err(map_deadlock_err) + }) + .await +} + +#[tauri::command] +pub async fn delete_deadlock_cfg_file( + gate: tauri::State<'_, WriteGate>, + path: String, +) -> Result, CommandError> { + let _guard = gate.lock_for_write().await?; + blocking(move || { + let root = confirmed_deadlock_root()?; + let profile_id = active_deadlock_profile_id(&root)?; + execs_core::delete_deadlock_cfg_file(&root, &profile_id, &path).map_err(map_deadlock_err) + }) + .await +} diff --git a/apps/desktop/src-tauri/src/commands/finder.rs b/apps/desktop/src-tauri/src/commands/finder.rs index 8dafa5a1..246ceac1 100644 --- a/apps/desktop/src-tauri/src/commands/finder.rs +++ b/apps/desktop/src-tauri/src/commands/finder.rs @@ -1,8 +1,8 @@ -//! Finding, confirming and locking the TF2 install. +//! Finding, confirming and locking the TF2 and Deadlock installs. use std::path::Path; -use execs_core::{Tf2Install, WriteLock}; +use execs_core::{DeadlockInstall, GameId, Tf2Install, WriteLock}; use tauri::AppHandle; use tauri_plugin_dialog::DialogExt; @@ -73,3 +73,82 @@ pub async fn get_missing_tf2_root() -> Result, CommandError> { pub async fn tf2_write_lock() -> Result { blocking(|| Ok(execs_core::write_lock_status())).await } + +fn deadlock_install_from_root(root: &Path) -> DeadlockInstall { + DeadlockInstall { + path: root.to_string_lossy().into_owned(), + client_version: execs_core::read_deadlock_client_version(root), + } +} + +#[tauri::command] +pub async fn scan_deadlock_installs() -> Result, CommandError> { + blocking(|| Ok(execs_core::scan_deadlock_installs())).await +} + +#[tauri::command] +pub async fn browse_deadlock_root(app: AppHandle) -> Result, CommandError> { + let picked = tauri::async_runtime::spawn_blocking(move || { + app.dialog() + .file() + .set_title("Pick Deadlock") + .blocking_pick_folder() + }) + .await + .map_err(|err| CommandError::unknown(err.to_string()))?; + let Some(picked) = picked else { + return Ok(None); + }; + let path = picked + .into_path() + .map_err(|err| CommandError::unknown(err.to_string()))?; + let root = execs_core::normalize_deadlock_root(&path)?; + Ok(Some(deadlock_install_from_root(&root))) +} + +#[tauri::command] +pub async fn confirm_deadlock_root( + gate: tauri::State<'_, WriteGate>, + path: String, +) -> Result { + let _guard = gate.lock_for_interrupted_recovery().await?; + blocking(move || { + let root = execs_core::remember_deadlock_root(Path::new(&path))?; + Ok(deadlock_install_from_root(&root)) + }) + .await +} + +#[tauri::command] +pub async fn get_deadlock_root() -> Result, CommandError> { + blocking(|| Ok(execs_core::remembered_deadlock_root().map(|p| deadlock_install_from_root(&p)))) + .await +} + +#[tauri::command] +pub async fn get_missing_deadlock_root() -> Result, CommandError> { + blocking(|| Ok(execs_core::unavailable_deadlock_root())).await +} + +#[tauri::command] +pub async fn deadlock_write_lock() -> Result { + blocking(|| Ok(execs_core::write_lock_status_for(GameId::Deadlock))).await +} + +#[tauri::command] +pub async fn launch_deadlock(gate: tauri::State<'_, WriteGate>) -> Result<(), CommandError> { + let _guard = gate.lock_for_interrupted_recovery().await?; + blocking(|| { + if execs_core::remembered_deadlock_root().is_none() { + return Err(CommandError::new( + "NoConfirmedRoot", + "Choose your Deadlock folder first.", + )); + } + execs_core::refuse_if_deadlock_running()?; + crate::external_open::open_url(GameId::Deadlock.steam_rungame_url()) + .map_err(|err| CommandError::unknown(err.to_string()))?; + Ok(()) + }) + .await +} diff --git a/apps/desktop/src-tauri/src/commands/mod.rs b/apps/desktop/src-tauri/src/commands/mod.rs index 9db80863..02d0f75e 100644 --- a/apps/desktop/src-tauri/src/commands/mod.rs +++ b/apps/desktop/src-tauri/src/commands/mod.rs @@ -5,6 +5,7 @@ pub mod app_settings; pub mod comfig; pub mod compare; pub mod crosshair; +pub mod deadlock; pub mod diagnostics; pub mod files; pub mod finder; @@ -53,9 +54,10 @@ pub async fn open_embedded_page(app: AppHandle, page: String) -> Result<(), Comm let url: tauri::Url = url .parse() .map_err(|_| CommandError::unknown("Invalid URL."))?; - tauri::WebviewWindowBuilder::new(&app, label, tauri::WebviewUrl::External(url)) + let window = tauri::WebviewWindowBuilder::new(&app, label, tauri::WebviewUrl::External(url)) .title(title) .inner_size(1160.0, 820.0) + .decorations(!crate::should_disable_linux_decorations()) .background_color(tauri::window::Color(18, 18, 18, 255)) // The window has no IPC, but remote pages still need an exact // navigation boundary. Separate window requests are denied below. @@ -66,6 +68,7 @@ pub async fn open_embedded_page(app: AppHandle, page: String) -> Result<(), Comm .on_new_window(|_, _| tauri::webview::NewWindowResponse::Deny) .build() .map_err(|err| CommandError::unknown(err.to_string()))?; + crate::configure_window_decorations(&window); Ok(()) } diff --git a/apps/desktop/src-tauri/src/commands/mods.rs b/apps/desktop/src-tauri/src/commands/mods.rs index e5893725..d7eaf1c8 100644 --- a/apps/desktop/src-tauri/src/commands/mods.rs +++ b/apps/desktop/src-tauri/src/commands/mods.rs @@ -132,7 +132,9 @@ pub async fn check_mod_updates() -> Result, CommandError> { /// bypasses a still-fresh native cache entry without changing the canonical /// request URL. #[tauri::command] +#[allow(clippy::too_many_arguments)] pub async fn search_gamebanana_mods( + game: Option, section: Option, query: String, sort: String, @@ -141,11 +143,13 @@ pub async fn search_gamebanana_mods( include_mature: Option, refresh: Option, ) -> Result { + let game_id = game.unwrap_or_default().gamebanana_game_id(); let include_mature = include_mature.unwrap_or(false); let refresh = refresh.unwrap_or(false); let section = GameBananaSection::parse(section.as_deref())?; blocking(move || { - Ok(gamebanana::search_mods( + Ok(gamebanana::search_mods_for_game( + game_id, section, &query, &sort, @@ -160,11 +164,20 @@ pub async fn search_gamebanana_mods( #[tauri::command] pub async fn gamebanana_mod_categories( + game: Option, section: Option, refresh: Option, ) -> Result, CommandError> { + let game_id = game.unwrap_or_default().gamebanana_game_id(); let section = GameBananaSection::parse(section.as_deref())?; - blocking(move || Ok(gamebanana::categories(section, refresh.unwrap_or(false))?)).await + blocking(move || { + Ok(gamebanana::categories_for_game( + game_id, + section, + refresh.unwrap_or(false), + )?) + }) + .await } /// Show the author's file names and descriptions before a specific file is diff --git a/apps/desktop/src-tauri/src/error.rs b/apps/desktop/src-tauri/src/error.rs index f2cd60bf..14d9e6a0 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -10,7 +10,7 @@ //! existing TS `invokeErrorMessage` already reads a `message` field off an //! object, so the UI keeps working unchanged while `code` becomes available. -use execs_core::{ProfileError, Tf2RootError, WriteLockError}; +use execs_core::{DeadlockRootError, ProfileError, Tf2RootError, WriteLockError}; use serde::Serialize; #[derive(Debug, Clone, PartialEq, Eq, Serialize)] @@ -77,6 +77,12 @@ impl From for CommandError { } } +impl From for CommandError { + fn from(err: DeadlockRootError) -> Self { + Self::new(err.code(), err.message()) + } +} + /// Everything that still speaks in bare strings — the fetch modules, the /// handful of hand-written command sentences — lands here. impl From for CommandError { diff --git a/apps/desktop/src-tauri/src/gamebanana.rs b/apps/desktop/src-tauri/src/gamebanana.rs index a4209eaf..f273516d 100644 --- a/apps/desktop/src-tauri/src/gamebanana.rs +++ b/apps/desktop/src-tauri/src/gamebanana.rs @@ -15,6 +15,7 @@ use serde::{Deserialize, Serialize}; use crate::net::{self, RemoteSource, MIB}; pub const TF2_GAME_ID: u64 = 297; +pub const DEADLOCK_GAME_ID: u64 = 20948; const API: &str = "https://gamebanana.com/apiv11"; @@ -299,6 +300,8 @@ struct ProfilePage { name: String, #[serde(rename = "_sProfileUrl", default)] profile_url: String, + #[serde(rename = "_aSubmitter", default)] + submitter: Option, #[serde(rename = "_aRootCategory", default)] root_category: Option, /// The immediate category, which tells a HUD apart from other GUI mods. @@ -322,6 +325,7 @@ pub struct GameBananaProfile { pub id: u64, pub name: String, pub url: String, + pub author: Option, pub updated_at: Option, /// `Mod`, `Hud`, or the Sounds slot a hit or kill sound upload is made for. pub route: GameBananaModRoute, @@ -378,6 +382,7 @@ fn index_sort(sort: &str) -> Result<&'static str, String> { /// installability allow-list still has to be checked page by page when no one /// installable category is selected because the API rejects a multi-category /// filter. +#[cfg(test)] pub fn search_mods( section: GameBananaSection, query: &str, @@ -387,9 +392,41 @@ pub fn search_mods( include_mature: bool, refresh: bool, ) -> Result { - let url = search_url(section, query, sort, category, page, include_mature)?; + search_mods_for_game( + TF2_GAME_ID, + section, + query, + sort, + category, + page, + include_mature, + refresh, + ) +} + +#[allow(clippy::too_many_arguments)] +pub fn search_mods_for_game( + game_id: u64, + section: GameBananaSection, + query: &str, + sort: &str, + category: Option, + page: u32, + include_mature: bool, + refresh: bool, +) -> Result { + let url = search_url_for_game( + game_id, + section, + query, + sort, + category, + page, + include_mature, + )?; let (response, cache): (IndexResponse, _) = fetch_json(&url, LIST_TTL, refresh)?; - Ok(page_from( + Ok(page_from_for_game( + game_id, section, response, category, @@ -398,6 +435,7 @@ pub fn search_mods( )) } +#[cfg(test)] fn search_url( section: GameBananaSection, query: &str, @@ -405,12 +443,32 @@ fn search_url( category: Option, page: u32, include_mature: bool, +) -> Result { + search_url_for_game( + TF2_GAME_ID, + section, + query, + sort, + category, + page, + include_mature, + ) +} + +fn search_url_for_game( + game_id: u64, + section: GameBananaSection, + query: &str, + sort: &str, + category: Option, + page: u32, + include_mature: bool, ) -> Result { if page == 0 { return Err("GameBanana pages start at 1.".into()); } let mut url = format!( - "{API}/{}/Index?_nPage={}&_nPerpage={PAGE_SIZE}&_aFilters[Generic_Game]={TF2_GAME_ID}&_sSort={}", + "{API}/{}/Index?_nPage={}&_nPerpage={PAGE_SIZE}&_aFilters[Generic_Game]={game_id}&_sSort={}", section.model(), page, index_sort(sort)? @@ -435,12 +493,31 @@ fn search_url( Ok(url) } +#[cfg(test)] fn page_from( section: GameBananaSection, response: IndexResponse, category: Option, include_mature: bool, cache: GameBananaCacheInfo, +) -> GameBananaPage { + page_from_for_game( + TF2_GAME_ID, + section, + response, + category, + include_mature, + cache, + ) +} + +fn page_from_for_game( + game_id: u64, + section: GameBananaSection, + response: IndexResponse, + category: Option, + include_mature: bool, + cache: GameBananaCacheInfo, ) -> GameBananaPage { // Repeat the server filters defensively, without changing the server's // authoritative order. Only submissions that are actually mods and safe @@ -449,9 +526,9 @@ fn page_from( .records .iter() .filter(|record| record.model.is_empty() || record.model == section.model()) - .map(|record| record_to_mod(section, record)) + .map(|record| record_to_mod_for_game(game_id, section, record)) .filter(|record| category.is_none_or_matches(record)) - .filter(|record| is_browsable_category(&record.category)) + .filter(|record| is_browsable_category_for(game_id, &record.category)) .filter(|record| include_mature || !record.mature) .collect(); let per_page = if response.metadata.per_page == 0 { @@ -502,13 +579,18 @@ impl CategoryFilter for Option { } } -fn record_to_mod(section: GameBananaSection, record: &RawRecord) -> GameBananaMod { +fn record_to_mod_for_game( + game_id: u64, + section: GameBananaSection, + record: &RawRecord, +) -> GameBananaMod { let category = record.root_category.as_ref(); let sub_category = record.sub_category.as_ref(); let category_id = category .and_then(|row| category_id_from_url(&row.profile_url, section)) .unwrap_or(0); - let is_gui = section == GameBananaSection::Mod + let is_gui = game_id == TF2_GAME_ID + && section == GameBananaSection::Mod && (category_id == 1644 || category.is_some_and(|row| row.name.eq_ignore_ascii_case("GUIs"))); GameBananaMod { @@ -527,8 +609,10 @@ fn record_to_mod(section: GameBananaSection, record: &RawRecord) -> GameBananaMo // custom packs; the installer still refuses a payload that is a HUD. route: if is_gui && sub_category.is_some_and(is_hud_category) { GameBananaModRoute::Hud - } else { + } else if game_id == TF2_GAME_ID { sound_slot_route(section, category_id).unwrap_or(GameBananaModRoute::Mod) + } else { + GameBananaModRoute::Mod }, likes: record.likes, views: record.views, @@ -647,18 +731,27 @@ const EXCLUDED_CATEGORIES: [&str; 3] = ["decal tool", "prefabs", "serverside wea /// /// The endpoint refuses a request with no `_sSort`, so `a_to_z` is passed /// explicitly rather than left to a default that does not exist. +#[cfg(test)] pub fn categories( section: GameBananaSection, refresh: bool, +) -> Result, String> { + categories_for_game(TF2_GAME_ID, section, refresh) +} + +pub fn categories_for_game( + game_id: u64, + section: GameBananaSection, + refresh: bool, ) -> Result, String> { let url = format!( - "{API}/{}/Categories?_idGameRow={TF2_GAME_ID}&_sSort=a_to_z", + "{API}/{}/Categories?_idGameRow={game_id}&_sSort=a_to_z", section.model() ); let (raw, _): (Vec, _) = fetch_json(&url, CATEGORY_TTL, refresh)?; Ok(raw .into_iter() - .filter(|category| is_browsable_category(&category.name)) + .filter(|category| is_browsable_category_for(game_id, &category.name)) .map(|category| GameBananaCategory { id: category.id, name: category.name, @@ -671,8 +764,13 @@ pub fn is_excluded_category(name: &str) -> bool { EXCLUDED_CATEGORIES.contains(&lower.as_str()) } +fn is_browsable_category_for(game_id: u64, name: &str) -> bool { + !name.trim().is_empty() && (game_id != TF2_GAME_ID || !is_excluded_category(name)) +} + +#[cfg(test)] fn is_browsable_category(name: &str) -> bool { - !name.trim().is_empty() && !is_excluded_category(name) + is_browsable_category_for(TF2_GAME_ID, name) } fn is_gui_category(category: &CategoryRow) -> bool { @@ -692,61 +790,94 @@ fn is_hud_category(category: &CategoryRow) -> bool { pub fn submission_profile( section: GameBananaSection, id: u64, +) -> Result { + submission_profile_for_game(TF2_GAME_ID, section, id) +} + +pub fn submission_profile_for_game( + game_id: u64, + section: GameBananaSection, + id: u64, ) -> Result { // ProfilePage exposes the immediate category (e.g. Training or HUDs), // not its root. Request the root explicitly so descendants cannot bypass // the same install policy applied to All and search results. let url = format!( - "{API}/{}/{id}?_csvProperties=_idRow,_sName,_sProfileUrl,_aRootCategory,_aCategory,_aGame,_tsDateUpdated", + "{API}/{}/{id}?_csvProperties=_idRow,_sName,_sProfileUrl,_aSubmitter,_aRootCategory,_aCategory,_aGame,_tsDateUpdated", section.model() ); let page: ProfilePage = net::get_json_for(&net::api_client()?, &url, RemoteSource::GameBananaApi) .map_err(|err| format!("Could not read that GameBanana mod ({err})"))?; - profile_from(page, id, section) + profile_from_for_game(game_id, page, id, section) } +#[cfg(test)] fn profile_from( page: ProfilePage, id: u64, section: GameBananaSection, +) -> Result { + profile_from_for_game(TF2_GAME_ID, page, id, section) +} + +fn profile_from_for_game( + game_id: u64, + page: ProfilePage, + id: u64, + section: GameBananaSection, ) -> Result { if page.id != id { return Err("GameBanana returned a different mod than the one requested.".into()); } - if page.game.as_ref().map(|game| game.id) != Some(TF2_GAME_ID) { - return Err("That GameBanana mod is not listed for Team Fortress 2.".into()); + if page.game.as_ref().map(|game| game.id) != Some(game_id) { + let game_name = match game_id { + DEADLOCK_GAME_ID => "Deadlock", + _ => "Team Fortress 2", + }; + return Err(format!( + "That GameBanana mod is not listed for {game_name}." + )); } let category = page .root_category .as_ref() .ok_or("Could not verify that mod's GameBanana category. Try again later.")?; - if !is_browsable_category(&category.name) { + if !is_browsable_category_for(game_id, &category.name) { return Err("That GameBanana category cannot be installed from Mods.".into()); } - let is_hud = section == GameBananaSection::Mod + let is_hud = game_id == TF2_GAME_ID + && section == GameBananaSection::Mod && is_gui_category(category) && is_hud_category( page.category .as_ref() .ok_or("Could not verify that mod's GameBanana category. Try again later.")?, ); - let route = match category_id_from_url(&category.profile_url, section) { - _ if is_hud => GameBananaModRoute::Hud, - Some(category_id) => { - sound_slot_route(section, category_id).unwrap_or(GameBananaModRoute::Mod) - } - // A sound whose category cannot be verified might be a hit or kill - // sound, so it is neither installed as a pack nor offered to Sounds. - None if section == GameBananaSection::Sound => { - return Err( - "Could not verify that sound's GameBanana category. Try again later.".into(), - ) + let route = if game_id != TF2_GAME_ID { + GameBananaModRoute::Mod + } else { + match category_id_from_url(&category.profile_url, section) { + _ if is_hud => GameBananaModRoute::Hud, + Some(category_id) => { + sound_slot_route(section, category_id).unwrap_or(GameBananaModRoute::Mod) + } + // A sound whose category cannot be verified might be a hit or kill + // sound, so it is neither installed as a pack nor offered to Sounds. + None if section == GameBananaSection::Sound => { + return Err( + "Could not verify that sound's GameBanana category. Try again later.".into(), + ) + } + None => GameBananaModRoute::Mod, } - None => GameBananaModRoute::Mod, }; Ok(GameBananaProfile { updated_at: valid_timestamp(page.updated), + author: page + .submitter + .map(|submitter| submitter.name.trim().to_string()) + .filter(|name| !name.is_empty()), name: if page.name.is_empty() { format!("GameBanana {} {id}", section.model().to_ascii_lowercase()) } else { @@ -806,6 +937,7 @@ pub struct GameBananaDownloadVariant { pub struct DownloadPick { pub url: String, pub file_name: String, + pub description: String, } /// The first four bytes of every VPK, v1 or v2: `0x55AA1234` little-endian. @@ -947,6 +1079,7 @@ fn pick_file_by_id( Ok(DownloadPick { url: validated_download_url(chosen).expect("validated above"), file_name: chosen.file.clone(), + description: chosen.description.trim().chars().take(1000).collect(), }) } @@ -1667,8 +1800,15 @@ mod tests { DownloadPick { url: "https://gamebanana.com/dl/2".into(), file_name: "middle.vpk".into(), + description: String::new(), } ); + assert_eq!( + pick_file_by_id(files.clone(), 3, FileUse::Pack) + .unwrap() + .description, + "Class select remake" + ); assert!(pick_file_by_id(files.clone(), 1, FileUse::Pack).is_ok()); assert!(pick_file_by_id(files, 999, FileUse::Pack).is_err()); @@ -2076,6 +2216,7 @@ mod tests { "_idRow": 7, "_sName": "A sound", "_sProfileUrl": "https://gamebanana.com/sounds/7", + "_aSubmitter": { "_sName": " SoundMaker " }, "_aRootCategory": category, "_aGame": { "_idRow": 297 } })) @@ -2088,6 +2229,7 @@ mod tests { "_sName": "Hitsound", "_sProfileUrl": "https://gamebanana.com/sounds/cats/381" })) .unwrap(); + assert_eq!(hit.author.as_deref(), Some("SoundMaker")); assert_eq!(hit.route, GameBananaModRoute::HitSound); assert_eq!(hit.url, "https://gamebanana.com/sounds/7"); assert!(hit.require_pack().unwrap_err().contains("Sounds")); @@ -2140,6 +2282,65 @@ mod tests { .contains("WAV")); } + #[test] + fn deadlock_browsing_and_profiles_use_game_20948_without_tf2_routing() { + let url = search_url_for_game( + DEADLOCK_GAME_ID, + GameBananaSection::Mod, + "calico", + "new", + None, + 1, + false, + ) + .unwrap(); + assert!(url.contains("Generic_Game]=20948")); + + let response: IndexResponse = serde_json::from_value(serde_json::json!({ + "_aRecords": [ + { "_idRow": 10, "_sModelName": "Mod", "_sName": "HUD++", + "_aRootCategory": { "_sName": "GUIs", "_sProfileUrl": "https://gamebanana.com/mods/cats/1644" }, + "_aSubCategory": { "_sName": "HUDs", "_sProfileUrl": "https://gamebanana.com/mods/cats/1649" } }, + { "_idRow": 11, "_sModelName": "Mod", "_sName": "Prefab Pack", + "_aRootCategory": { "_sName": "Prefabs" } } + ] + })) + .unwrap(); + let page = page_from_for_game( + DEADLOCK_GAME_ID, + GameBananaSection::Mod, + response, + None, + false, + network_cache_info(), + ); + assert_eq!(page.records.len(), 2); + assert_eq!(page.records[0].route, GameBananaModRoute::Mod); + assert_eq!(page.records[1].route, GameBananaModRoute::Mod); + + let dl_page: ProfilePage = serde_json::from_value(serde_json::json!({ + "_idRow": 99, + "_sName": "Deadlock Sound", + "_aGame": { "_idRow": 20948 }, + "_aRootCategory": { "_sName": "Skins", "_sProfileUrl": "https://gamebanana.com/sounds/cats/381" } + })) + .unwrap(); + let profile = + profile_from_for_game(DEADLOCK_GAME_ID, dl_page, 99, GameBananaSection::Sound).unwrap(); + assert_eq!(profile.route, GameBananaModRoute::Mod); + + let tf2_page: ProfilePage = serde_json::from_value(serde_json::json!({ + "_idRow": 7, + "_sName": "TF2 Mod", + "_aGame": { "_idRow": 297 }, + "_aRootCategory": { "_sName": "Skins" } + })) + .unwrap(); + let err = profile_from_for_game(DEADLOCK_GAME_ID, tf2_page, 7, GameBananaSection::Mod) + .unwrap_err(); + assert!(err.contains("Deadlock"), "{err}"); + } + /// Hits the live API. Ignored so CI stays offline: /// `cargo test -p execs -- --ignored gamebanana`. #[test] diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index ec9d3a4c..c0b4728c 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -715,6 +715,35 @@ pub fn run() { commands::finder::confirm_tf2_root, commands::finder::get_tf2_root, commands::finder::get_missing_tf2_root, + commands::finder::scan_deadlock_installs, + commands::finder::browse_deadlock_root, + commands::finder::confirm_deadlock_root, + commands::finder::get_deadlock_root, + commands::finder::get_missing_deadlock_root, + commands::finder::deadlock_write_lock, + commands::deadlock::get_deadlock_library, + commands::deadlock::get_deadlock_profile_detail, + commands::deadlock::capture_deadlock_profile, + commands::deadlock::create_deadlock_profile, + commands::deadlock::switch_deadlock_profile, + commands::deadlock::rename_deadlock_profile, + commands::deadlock::delete_deadlock_profile, + commands::deadlock::adopt_deadlock_live_gameinfo, + commands::deadlock::reset_deadlock_profile_gameinfo_to_stock, + commands::deadlock::install_deadlock_gamebanana_mod, + commands::deadlock::import_deadlock_mod_dialog, + commands::deadlock::confirm_deadlock_staged_mod, + commands::deadlock::cancel_deadlock_staged_mod, + commands::deadlock::set_deadlock_mod_enabled, + commands::deadlock::reorder_deadlock_mods, + commands::deadlock::remove_deadlock_mod, + commands::deadlock::get_deadlock_launch_sync_status, + commands::deadlock::set_deadlock_launch_options, + commands::deadlock::adopt_deadlock_steam_launch_options, + commands::deadlock::get_deadlock_cfg_files, + commands::deadlock::save_deadlock_cfg_file, + commands::deadlock::delete_deadlock_cfg_file, + commands::finder::launch_deadlock, commands::app_settings::run_automatic_tidy_up, commands::app_settings::tidy_up_again, commands::finder::tf2_write_lock, @@ -737,6 +766,7 @@ pub fn run() { commands::restore_points::restore_restore_point, commands::app_settings::get_app_settings, commands::app_settings::set_app_preferences, + commands::app_settings::set_active_game, commands::app_settings::get_storage_usage, commands::app_settings::clear_download_caches, commands::app_settings::get_hud_backups, @@ -859,11 +889,18 @@ pub fn run() { } }) .setup(move |app| { + if let Some(window) = app.get_webview_window("main") { + configure_window_decorations(&window); + } restore_window_placement(app); + if let Some(window) = app.get_webview_window("main") { + let _ = window.show(); + } bind_mouse::install(app)?; app.manage(write_gate); app.manage(commands::library::PendingProfileImport::default()); app.manage(commands::mod_import::PendingModImport::default()); + app.manage(commands::deadlock::PendingDeadlockModInstall::default()); app.manage(HitsoundCacheGate::default()); if let Some(token) = restored_launch { spawn_launch_monitor(token, data_dir); @@ -875,6 +912,42 @@ pub fn run() { .expect("error while running execs"); } +/// Suppress GTK3's Wayland headerbar when Hyprland provides server-side titlebars. +#[cfg(any(target_os = "linux", test))] +fn disable_linux_decorations_for_env(hyprland_sig: Option<&std::ffi::OsStr>) -> bool { + hyprland_sig.is_some_and(|value| !value.is_empty()) +} + +pub(crate) fn should_disable_linux_decorations() -> bool { + #[cfg(target_os = "linux")] + { + disable_linux_decorations_for_env( + std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").as_deref(), + ) + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + +pub(crate) fn configure_window_decorations(window: &tauri::WebviewWindow) { + #[cfg(target_os = "linux")] + if should_disable_linux_decorations() { + use gtk::prelude::{GtkWindowExt, WidgetExt}; + let _ = window.set_decorations(false); + if let Ok(gtk_win) = window.gtk_window() { + gtk_win.set_decorated(false); + if let Some(titlebar) = gtk_win.titlebar() { + titlebar.set_no_show_all(true); + titlebar.hide(); + } + } + } + #[cfg(not(target_os = "linux"))] + let _ = window; +} + /// Reopen the main window where it was, unless that monitor is gone. fn restore_window_placement(app: &tauri::App) { let Some(window) = app.get_webview_window("main") else { @@ -939,7 +1012,8 @@ const MAX_CONSECUTIVE_PANICS: u32 = 10; fn spawn_lock_poller(app: AppHandle) { std::thread::spawn(move || { - let mut last = None; + let mut last_tf2 = None; + let mut last_deadlock = None; let mut panics = 0u32; loop { // The whole tick, emit included: an emit panic would otherwise @@ -947,18 +1021,24 @@ fn spawn_lock_poller(app: AppHandle) { // its last value forever. let app = app.clone(); let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let running = execs_core::is_tf2_running(); + let names = execs_core::process_lock::live_process_names(); + let tf2 = execs_core::process_lock::tf2_running_among(&names); + let deadlock = execs_core::process_lock::deadlock_running_among(&names); // Unconditionally on the first tick: the webview subscribes // after `setup` runs, and a change-only emit would drop the // opening state. - if last != Some(running) { - let _ = app.emit("tf2-running", running); + if last_tf2 != Some(tf2) { + let _ = app.emit("tf2-running", tf2); + } + if last_deadlock != Some(deadlock) { + let _ = app.emit("deadlock-running", deadlock); } - running + (tf2, deadlock) })); match outcome { - Ok(running) => { - last = Some(running); + Ok((tf2, deadlock)) => { + last_tf2 = Some(tf2); + last_deadlock = Some(deadlock); panics = 0; } Err(_) => { @@ -967,6 +1047,7 @@ fn spawn_lock_poller(app: AppHandle) { // Say so once, then stop. A stuck lock indicator the // UI knows about beats one it does not. let _ = app.emit("tf2-lock-unavailable", true); + let _ = app.emit("deadlock-lock-unavailable", true); return; } } @@ -976,6 +1057,22 @@ fn spawn_lock_poller(app: AppHandle) { }); } +#[cfg(test)] +mod decoration_tests { + use std::ffi::OsStr; + + use super::disable_linux_decorations_for_env; + + #[test] + fn linux_decorations_are_disabled_only_with_non_empty_hyprland_signature() { + assert!(!disable_linux_decorations_for_env(None)); + assert!(!disable_linux_decorations_for_env(Some(OsStr::new("")))); + assert!(disable_linux_decorations_for_env(Some(OsStr::new( + "sig_123" + )))); + } +} + #[cfg(test)] mod startup_tests { use std::sync::atomic::Ordering; diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 59f9251c..6c9c7924 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -19,6 +19,7 @@ "height": 800, "minWidth": 960, "minHeight": 640, + "visible": false, "zoomHotkeysEnabled": true, "dragDropEnabled": false, "backgroundColor": { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index b9206270..45a5884a 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -11,8 +11,12 @@ import { import { AppSettingsPane } from "./AppSettingsPane"; import { AppFooter } from "./components/AppFooter"; import { BootSplash } from "./components/BootSplash"; +import { DeadlockWorkspace } from "./components/DeadlockWorkspace"; import { DotBackdrop } from "./components/DotBackdrop"; import { FinderPanel } from "./components/FinderPanel"; +import { GameContext } from "./components/GameContext"; +import { GameSwitcher } from "./components/GameSwitcher"; +import { GameSwitchOverlay } from "./components/GameSwitchOverlay"; import { HudOwnershipDialog } from "./components/HudOwnershipDialog"; import { ReadyPanel } from "./components/ReadyPanel/ReadyPanel"; import { ReleaseNotes } from "./components/ReleaseNotes"; @@ -29,6 +33,8 @@ import { FirstRunExisting } from "./FirstRunExisting"; import { useAppPreferences } from "./hooks/useAppPreferences"; import { AppStatusProvider } from "./hooks/useAppStatus"; import { useAppUpdate } from "./hooks/useAppUpdate"; +import { useDeadlockInstall } from "./hooks/useDeadlockInstall"; +import { useDeadlockWriteLock } from "./hooks/useDeadlockWriteLock"; import { useFilesExitGuard } from "./hooks/useFilesExitGuard"; import { useFirstRun } from "./hooks/useFirstRun"; import { useLifecycleStatus } from "./hooks/useLifecycleStatus"; @@ -52,12 +58,16 @@ import { motionHold, revealPane, revealScreen } from "./lib/entrance"; import { createFilesDraftStore } from "./lib/files-drafts"; import { confirmEnabled } from "./lib/finder-ui"; import { firstRunSurface, showStartFromChoice } from "./lib/first-run-ui"; +import type { GameId } from "./lib/game"; import { guideUrl } from "./lib/guide"; import { launchSyncAction, launchSyncWarning } from "./lib/launch-ui"; import { previewSwitchStep } from "./lib/library-ui"; import { type PreviewState, previewCreating, + previewDeadlockModsTask, + previewDeadlockTab, + previewGame, previewSettingsTab, previewUpdateProgress, previewWelcome, @@ -87,6 +97,32 @@ export function App({ bootSplash?: boolean; }) { const { error, setError, dismissError } = useOperationErrors(); + const [activeGame, setActiveGame] = useState(() => previewGame(preview)); + const [gameTransition, setGameTransition] = useState<{ + to: GameId; + phase: "in" | "out"; + } | null>(null); + const transitionTimers = useRef([]); + const activeGameRef = useRef(activeGame); + activeGameRef.current = activeGame; + const activeGameUserSet = useRef(false); + const themeGame = gameTransition?.to ?? activeGame; + useLayoutEffect(() => { + if (themeGame === "deadlock") { + document.documentElement.dataset.game = "deadlock"; + } else { + delete document.documentElement.dataset.game; + } + return () => { + delete document.documentElement.dataset.game; + }; + }, [themeGame]); + useEffect(() => { + return () => { + for (const timer of transitionTimers.current) window.clearTimeout(timer); + transitionTimers.current = []; + }; + }, []); const [splash, setSplash] = useState<"shown" | "leaving" | "gone">(bootSplash ? "shown" : "gone"); const [settingsSettled, setSettingsSettled] = useState(false); // A newly confirmed install stays on the finder for a beat, so the @@ -175,6 +211,7 @@ export function App({ }, [appSettingsOpen, closeAppSettings]); const lock = useWriteLock(api); + const deadlockLock = useDeadlockWriteLock(api); const [filesDraftStore] = useState(createFilesDraftStore); const lifecycle = useLifecycleStatus(api); useEffect(() => { @@ -187,12 +224,17 @@ export function App({ }, [lifecycle.launchWaitExpired, setError]); const progress = useSwitchProgress(api, preview === "switch" ? previewSwitchStep() : null); const appSettings = useAppPreferences(api); + useEffect(() => { + if (activeGameUserSet.current || !appSettings.data) return; + setActiveGame(appSettings.data.activeGame); + }, [appSettings.data]); const update = useAppUpdate(api, { setError, seedProgress: previewUpdateProgress(preview), checkOnStartup: appSettings.data?.preferences.checkForUpdatesOnStartup ?? null, }); const launchPending = launching || lifecycle.launchingTf2; + const [launchingDeadlock, setLaunchingDeadlock] = useState(false); const lifecycleBusy = !lifecycle.available || lifecycle.launchingTf2 || @@ -225,6 +267,77 @@ export function App({ preloaderRecovery || update.progress !== null; + const deadlockInstall = useDeadlockInstall(api, { + enabled: activeGame === "deadlock", + setError, + setBusy, + }); + + const switchGame = useCallback( + (next: GameId) => { + if (next === activeGameRef.current) return; + const run = () => { + const previous = activeGameRef.current; + if (next === previous) return; + activeGameUserSet.current = true; + for (const timer of transitionTimers.current) window.clearTimeout(timer); + transitionTimers.current = []; + + const commitSwitch = () => { + setAppSettingsOpen(false); + dismissError(); + setActiveGame(next); + void api.setActiveGame(next).catch((err) => { + setActiveGame(previous); + setError(invokeErrorMessage(err), "game:switch"); + }); + }; + + if (motionHold(1) === 0) { + setGameTransition(null); + commitSwitch(); + return; + } + + setGameTransition({ to: next, phase: "in" }); + const t1 = window.setTimeout(() => { + commitSwitch(); + }, 290); + const t2 = window.setTimeout(() => { + setGameTransition((curr) => (curr?.to === next ? { to: next, phase: "out" } : curr)); + revealScreen(shell.current, 10, { keepHeader: false }); + }, 390); + const t3 = window.setTimeout(() => { + setGameTransition((curr) => (curr?.to === next ? null : curr)); + }, 690); + transitionTimers.current = [t1, t2, t3]; + }; + if (activeGameRef.current === "tf2") { + filesExit.request(run); + } else { + run(); + } + }, + [api, dismissError, filesExit, setError], + ); + + const gameSwitcher = ( + + ); + + const onboardingGameSwitcher = ( + + ); + const install = useTf2Install(api, { setError, setBusy, @@ -433,6 +546,14 @@ export function App({ // The sidebar holds App settings. Without it (first run, or a ready shell // with no active profile) the footer is the way there. const sidebarShown = readyShellOpen && showSettingsChrome(profiles.library); + const deadlockReady = + activeGame === "deadlock" && + deadlockInstall.screen === "ready" && + deadlockInstall.confirmed !== null; + const deadlockWorkspaceOpen = deadlockReady; + const fullBleedShell = activeGame === "deadlock" ? deadlockWorkspaceOpen : readyShellOpen; + const hideChromeBackdropAndFooter = + activeGame === "deadlock" ? deadlockWorkspaceOpen : sidebarShown; // Startup and a confirmed install each wait for the first screen's reads. const stageInput = { @@ -446,7 +567,13 @@ export function App({ paneLabel: SETTINGS_TAB_LABELS[settingsTab], failed: error !== null, }; - const boot = bootStage(stageInput); + const boot = + activeGame === "deadlock" + ? { + settled: !deadlockInstall.scanning || error !== null, + status: deadlockInstall.scanning ? "Looking for Deadlock…" : "", + } + : bootStage(stageInput); const handoff = bootStage({ ...stageInput, settingsOpen: false }); const bootSettled = boot.settled; useEffect(() => { @@ -476,26 +603,36 @@ export function App({ const screen = splash === "shown" ? "boot" - : appSettingsOpen && !settingsOpen - ? "app" - : !installReady - ? "finder" - : surface === "first-existing" - ? "existing" - : surface === "first-unused" || creating - ? "wizard" - : surface === "loading" - ? "loading" - : settingsOpen - ? "workspace" - : "shell"; + : activeGame === "deadlock" + ? deadlockReady + ? "deadlock-workspace" + : appSettingsOpen + ? "deadlock-app" + : "deadlock-finder" + : appSettingsOpen && !settingsOpen + ? "app" + : !installReady + ? "finder" + : surface === "first-existing" + ? "existing" + : surface === "first-unused" || creating + ? "wizard" + : surface === "loading" + ? "loading" + : settingsOpen + ? "workspace" + : "shell"; const lastScreen = useRef(screen); + const lastGame = useRef(activeGame); useLayoutEffect(() => { const previous = lastScreen.current; + const gameChanged = lastGame.current !== activeGame; lastScreen.current = screen; - if (screen === "boot" || previous === screen) return; - revealScreen(shell.current, previous === "boot" ? 160 : 0); - }, [screen]); + lastGame.current = activeGame; + if (screen === "boot" || (previous === screen && !gameChanged)) return; + if (gameTransition?.phase === "in") return; + revealScreen(shell.current, previous === "boot" ? 160 : 0, { keepHeader: gameChanged }); + }, [screen, activeGame, gameTransition?.phase]); // A profile's settings finishing their read (after a switch) reveal the pane. const wasSettled = useRef(settingsSettled); useLayoutEffect(() => { @@ -541,10 +678,64 @@ export function App({ }); } + function onLaunchDeadlock() { + setLaunchingDeadlock(true); + void api + .launchDeadlock() + .then(() => setError(null, "deadlock:launch")) + .catch((err) => setError(invokeErrorMessage(err), "deadlock:launch")) + .finally(() => { + setLaunchingDeadlock(false); + }); + } + function renderAppPreferences() { + if (activeGame === "deadlock") { + const deadlockBusy = + launchingDeadlock || lifecycle.installingUpdate || update.progress !== null; + return ( + +