diff --git a/src/instance/content/provider.rs b/src/instance/content/provider.rs index 266dbd9..563e8af 100644 --- a/src/instance/content/provider.rs +++ b/src/instance/content/provider.rs @@ -368,6 +368,16 @@ pub struct ProviderRegistry { providers: Vec>, } +pub(crate) fn has_newer_compatible_version( + versions: &[VersionInfo], + installed_version_id: &str, +) -> bool { + versions + .iter() + .position(|version| version.id == installed_version_id) + .is_some_and(|position| position > 0) +} + impl ProviderRegistry { pub(crate) fn new(providers: Vec>) -> Self { Self { providers } diff --git a/src/instance/import/curseforge.rs b/src/instance/import/curseforge.rs index 5e9f180..512a208 100644 --- a/src/instance/import/curseforge.rs +++ b/src/instance/import/curseforge.rs @@ -104,6 +104,7 @@ pub fn build_summary(path: &Path) -> Result { override_count, format: PackFormat::CurseForge, archive_path: path.to_owned(), + source: None, }) } diff --git a/src/instance/import/mmc.rs b/src/instance/import/mmc.rs index 0c9438b..302a110 100644 --- a/src/instance/import/mmc.rs +++ b/src/instance/import/mmc.rs @@ -87,6 +87,7 @@ pub fn build_summary(path: &Path) -> Result { override_count, format: PackFormat::Mmc, archive_path: path.to_path_buf(), + source: None, }) } diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index f333ed2..a2545a3 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -71,6 +71,7 @@ pub struct ImportSummary { pub override_count: usize, pub format: PackFormat, pub archive_path: PathBuf, + pub source: Option, } // peeks inside a zip to figure out what format it is. @@ -175,11 +176,16 @@ pub async fn execute_import( summary.name, summary.archive_path.display() ); - match summary.format { + let mut config = match summary.format { PackFormat::CurseForge => curseforge::execute_import(summary, manager).await, PackFormat::Mrpack => mrpack::execute_import(summary, manager).await, PackFormat::Mmc => mmc::execute_import(summary, manager).await, + }?; + if summary.source.is_some() { + config.modpack_source = summary.source.clone(); + manager.save(&config)?; } + Ok(config) } fn cleanup_failed_import(manager: &InstanceManager, name: &str) { diff --git a/src/instance/import/mrpack.rs b/src/instance/import/mrpack.rs index 00964f8..e4a66d1 100644 --- a/src/instance/import/mrpack.rs +++ b/src/instance/import/mrpack.rs @@ -125,6 +125,7 @@ pub fn build_summary(path: &Path) -> Result { override_count, format: PackFormat::Mrpack, archive_path: path.to_path_buf(), + source: None, }) } diff --git a/src/instance/manager.rs b/src/instance/manager.rs index dcf0da6..0162680 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -272,6 +272,7 @@ impl InstanceManager { jvm_args: vec![], resolution: None, config_sync_profile: None, + modpack_source: None, }; self.save(&config)?; diff --git a/src/instance/models.rs b/src/instance/models.rs index 34bbf37..2881d44 100644 --- a/src/instance/models.rs +++ b/src/instance/models.rs @@ -49,6 +49,8 @@ pub struct InstanceConfig { pub resolution: Option<(u32, u32)>, #[serde(default)] pub config_sync_profile: Option, + #[serde(default)] + pub modpack_source: Option, } pub fn normalize_memory_value(raw: &str) -> Option { diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index 082b84a..4264ad9 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -200,6 +200,7 @@ fn instance() -> InstanceConfig { jvm_args: Vec::new(), resolution: None, config_sync_profile: None, + modpack_source: None, } } diff --git a/src/instance/tests/content/provider.rs b/src/instance/tests/content/provider.rs index 6b1fea4..acb56a5 100644 --- a/src/instance/tests/content/provider.rs +++ b/src/instance/tests/content/provider.rs @@ -5,3 +5,24 @@ fn registry_falls_back_to_first_capable_provider() { let registry = ProviderRegistry::modrinth(crate::net::HttpClient::new()); assert_eq!(registry.preferred("unknown").unwrap().id(), "modrinth"); } + +#[test] +fn update_check_requires_the_installed_version_behind_a_newer_result() { + let version = |id: &str| VersionInfo { + id: id.to_owned(), + project_id: "project".to_owned(), + name: id.to_owned(), + version_number: id.to_owned(), + game_versions: vec!["1.21.1".to_owned()], + loaders: vec!["fabric".to_owned()], + version_type: crate::net::modrinth::VersionType::Release, + dependencies: Vec::new(), + date_published: String::new(), + files: Vec::new(), + }; + let versions = vec![version("new"), version("installed")]; + + assert!(has_newer_compatible_version(&versions, "installed")); + assert!(!has_newer_compatible_version(&versions, "new")); + assert!(!has_newer_compatible_version(&versions, "missing")); +} diff --git a/src/instance/tests/content/reconcile.rs b/src/instance/tests/content/reconcile.rs index 120e75b..822fe1d 100644 --- a/src/instance/tests/content/reconcile.rs +++ b/src/instance/tests/content/reconcile.rs @@ -23,6 +23,7 @@ fn job(name: &str) -> ReconcileJob { jvm_args: Vec::new(), resolution: None, config_sync_profile: None, + modpack_source: None, }, instances_dir: PathBuf::new(), client: crate::net::HttpClient::new(), diff --git a/src/instance/tests/launch/pipeline.rs b/src/instance/tests/launch/pipeline.rs index 6ab7281..0ef3bc9 100644 --- a/src/instance/tests/launch/pipeline.rs +++ b/src/instance/tests/launch/pipeline.rs @@ -179,6 +179,7 @@ async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() { jvm_args: Vec::new(), resolution: None, config_sync_profile: None, + modpack_source: None, }; let result = @@ -227,6 +228,7 @@ async fn migrate_legacy_loader_profile_skips_fabric() { jvm_args: Vec::new(), resolution: None, config_sync_profile: None, + modpack_source: None, }; let result = migrate_legacy_loader_profile_if_needed( diff --git a/src/instance/tests/manager.rs b/src/instance/tests/manager.rs index a56f9a5..8756366 100644 --- a/src/instance/tests/manager.rs +++ b/src/instance/tests/manager.rs @@ -26,6 +26,7 @@ fn dummy_config(name: &str) -> InstanceConfig { jvm_args: vec![], resolution: None, config_sync_profile: None, + modpack_source: None, } } diff --git a/src/instance/tests/models.rs b/src/instance/tests/models.rs index 6189ed7..fde155b 100644 --- a/src/instance/tests/models.rs +++ b/src/instance/tests/models.rs @@ -15,6 +15,11 @@ fn instance_config_roundtrips_through_json() { jvm_args: vec![], resolution: Some((1920, 1080)), config_sync_profile: None, + modpack_source: Some(crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "pack".to_owned(), + version_id: "version".to_owned(), + }), }; let json = serde_json::to_string_pretty(&config).expect("serialize"); let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize"); @@ -22,6 +27,7 @@ fn instance_config_roundtrips_through_json() { assert_eq!(parsed.game_version, config.game_version); assert_eq!(parsed.loader, config.loader); assert_eq!(parsed.resolution, config.resolution); + assert_eq!(parsed.modpack_source, config.modpack_source); } #[test] diff --git a/src/tui/app.rs b/src/tui/app.rs index de8539d..0aa4d5a 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -115,6 +115,7 @@ impl App { let manager = InstanceManager::new(instances_dir, meta_dir); let instances = manager.load_all(); + instances::spawn_modpack_update_checks(&instances); let instances_state = instances::State::with_instances(instances); let mut mods_state = widgets::content::list::ContentListState::default(); diff --git a/src/tui/event.rs b/src/tui/event.rs index 55b5575..cd34a00 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -40,6 +40,7 @@ impl App { // every content type has its own pending queue because they each // get scanned/loaded on separate tokio tasks self.drain_pending_instances(); + self.instances_state.drain_modpack_updates(); self.drain_pending_last_played(); let mut local_streamed = false; let mut content_changed = false; @@ -686,6 +687,7 @@ impl App { fn drain_pending_instances(&mut self) { if let Ok(mut pending) = PENDING_INSTANCES.lock() { for config in pending.drain(..) { + widgets::instances::spawn_modpack_update_check(&config); self.instances_state.add_instance(config); } } diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 9b2c797..649df93 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -122,6 +122,7 @@ impl UiHarness { jvm_args: Vec::new(), resolution: None, config_sync_profile: None, + modpack_source: None, }; std::fs::create_dir_all(self.instance_path(name)).expect("instance directory"); self.app diff --git a/src/tui/tests/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index 132772c..c5871f6 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -42,6 +42,7 @@ fn instance(name: &str, version: &str) -> InstanceConfig { jvm_args: Vec::new(), resolution: None, config_sync_profile: None, + modpack_source: None, } } diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index aa489b6..1ca61eb 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -15,9 +15,9 @@ use ratatui::{ use super::{ ContentListState, WatcherEventHandling, available_description_width, description_text_width, - diff_directory, diff_event_paths, ellipsize, has_newer_compatible_version, - 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, + 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, }; fn entry(name: &str) -> ContentEntry { @@ -695,24 +695,3 @@ async fn provider_metadata_loads_from_cache_without_network() { assert_eq!(description, "Cached description"); assert!(!update_available); } - -#[test] -fn update_check_requires_the_installed_version_behind_a_newer_result() { - let version = |id: &str| crate::net::modrinth::VersionInfo { - id: id.to_owned(), - project_id: "project".to_owned(), - name: id.to_owned(), - version_number: id.to_owned(), - game_versions: vec!["1.21.1".to_owned()], - loaders: vec!["fabric".to_owned()], - version_type: crate::net::modrinth::VersionType::Release, - dependencies: Vec::new(), - date_published: String::new(), - files: Vec::new(), - }; - let versions = vec![version("new"), version("installed")]; - - assert!(has_newer_compatible_version(&versions, "installed")); - assert!(!has_newer_compatible_version(&versions, "new")); - assert!(!has_newer_compatible_version(&versions, "missing")); -} diff --git a/src/tui/tests/widgets/instances.rs b/src/tui/tests/widgets/instances.rs index ec2ed88..88efaec 100644 --- a/src/tui/tests/widgets/instances.rs +++ b/src/tui/tests/widgets/instances.rs @@ -46,6 +46,7 @@ fn synthetic_instance(name: &str) -> InstanceConfig { jvm_args: vec![], resolution: None, config_sync_profile: None, + modpack_source: None, } } @@ -78,3 +79,24 @@ fn instances_list_renders_empty() { insta::assert_snapshot!(terminal.backend()); } + +#[test] +fn managed_modpack_update_is_badged_in_the_instance_list() { + let mut state = State::with_instances(vec![synthetic_instance("Managed Pack")]); + state.modpack_updates.insert("Managed Pack".to_owned()); + let backend = TestBackend::new(40, 5); + let mut terminal = Terminal::new(backend).unwrap(); + + terminal + .draw(|frame| render(frame, frame.area(), FocusedArea::Instances, &mut state)) + .unwrap(); + + let text = terminal + .backend() + .buffer() + .content() + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains("Managed Pack Update")); +} diff --git a/src/tui/tests/widgets/popups/import_modpack/render.rs b/src/tui/tests/widgets/popups/import_modpack/render.rs index db20f30..51431ca 100644 --- a/src/tui/tests/widgets/popups/import_modpack/render.rs +++ b/src/tui/tests/widgets/popups/import_modpack/render.rs @@ -154,6 +154,7 @@ fn import_modpack_renders_confirm_step() { override_count: 3, format: PackFormat::Mrpack, archive_path: PathBuf::from("/tmp/synthetic.mrpack"), + source: None, }); } @@ -197,6 +198,7 @@ fn import_modpack_renders_confirm_step_without_loader_version() { override_count: 12, format: PackFormat::Mmc, archive_path: PathBuf::from("/tmp/vanilla.zip"), + source: None, }); } diff --git a/src/tui/tests/widgets/popups/import_modpack/state.rs b/src/tui/tests/widgets/popups/import_modpack/state.rs index a9c0fa7..d170078 100644 --- a/src/tui/tests/widgets/popups/import_modpack/state.rs +++ b/src/tui/tests/widgets/popups/import_modpack/state.rs @@ -24,6 +24,7 @@ fn summary() -> ImportSummary { override_count: 1, format: PackFormat::Mrpack, archive_path: PathBuf::from("test.mrpack"), + source: None, } } diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 45498ab..be93663 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -1399,7 +1399,10 @@ async fn load_provider_metadata( ) .await { - Ok(versions) => has_newer_compatible_version(&versions, &installed.version_id), + Ok(versions) => crate::instance::content::provider::has_newer_compatible_version( + &versions, + &installed.version_id, + ), Err(error) => { tracing::debug!("Could not check updates for project '{project_id}': {error}"); false @@ -1428,16 +1431,6 @@ async fn load_provider_metadata( Ok((bytes, project.description, update_available)) } -fn has_newer_compatible_version( - versions: &[crate::net::modrinth::VersionInfo], - installed_version_id: &str, -) -> bool { - versions - .iter() - .position(|version| version.id == installed_version_id) - .is_some_and(|position| position > 0) -} - pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState) -> bool { handle_key_inner(key_event, state, false) } diff --git a/src/tui/widgets/instances.rs b/src/tui/widgets/instances.rs index 0dd0305..74129b5 100644 --- a/src/tui/widgets/instances.rs +++ b/src/tui/widgets/instances.rs @@ -11,6 +11,8 @@ use ratatui::{ text::{Line, Span, Text}, widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState}, }; +use std::collections::HashSet; +use std::sync::{Arc, LazyLock, Mutex}; use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use crate::instance::models::InstanceConfig; @@ -20,6 +22,55 @@ use crate::tui::app::FocusedArea; use super::{WidgetKey, search::SearchState, styled_title}; +static PENDING_MODPACK_UPDATES: LazyLock< + Mutex>, +> = LazyLock::new(|| Mutex::new(Vec::new())); +static MODPACK_UPDATE_SLOTS: LazyLock> = + LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(4))); + +pub fn spawn_modpack_update_checks(instances: &[InstanceConfig]) { + for instance in instances { + spawn_modpack_update_check(instance); + } +} + +pub fn spawn_modpack_update_check(instance: &InstanceConfig) { + let Some(source) = instance.modpack_source.clone() else { + return; + }; + let instance = instance.clone(); + tokio::spawn(async move { + let Ok(_permit) = MODPACK_UPDATE_SLOTS.clone().acquire_owned().await else { + return; + }; + let registry = crate::instance::content::provider::ProviderRegistry::configured( + crate::net::HttpClient::new(), + ); + let Some(provider) = registry.get(&source.provider) else { + return; + }; + let Ok(versions) = provider + .compatible_versions( + &source.project_id, + crate::instance::ContentKind::Mod, + &instance.game_version, + instance.loader, + ) + .await + else { + return; + }; + let update = crate::instance::content::provider::has_newer_compatible_version( + &versions, + &source.version_id, + ); + if let Ok(mut pending) = PENDING_MODPACK_UPDATES.lock() { + pending.push((instance.name, source, update)); + crate::feedback::request_redraw(); + } + }); +} + #[derive(Debug, Default)] pub struct State { pub instances: Vec, @@ -29,6 +80,7 @@ pub struct State { pub show_import_popup: bool, pub search: SearchState, pub renaming: Option, + pub(crate) modpack_updates: HashSet, } impl State { @@ -42,6 +94,7 @@ impl State { show_import_popup: false, search: SearchState::default(), renaming: None, + modpack_updates: HashSet::new(), }; if count > 0 { s.list_state.selected = Some(0); @@ -122,10 +175,33 @@ impl State { self.instances.retain(|i| i.name != name); let after = self.instances.len(); if after < before { + self.modpack_updates.remove(name); self.update_scrollbar(); } } + pub fn drain_modpack_updates(&mut self) { + let Ok(mut pending) = PENDING_MODPACK_UPDATES.lock() else { + return; + }; + for (name, source, available) in pending.drain(..) { + if self + .instances + .iter() + .find(|instance| instance.name == name) + .and_then(|instance| instance.modpack_source.as_ref()) + != Some(&source) + { + continue; + } + if available { + self.modpack_updates.insert(name); + } else { + self.modpack_updates.remove(&name); + } + } + } + pub fn add_instance(&mut self, instance: InstanceConfig) { self.instances.push(instance); self.list_state.selected = self.filtered_indices().len().checked_sub(1); @@ -275,6 +351,18 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S } else { let mut spans = vec![selector.clone()]; spans.extend(state.search.highlight_spans(&instance.name, name_style)); + if state.modpack_updates.contains(&instance.name) { + spans.extend([ + Span::raw(" "), + Span::styled( + "Update", + Style::default() + .fg(theme.background()) + .bg(theme.warning()) + .add_modifier(Modifier::BOLD), + ), + ]); + } Line::from(spans) }; diff --git a/src/tui/widgets/popups/import_modpack/state.rs b/src/tui/widgets/popups/import_modpack/state.rs index 4007701..86de361 100644 --- a/src/tui/widgets/popups/import_modpack/state.rs +++ b/src/tui/widgets/popups/import_modpack/state.rs @@ -667,7 +667,12 @@ fn start_discovered_download(request: crate::tui::widgets::content::discovery::I let tmp_dir = crate::storage::MetadataPaths::new(crate::config::SETTINGS.paths.resolve_meta_dir()) .temporary(); - let result = async { + let result: Result = async { + let source = crate::instance::ProviderProject { + provider: request.provider.clone(), + project_id: request.project_id.clone(), + version_id: request.version.id.clone(), + }; tokio::fs::create_dir_all(&tmp_dir).await?; let provider = registry.get(&request.provider).ok_or_else(|| { crate::net::NetError::Parse(format!( @@ -682,7 +687,10 @@ fn start_discovered_download(request: crate::tui::widgets::content::discovery::I crate::net::modrinth::DownloadOutcome::Downloaded(path) | crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => path, }; - crate::instance::import::build_summary(&path).map_err(crate::net::NetError::Parse) + let mut summary = crate::instance::import::build_summary(&path) + .map_err(crate::net::NetError::Parse)?; + summary.source = Some(source); + Ok(summary) } .await; match result { diff --git a/tests/launch_pipeline.rs b/tests/launch_pipeline.rs index d770758..b93f853 100644 --- a/tests/launch_pipeline.rs +++ b/tests/launch_pipeline.rs @@ -55,6 +55,7 @@ fn make_config_with( jvm_args: Vec::new(), resolution: None, config_sync_profile: None, + modpack_source: None, } }