diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 7264c83..939c7bf 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1369,11 +1369,17 @@ async fn save_config(app: tauri::AppHandle, mut config: Config) -> Result Result, String> { let config = get_config(app.clone()).await?; - if config.game_dir.is_empty() { return Ok(vec![]); } + let mut backups = Vec::new(); + let title_ids = tauri::async_runtime::spawn_blocking(crate::proxy::get_all_title_ids) + .await + .unwrap_or_default(); + if config.game_dir.is_empty() { + push_title_backups(&mut backups, title_ids); + return Ok(backups); + } let items = get_items(app.clone(), None).await.unwrap_or_default(); let swaps = load_swaps(&app); - let mut backups = Vec::new(); let mut seen_ids = std::collections::HashSet::::new(); // Count how many paint variants exist for each spawned item @@ -1440,9 +1446,27 @@ async fn get_backups(app: tauri::AppHandle) -> Result, String> { }); } + push_title_backups(&mut backups, title_ids); Ok(backups) } +fn push_title_backups(backups: &mut Vec, title_ids: Vec) { + for tid in title_ids { + let label = tid.replace('_', " "); + backups.push(BackupFile { + name: label.clone(), + path: format!("title_{tid}"), + image_url: String::new(), + swap_from: label.clone(), + swap_from_paint: String::new(), + swap_to: label, + swap_to_image: String::new(), + slot: "Player Title".to_string(), + paint_name: String::new(), + }); + } +} + fn integrity_state_path(app: &tauri::AppHandle) -> Result { let dir = app.path().app_config_dir().map_err(|e| e.to_string())?; Ok(integrity::integrity_path(&dir)) @@ -1946,6 +1970,19 @@ async fn clear_spawned_items(app: tauri::AppHandle) -> Result<(), String> { Ok(()) } +#[tauri::command] +async fn spawn_titles(title_ids: Vec) -> Result { + let ids = crate::psynet::clean_title_ids(&title_ids); + if ids.is_empty() { + return Err("No titles selected".into()); + } + let added = tauri::async_runtime::spawn_blocking(move || crate::proxy::register_title_ids(&ids)) + .await + .map_err(|e| format!("Spawn task failed: {e}"))??; + applog::event(&format!("spawn_titles: registered {} new title(s)", added.len())); + Ok(added.len()) +} + #[tauri::command] async fn spawn_items_batch( app: tauri::AppHandle, @@ -2091,6 +2128,15 @@ fn remove_proxy_inventory_items(ids: Option<&[i32]>) -> Result<(), String> { #[tauri::command] async fn restore_single_backup(app: tauri::AppHandle, path: String) -> Result { + if let Some(tid) = path.strip_prefix("title_").map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) { + let removed = tid.clone(); + tauri::async_runtime::spawn_blocking(move || crate::proxy::unregister_title_id(&removed)) + .await + .map_err(|e| format!("Restore task failed: {e}"))??; + record_swap_history(&app, "restore", &[], &format!("restored title {tid}")); + applog::event(&format!("restore_single_backup: removed spawned title {tid}")); + return Ok("Title removed. Restart Rocket League to clear its current inventory cache.".to_string()); + } let id = path.strip_prefix("item_").and_then(|s| s.parse::().ok()) .filter(|id| *id > 0).ok_or("Invalid inventory entry; refresh the list and try again")?; tauri::async_runtime::spawn_blocking(move || { @@ -2109,13 +2155,19 @@ async fn restore_single_backup(app: tauri::AppHandle, path: String) -> Result Result { tauri::async_runtime::spawn_blocking(move || { + let titles = crate::proxy::clear_all_title_ids()?; let count = load_swaps(&app).len(); save_swaps_checked(&app, &[])?; remove_proxy_inventory_items(None)?; crate::proxy::clear_all_swap_files(); record_swap_history(&app, "restore_all", &[], "restored all active items"); - applog::event(&format!("restore_backups: removed {count} entries and cleared loadout wire")); - Ok(format!("Removed {count} item(s). Restart Rocket League to clear its current inventory cache.")) + applog::event(&format!("restore_backups: removed {count} entries and {titles} title(s), cleared loadout wire")); + let summary = match (count, titles) { + (_, 0) => format!("Removed {count} item(s)."), + (0, _) => format!("Removed {titles} title(s)."), + _ => format!("Removed {count} item(s) and {titles} title(s)."), + }; + Ok(format!("{summary} Restart Rocket League to clear its current inventory cache.")) }).await.map_err(|e| format!("Restore task failed: {e}"))? } @@ -3899,6 +3951,7 @@ pub fn run() { let _ = tracker::create_overlay_window(app); psynet::load_proxy_dir_override(app.handle()); + psynet::cleanup_stale_state_files(); let app_handle = app.handle().clone(); let _ = psynet::merge_palette_spoof(load_integrity(app.handle()).palette_active); @@ -4113,6 +4166,7 @@ pub fn run() { apply_swap, spawn_item, spawn_items_batch, + spawn_titles, spawn_drops, make_savedata, reswap_all, diff --git a/src-tauri/src/proxy.rs b/src-tauri/src/proxy.rs index 87bc60f..d70ac51 100644 --- a/src-tauri/src/proxy.rs +++ b/src-tauri/src/proxy.rs @@ -5970,25 +5970,24 @@ fn spawned_title_ids() -> Vec { if cfg!(test) { return Vec::new(); } - let mut ids: Vec = Vec::new(); - let mut push = |id: &str| { - let id = id.trim(); - if !id.is_empty() && id != "custom" && !ids.iter().any(|x| x == id) { - ids.push(id.to_string()); - } - }; - if let Some(cfg) = crate::psynet::load_active_spoof_from_disk() { - if cfg.enabled { - push(&cfg.equip_title_id); - for sw in cfg.swaps.iter().flatten() { - push(if sw.equip_title_id.trim().is_empty() { &sw.display_title_id } else { &sw.equip_title_id }); - } - } - } - for id in get_all_title_ids() { - push(&id); - } - ids + let mut ids = get_all_title_ids(); + ids.extend(crate::psynet::load_title_swap_equip_ids()); + crate::psynet::clean_title_ids(&ids) +} + +fn title_product_json(title_id: &str, timestamp: i64) -> serde_json::Value { + serde_json::json!({ + "ProductID": TITLE_PRODUCT_ID, + "InstanceID": title_instance_id(title_id), + "SeriesID": lookup_series_id_for_product(TITLE_PRODUCT_ID), + "Amount": 1, + "ExpirationTime": -1, + "IsTradable": false, + "TradeHold": -1, + "AddedTimestamp": timestamp, + "UpdatedTimestamp": timestamp, + "Attributes": [{ "Key": "TitleId", "Value": title_id }], + }) } fn title_instance_id(title_id: &str) -> String { @@ -6973,33 +6972,7 @@ pub fn load_active_swap_rules(cfg: Option<&crate::psynet::SpoofPayload>) -> Vec< let mut rules = Vec::new(); let mut seen = std::collections::HashSet::new(); - let mut candidate_paths = vec![ - crate::psynet::config_dir().join("swaps.json"), - ]; - - if let Some(parent) = crate::psynet::config_dir().parent() { - candidate_paths.push(parent.join("swaps.json")); - } - - #[cfg(target_os = "windows")] - { - if let Ok(appdata) = std::env::var("APPDATA") { - candidate_paths.push(std::path::PathBuf::from(&appdata).join("com.velocityrl.app").join("swaps.json")); - candidate_paths.push(std::path::PathBuf::from(&appdata).join("VelocityRL").join("swaps.json")); - } - if let Ok(localappdata) = std::env::var("LOCALAPPDATA") { - candidate_paths.push(std::path::PathBuf::from(&localappdata).join("com.velocityrl.app").join("swaps.json")); - candidate_paths.push(std::path::PathBuf::from(&localappdata).join("VelocityRL").join("swaps.json")); - } - } - - #[cfg(not(target_os = "windows"))] - { - if let Ok(home) = std::env::var("HOME") { - candidate_paths.push(std::path::PathBuf::from(&home).join(".config").join("com.velocityrl.app").join("swaps.json")); - candidate_paths.push(std::path::PathBuf::from(&home).join(".config").join("VelocityRL").join("swaps.json")); - } - } + let candidate_paths = crate::psynet::canonical_swaps_paths(); for entry in load_swap_entries_from_paths(&candidate_paths) { let wid = entry.get("wanted_id").and_then(|v| v.as_i64()).unwrap_or(0) as i32; @@ -7061,12 +7034,6 @@ pub fn load_active_swap_rules(cfg: Option<&crate::psynet::SpoofPayload>) -> Vec< static DYNAMIC_SPAWNED_ITEMS: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); static SPAWNED_ITEMS_INITIALIZED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// Maps title_id string -> title_id string (set semantics) for every title the player owns via -/// VelocityRL inventory injection. Keyed and valued by the same string so we can iterate -/// cheaply and do O(1) lookup. Persisted alongside spawned_items.json via the title_ids.json -/// sidecar file so titles survive restarts. -static DYNAMIC_TITLE_IDS: std::sync::LazyLock>> = - std::sync::LazyLock::new(|| std::sync::RwLock::new(std::collections::HashSet::new())); static CONTAINER_COUNTS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| std::sync::RwLock::new(std::collections::HashMap::new())); @@ -7074,62 +7041,84 @@ fn get_spawned_items_file_path() -> std::path::PathBuf { crate::psynet::config_dir().join("spawned_items.json") } -fn get_title_ids_file_path() -> std::path::PathBuf { +fn get_legacy_title_ids_file_path() -> std::path::PathBuf { crate::psynet::config_dir().join("title_ids.json") } -fn load_persisted_title_ids() -> std::collections::HashSet { - let path = get_title_ids_file_path(); - if let Ok(content) = std::fs::read_to_string(&path) { - if let Ok(ids) = serde_json::from_str::>(&content) { - return ids.into_iter().filter(|s| !s.is_empty()).collect(); +pub fn migrate_legacy_title_ids() { + static DONE: std::sync::Once = std::sync::Once::new(); + DONE.call_once(|| { + if cfg!(test) { + return; } - } - std::collections::HashSet::new() + let path = get_legacy_title_ids_file_path(); + if let Ok(content) = std::fs::read_to_string(&path) { + let legacy: Vec = serde_json::from_str(&content).unwrap_or_default(); + let mut ids = crate::psynet::load_spawned_titles(); + ids.extend(legacy); + if crate::psynet::write_spawned_titles(&ids).is_ok() { + let _ = std::fs::remove_file(&path); + crate::applog::event("proxy: migrated title_ids.json into spoof config spawned_titles"); + } + } + match crate::psynet::migrate_spawn_title_swaps() { + Ok(0) => {} + Ok(n) => crate::applog::event(&format!("proxy: moved {n} spawned title swap(s) into spawned_titles")), + Err(e) => crate::applog::event(&format!("proxy: title swap migration failed: {e}")), + } + }); } -fn save_persisted_title_ids(ids: &std::collections::HashSet) { - let path = get_title_ids_file_path(); - let list: Vec<&String> = ids.iter().collect(); - if let Ok(data) = serde_json::to_string_pretty(&list) { - let _ = std::fs::write(&path, data); +fn store_spawned_titles(ids: &[String]) -> Result<(), String> { + let cfg = crate::psynet::write_spawned_titles(ids)?; + if tokio::runtime::Handle::try_current().is_ok() { + tauri::async_runtime::spawn(set_spoof_config(cfg)); + } else { + tauri::async_runtime::block_on(set_spoof_config(cfg)); } + notify_inventory_updated(); + Ok(()) } -/// Register one or more title IDs as owned by the player (spawned via VelocityRL). -pub fn register_title_ids(ids: &[String]) { - if ids.is_empty() { return; } - if let Ok(mut g) = DYNAMIC_TITLE_IDS.write() { - for id in ids { - if !id.is_empty() { - g.insert(id.clone()); - } - } - save_persisted_title_ids(&g); +/// Adds titles to the spawned set and returns the ones that were not already owned. +pub fn register_title_ids(ids: &[String]) -> Result, String> { + migrate_legacy_title_ids(); + let mut current = crate::psynet::load_spawned_titles(); + let new_ids: Vec = crate::psynet::clean_title_ids(ids) + .into_iter() + .filter(|id| !current.contains(id)) + .collect(); + if new_ids.is_empty() { + return Ok(new_ids); } + current.extend(new_ids.iter().cloned()); + store_spawned_titles(¤t)?; + let push = new_ids.clone(); + tauri::async_runtime::spawn(async move { + if let Err(e) = inject_title_reward_drop(&push).await { + crate::applog::event(&format!("proxy: live title push failed: {e}")); + } + }); + Ok(new_ids) } -/// Remove a title ID from the owned set (called when item is restored). -pub fn unregister_title_id(id: &str) { - if let Ok(mut g) = DYNAMIC_TITLE_IDS.write() { - g.remove(id); - save_persisted_title_ids(&g); - } +pub fn unregister_title_id(id: &str) -> Result<(), String> { + migrate_legacy_title_ids(); + let mut current = crate::psynet::load_spawned_titles(); + current.retain(|t| t != id.trim()); + store_spawned_titles(¤t) } -/// Return a snapshot of all currently owned (spawned) title ID strings. pub fn get_all_title_ids() -> Vec { - DYNAMIC_TITLE_IDS.read() - .map(|g| g.iter().cloned().collect()) - .unwrap_or_default() + migrate_legacy_title_ids(); + crate::psynet::load_spawned_titles() } -/// Clear all spawned title IDs from memory and disk. -fn clear_all_title_ids() { - if let Ok(mut g) = DYNAMIC_TITLE_IDS.write() { - g.clear(); - save_persisted_title_ids(&g); - } +pub fn clear_all_title_ids() -> Result { + migrate_legacy_title_ids(); + let count = crate::psynet::load_spawned_titles().len(); + store_spawned_titles(&[])?; + Ok(count) } fn get_container_counts_file_path() -> std::path::PathBuf { @@ -7275,31 +7264,7 @@ pub fn lookup_product_details(pid: i32) -> (String, String, String) { } pub fn candidate_swaps_paths() -> Vec { - let mut candidate_paths = vec![ - crate::psynet::config_dir().join("swaps.json"), - ]; - if let Some(parent) = crate::psynet::config_dir().parent() { - candidate_paths.push(parent.join("swaps.json")); - } - #[cfg(target_os = "windows")] - { - if let Ok(appdata) = std::env::var("APPDATA") { - candidate_paths.push(std::path::PathBuf::from(&appdata).join("com.velocityrl.app").join("swaps.json")); - candidate_paths.push(std::path::PathBuf::from(&appdata).join("VelocityRL").join("swaps.json")); - } - if let Ok(localappdata) = std::env::var("LOCALAPPDATA") { - candidate_paths.push(std::path::PathBuf::from(&localappdata).join("com.velocityrl.app").join("swaps.json")); - candidate_paths.push(std::path::PathBuf::from(&localappdata).join("VelocityRL").join("swaps.json")); - } - } - #[cfg(not(target_os = "windows"))] - { - if let Ok(home) = std::env::var("HOME") { - candidate_paths.push(std::path::PathBuf::from(&home).join(".config").join("com.velocityrl.app").join("swaps.json")); - candidate_paths.push(std::path::PathBuf::from(&home).join(".config").join("VelocityRL").join("swaps.json")); - } - } - candidate_paths + crate::psynet::canonical_swaps_paths() } pub fn sync_spawned_items_to_swaps(items: &[(i32, i32)]) { @@ -7406,15 +7371,6 @@ fn ensure_spawned_items_loaded() { } } } - // Load persisted title IDs (titles spawned in previous sessions) - let persisted_titles = load_persisted_title_ids(); - if !persisted_titles.is_empty() { - if let Ok(mut g) = DYNAMIC_TITLE_IDS.write() { - for tid in persisted_titles { - g.insert(tid); - } - } - } } } @@ -7505,18 +7461,6 @@ pub async fn inject_reward_drop_with_series(items: &[(i32, i32, i32)]) -> Result if items.is_empty() { return Ok(false); } - let sender_opt = { - if let Ok(g) = CLIENT_WS_SENDER.read() { - g.clone() - } else { - None - } - }; - let Some(sender) = sender_opt else { - crate::applog::event("proxy: no active client WebSocket tunnel to push RewardResult frame"); - return Ok(false); - }; - let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() @@ -7564,6 +7508,21 @@ pub async fn inject_reward_drop_with_series(items: &[(i32, i32, i32)]) -> Result return Ok(false); } + send_reward_result_frame(product_data).await +} + +async fn send_reward_result_frame(product_data: Vec) -> Result { + let sender_opt = CLIENT_WS_SENDER.read().ok().and_then(|g| g.clone()); + let Some(sender) = sender_opt else { + crate::applog::event("proxy: no active client WebSocket tunnel to push RewardResult frame"); + return Ok(false); + }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() as i64; + let count = product_data.len(); + let body_json = serde_json::json!({ "Drops": product_data, "ProductData": product_data, @@ -7589,8 +7548,7 @@ pub async fn inject_reward_drop_with_series(items: &[(i32, i32, i32)]) -> Result ); crate::applog::event(&format!( - "proxy: injecting live Reward/RewardResult frame for {} spawned items downstream over WebSocket", - items.len() + "proxy: injecting live Reward/RewardResult frame for {count} product(s) downstream over WebSocket" )); sender @@ -7600,6 +7558,18 @@ pub async fn inject_reward_drop_with_series(items: &[(i32, i32, i32)]) -> Result Ok(true) } +pub async fn inject_title_reward_drop(title_ids: &[String]) -> Result { + if title_ids.is_empty() { + return Ok(false); + } + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() as i64; + let product_data = title_ids.iter().map(|t| title_product_json(t, now)).collect(); + send_reward_result_frame(product_data).await +} + pub async fn inject_reward_drop(items: &[(i32, i32)]) -> Result { let items_with_series: Vec<(i32, i32, i32)> = items .iter() @@ -8621,18 +8591,7 @@ pub fn patch_player_products_json_with_titles( if arr.iter().any(|it| item_title_id(it) == Some(tid.as_str())) { continue; } - arr.push(serde_json::json!({ - "ProductID": TITLE_PRODUCT_ID, - "InstanceID": title_instance_id(tid), - "SeriesID": lookup_series_id_for_product(TITLE_PRODUCT_ID), - "Amount": 1, - "ExpirationTime": -1, - "IsTradable": false, - "TradeHold": -1, - "AddedTimestamp": 1700000000i64, - "UpdatedTimestamp": 1700000000i64, - "Attributes": [{ "Key": "TitleId", "Value": tid }], - })); + arr.push(title_product_json(tid, 1700000000)); changed = true; } diff --git a/src-tauri/src/psynet.rs b/src-tauri/src/psynet.rs index b412a91..d443a19 100644 --- a/src-tauri/src/psynet.rs +++ b/src-tauri/src/psynet.rs @@ -336,6 +336,8 @@ pub struct SpoofPayload { pub title_color: Option, #[serde(default)] pub swaps: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spawned_titles: Option>, #[serde(default = "default_method")] pub method: String, } @@ -456,6 +458,7 @@ pub fn default_spoof_payload() -> SpoofPayload { category: "RLCS_Champion".into(), title_color: None, }]), + spawned_titles: None, method: "raw".into(), } } @@ -708,6 +711,188 @@ fn resolve_swaps(payload: &SpoofPayload) -> Option> { }]) } +/// Roaming-only locations VelocityRL keeps swaps.json. Both are %APPDATA% dirs +/// (the proxy config dir and the Tauri identifier dir); LOCALAPPDATA and bare-parent +/// copies are legacy and purged by cleanup_stale_state_files(). +pub fn canonical_swaps_paths() -> Vec { + let mut paths = vec![config_dir().join("swaps.json")]; + #[cfg(windows)] + if let Some(appdata) = std::env::var_os("APPDATA") { + paths.push(PathBuf::from(appdata).join("com.velocityrl.app").join("swaps.json")); + } + #[cfg(not(windows))] + if let Some(home) = std::env::var_os("HOME") { + paths.push(PathBuf::from(home).join(".config").join("com.velocityrl.app").join("swaps.json")); + } + paths.sort(); + paths.dedup(); + paths +} + +fn read_swap_array(path: &Path) -> Vec { + fs::read_to_string(path) + .ok() + .and_then(|c| serde_json::from_str::>(&c).ok()) + .unwrap_or_default() +} + +fn swap_identity(v: &serde_json::Value) -> (i64, i64, i64, String) { + ( + v.get("owned_id").and_then(|x| x.as_i64()).unwrap_or(0), + v.get("wanted_id").and_then(|x| x.as_i64()).unwrap_or(0), + v.get("paint_id").and_then(|x| x.as_i64()).unwrap_or(0), + v.get("custom_paint_hex").and_then(|x| x.as_str()).unwrap_or("").to_string(), + ) +} + +/// One-time consolidation: fold any entries from legacy state-file copies into the +/// canonical Roaming files, then delete the legacy copies so Restore can no longer +/// resurrect items from LOCALAPPDATA or the bare %APPDATA%\VelocityRL folder. +pub fn cleanup_stale_state_files() { + crate::proxy::migrate_legacy_title_ids(); + let proxy_dir = config_dir(); + let canonical_swaps = proxy_dir.join("swaps.json"); + + let mut stale_swaps: Vec = Vec::new(); + let mut stale_titles: Vec = Vec::new(); + if let Some(parent) = proxy_dir.parent() { + stale_swaps.push(parent.join("swaps.json")); + stale_titles.push(parent.join("title_ids.json")); + } + #[cfg(windows)] + if let Some(local) = std::env::var_os("LOCALAPPDATA") { + let local = PathBuf::from(local); + for sub in ["com.velocityrl.app", "VelocityRL", r"VelocityRL\proxy"] { + stale_swaps.push(local.join(sub).join("swaps.json")); + stale_titles.push(local.join(sub).join("title_ids.json")); + } + } + stale_swaps.retain(|p| p != &canonical_swaps); + + // Fold stale swap entries into the canonical proxy swaps.json (union, no data loss). + let mut merged = read_swap_array(&canonical_swaps); + let mut seen: std::collections::HashSet<(i64, i64, i64, String)> = + merged.iter().map(swap_identity).collect(); + let mut changed = false; + for path in &stale_swaps { + for entry in read_swap_array(path) { + if seen.insert(swap_identity(&entry)) { + merged.push(entry); + changed = true; + } + } + } + if changed { + if let Ok(data) = serde_json::to_string_pretty(&merged) { + let _ = fs::write(&canonical_swaps, data); + } + } + + // Fold stale title_ids.json into spawned_titles before deleting them. + let mut titles = load_spawned_titles(); + let mut titles_changed = false; + for path in &stale_titles { + if let Ok(content) = fs::read_to_string(path) { + if let Ok(ids) = serde_json::from_str::>(&content) { + for id in ids { + if !id.trim().is_empty() { + titles.push(id); + titles_changed = true; + } + } + } + } + } + if titles_changed { + let _ = write_spawned_titles(&titles); + } + + let mut removed = 0usize; + for path in stale_swaps.iter().chain(stale_titles.iter()) { + if path.is_file() && fs::remove_file(path).is_ok() { + removed += 1; + } + } + if removed > 0 || changed || titles_changed { + crate::applog::event(&format!( + "psynet: consolidated state onto Roaming, removed {removed} stale file(s)" + )); + } +} + +pub fn clean_title_ids(ids: &[String]) -> Vec { + let mut out: Vec = ids + .iter() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty() && s != "custom") + .collect(); + out.sort(); + out.dedup(); + out +} + +fn load_spoof_file() -> Option { + let path = config_path(&config_dir()); + let raw = fs::read_to_string(&path).ok()?; + serde_json::from_str(raw.trim_start_matches('\u{feff}')).ok() +} + +pub fn load_spawned_titles() -> Vec { + load_spoof_file() + .and_then(|c| c.spawned_titles) + .map(|t| clean_title_ids(&t)) + .unwrap_or_default() +} + +pub fn load_title_swap_equip_ids() -> Vec { + let Some(cfg) = load_spoof_file().filter(|c| c.enabled) else { + return Vec::new(); + }; + let mut ids: Vec = cfg + .swaps + .iter() + .flatten() + .map(|sw| if sw.equip_title_id.trim().is_empty() { sw.display_title_id.clone() } else { sw.equip_title_id.clone() }) + .collect(); + if cfg.swaps.is_none() { + ids.push(cfg.equip_title_id.clone()); + } + clean_title_ids(&ids) +} + +pub fn migrate_spawn_title_swaps() -> Result { + let Some(cfg) = load_spoof_file() else { return Ok(0) }; + let Some(swaps) = cfg.swaps.clone() else { return Ok(0) }; + let (spawned, kept): (Vec, Vec) = swaps.into_iter().partition(|sw| { + let id = sw.equip_title_id.trim(); + !id.is_empty() && id == sw.display_title_id.trim() + }); + if spawned.is_empty() { + return Ok(0); + } + let mut titles = cfg.spawned_titles.clone().unwrap_or_default(); + titles.extend(spawned.iter().map(|sw| sw.equip_title_id.clone())); + let payload = SpoofPayload { + enabled: !kept.is_empty(), + swaps: Some(kept), + spawned_titles: Some(clean_title_ids(&titles)), + method: "raw".into(), + ..Default::default() + }; + write_spoof(&config_dir(), &payload)?; + Ok(spawned.len()) +} + +pub fn write_spawned_titles(titles: &[String]) -> Result { + let payload = SpoofPayload { + spawned_titles: Some(clean_title_ids(titles)), + method: "raw".into(), + ..Default::default() + }; + write_spoof(&config_dir(), &payload)?; + load_active_spoof_from_disk().ok_or_else(|| "spoof config unreadable after write".to_string()) +} + pub(crate) fn write_spoof(dir: &Path, payload: &SpoofPayload) -> Result { let path = config_path(dir); @@ -889,6 +1074,10 @@ pub(crate) fn write_spoof(dir: &Path, payload: &SpoofPayload) -> Result Result { #[tauri::command] pub async fn get_psynet_spoof() -> Result { + crate::proxy::migrate_legacy_title_ids(); let dir = config_dir(); let path = config_path(&dir); if !path.is_file() { diff --git a/ui/main.js b/ui/main.js index b7c7eb2..01d5668 100644 --- a/ui/main.js +++ b/ui/main.js @@ -2702,31 +2702,13 @@ function initCatalogGrid() { } if (titleItemsToSpawn.length > 0) { - ensureTitleSwapsLoaded(); - for (const tEntry of titleItemsToSpawn) { - const tItem = tEntry.item; - const tId = tItem.titleId || (tItem.id && String(tItem.id).startsWith('title_') ? String(tItem.id).slice(6) : tItem.id) || tItem.product || 'CustomTitle'; - const text = tItem.titleText || tItem.product || tItem.Product || tItem.name || 'Custom Title'; - const cat = tItem.titleCategory || tItem.category || tItem.group || 'Special Titles'; - const textColor = (typeof tItem.titleColor === 'string' && tItem.titleColor) ? tItem.titleColor : (tItem.color?.text_color || ''); - const glowColor = (typeof tItem.titleGlow === 'string' && tItem.titleGlow) ? tItem.titleGlow : (tItem.color?.glow_color || ''); - const swapObj = { - equip_title_id: String(tId), - display_title_id: String(tId), - custom_text: text, - category: cat, - title_color: (textColor || glowColor) ? { - text_color: textColor, - glow_color: glowColor, - } : undefined, - }; - titleSwaps = titleSwaps.filter((s) => s.equip_title_id !== String(tId)); - titleSwaps.unshift(swapObj); + const titleIds = titleItemsToSpawn.map((tEntry) => { + const tItem = tEntry.item || {}; + return String(tItem.titleId || (tItem.id && String(tItem.id).startsWith('title_') ? String(tItem.id).slice(6) : '') || ''); + }).filter(Boolean); + if (titleIds.length > 0) { + spawnedCount += await invoke('spawn_titles', { titleIds }); } - persistTitleSpoofLocal(); - await runToolSave(null, 'titles', titleSpoofPayload(), { enabled: true }); - renderTitleSwapList(); - spawnedCount += titleItemsToSpawn.length; } showProgress(true, 100); @@ -2858,8 +2840,13 @@ function wirePresetsUI() { } let refreshBackupsInFlight = false; +let refreshBackupsQueued = false; async function refreshBackups() { - if (!backupContainer || refreshBackupsInFlight) return; + if (!backupContainer) return; + if (refreshBackupsInFlight) { + refreshBackupsQueued = true; + return; + } refreshBackupsInFlight = true; wireReswapButton(); const countLabel = document.getElementById('restore-count-label'); @@ -2980,6 +2967,10 @@ async function refreshBackups() { try { await invoke('append_launch_log', { message: `ui: get_backups failed: ${String(err)}` }); } catch {} } finally { refreshBackupsInFlight = false; + if (refreshBackupsQueued) { + refreshBackupsQueued = false; + refreshBackups(); + } } } @@ -2990,7 +2981,7 @@ async function restoreSingle(path) { const result = await invoke('restore_single_backup', { path }); updateStatus('Removed; game restart required', false); showToast(result, 'success', 9000); - refreshBackups(); + await refreshBackups(); setTimeout(() => updateStatus('bitsfdb', false), 2000); } catch (err) { updateStatus('Error', true);