diff --git a/src/cli/tests/content.rs b/src/cli/tests/content.rs index 980ce5b..a479b92 100644 --- a/src/cli/tests/content.rs +++ b/src/cli/tests/content.rs @@ -12,6 +12,7 @@ fn entry(file_stem: &str) -> ContentEntry { world_details: None, title_suffix: None, footer_label: None, + footer_change: None, description: String::new(), enabled: true, icon_bytes: None, diff --git a/src/instance/content/entry.rs b/src/instance/content/entry.rs index c2dc6c6..3fe074b 100644 --- a/src/instance/content/entry.rs +++ b/src/instance/content/entry.rs @@ -42,6 +42,7 @@ pub struct ContentEntry { pub world_details: Option, pub title_suffix: Option, pub footer_label: Option, + pub footer_change: Option<(String, String)>, pub description: String, pub enabled: bool, pub icon_bytes: Option>, diff --git a/src/instance/content/mods.rs b/src/instance/content/mods.rs index 6224485..63fce9d 100644 --- a/src/instance/content/mods.rs +++ b/src/instance/content/mods.rs @@ -19,6 +19,8 @@ struct FabricModJson { #[serde(default)] description: String, #[serde(default)] + version: String, + #[serde(default)] icon: serde_json::Value, } @@ -51,6 +53,8 @@ struct QuiltModJson { #[derive(Deserialize, Default)] struct QuiltLoader { + #[serde(default)] + version: String, #[serde(default)] metadata: QuiltMetadata, } @@ -72,7 +76,7 @@ impl QuiltMetadata { } pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry { - let (name, description, icon_bytes) = read_mod_metadata(path); + let (name, description, version, icon_bytes) = read_mod_metadata(path); let icon_lines = icon_bytes .as_ref() .and_then(|bytes| make_icon_pixels(bytes, 6, 3)) @@ -92,7 +96,8 @@ pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry provider_project: None, world_details: None, title_suffix: None, - footer_label: None, + footer_label: display_version(version), + footer_change: None, description, enabled, icon_bytes, @@ -138,12 +143,12 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec // checks fabric.mod.json, quilt.mod.json, META-INF/mods.toml (forge), // META-INF/neoforge.mods.toml, and mcmod.info (legacy forge). if none of // those yield an icon, falls back to common root-level paths. -fn read_mod_metadata(jar_path: &Path) -> (String, String, Option>) { +fn read_mod_metadata(jar_path: &Path) -> (String, String, String, Option>) { let file = match std::fs::File::open(jar_path) { Ok(file) => file, Err(e) => { tracing::trace!("Failed to open mod JAR {}: {}", jar_path.display(), e); - return (String::new(), String::new(), None); + return (String::new(), String::new(), String::new(), None); } }; @@ -155,13 +160,14 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option>) { jar_path.display(), e ); - return (String::new(), String::new(), None); + return (String::new(), String::new(), String::new(), None); } }; // try each loader's metadata in order. if we get metadata but the // declared icon path is missing, fall back to common root-level icons. - type MetaReader = fn(&mut zip::ZipArchive) -> Option<(String, String, String)>; + type MetaReader = + fn(&mut zip::ZipArchive) -> Option<(String, String, String, String)>; let readers: [MetaReader; 4] = [ read_fabric_meta, read_quilt_meta, @@ -170,7 +176,7 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option>) { ]; for reader in &readers { - if let Some((name, description, icon_path)) = reader(&mut archive) { + if let Some((name, description, version, icon_path)) = reader(&mut archive) { let icon_path = icon_path.trim_start_matches('/'); let icon = if icon_path.is_empty() { None @@ -184,7 +190,7 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option>) { name, !icon_path.is_empty() ); - return (name, description, icon); + return (name, description, version, icon); } } @@ -195,7 +201,12 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option>) { jar_path.display(), icon_bytes.is_some() ); - (String::new(), String::new(), icon_bytes) + (String::new(), String::new(), String::new(), icon_bytes) +} + +fn display_version(version: String) -> Option { + let version = version.trim(); + (!version.is_empty() && !version.contains("${")).then(|| version.to_owned()) } fn try_fallback_icons(archive: &mut zip::ZipArchive) -> Option> { @@ -209,27 +220,28 @@ fn try_fallback_icons(archive: &mut zip::ZipArchive) -> Option, -) -> Option<(String, String, String)> { +) -> Option<(String, String, String, String)> { let mut entry = archive.by_name("fabric.mod.json").ok()?; let mut raw = String::new(); entry.read_to_string(&mut raw).ok()?; let sanitized = sanitize_json_strings(&raw); let data: FabricModJson = serde_json::from_str(&sanitized).ok()?; let icon = data.icon_path(); - Some((data.name, data.description, icon)) + Some((data.name, data.description, data.version, icon)) } fn read_quilt_meta( archive: &mut zip::ZipArchive, -) -> Option<(String, String, String)> { +) -> Option<(String, String, String, String)> { let mut entry = archive.by_name("quilt.mod.json").ok()?; let mut raw = String::new(); entry.read_to_string(&mut raw).ok()?; let sanitized = sanitize_json_strings(&raw); let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?; + let version = data.quilt_loader.version; let meta = data.quilt_loader.metadata; let icon = meta.icon_path(); - Some((meta.name, meta.description, icon)) + Some((meta.name, meta.description, version, icon)) } // forge (META-INF/mods.toml) and neoforge (META-INF/neoforge.mods.toml) @@ -239,7 +251,7 @@ fn read_quilt_meta( // but no [[mods]] section. we still want the icon in that case. fn read_forge_toml_meta( archive: &mut zip::ZipArchive, -) -> Option<(String, String, String)> { +) -> Option<(String, String, String, String)> { let raw = read_zip_string(archive, "META-INF/neoforge.mods.toml") .or_else(|| read_zip_string(archive, "META-INF/mods.toml"))?; let table: toml::Table = raw.parse().ok()?; @@ -248,7 +260,7 @@ fn read_forge_toml_meta( .and_then(|v| v.as_str()) .unwrap_or("") .to_owned(); - let (name, description) = table + let (name, description, version) = table .get("mods") .and_then(|v| v.as_array()) .and_then(|a| a.first()) @@ -265,17 +277,22 @@ fn read_forge_toml_meta( .unwrap_or("") .trim() .to_owned(); - (n, d) + let version = first + .get("version") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_owned(); + (n, d, version) }) .unwrap_or_default(); - Some((name, description, logo)) + Some((name, description, version, logo)) } // legacy forge mcmod.info is either a bare json array of mod entries // or an object with a "modList" key wrapping the array fn read_mcmod_info( archive: &mut zip::ZipArchive, -) -> Option<(String, String, String)> { +) -> Option<(String, String, String, String)> { let mut entry = archive.by_name("mcmod.info").ok()?; let mut raw = String::new(); entry.read_to_string(&mut raw).ok()?; @@ -296,12 +313,17 @@ fn read_mcmod_info( .and_then(|v| v.as_str()) .unwrap_or("") .to_owned(); + let version = first + .get("version") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_owned(); let logo = first .get("logoFile") .and_then(|v| v.as_str()) .unwrap_or("") .to_owned(); - Some((name, description, logo)) + Some((name, description, version, logo)) } fn read_zip_string(archive: &mut zip::ZipArchive, path: &str) -> Option { diff --git a/src/instance/content/packs.rs b/src/instance/content/packs.rs index 4708857..12a7de4 100644 --- a/src/instance/content/packs.rs +++ b/src/instance/content/packs.rs @@ -62,6 +62,7 @@ pub(crate) fn scan_one_pack(path: &Path, file_stem: &str, enabled: bool) -> Cont world_details: None, title_suffix: None, footer_label: None, + footer_change: None, description, enabled, icon_bytes, diff --git a/src/instance/content/updates.rs b/src/instance/content/updates.rs index e2a4af8..4e4ceb6 100644 --- a/src/instance/content/updates.rs +++ b/src/instance/content/updates.rs @@ -20,6 +20,8 @@ pub struct AvailableUpdate { pub struct UpdateSnapshot { pub game_version: String, pub loader: ModLoader, + #[serde(default)] + pub inventory: Vec, pub updates: Vec, pub failures: Vec, } @@ -47,6 +49,7 @@ pub struct UpdateRequest { #[derive(Debug, Clone)] pub struct PlannedRootUpdate { pub title: String, + pub installed_path: std::path::PathBuf, pub current_version: String, pub target: VersionInfo, } @@ -79,6 +82,10 @@ impl UpdateSnapshot { self.game_version == instance.game_version && self.loader == instance.loader } + pub fn matches_manifest(&self, manifest: &ContentManifest) -> bool { + self.inventory == resolved_inventory(manifest) + } + pub fn update_for(&self, installed: &ProviderProject) -> Option<&AvailableUpdate> { self.updates.iter().find(|update| { update.installed.provider == installed.provider @@ -129,6 +136,10 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda && left.0.project_id == right.0.project_id && left.0.version_id == right.0.version_id }); + let inventory = projects + .iter() + .map(|(project, _)| project.clone()) + .collect(); let slots = Arc::new(tokio::sync::Semaphore::new(8)); let mut tasks = tokio::task::JoinSet::new(); @@ -195,11 +206,29 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda UpdateSnapshot { game_version: instance.game_version.clone(), loader: instance.loader, + inventory, updates, failures, } } +fn resolved_inventory(manifest: &ContentManifest) -> Vec { + let mut inventory = manifest + .files + .iter() + .filter_map(|record| record.resolved_project().cloned()) + .collect::>(); + inventory.sort_by(|left, right| { + (&left.provider, &left.project_id, &left.version_id).cmp(&( + &right.provider, + &right.project_id, + &right.version_id, + )) + }); + inventory.dedup(); + inventory +} + pub async fn plan_bulk( instance: &InstanceConfig, manifest: &ContentManifest, @@ -249,6 +278,7 @@ pub async fn plan_bulk( } roots.push(PlannedRootUpdate { title: request.title, + installed_path: request.installed_path, current_version: request.update.current.as_ref().map_or_else( || request.update.installed.version_id.clone(), |version| version.version_number.clone(), @@ -298,6 +328,7 @@ mod tests { let snapshot = UpdateSnapshot { game_version: "1.21.1".to_owned(), loader: ModLoader::Fabric, + inventory: vec![installed.clone()], updates: vec![AvailableUpdate { installed: installed.clone(), current: Some(version("old")), @@ -317,4 +348,43 @@ mod tests { .is_none() ); } + + #[test] + fn cached_updates_require_the_same_content_inventory() { + let project = ProviderProject { + provider: "modrinth".to_owned(), + project_id: "project".to_owned(), + version_id: "old".to_owned(), + }; + let snapshot = UpdateSnapshot { + game_version: "1.21.1".to_owned(), + loader: ModLoader::Fabric, + inventory: vec![project.clone()], + updates: Vec::new(), + failures: Vec::new(), + }; + let mut manifest = ContentManifest::default(); + manifest.files.push(crate::instance::ContentFileRecord { + relative_path: "mods/example.jar".into(), + kind: ContentKind::Mod, + enabled: true, + fingerprint: crate::instance::FileFingerprint { + size: 0, + modified_ns: 0, + hashes: Default::default(), + }, + resolution: crate::instance::Resolution::Resolved { project }, + provider_aliases: Vec::new(), + required_dependencies: Vec::new(), + automatic_dependency: false, + cleanup_eligible: false, + }); + + assert!(snapshot.matches_manifest(&manifest)); + manifest.files[0].resolution = crate::instance::Resolution::Unmatched { + checked_at: 0, + providers: Vec::new(), + }; + assert!(!snapshot.matches_manifest(&manifest)); + } } diff --git a/src/instance/content/worlds.rs b/src/instance/content/worlds.rs index eae5235..4097dbb 100644 --- a/src/instance/content/worlds.rs +++ b/src/instance/content/worlds.rs @@ -47,6 +47,7 @@ pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEnt world_details: Some(world_details), title_suffix: None, footer_label: None, + footer_change: None, description: String::new(), enabled, icon_bytes, diff --git a/src/instance/tests/content/mods.rs b/src/instance/tests/content/mods.rs index b1a7e32..5186bc9 100644 --- a/src/instance/tests/content/mods.rs +++ b/src/instance/tests/content/mods.rs @@ -78,6 +78,7 @@ fn toggle_entry_enable() { world_details: None, title_suffix: None, footer_label: None, + footer_change: None, description: String::new(), enabled: false, icon_bytes: None, @@ -111,7 +112,8 @@ fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) { fn scan_mods_reads_fabric_metadata() { let tmp = tempfile::tempdir().unwrap(); let dir = setup_mods_dir(tmp.path(), "inst"); - let meta = r#"{"name":"Fabric Mod","description":"A fabric mod","icon":"icon.png"}"#; + let meta = + r#"{"name":"Fabric Mod","description":"A fabric mod","version":"1.2.3","icon":"icon.png"}"#; make_jar( &dir, "fabric-mod.jar", @@ -121,6 +123,7 @@ fn scan_mods_reads_fabric_metadata() { assert_eq!(mods.len(), 1); assert_eq!(mods[0].name, "Fabric Mod"); assert_eq!(mods[0].description, "A fabric mod"); + assert_eq!(mods[0].footer_label.as_deref(), Some("1.2.3")); } #[test] @@ -355,6 +358,7 @@ fn toggle_entry_disable() { world_details: None, title_suffix: None, footer_label: None, + footer_change: None, description: String::new(), enabled: true, icon_bytes: None, diff --git a/src/tui/event.rs b/src/tui/event.rs index 197ab44..b363ab2 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -42,10 +42,17 @@ impl App { self.drain_pending_instances(); self.instances_state.drain_modpack_updates(); self.drain_pending_last_played(); - if let Some(update) = self.content_update_popup.as_mut() { + let content_update_completed = self.content_update_popup.as_mut().and_then(|update| { update.drain(); - if update.completed { - self.content_update_popup = None; + update.list.request_image_loads(&self.picker); + update.list.drain_image_loads(&self.picker); + update.completed.then_some(update.applied) + }); + if let Some(applied) = content_update_completed { + self.content_update_popup = None; + if applied { + self.content_update_snapshot = None; + self.apply_content_update_snapshot(); } } let completed_modpack = self.modpack_update_popup.as_mut().and_then(|update| { @@ -197,7 +204,11 @@ impl App { + usize::from(self.focused == super::app::FocusedArea::OverviewExpanded) + usize::from(self.focused == super::app::FocusedArea::ConfirmDelete) + usize::from(self.provider_conflict.is_some()) - + usize::from(self.content_update_popup.is_some()) + + usize::from( + self.content_update_popup + .as_ref() + .is_some_and(widgets::content::update::State::visible), + ) + usize::from(self.modpack_update_popup.is_some()) + usize::from(!matches!( &self.account_state.add_mode, @@ -379,7 +390,9 @@ impl App { ); self.content_update_snapshot = crate::instance::content::updates::UpdateSnapshot::load(&paths.content_updates()) - .filter(|snapshot| snapshot.applies_to(&selected)) + .filter(|snapshot| { + snapshot.applies_to(&selected) && snapshot.matches_manifest(&result.manifest) + }) .map(|snapshot| (result.instance_name.clone(), snapshot)); self.content_manifest = Some((result.instance_name.clone(), result.manifest.clone())); self.apply_content_update_snapshot(); @@ -439,6 +452,14 @@ impl App { let Some(snapshot) = snapshot else { return; }; + let current_manifest = self + .content_manifest + .as_ref() + .filter(|(name, _)| name == &snapshot.instance_name) + .map(|(_, manifest)| manifest); + if current_manifest.is_none_or(|manifest| !snapshot.snapshot.matches_manifest(manifest)) { + return; + } self.content_update_snapshot = Some((snapshot.instance_name, snapshot.snapshot)); self.apply_content_update_snapshot(); } @@ -451,7 +472,14 @@ impl App { self.instances_state .selected_instance() .filter(|instance| instance.name == *name && snapshot.applies_to(instance)) - .map(|_| snapshot) + .and_then(|_| { + self.content_manifest + .as_ref() + .filter(|(manifest_name, manifest)| { + manifest_name == name && snapshot.matches_manifest(manifest) + }) + .map(|_| snapshot) + }) }); self.mods_state.apply_update_snapshot(snapshot); self.resource_packs_state.apply_update_snapshot(snapshot); diff --git a/src/tui/input.rs b/src/tui/input.rs index 50e94b5..fabfb20 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -60,7 +60,11 @@ impl App { } pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> { - if self.content_update_popup.is_some() { + if self + .content_update_popup + .as_ref() + .is_some_and(widgets::content::update::State::visible) + { self.handle_content_update_key(key_event); return Ok(()); } @@ -969,6 +973,9 @@ impl App { } fn spawn_bulk_content_updates(&mut self) { + if self.content_update_popup.is_some() { + return; + } let Some(instance) = self.instances_state.selected_instance().cloned() else { return; }; @@ -998,14 +1005,37 @@ impl App { let paths = crate::storage::InstancePaths::new( self.instance_manager.instances_dir.join(&instance.name), ); - let state = widgets::content::update::State::checking(kind, target_world.clone()); + let source_entries = match self.content_tab { + widgets::content::ContentTab::Mods => self.mods_state.entries.clone(), + widgets::content::ContentTab::ResourcePacks => { + self.resource_packs_state.entries.clone() + } + widgets::content::ContentTab::Shaders => self.shaders_state.entries.clone(), + widgets::content::ContentTab::Worlds => self.world_datapacks_state.entries.clone(), + _ => return, + }; + let cached_snapshot = self + .content_update_snapshot + .as_ref() + .filter(|(name, snapshot)| { + name == &instance.name + && snapshot.applies_to(&instance) + && snapshot.matches_manifest(&manifest) + }) + .map(|(_, snapshot)| snapshot.clone()); + if cached_snapshot + .as_ref() + .is_none_or(|snapshot| !snapshot.updates.iter().any(|update| update.kind == kind)) + { + return; + } + let state = + widgets::content::update::State::checking(kind, target_world.clone(), source_entries); let pending = state.pending.clone(); self.content_update_popup = Some(state); tokio::spawn(async move { - let snapshot = crate::instance::content::updates::scan(&instance, &manifest).await; - if let Ok(bytes) = serde_json::to_vec_pretty(&snapshot) { - let _ = crate::storage::write_atomic(&paths.content_updates(), &bytes); - } + let progress = crate::feedback::progress::ProgressTask::start("Preparing updates"); + let snapshot = cached_snapshot.expect("checked above"); let target_directory = target_world .as_ref() .map(|(_, world)| world.join("datapacks")); @@ -1057,6 +1087,7 @@ impl App { conflicts, ) .await; + progress.finish(); if let Ok(mut pending) = pending.lock() { pending.push(widgets::content::update::PendingResult::Prepared( snapshot, plan, @@ -1076,29 +1107,23 @@ impl App { | (widgets::content::update::Phase::Conflicts, KeyCode::Esc) => { self.content_update_popup = None; } - (widgets::content::update::Phase::Conflicts, KeyCode::Char('j') | KeyCode::Down) => { - let count = state.plan.as_ref().map_or(0, |plan| plan.conflicts.len()); - state.selected = (state.selected + 1).min(count.saturating_sub(1)); - } - (widgets::content::update::Phase::Conflicts, KeyCode::Char('k') | KeyCode::Up) => { - state.selected = state.selected.saturating_sub(1); - } - (widgets::content::update::Phase::Conflicts, KeyCode::Char(' ')) => { - if let Some(retry) = state.retry_conflicts.get_mut(state.selected) { - *retry = !*retry; - } + (widgets::content::update::Phase::Conflicts, KeyCode::Char('h')) => { + self.content_update_popup = None; } (widgets::content::update::Phase::Conflicts, KeyCode::Enter) => { - if state.has_retry() { - self.spawn_bulk_content_updates(); - } else { - state.phase = widgets::content::update::Phase::Review; - state.selected = 0; + if state.has_updates() { + state.show_review(); } } + (widgets::content::update::Phase::Review, KeyCode::Char('h')) => { + state.show_conflicts(); + } (widgets::content::update::Phase::Review, KeyCode::Enter) => { self.spawn_bulk_content_install(); } + (_, KeyCode::Char('j') | KeyCode::Down | KeyCode::Char('k') | KeyCode::Up) => { + widgets::content::list::handle_key_no_toggle(&key_event, &mut state.list); + } _ => {} } } @@ -1118,7 +1143,6 @@ impl App { return; } state.phase = widgets::content::update::Phase::Applying; - state.error = None; let pending = state.pending.clone(); let instances_dir = self.instance_manager.instances_dir.clone(); let paths = crate::storage::InstancePaths::new(instances_dir.join(&instance.name)); diff --git a/src/tui/render.rs b/src/tui/render.rs index 070159d..0f1ae6f 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -179,8 +179,8 @@ impl App { render_provider_conflict(frame, conflict); } - if let Some(update) = &self.content_update_popup { - widgets::content::update::render(frame, update); + if let Some(update) = self.content_update_popup.as_mut() { + widgets::content::update::render(frame, update, &self.picker); } if let Some(update) = &self.modpack_update_popup { diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index 86beb56..c0063d9 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -238,6 +238,7 @@ fn content_entry(name: &str, path: PathBuf) -> ContentEntry { world_details: None, title_suffix: None, footer_label: None, + footer_change: None, description: String::new(), enabled: true, icon_bytes: None, diff --git a/src/tui/tests/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index 6abf094..789b2b0 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -407,6 +407,7 @@ fn installed_version_popup_tracks_current_version_and_reinstalls_it() { world_details: None, title_suffix: None, footer_label: None, + footer_change: None, description: String::new(), enabled: true, icon_bytes: None, diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index a54c4c2..d5d4f81 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -16,8 +16,8 @@ use ratatui::{ use super::{ ContentListState, WatcherEventHandling, available_description_width, description_text_width, diff_directory, diff_event_paths, ellipsize, load_provider_metadata, read_dir_stems, - right_aligned_footer_spans, square_icon_columns, title_suffix_spans, watcher_event_handling, - world_descriptions, world_game_mode_color, + right_aligned_footer_spans, square_icon_columns, title_suffix_spans, version_change_spans, + watcher_event_handling, world_descriptions, world_game_mode_color, }; fn entry(name: &str) -> ContentEntry { @@ -30,6 +30,7 @@ fn entry(name: &str) -> ContentEntry { world_details: None, title_suffix: None, footer_label: None, + footer_change: None, description: String::new(), enabled: true, icon_bytes: None, @@ -149,6 +150,60 @@ fn pure_toggle_does_not_request_reconciliation() { ); } +#[test] +fn content_watcher_replaces_a_version_without_removing_its_row() { + let mut state = ContentListState::default(); + let mut installed = entry("Example Mod"); + installed.file_stem = "example-1.0".to_owned(); + installed.path = PathBuf::from("mods/example-1.0.jar"); + installed.description = "Cached description".to_owned(); + installed.provider_description = true; + installed.icon_bytes = Some(vec![1, 2, 3]); + state.entries.push(installed); + *state.watcher_diff.lock().unwrap() = Some(super::WatcherDiff { + toggled: Vec::new(), + removed: vec!["example-1.0".to_owned()], + added: Vec::new(), + }); + + state.drain_watcher(); + assert_eq!(state.entries.len(), 1); + + let mut replacement = entry("Example Mod"); + replacement.file_stem = "example-2.0".to_owned(); + replacement.path = PathBuf::from("mods/example-2.0.jar"); + *state.watcher_diff.lock().unwrap() = Some(super::WatcherDiff { + toggled: Vec::new(), + removed: Vec::new(), + added: vec![replacement], + }); + + state.drain_watcher(); + + assert_eq!(state.entries.len(), 1); + assert_eq!(state.entries[0].path, PathBuf::from("mods/example-2.0.jar")); + assert_eq!(state.entries[0].description, "Cached description"); + assert_eq!(state.entries[0].icon_bytes, Some(vec![1, 2, 3])); +} + +#[test] +fn content_watcher_removes_a_file_after_the_replacement_grace_period() { + let mut state = ContentListState::default(); + let mut installed = entry("Removed Mod"); + installed.file_stem = "removed".to_owned(); + installed.path = PathBuf::from("mods/removed.jar"); + state.entries.push(installed); + state.pending_removals.insert( + "removed".to_owned(), + std::time::Instant::now() - super::REMOVAL_GRACE, + ); + + let update = state.drain_watcher(); + + assert!(state.entries.is_empty()); + assert!(update.requires_reconcile); +} + #[test] fn irrelevant_watcher_paths_do_not_emit_an_empty_diff() { let temp = tempfile::tempdir().unwrap(); @@ -250,9 +305,9 @@ fn description_width_reserves_the_row_chrome() { #[test] fn description_width_reserves_the_download_metadata() { - assert_eq!(description_text_width(40, Some("1.2K downloads"), true), 25); - assert_eq!(description_text_width(10, Some("1.2K downloads"), true), 0); - assert_eq!(description_text_width(40, None, true), 40); + assert_eq!(description_text_width(40, 14, true), 25); + assert_eq!(description_text_width(10, 14, true), 0); + assert_eq!(description_text_width(40, 0, true), 40); } #[test] @@ -262,8 +317,7 @@ fn footer_metadata_is_right_aligned_without_a_separator() { 30, "Description", true, - "1.2K downloads", - Style::default(), + vec![Span::raw("1.2K downloads")], )); let line = Line::from(spans); @@ -271,6 +325,13 @@ fn footer_metadata_is_right_aligned_without_a_separator() { assert_eq!(line.to_string(), "Description 1.2K downloads"); } +#[test] +fn version_changes_render_as_two_labels_with_a_directional_arrow() { + let spans = version_change_spans("1.0", "2.0"); + + assert_eq!(Line::from(spans).to_string(), " 1.0 ➜ 2.0 "); +} + #[test] fn content_stream_inserts_entries_and_icons_incrementally() { let mut state = ContentListState::default(); diff --git a/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__update__tests__update_review_reuses_content_rows.snap b/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__update__tests__update_review_reuses_content_rows.snap new file mode 100644 index 0000000..566933e --- /dev/null +++ b/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__update__tests__update_review_reuses_content_rows.snap @@ -0,0 +1,28 @@ +--- +source: src/tui/tests/widgets/content/update.rs +expression: terminal.backend() +--- +" " +" " +" " +" " +" " +" " +" " +" " +" " +" " +" ╭Update installed content──────────────────────────────────╮ " +" │▌▄▄▄▄▄▄ Example Mod Update │ " +" │▌▄▄▄▄▄▄ 1.0 ➜ 2.0 │ " +" │▌▄▄▄▄▄▄ │ " +" ╰───────────[j/k] navigate [Enter] update all [Esc] close╯ " +" " +" " +" " +" " +" " +" " +" " +" " +" " diff --git a/src/tui/tests/widgets/content/update.rs b/src/tui/tests/widgets/content/update.rs new file mode 100644 index 0000000..87e9c62 --- /dev/null +++ b/src/tui/tests/widgets/content/update.rs @@ -0,0 +1,115 @@ +use std::path::PathBuf; + +use ratatui::{Terminal, backend::TestBackend}; + +use super::*; + +fn entry(name: &str, path: &str) -> ContentEntry { + ContentEntry { + file_stem: name.to_lowercase(), + name: name.to_owned(), + source_slug: None, + installed_path: Some(PathBuf::from(path)), + provider_project: None, + world_details: None, + title_suffix: None, + footer_label: None, + footer_change: None, + description: "Existing project description".to_owned(), + enabled: true, + icon_bytes: None, + provider_icon: false, + provider_description: false, + path: PathBuf::from(path), + icon_lines: Some(crate::instance::content::fallback_icon()), + } +} + +fn version(number: &str) -> crate::net::modrinth::VersionInfo { + crate::net::modrinth::VersionInfo { + id: number.to_owned(), + project_id: "project".to_owned(), + name: number.to_owned(), + version_number: number.to_owned(), + game_versions: Vec::new(), + loaders: Vec::new(), + version_type: crate::net::modrinth::VersionType::Release, + dependencies: Vec::new(), + date_published: String::new(), + files: Vec::new(), + } +} + +fn plan() -> BulkUpdatePlan { + BulkUpdatePlan { + dependency_plan: crate::instance::content::dependencies::DependencyPlan { + items: Vec::new(), + root_count: 0, + optional_dependencies: 0, + }, + roots: vec![crate::instance::content::updates::PlannedRootUpdate { + title: "Example Mod".to_owned(), + installed_path: PathBuf::from("mods/example.jar"), + current_version: "1.0".to_owned(), + target: version("2.0"), + }], + conflicts: Vec::new(), + } +} + +fn snapshot() -> UpdateSnapshot { + UpdateSnapshot { + game_version: "1.21.1".to_owned(), + loader: crate::instance::ModLoader::Fabric, + inventory: Vec::new(), + updates: Vec::new(), + failures: Vec::new(), + } +} + +#[test] +fn update_review_reuses_content_rows() { + let mut state = State::checking( + ContentKind::Mod, + None, + vec![entry("Example Mod", "mods/example.jar")], + ); + state.push(PendingResult::Prepared(snapshot(), plan())); + state.drain(); + let picker = ratatui_image::picker::Picker::halfblocks(); + let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); + + terminal + .draw(|frame| render(frame, &mut state, &picker)) + .unwrap(); + + insta::assert_snapshot!(terminal.backend()); +} + +#[test] +fn update_conflicts_explain_why_the_item_was_not_updated() { + let mut plan = plan(); + plan.conflicts + .push(crate::instance::content::updates::UpdateConflict { + title: "Example Mod".to_owned(), + installed_path: PathBuf::from("mods/example.jar"), + reason: "Parse error: Conflicting selected versions for 'Library': '1.0' and '2.0'" + .to_owned(), + }); + let mut state = State::checking( + ContentKind::Mod, + None, + vec![entry("Example Mod", "mods/example.jar")], + ); + state.push(PendingResult::Prepared(snapshot(), plan)); + state.drain(); + + assert_eq!( + state.list.entries[0].title_suffix.as_deref(), + Some("Skipped") + ); + assert_eq!( + state.list.entries[0].description, + "Other updates need different Library versions (1.0 and 2.0). This mod was left unchanged; update it separately with v." + ); +} diff --git a/src/tui/widgets/content/discovery.rs b/src/tui/widgets/content/discovery.rs index e94e917..8e0c0ee 100644 --- a/src/tui/widgets/content/discovery.rs +++ b/src/tui/widgets/content/discovery.rs @@ -1656,6 +1656,7 @@ pub(crate) fn provider_project_entry( world_details: None, title_suffix: installed_path.is_some().then(|| "Installed".to_owned()), footer_label: Some(format!("{} downloads", format_downloads(project.downloads))), + footer_change: None, description: project.description, enabled: true, icon_bytes: project.icon_bytes, diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 41bb011..75efffc 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -148,6 +148,8 @@ struct PaginationState { hits: Vec<(Rect, usize)>, } +const REMOVAL_GRACE: std::time::Duration = std::time::Duration::from_millis(500); + // result from the notify-triggered background diff struct WatcherDiff { toggled: Vec<(String, bool, std::path::PathBuf)>, @@ -198,6 +200,7 @@ pub struct ContentListState { scan_one_fn: Option, content_ext: Option<&'static str>, pagination: Option, + pending_removals: HashMap, } #[derive(Clone, Debug)] @@ -235,11 +238,25 @@ impl Default for ContentListState { scan_one_fn: None, content_ext: None, pagination: None, + pending_removals: HashMap::new(), } } } impl ContentListState { + pub(crate) fn set_entries(&mut self, entries: Vec) { + self.entries = entries; + self.list_state = TuiListState::default(); + self.list_state.selected = (!self.entries.is_empty()).then_some(0); + self.image_protocols.clear(); + self.requested_images.clear(); + self.pending_entry_images.clear(); + self.pending_removals.clear(); + self.images_dirty = true; + self.rebuild_display_metadata(); + self.update_scrollbar(); + } + pub fn apply_manifest( &mut self, manifest: &crate::instance::ContentManifest, @@ -500,6 +517,7 @@ impl ContentListState { self.image_protocols.clear(); self.requested_images.clear(); self.pending_entry_images.clear(); + self.pending_removals.clear(); self.requested_provider_icons.clear(); self.entries.clear(); self.display_metadata.clear(); @@ -788,16 +806,21 @@ impl ContentListState { return ContentWatcherUpdate::default(); } + let expired_removals = self.expire_pending_removals(); + let diff = match self.watcher_diff.lock() { Ok(mut slot) => slot.take(), _ => None, }; let Some(diff) = diff else { - return ContentWatcherUpdate::default(); + return ContentWatcherUpdate { + requires_reconcile: expired_removals, + ..ContentWatcherUpdate::default() + }; }; let mut update = ContentWatcherUpdate { - requires_reconcile: !diff.removed.is_empty() || !diff.added.is_empty(), + requires_reconcile: expired_removals || !diff.added.is_empty(), ..ContentWatcherUpdate::default() }; self.images_dirty |= update.requires_reconcile; @@ -811,6 +834,7 @@ impl ContentListState { diff.added.len() ); for (stem, enabled, path) in &diff.toggled { + self.pending_removals.remove(stem); if let Some(entry) = self.entries.iter_mut().find(|e| &e.file_stem == stem) { let old_path = if entry.path == *path { opposite_toggle_path(path, *enabled) @@ -829,17 +853,46 @@ impl ContentListState { } } - // apply removals - if !diff.removed.is_empty() { - self.entries - .retain(|e| !diff.removed.contains(&e.file_stem)); - for stem in &diff.removed { - self.display_metadata.remove(stem); - } + // A version change is reported by the filesystem as a removal followed + // by an addition. Keep the old row briefly so the replacement can take + // its place without flashing out of the list. + for stem in diff.removed { + self.pending_removals + .entry(stem) + .or_insert_with(std::time::Instant::now); } // insert new entries in sorted position - for entry in diff.added { + for mut entry in diff.added { + let replacement = self.entries.iter().position(|existing| { + self.pending_removals.contains_key(&existing.file_stem) + && existing.name.eq_ignore_ascii_case(&entry.name) + }); + if let Some(index) = replacement { + let old_stem = self.entries[index].file_stem.clone(); + self.pending_removals.remove(&old_stem); + preserve_visual_metadata(&mut entry, &mut self.entries[index]); + self.display_metadata.remove(&old_stem); + let protocol = self.image_protocols.remove(&old_stem); + let image_requested = self.requested_images.remove(&old_stem); + let image_pending = self.pending_entry_images.remove(&old_stem); + self.entries[index] = entry; + let entry = &self.entries[index]; + if let Some(protocol) = protocol { + self.image_protocols + .insert(entry.file_stem.clone(), protocol); + } + if image_requested { + self.requested_images.insert(entry.file_stem.clone()); + } + if image_pending { + self.pending_entry_images.insert(entry.file_stem.clone()); + } + self.display_metadata + .insert(entry.file_stem.clone(), display_metadata(entry)); + self.images_dirty = true; + continue; + } if entry.icon_bytes.is_some() { self.pending_entry_images.insert(entry.file_stem.clone()); } @@ -865,6 +918,39 @@ impl ContentListState { update } + fn expire_pending_removals(&mut self) -> bool { + let expired = self + .pending_removals + .iter() + .filter(|(_, since)| since.elapsed() >= REMOVAL_GRACE) + .map(|(stem, _)| stem.clone()) + .collect::>(); + let mut removed = false; + for stem in expired { + self.pending_removals.remove(&stem); + let restored = self + .entries + .iter() + .find(|entry| entry.file_stem == stem) + .is_some_and(|entry| entry.path.exists()); + if restored { + continue; + } + let before = self.entries.len(); + self.entries.retain(|entry| entry.file_stem != stem); + removed |= self.entries.len() != before; + self.display_metadata.remove(&stem); + self.image_protocols.remove(&stem); + self.requested_images.remove(&stem); + self.pending_entry_images.remove(&stem); + } + if removed { + self.images_dirty = true; + self.update_scrollbar(); + } + removed + } + // starts a notify file watcher on the given directory. changes trigger // a background diff that lands in watcher_diff for drain_watcher to apply. pub fn watch_dir(&mut self, dir: std::path::PathBuf) { @@ -1081,6 +1167,7 @@ impl ContentListState { self.image_protocols.clear(); self.requested_images.clear(); self.pending_entry_images.clear(); + self.pending_removals.clear(); // save current entries to cache if let Some(prev) = self.loaded_for.take() @@ -1571,7 +1658,7 @@ pub fn render( .and_then(|details| details.game_mode) .map(world_game_mode_color) .unwrap_or_else(|| { - if title_suffix == Some("Update") { + if matches!(title_suffix, Some("Update" | "Skipped")) { theme.warning() } else { theme.success() @@ -1586,6 +1673,16 @@ pub fn render( } else { theme.text() }); + let footer_spans = entry.footer_change.as_ref().map_or_else( + || { + footer_label.map_or_else(Vec::new, |label| { + vec![Span::styled(label.to_owned(), footer_label_style)] + }) + }, + |(from, to)| version_change_spans(from, to), + ); + let footer_width = footer_spans.iter().map(Span::width).sum(); + let has_footer = !footer_spans.is_empty(); let world_descriptions = world_details.map(world_descriptions); let has_icon = icon_pixels.is_some(); @@ -1627,7 +1724,7 @@ pub fn render( ellipsize( description, if index == 0 { - description_text_width(description_width, footer_label, has_description) + description_text_width(description_width, footer_width, has_description) } else { description_width }, @@ -1635,7 +1732,7 @@ pub fn render( }) .collect::>(); let visible_description = visible_descriptions.first().map_or("", String::as_str); - let compact = !has_icon && !has_description && footer_label.is_none(); + let compact = !has_icon && !has_description && !has_footer; let selector = if show_selected { Span::styled("\u{258c}", Style::default().fg(theme.accent())) @@ -1657,9 +1754,7 @@ pub fn render( (item, 1) } else if has_icon { let icon_row_count = icon_pixels.as_ref().map(|r| r.len()).unwrap_or(0); - let text_rows = 1 + visible_descriptions - .len() - .max(usize::from(footer_label.is_some())); + let text_rows = 1 + visible_descriptions.len().max(usize::from(has_footer)); let height = icon_row_count.max(text_rows) as u16; let pad = if show_selected { @@ -1697,15 +1792,12 @@ pub fn render( if let Some(description) = visible_descriptions.get(r - 1) { row.extend(search.highlight_spans(description, description_style)); } - if r == 1 - && let Some(footer_label) = footer_label - { + if r == 1 && has_footer { row.extend(right_aligned_footer_spans( description_width, visible_description, has_description, - footer_label, - footer_label_style, + footer_spans.clone(), )); } lines.push(Line::from(row)); @@ -1736,7 +1828,7 @@ pub fn render( let mut lines = vec![Line::from(line_0)]; - if has_description || footer_label.is_some() { + if has_description || has_footer { let pad = if show_selected { Span::styled("\u{258c}", Style::default().fg(theme.accent())) } else { @@ -1747,13 +1839,12 @@ pub fn render( description .extend(search.highlight_spans(visible_description, description_style)); } - if let Some(footer_label) = footer_label { + if has_footer { description.extend(right_aligned_footer_spans( description_width, visible_description, has_description, - footer_label, - footer_label_style, + footer_spans.clone(), )); } lines.push(Line::from(description)); @@ -2083,6 +2174,21 @@ fn display_metadata(entry: &ContentEntry) -> DisplayMetadata { } } +fn preserve_visual_metadata(entry: &mut ContentEntry, previous: &mut ContentEntry) { + if entry.icon_bytes.is_none() { + entry.icon_bytes = previous.icon_bytes.take(); + entry.icon_lines = previous.icon_lines.take(); + entry.provider_icon = previous.provider_icon; + } + if entry.description.trim().is_empty() && previous.provider_description { + entry.description = std::mem::take(&mut previous.description); + entry.provider_description = true; + } + if entry.provider_project.is_none() { + entry.provider_project = previous.provider_project.clone(); + } +} + // renders one row of a mod icon using half-block characters (U+2584). // each cell packs two vertical pixels via fg/bg colors, giving // double the vertical resolution out of the terminal @@ -2181,32 +2287,49 @@ fn available_description_width( fn description_text_width( available_width: usize, - footer_label: Option<&str>, + footer_width: usize, has_description: bool, ) -> usize { - let footer_width = footer_label.map_or(0, |footer_label| { - Span::raw(footer_label).width() + usize::from(has_description) - }); - available_width.saturating_sub(footer_width) + available_width.saturating_sub(footer_width + usize::from(has_description && footer_width > 0)) } fn right_aligned_footer_spans( available_width: usize, description: &str, has_description: bool, - footer_label: &str, - footer_style: Style, + footer: Vec>, ) -> Vec> { let description_width = if has_description { Span::raw(description).width() } else { 0 }; - let footer_width = Span::raw(footer_label).width(); + let footer_width = footer.iter().map(Span::width).sum::(); let padding = available_width.saturating_sub(description_width + footer_width); + let mut spans = vec![Span::raw(" ".repeat(padding))]; + spans.extend(footer); + spans +} + +fn version_change_spans(from: &str, to: &str) -> Vec> { + let theme = THEME.as_ref(); + let old = Style::default() + .fg(theme.background()) + .bg(theme.text_dim()) + .add_modifier(Modifier::BOLD); + let new = Style::default() + .fg(theme.background()) + .bg(theme.success()) + .add_modifier(Modifier::BOLD); vec![ - Span::raw(" ".repeat(padding)), - Span::styled(footer_label.to_owned(), footer_style), + Span::styled(format!(" {from} "), old), + Span::styled( + " ➜ ", + Style::default() + .fg(theme.accent()) + .add_modifier(Modifier::BOLD), + ), + Span::styled(format!(" {to} "), new), ] } diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index cd0a733..8d63d5f 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -291,6 +291,16 @@ pub fn render( .is_some(), _ => false, }); + let has_updates = match tab { + ContentTab::Mods => mods_state.entries.iter(), + ContentTab::ResourcePacks => resource_packs_state.entries.iter(), + ContentTab::Shaders => shaders_state.entries.iter(), + ContentTab::Worlds if open_world_datapacks.is_some() => { + world_datapacks_state.entries.iter() + } + _ => worlds_state.entries.iter(), + } + .any(|entry| entry.title_suffix.as_deref() == Some("Update")); // keybinds change depending on which tab is active and whether // the content panel or instances panel has focus @@ -414,9 +424,12 @@ pub fn render( None }; - let keybind_lines = kb.map_or_else(Vec::new, |keybinds| { - crate::tui::widgets::popups::keybind_lines_wrapped(keybinds, area.width.saturating_sub(2)) - }); + let mut keybinds = kb.map_or_else(Vec::new, <[_]>::to_vec); + if is_focused && mode == ContentMode::Installed && !has_updates { + keybinds.retain(|(key, _)| *key != "u"); + } + let keybind_lines = + crate::tui::widgets::popups::keybind_lines_wrapped(&keybinds, area.width.saturating_sub(2)); if let Some(line) = keybind_lines.last() { block = block.title_bottom(line.clone()); } @@ -833,14 +846,23 @@ fn render_version_popup( popup .visible_versions() .map(|version| { - let style = if current_version_id.as_deref() == Some(version.id.as_str()) { - Style::default() - .fg(theme.text()) - .add_modifier(Modifier::ITALIC) - } else { - Style::default().fg(theme.text()) - }; - ListItem::new(discovery_version_label(version)).style(style) + let mut spans = vec![Span::styled( + discovery_version_label(version), + Style::default().fg(theme.text()), + )]; + if current_version_id.as_deref() == Some(version.id.as_str()) { + spans.extend([ + Span::raw(" "), + Span::styled( + " Installed ", + Style::default() + .fg(theme.background()) + .bg(theme.success()) + .add_modifier(Modifier::BOLD), + ), + ]); + } + ListItem::new(Line::from(spans)) }) .collect::>() }; diff --git a/src/tui/widgets/content/update.rs b/src/tui/widgets/content/update.rs index 76959a5..c20799c 100644 --- a/src/tui/widgets/content/update.rs +++ b/src/tui/widgets/content/update.rs @@ -1,16 +1,17 @@ +use std::collections::HashMap; +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; +use std::time::Instant; use ratatui::{ Frame, - layout::{Constraint, Flex, Layout}, - style::{Modifier, Style}, - text::{Line, Span}, - widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph}, + layout::{Constraint, Margin}, }; -use crate::config::theme::{BORDER_STYLE, THEME}; use crate::instance::ContentKind; +use crate::instance::content::entry::ContentEntry; use crate::instance::content::updates::{BulkUpdatePlan, UpdateSnapshot}; +use crate::tui::widgets::popups::base::PopupFrame; pub enum PendingResult { Prepared(UpdateSnapshot, BulkUpdatePlan), @@ -29,28 +30,35 @@ pub struct State { pub phase: Phase, pub plan: Option, pub snapshot: Option, - pub selected: usize, - pub retry_conflicts: Vec, - pub error: Option, pub pending: Arc>>, pub kind: ContentKind, - pub target_world: Option<(String, std::path::PathBuf)>, + pub target_world: Option<(String, PathBuf)>, pub completed: bool, + pub applied: bool, + pub list: super::list::ContentListState, + source_entries: HashMap, } impl State { - pub fn checking(kind: ContentKind, target_world: Option<(String, std::path::PathBuf)>) -> Self { + pub fn checking( + kind: ContentKind, + target_world: Option<(String, PathBuf)>, + entries: Vec, + ) -> Self { Self { phase: Phase::Checking, plan: None, snapshot: None, - selected: 0, - retry_conflicts: Vec::new(), - error: None, pending: Arc::new(Mutex::new(Vec::new())), kind, target_world, completed: false, + applied: false, + list: super::list::ContentListState::default(), + source_entries: entries + .into_iter() + .map(|entry| (entry.path.clone(), entry)) + .collect(), } } @@ -64,21 +72,30 @@ impl State { changed = true; match result { PendingResult::Prepared(snapshot, plan) => { - self.retry_conflicts = vec![false; plan.conflicts.len()]; - self.phase = if plan.conflicts.is_empty() { + self.phase = if !plan.conflicts.is_empty() { + Phase::Conflicts + } else if !plan.roots.is_empty() { Phase::Review } else { - Phase::Conflicts + self.completed = true; + Phase::Review }; - self.selected = 0; self.snapshot = Some(snapshot); self.plan = Some(plan); - self.error = None; + self.rebuild_list(); + } + PendingResult::Applied(Ok(())) => { + self.completed = true; + self.applied = true; } - PendingResult::Applied(Ok(())) => self.completed = true, PendingResult::Applied(Err(error)) => { - self.phase = Phase::Review; - self.error = Some(error); + crate::feedback::errors::push_error(crate::feedback::errors::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: format!("Failed to update content: {error}"), + pushed_at: Instant::now(), + }); + self.completed = true; } } } @@ -92,111 +109,189 @@ impl State { } } - pub fn has_retry(&self) -> bool { - self.retry_conflicts.iter().any(|retry| *retry) + pub fn visible(&self) -> bool { + matches!(self.phase, Phase::Conflicts | Phase::Review) && !self.completed } -} -pub fn render(frame: &mut Frame, state: &State) { - let theme = THEME.as_ref(); - let item_count = match state.phase { - Phase::Conflicts => state.plan.as_ref().map_or(0, |plan| plan.conflicts.len()), - Phase::Review => state.plan.as_ref().map_or(0, |plan| plan.roots.len()), - _ => 1, - }; - let height = (item_count as u16 + 5).clamp(7, 20); - let [area] = Layout::vertical([Constraint::Length(height)]) - .flex(Flex::Center) - .areas(frame.area()); - let [area] = Layout::horizontal([Constraint::Percentage(62)]) - .flex(Flex::Center) - .areas(area); - frame.render_widget(Clear, area); + pub fn has_updates(&self) -> bool { + self.plan + .as_ref() + .is_some_and(|plan| !plan.roots.is_empty()) + } - let (title, footer) = match state.phase { - Phase::Checking => (" Check for updates ", " [Esc] close "), - Phase::Conflicts => ( - " Resolve update conflicts ", - " [j/k] select [Space] keep/retry [Enter] continue [Esc] close ", - ), - Phase::Review => ( - " Update installed content ", - " [Enter] update all [Esc] close ", - ), - Phase::Applying => (" Updating installed content ", " Please wait "), - }; - let block = Block::default() - .title(title) - .title_bottom(Line::from(footer).centered()) - .borders(Borders::ALL) - .border_type(BORDER_STYLE.to_border_type()) - .border_style(Style::default().fg(theme.accent())) - .style(Style::default().fg(theme.text()).bg(theme.surface())); + pub fn show_review(&mut self) { + self.phase = Phase::Review; + self.rebuild_list(); + } - match state.phase { - Phase::Checking | Phase::Applying => { - let message = if state.phase == Phase::Checking { - "Checking compatible versions and dependencies…" - } else { - "Installing the accepted update set…" - }; - frame.render_widget(Paragraph::new(message).block(block), area); + pub fn show_conflicts(&mut self) { + if self + .plan + .as_ref() + .is_some_and(|plan| !plan.conflicts.is_empty()) + { + self.phase = Phase::Conflicts; + self.rebuild_list(); } - Phase::Conflicts => { - let items = state + } + + fn rebuild_list(&mut self) { + let entries = match self.phase { + Phase::Conflicts => self .plan .as_ref() .into_iter() .flat_map(|plan| plan.conflicts.iter()) - .enumerate() - .map(|(index, conflict)| { - let action = if state.retry_conflicts.get(index) == Some(&true) { - "Retry" - } else { - "Keep" - }; - ListItem::new(vec![ - Line::from(vec![ - Span::styled( - conflict.title.clone(), - Style::default().add_modifier(Modifier::BOLD), - ), - Span::raw(" "), - Span::styled(action, Style::default().fg(theme.accent())), - ]), - Line::from(conflict.reason.clone()) - .style(Style::default().fg(theme.text_dim())), - ]) - }); - let mut selected = ListState::default().with_selected(Some(state.selected)); - let list = List::new(items) - .block(block) - .highlight_symbol("▌") - .highlight_style(Style::default().bg(theme.stripe())); - frame.render_stateful_widget(list, area, &mut selected); - } - Phase::Review => { - let mut items = state + .map(|conflict| { + let mut entry = self.entry_for(&conflict.installed_path, &conflict.title); + entry.description = user_conflict_reason(&conflict.reason); + entry.title_suffix = Some("Skipped".to_owned()); + entry.footer_label = None; + entry.footer_change = None; + entry + }) + .collect(), + Phase::Review => self .plan .as_ref() .into_iter() .flat_map(|plan| plan.roots.iter()) .map(|root| { - ListItem::new(Line::from(format!( - "• {} {} → {}", - root.title, root.current_version, root.target.version_number - ))) + let mut entry = self.entry_for(&root.installed_path, &root.title); + entry.title_suffix = Some("Update".to_owned()); + entry.description.clear(); + entry.footer_label = None; + entry.footer_change = Some(( + root.current_version.clone(), + root.target.version_number.clone(), + )); + entry }) - .collect::>(); - if items.is_empty() { - items.push(ListItem::new("No compatible updates available.")); - } - if let Some(error) = &state.error { - items.push(ListItem::new( - Line::from(error.clone()).style(Style::default().fg(theme.error())), - )); - } - frame.render_widget(List::new(items).block(block), area); - } + .collect(), + Phase::Checking | Phase::Applying => Vec::new(), + }; + self.list.set_entries(entries); + } + + fn entry_for(&self, path: &Path, title: &str) -> ContentEntry { + self.source_entries + .get(path) + .cloned() + .unwrap_or_else(|| ContentEntry { + file_stem: path + .file_stem() + .and_then(|stem| stem.to_str()) + .unwrap_or(title) + .to_owned(), + name: title.to_owned(), + source_slug: None, + installed_path: Some(path.to_owned()), + provider_project: None, + world_details: None, + title_suffix: None, + footer_label: None, + footer_change: None, + description: String::new(), + enabled: true, + icon_bytes: None, + provider_icon: false, + provider_description: false, + path: path.to_owned(), + icon_lines: Some(crate::instance::content::fallback_icon()), + }) } } + +pub fn render(frame: &mut Frame, state: &mut State, picker: &ratatui_image::picker::Picker) { + if !state.visible() { + return; + } + let count = state.list.entries.len() as u16; + let height = count.saturating_mul(3).saturating_add(2).clamp(5, 20); + let area = frame.area().centered( + Constraint::Percentage(60), + Constraint::Length(height.min(frame.area().height.saturating_sub(4))), + ); + let theme = crate::config::theme::THEME.as_ref(); + let (title, keybinds) = match state.phase { + Phase::Conflicts => ( + "Updates needing attention", + if state.has_updates() { + crate::tui::widgets::popups::keybind_line(&[ + ("j/k", " navigate"), + ("Enter", " review updates"), + ("h/Esc", " close"), + ]) + } else { + crate::tui::widgets::popups::keybind_line(&[ + ("j/k", " navigate"), + ("h/Esc", " close"), + ]) + }, + ), + Phase::Review => ( + "Update installed content", + if state + .plan + .as_ref() + .is_some_and(|plan| !plan.conflicts.is_empty()) + { + crate::tui::widgets::popups::keybind_line(&[ + ("j/k", " navigate"), + ("h", " back"), + ("Enter", " update all"), + ("Esc", " close"), + ]) + } else { + crate::tui::widgets::popups::keybind_line(&[ + ("j/k", " navigate"), + ("Enter", " update all"), + ("Esc", " close"), + ]) + }, + ), + Phase::Checking | Phase::Applying => return, + }; + let popup = PopupFrame { + title: crate::tui::widgets::styled_title(title, false), + border_color: theme.accent(), + bg: Some(theme.surface()), + keybinds: Some(keybinds), + search_line: None, + content: Box::new(|_, _| {}), + }; + frame.render_widget(popup, area); + super::list::render( + frame, + area.inner(Margin::new(1, 1)), + &mut state.list, + true, + "", + "", + picker, + false, + false, + ); +} + +fn user_conflict_reason(reason: &str) -> String { + let reason = reason.strip_prefix("Parse error: ").unwrap_or(reason); + if let Some(details) = reason + .strip_prefix("Conflicting selected versions for '") + .or_else(|| reason.strip_prefix("Conflicting required versions for '")) + && let Some((dependency, versions)) = details.split_once("': '") + && let Some((first, second)) = versions.split_once("' and '") + { + return format!( + "Other updates need different {dependency} versions ({first} and {}). This mod was left unchanged; update it separately with v.", + second.trim_end_matches('\'') + ); + } + format!( + "This update could not be prepared: {reason}. The installed version was left unchanged; try updating it separately with v." + ) +} + +#[cfg(test)] +#[path = "../../tests/widgets/content/update.rs"] +mod tests;