feat(tui): integrate content migration workflow
This commit is contained in:
1 parent
fbf8142ea0
commit
8a2a562235
11 files changed
+1477
-305
No files matched your search
+22
-1
@@ -3,7 +3,8 @@
|
||||
// kinda pushes you into this pattern since you need mutable access
|
||||
// to all the widget states during rendering.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
|
||||
use tachyonfx::Effect;
|
||||
@@ -44,6 +45,17 @@ pub struct App {
|
||||
pub(super) throbber_tick: u8,
|
||||
pub(super) error_effects: HashMap<u64, ErrorEffectState>,
|
||||
pub(super) pending_editor: Option<std::path::PathBuf>,
|
||||
pub(super) reconciliation_for: Option<String>,
|
||||
pub(super) content_manifest: Option<(String, crate::instance::ContentManifest)>,
|
||||
pub(super) content_icons: HashMap<(String, String), Vec<u8>>,
|
||||
pub(super) provider_conflict: Option<ProviderConflictState>,
|
||||
pub(super) dismissed_provider_conflicts: HashSet<PathBuf>,
|
||||
}
|
||||
|
||||
pub(super) struct ProviderConflictState {
|
||||
pub relative_path: PathBuf,
|
||||
pub candidates: Vec<crate::instance::ProviderProject>,
|
||||
pub selected: usize,
|
||||
}
|
||||
|
||||
// lifecycle of an error toast animation: slide in -> sit there -> fade out
|
||||
@@ -118,6 +130,15 @@ impl App {
|
||||
throbber_tick: 0,
|
||||
error_effects: HashMap::new(),
|
||||
pending_editor: None,
|
||||
reconciliation_for: None,
|
||||
content_manifest: None,
|
||||
content_icons: HashMap::new(),
|
||||
provider_conflict: None,
|
||||
dismissed_provider_conflicts: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn into_picker(self) -> ratatui_image::picker::Picker {
|
||||
self.picker
|
||||
}
|
||||
}
|
||||
+192
-33
@@ -34,19 +34,10 @@ impl App {
|
||||
// get scanned/loaded on separate tokio tasks
|
||||
self.drain_pending_instances();
|
||||
self.drain_pending_last_played();
|
||||
self.mods_state.drain_pending();
|
||||
self.mods_state.drain_watcher();
|
||||
let local_streamed = self.mods_state.drain_pending();
|
||||
let content_changed = self.mods_state.drain_watcher();
|
||||
self.mods_state.request_image_loads(&self.picker);
|
||||
self.mods_state.drain_image_loads(&self.picker);
|
||||
if self.mods_state.loaded_for.as_deref()
|
||||
== self
|
||||
.instances_state
|
||||
.selected_instance()
|
||||
.map(|instance| instance.name.as_str())
|
||||
{
|
||||
self.mods_discovery_state
|
||||
.refresh_installed_labels(&self.mods_state.entries);
|
||||
}
|
||||
self.mods_discovery_state.drain_pending();
|
||||
self.mods_discovery_state.list.drain_pending();
|
||||
self.mods_discovery_state
|
||||
@@ -55,19 +46,10 @@ impl App {
|
||||
self.mods_discovery_state
|
||||
.list
|
||||
.drain_image_loads(&self.picker);
|
||||
self.resource_packs_state.drain_pending();
|
||||
self.resource_packs_state.drain_watcher();
|
||||
let local_streamed = self.resource_packs_state.drain_pending() || local_streamed;
|
||||
let content_changed = self.resource_packs_state.drain_watcher() || content_changed;
|
||||
self.resource_packs_state.request_image_loads(&self.picker);
|
||||
self.resource_packs_state.drain_image_loads(&self.picker);
|
||||
if self.resource_packs_state.loaded_for.as_deref()
|
||||
== self
|
||||
.instances_state
|
||||
.selected_instance()
|
||||
.map(|instance| instance.name.as_str())
|
||||
{
|
||||
self.resource_packs_discovery_state
|
||||
.refresh_installed_labels(&self.resource_packs_state.entries);
|
||||
}
|
||||
self.resource_packs_discovery_state.drain_pending();
|
||||
self.resource_packs_discovery_state.list.drain_pending();
|
||||
self.resource_packs_discovery_state
|
||||
@@ -76,19 +58,10 @@ impl App {
|
||||
self.resource_packs_discovery_state
|
||||
.list
|
||||
.drain_image_loads(&self.picker);
|
||||
self.shaders_state.drain_pending();
|
||||
self.shaders_state.drain_watcher();
|
||||
let local_streamed = self.shaders_state.drain_pending() || local_streamed;
|
||||
let content_changed = self.shaders_state.drain_watcher() || content_changed;
|
||||
self.shaders_state.request_image_loads(&self.picker);
|
||||
self.shaders_state.drain_image_loads(&self.picker);
|
||||
if self.shaders_state.loaded_for.as_deref()
|
||||
== self
|
||||
.instances_state
|
||||
.selected_instance()
|
||||
.map(|instance| instance.name.as_str())
|
||||
{
|
||||
self.shaders_discovery_state
|
||||
.refresh_installed_labels(&self.shaders_state.entries);
|
||||
}
|
||||
self.shaders_discovery_state.drain_pending();
|
||||
self.shaders_discovery_state.list.drain_pending();
|
||||
self.shaders_discovery_state
|
||||
@@ -108,6 +81,21 @@ impl App {
|
||||
self.screenshots_state.drain_pending_entries();
|
||||
self.screenshots_state.request_visible_loads();
|
||||
self.create_screenshot_protocols();
|
||||
if content_changed {
|
||||
self.reconciliation_for = None;
|
||||
if let Some(instance) = self.instances_state.selected_instance()
|
||||
&& let Ok(mut results) =
|
||||
crate::instance::content::reconcile::PENDING_RECONCILIATIONS.lock()
|
||||
{
|
||||
results.retain(|result| result.instance_name != instance.name);
|
||||
}
|
||||
}
|
||||
self.drain_content_reconciliation();
|
||||
self.ensure_content_reconciliation(content_changed);
|
||||
if local_streamed {
|
||||
self.apply_cached_content_manifest();
|
||||
}
|
||||
self.ensure_provider_conflict_popup();
|
||||
self.ensure_active_discovery_loaded();
|
||||
let progress_active = progress::is_active();
|
||||
let spinner_active = progress_active || crate::running::has_active();
|
||||
@@ -136,6 +124,177 @@ impl App {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_content_reconciliation(&mut self, changed: bool) {
|
||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||
self.reconciliation_for = None;
|
||||
self.content_manifest = None;
|
||||
self.content_icons.clear();
|
||||
return;
|
||||
};
|
||||
if !changed && self.reconciliation_for.as_deref() == Some(instance.name.as_str()) {
|
||||
return;
|
||||
}
|
||||
if self.reconciliation_for.as_deref() != Some(instance.name.as_str()) {
|
||||
self.provider_conflict = None;
|
||||
self.dismissed_provider_conflicts.clear();
|
||||
}
|
||||
self.reconciliation_for = Some(instance.name.clone());
|
||||
self.content_manifest = None;
|
||||
self.content_icons.clear();
|
||||
for discovery in [
|
||||
&mut self.mods_discovery_state,
|
||||
&mut self.resource_packs_discovery_state,
|
||||
&mut self.shaders_discovery_state,
|
||||
] {
|
||||
discovery.refresh_installed_manifest(
|
||||
&crate::instance::ContentManifest::default(),
|
||||
&crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(&instance.name),
|
||||
)
|
||||
.minecraft(),
|
||||
);
|
||||
}
|
||||
if changed {
|
||||
crate::instance::content::reconcile::spawn_after_change(
|
||||
instance,
|
||||
self.instance_manager.instances_dir.clone(),
|
||||
self.instance_manager.meta_dir.clone(),
|
||||
crate::net::HttpClient::new(),
|
||||
);
|
||||
} else {
|
||||
crate::instance::content::reconcile::spawn(
|
||||
instance,
|
||||
self.instance_manager.instances_dir.clone(),
|
||||
self.instance_manager.meta_dir.clone(),
|
||||
crate::net::HttpClient::new(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn drain_content_reconciliation(&mut self) {
|
||||
let Some(selected) = self.instances_state.selected_instance() else {
|
||||
return;
|
||||
};
|
||||
let result = match crate::instance::content::reconcile::PENDING_RECONCILIATIONS.lock() {
|
||||
Ok(mut results) => results
|
||||
.iter()
|
||||
.position(|result| result.instance_name == selected.name)
|
||||
.map(|index| results.remove(index)),
|
||||
Err(_) => return,
|
||||
};
|
||||
let Some(result) = result else {
|
||||
return;
|
||||
};
|
||||
self.reconciliation_for = Some(result.instance_name.clone());
|
||||
if let Some(error) = result.error {
|
||||
tracing::warn!(
|
||||
"Content reconciliation for {} was incomplete: {}",
|
||||
result.instance_name,
|
||||
error
|
||||
);
|
||||
}
|
||||
let minecraft_dir = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(&selected.name),
|
||||
)
|
||||
.minecraft();
|
||||
self.mods_state.apply_manifest(
|
||||
&result.manifest,
|
||||
&minecraft_dir,
|
||||
crate::instance::ContentKind::Mod,
|
||||
&result.icons,
|
||||
);
|
||||
self.resource_packs_state.apply_manifest(
|
||||
&result.manifest,
|
||||
&minecraft_dir,
|
||||
crate::instance::ContentKind::ResourcePack,
|
||||
&result.icons,
|
||||
);
|
||||
self.shaders_state.apply_manifest(
|
||||
&result.manifest,
|
||||
&minecraft_dir,
|
||||
crate::instance::ContentKind::Shader,
|
||||
&result.icons,
|
||||
);
|
||||
self.mods_discovery_state
|
||||
.refresh_installed_manifest(&result.manifest, &minecraft_dir);
|
||||
self.resource_packs_discovery_state
|
||||
.refresh_installed_manifest(&result.manifest, &minecraft_dir);
|
||||
self.shaders_discovery_state
|
||||
.refresh_installed_manifest(&result.manifest, &minecraft_dir);
|
||||
self.content_icons = result.icons;
|
||||
self.content_manifest = Some((result.instance_name, result.manifest));
|
||||
}
|
||||
|
||||
fn apply_cached_content_manifest(&mut self) {
|
||||
let Some((instance_name, manifest)) = &self.content_manifest else {
|
||||
return;
|
||||
};
|
||||
if self
|
||||
.instances_state
|
||||
.selected_instance()
|
||||
.is_none_or(|instance| instance.name != *instance_name)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let minecraft_dir = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(instance_name),
|
||||
)
|
||||
.minecraft();
|
||||
self.mods_state.apply_manifest(
|
||||
manifest,
|
||||
&minecraft_dir,
|
||||
crate::instance::ContentKind::Mod,
|
||||
&self.content_icons,
|
||||
);
|
||||
self.resource_packs_state.apply_manifest(
|
||||
manifest,
|
||||
&minecraft_dir,
|
||||
crate::instance::ContentKind::ResourcePack,
|
||||
&self.content_icons,
|
||||
);
|
||||
self.shaders_state.apply_manifest(
|
||||
manifest,
|
||||
&minecraft_dir,
|
||||
crate::instance::ContentKind::Shader,
|
||||
&self.content_icons,
|
||||
);
|
||||
}
|
||||
|
||||
fn ensure_provider_conflict_popup(&mut self) {
|
||||
if !crate::config::SETTINGS.content.ask_on_provider_conflict
|
||||
|| self.focused != super::app::FocusedArea::Content
|
||||
|| self.provider_conflict.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some((instance_name, manifest)) = &self.content_manifest else {
|
||||
return;
|
||||
};
|
||||
if self
|
||||
.instances_state
|
||||
.selected_instance()
|
||||
.is_none_or(|instance| instance.name != *instance_name)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.provider_conflict = manifest.files.iter().find_map(|record| {
|
||||
if self
|
||||
.dismissed_provider_conflicts
|
||||
.contains(&record.relative_path)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let crate::instance::Resolution::Ambiguous { candidates } = &record.resolution else {
|
||||
return None;
|
||||
};
|
||||
Some(super::app::ProviderConflictState {
|
||||
relative_path: record.relative_path.clone(),
|
||||
candidates: candidates.clone(),
|
||||
selected: 0,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// polls for input with a 16ms timeout (~60fps). only key presses are handled,
|
||||
// releases and repeats are ignored thanks to the enhanced keyboard protocol
|
||||
fn handle_events(&mut self) -> color_eyre::Result<bool> {
|
||||
|
||||
+214
-90
@@ -13,6 +13,45 @@ use crate::tui::error_buffer;
|
||||
|
||||
impl App {
|
||||
pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> {
|
||||
if let Some(conflict) = self.provider_conflict.as_mut() {
|
||||
match key_event.code {
|
||||
KeyCode::Char('j') | KeyCode::Down => {
|
||||
conflict.selected =
|
||||
(conflict.selected + 1).min(conflict.candidates.len().saturating_sub(1));
|
||||
}
|
||||
KeyCode::Char('k') | KeyCode::Up => {
|
||||
conflict.selected = conflict.selected.saturating_sub(1);
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
let relative_path = conflict.relative_path.clone();
|
||||
let project = conflict.candidates.get(conflict.selected).cloned();
|
||||
if let Some(project) = project
|
||||
&& let Some((instance_name, manifest)) = &mut self.content_manifest
|
||||
&& let Some(record) = manifest
|
||||
.files
|
||||
.iter_mut()
|
||||
.find(|record| record.relative_path == relative_path)
|
||||
{
|
||||
record.resolution = crate::instance::Resolution::Resolved { project };
|
||||
let manifest_path = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(instance_name),
|
||||
)
|
||||
.content_manifest();
|
||||
manifest.save(&manifest_path)?;
|
||||
self.provider_conflict = None;
|
||||
self.reconciliation_for = None;
|
||||
}
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
self.dismissed_provider_conflicts
|
||||
.insert(conflict.relative_path.clone());
|
||||
self.provider_conflict = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// log overlay eats all input when open, including its own search sub-mode
|
||||
if self.focused == FocusedArea::OverviewExpanded {
|
||||
if self.log_overlay_search.active {
|
||||
@@ -166,7 +205,15 @@ impl App {
|
||||
return Ok(());
|
||||
}
|
||||
if popup_open && key_event.code == KeyCode::Enter {
|
||||
self.spawn_active_discovery_install();
|
||||
let confirming = self
|
||||
.active_discovery_state_mut()
|
||||
.and_then(|state| state.version_popup.as_ref())
|
||||
.is_some_and(|popup| popup.confirming);
|
||||
if confirming {
|
||||
self.spawn_active_discovery_install();
|
||||
} else if let Some(state) = self.active_discovery_state_mut() {
|
||||
state.begin_confirmation();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let handled = {
|
||||
@@ -469,7 +516,7 @@ impl App {
|
||||
.instance_manager
|
||||
.instances_dir
|
||||
.join(&instance.name)
|
||||
.join(".minecraft");
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
if let Err(e) = open::that_detached(&dir) {
|
||||
tracing::error!("Failed to open instance directory: {}", e);
|
||||
}
|
||||
@@ -595,16 +642,20 @@ impl App {
|
||||
return;
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
let client = crate::net::HttpClient::new();
|
||||
let result = crate::net::modrinth::fetch_content_versions(
|
||||
&client,
|
||||
&request.project_id,
|
||||
kind,
|
||||
&instance.game_version,
|
||||
instance.loader,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string());
|
||||
let registry =
|
||||
crate::content_provider::ProviderRegistry::modrinth(crate::net::HttpClient::new());
|
||||
let result = match registry.preferred("modrinth") {
|
||||
Some(provider) => provider
|
||||
.compatible_versions(
|
||||
&request.project_id,
|
||||
discovery_content_kind(kind),
|
||||
&instance.game_version,
|
||||
instance.loader,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string()),
|
||||
None => Err("Modrinth content provider is unavailable".to_owned()),
|
||||
};
|
||||
widgets::content::DiscoveryState::push_action_result(
|
||||
&request.pending,
|
||||
widgets::content::discovery::DiscoveryActionResult::Versions {
|
||||
@@ -638,39 +689,80 @@ impl App {
|
||||
.instance_manager
|
||||
.instances_dir
|
||||
.join(&instance.name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join(match kind {
|
||||
crate::net::modrinth::DiscoveryKind::Mod => "mods",
|
||||
crate::net::modrinth::DiscoveryKind::ResourcePack => "resourcepacks",
|
||||
crate::net::modrinth::DiscoveryKind::Shader => "shaderpacks",
|
||||
});
|
||||
let instance_paths = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(&instance.name),
|
||||
);
|
||||
let manifest_path = instance_paths.content_manifest();
|
||||
let minecraft_dir = instance_paths.minecraft();
|
||||
let content_kind = match kind {
|
||||
crate::net::modrinth::DiscoveryKind::Mod => crate::instance::ContentKind::Mod,
|
||||
crate::net::modrinth::DiscoveryKind::ResourcePack => {
|
||||
crate::instance::ContentKind::ResourcePack
|
||||
}
|
||||
crate::net::modrinth::DiscoveryKind::Shader => crate::instance::ContentKind::Shader,
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
let client = crate::net::HttpClient::new();
|
||||
let result = async {
|
||||
tokio::fs::create_dir_all(&destination)
|
||||
.await
|
||||
.map_err(crate::net::NetError::from)?;
|
||||
let outcome = if let Some(installed_path) = request.installed_path.as_deref() {
|
||||
crate::net::modrinth::download_version_file_for_update(
|
||||
&client,
|
||||
let registry = crate::content_provider::ProviderRegistry::modrinth(client);
|
||||
let provider = registry.preferred("modrinth").ok_or_else(|| {
|
||||
crate::net::NetError::Parse(
|
||||
"Modrinth content provider is unavailable".to_owned(),
|
||||
)
|
||||
})?;
|
||||
let outcome = provider
|
||||
.download_version(
|
||||
&request.version,
|
||||
&destination,
|
||||
installed_path,
|
||||
request.installed_path.as_deref(),
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
crate::net::modrinth::download_version_file(
|
||||
&client,
|
||||
&request.version,
|
||||
&destination,
|
||||
)
|
||||
.await?
|
||||
};
|
||||
.await?;
|
||||
let (path, skipped) = match outcome {
|
||||
crate::net::modrinth::DownloadOutcome::Downloaded(path) => (path, false),
|
||||
crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => (path, true),
|
||||
};
|
||||
let replaced = request.installed_path.is_some() && !skipped;
|
||||
let mut manifest = crate::instance::ContentManifest::load(&manifest_path)
|
||||
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
|
||||
if let Some(old_path) = request.installed_path.as_ref()
|
||||
&& let Ok(relative) = old_path.strip_prefix(&minecraft_dir)
|
||||
&& old_path != &path
|
||||
{
|
||||
manifest.remove(relative);
|
||||
}
|
||||
let relative_path = path
|
||||
.strip_prefix(&minecraft_dir)
|
||||
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?
|
||||
.to_path_buf();
|
||||
let fingerprint = crate::instance::content::manifest::fingerprint(&path)?;
|
||||
manifest.upsert(crate::instance::ContentFileRecord {
|
||||
relative_path,
|
||||
kind: content_kind,
|
||||
enabled: !path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.ends_with(".disabled")),
|
||||
fingerprint,
|
||||
resolution: crate::instance::Resolution::Resolved {
|
||||
project: crate::instance::ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: request.project_id.clone(),
|
||||
version_id: request.version.id.clone(),
|
||||
},
|
||||
},
|
||||
});
|
||||
manifest
|
||||
.save(&manifest_path)
|
||||
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
|
||||
if !skipped
|
||||
&& let Some(old_path) = request
|
||||
.installed_path
|
||||
@@ -702,28 +794,17 @@ impl App {
|
||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||
return;
|
||||
};
|
||||
let installed_entries = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods
|
||||
if self.mods_state.loaded_for.as_deref() == Some(instance.name.as_str()) =>
|
||||
{
|
||||
self.mods_state.entries.clone()
|
||||
}
|
||||
widgets::content::ContentTab::ResourcePacks
|
||||
if self.resource_packs_state.loaded_for.as_deref()
|
||||
== Some(instance.name.as_str()) =>
|
||||
{
|
||||
self.resource_packs_state.entries.clone()
|
||||
}
|
||||
widgets::content::ContentTab::Shaders
|
||||
if self.shaders_state.loaded_for.as_deref() == Some(instance.name.as_str()) =>
|
||||
{
|
||||
self.shaders_state.entries.clone()
|
||||
}
|
||||
widgets::content::ContentTab::Mods
|
||||
| widgets::content::ContentTab::ResourcePacks
|
||||
| widgets::content::ContentTab::Shaders => Vec::new(),
|
||||
_ => return,
|
||||
};
|
||||
let manifest = self
|
||||
.content_manifest
|
||||
.as_ref()
|
||||
.filter(|(name, _)| name == &instance.name)
|
||||
.map(|(_, manifest)| manifest.clone());
|
||||
let minecraft_dir = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(&instance.name),
|
||||
)
|
||||
.minecraft();
|
||||
let icon_cache = crate::storage::MetadataPaths::new(&self.instance_manager.meta_dir)
|
||||
.provider_icons("modrinth");
|
||||
let state = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods => &mut self.mods_discovery_state,
|
||||
widgets::content::ContentTab::ResourcePacks => &mut self.resource_packs_discovery_state,
|
||||
@@ -733,35 +814,32 @@ impl App {
|
||||
let kind = state.kind;
|
||||
let query = state.search.query.clone();
|
||||
let request = state.begin_search(&instance);
|
||||
Self::spawn_discovery_request(instance, kind, query, installed_entries, request);
|
||||
Self::spawn_discovery_request(
|
||||
instance,
|
||||
kind,
|
||||
query,
|
||||
manifest,
|
||||
minecraft_dir,
|
||||
icon_cache,
|
||||
request,
|
||||
);
|
||||
}
|
||||
|
||||
fn spawn_active_discovery_page(&mut self) {
|
||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||
return;
|
||||
};
|
||||
let installed_entries = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods
|
||||
if self.mods_state.loaded_for.as_deref() == Some(instance.name.as_str()) =>
|
||||
{
|
||||
self.mods_state.entries.clone()
|
||||
}
|
||||
widgets::content::ContentTab::ResourcePacks
|
||||
if self.resource_packs_state.loaded_for.as_deref()
|
||||
== Some(instance.name.as_str()) =>
|
||||
{
|
||||
self.resource_packs_state.entries.clone()
|
||||
}
|
||||
widgets::content::ContentTab::Shaders
|
||||
if self.shaders_state.loaded_for.as_deref() == Some(instance.name.as_str()) =>
|
||||
{
|
||||
self.shaders_state.entries.clone()
|
||||
}
|
||||
widgets::content::ContentTab::Mods
|
||||
| widgets::content::ContentTab::ResourcePacks
|
||||
| widgets::content::ContentTab::Shaders => Vec::new(),
|
||||
_ => return,
|
||||
};
|
||||
let manifest = self
|
||||
.content_manifest
|
||||
.as_ref()
|
||||
.filter(|(name, _)| name == &instance.name)
|
||||
.map(|(_, manifest)| manifest.clone());
|
||||
let minecraft_dir = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(&instance.name),
|
||||
)
|
||||
.minecraft();
|
||||
let icon_cache = crate::storage::MetadataPaths::new(&self.instance_manager.meta_dir)
|
||||
.provider_icons("modrinth");
|
||||
let state = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods => &mut self.mods_discovery_state,
|
||||
widgets::content::ContentTab::ResourcePacks => &mut self.resource_packs_discovery_state,
|
||||
@@ -773,14 +851,24 @@ impl App {
|
||||
let Some(request) = state.begin_next_page() else {
|
||||
return;
|
||||
};
|
||||
Self::spawn_discovery_request(instance, kind, query, installed_entries, request);
|
||||
Self::spawn_discovery_request(
|
||||
instance,
|
||||
kind,
|
||||
query,
|
||||
manifest,
|
||||
minecraft_dir,
|
||||
icon_cache,
|
||||
request,
|
||||
);
|
||||
}
|
||||
|
||||
fn spawn_discovery_request(
|
||||
instance: crate::instance::InstanceConfig,
|
||||
kind: crate::net::modrinth::DiscoveryKind,
|
||||
query: String,
|
||||
installed_entries: Vec<crate::instance::ContentEntry>,
|
||||
manifest: Option<crate::instance::ContentManifest>,
|
||||
minecraft_dir: std::path::PathBuf,
|
||||
icon_cache: std::path::PathBuf,
|
||||
request: widgets::content::discovery::DiscoveryRequest,
|
||||
) {
|
||||
let widgets::content::discovery::DiscoveryRequest {
|
||||
@@ -794,16 +882,23 @@ impl App {
|
||||
|
||||
tokio::spawn(async move {
|
||||
let client = crate::net::HttpClient::new();
|
||||
let result = crate::net::modrinth::search_discovery(
|
||||
&client,
|
||||
kind,
|
||||
&query,
|
||||
&instance.game_version,
|
||||
instance.loader,
|
||||
offset,
|
||||
widgets::content::discovery::PAGE_SIZE,
|
||||
)
|
||||
.await;
|
||||
let registry = crate::content_provider::ProviderRegistry::modrinth(client.clone());
|
||||
let result = match registry.preferred("modrinth") {
|
||||
Some(provider) => {
|
||||
provider
|
||||
.search(
|
||||
discovery_content_kind(kind),
|
||||
&query,
|
||||
&instance,
|
||||
offset,
|
||||
widgets::content::discovery::PAGE_SIZE,
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => Err(crate::net::NetError::Parse(
|
||||
"Modrinth content provider is unavailable".to_owned(),
|
||||
)),
|
||||
};
|
||||
let result = match result {
|
||||
Ok(results) => {
|
||||
let total_hits = results.total_hits;
|
||||
@@ -812,13 +907,21 @@ impl App {
|
||||
let icon_slots = std::sync::Arc::new(tokio::sync::Semaphore::new(8));
|
||||
for mut project in results.projects {
|
||||
returned_stems.insert(project.id.clone());
|
||||
let installed_path = widgets::content::discovery::installed_project_path(
|
||||
&project,
|
||||
&installed_entries,
|
||||
);
|
||||
let icon_url = (!loaded_icon_stems.contains(&project.id))
|
||||
.then(|| project.icon_url.take())
|
||||
.flatten();
|
||||
let project_id = project.id.clone();
|
||||
let installed_path = manifest.as_ref().and_then(|manifest| {
|
||||
manifest.resolved_project_path("modrinth", &project.id, &minecraft_dir)
|
||||
});
|
||||
let cached_icon = icon_cache.join(format!("{project_id}.img"));
|
||||
if !loaded_icon_stems.contains(&project.id)
|
||||
&& let Ok(bytes) = tokio::fs::read(&cached_icon).await
|
||||
&& !bytes.is_empty()
|
||||
{
|
||||
project.icon_bytes = Some(bytes);
|
||||
}
|
||||
let icon_url = (!loaded_icon_stems.contains(&project.id)
|
||||
&& project.icon_bytes.is_none())
|
||||
.then(|| project.icon_url.take())
|
||||
.flatten();
|
||||
let entry =
|
||||
widgets::content::discovery::project_entry(project, installed_path);
|
||||
let icon =
|
||||
@@ -830,13 +933,22 @@ impl App {
|
||||
let client = client.clone();
|
||||
let stream = stream.clone();
|
||||
let icon_slots = icon_slots.clone();
|
||||
let cached_icon = cached_icon.clone();
|
||||
tokio::spawn(async move {
|
||||
let Ok(_permit) = icon_slots.acquire_owned().await else {
|
||||
return;
|
||||
};
|
||||
let progress = crate::tui::progress::ProgressTask::start(format!(
|
||||
"Downloading icon for {file_stem}"
|
||||
));
|
||||
match client.get_bytes(&url).await {
|
||||
Ok(bytes) if !bytes.is_empty() => {
|
||||
if let Some(parent) = cached_icon.parent() {
|
||||
let _ = tokio::fs::create_dir_all(parent).await;
|
||||
}
|
||||
let _ = tokio::fs::write(cached_icon, &bytes).await;
|
||||
stream.send_icon(file_stem, path, bytes);
|
||||
progress.finish();
|
||||
}
|
||||
Ok(_) => tracing::debug!(
|
||||
"Modrinth icon for '{}' was empty; using fallback",
|
||||
@@ -903,6 +1015,18 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn discovery_content_kind(
|
||||
kind: crate::net::modrinth::DiscoveryKind,
|
||||
) -> crate::instance::ContentKind {
|
||||
match kind {
|
||||
crate::net::modrinth::DiscoveryKind::Mod => crate::instance::ContentKind::Mod,
|
||||
crate::net::modrinth::DiscoveryKind::ResourcePack => {
|
||||
crate::instance::ContentKind::ResourcePack
|
||||
}
|
||||
crate::net::modrinth::DiscoveryKind::Shader => crate::instance::ContentKind::Shader,
|
||||
}
|
||||
}
|
||||
|
||||
fn delete_content_path(path: &std::path::Path) -> std::io::Result<()> {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(path),
|
||||
|
||||
+362
-1
@@ -71,7 +71,25 @@ pub async fn show() -> color_eyre::Result<()> {
|
||||
};
|
||||
picker.set_protocol_type(requested_protocol);
|
||||
|
||||
let result = app::App::new(picker).run(&mut terminal).await;
|
||||
let mut app = app::App::new(picker);
|
||||
match run_layout_migration_screen(&mut terminal, &mut app).await? {
|
||||
MigrationScreenOutcome::NotNeeded => {}
|
||||
MigrationScreenOutcome::Migrated => {
|
||||
// the modal uses pre-migration state as its background. rebuild the
|
||||
// app after confirmation so no instance or profile data stays stale
|
||||
let picker = app.into_picker();
|
||||
app = app::App::new(picker);
|
||||
}
|
||||
MigrationScreenOutcome::Quit => {
|
||||
let _ = crossterm::execute!(
|
||||
std::io::stdout(),
|
||||
crossterm::event::PopKeyboardEnhancementFlags
|
||||
);
|
||||
ratatui::restore();
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let result = app.run(&mut terminal).await;
|
||||
|
||||
let _ = crossterm::execute!(
|
||||
std::io::stdout(),
|
||||
@@ -81,3 +99,346 @@ pub async fn show() -> color_eyre::Result<()> {
|
||||
ratatui::restore();
|
||||
result
|
||||
}
|
||||
|
||||
enum MigrationScreenOutcome {
|
||||
NotNeeded,
|
||||
Migrated,
|
||||
Quit,
|
||||
}
|
||||
|
||||
async fn run_layout_migration_screen(
|
||||
terminal: &mut Tui,
|
||||
app: &mut app::App,
|
||||
) -> color_eyre::Result<MigrationScreenOutcome> {
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
||||
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
||||
if !crate::layout_migration::is_needed(&instances_dir, &meta_dir) {
|
||||
crate::layout_migration::initialize_new_layout(&meta_dir)?;
|
||||
return Ok(MigrationScreenOutcome::NotNeeded);
|
||||
}
|
||||
let config = crate::config::get_config_path().join("config.toml");
|
||||
|
||||
loop {
|
||||
let progress = Arc::new(Mutex::new(crate::layout_migration::MigrationProgress {
|
||||
phase: "Preparing migration".to_owned(),
|
||||
item: "Inventorying launcher data".to_owned(),
|
||||
current: 0,
|
||||
total: 1,
|
||||
item_current: None,
|
||||
item_total: None,
|
||||
backup_dir: None,
|
||||
}));
|
||||
let task_progress = progress.clone();
|
||||
let task_instances = instances_dir.clone();
|
||||
let task_meta = meta_dir.clone();
|
||||
let task_config = config.clone();
|
||||
let task = tokio::task::spawn_blocking(move || {
|
||||
crate::layout_migration::run(&task_instances, &task_meta, &task_config, |update| {
|
||||
if let Ok(mut current) = task_progress.lock() {
|
||||
*current = update;
|
||||
}
|
||||
request_redraw();
|
||||
})
|
||||
});
|
||||
|
||||
while !task.is_finished() {
|
||||
let current = progress.lock().ok().map(|state| state.clone());
|
||||
terminal.draw(|frame| {
|
||||
app.render_migration_frame(frame);
|
||||
if let Some(current) = ¤t {
|
||||
let item_fraction = match (current.item_current, current.item_total) {
|
||||
(Some(value), Some(total)) if total > 0 => {
|
||||
value.min(total) as f64 / total as f64
|
||||
}
|
||||
_ => 0.0,
|
||||
};
|
||||
let ratio = if current.total == 0 {
|
||||
0.0
|
||||
} else {
|
||||
((current.current as f64 + item_fraction) / current.total as f64)
|
||||
.clamp(0.0, 1.0)
|
||||
};
|
||||
render_migration_progress_popup(
|
||||
frame,
|
||||
ratio,
|
||||
current.phase.clone(),
|
||||
current.item.clone(),
|
||||
);
|
||||
}
|
||||
})?;
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
|
||||
match task.await? {
|
||||
Ok(backup) => {
|
||||
tracing::info!("Layout migration complete; backup at {}", backup.display());
|
||||
if crate::layout_migration::cache_rebuild_pending(&meta_dir) {
|
||||
if let Err(error) =
|
||||
rebuild_runtime_cache_screen(terminal, app, &instances_dir, &meta_dir).await
|
||||
{
|
||||
if migration_retry_requested(terminal, app, &error).await? {
|
||||
continue;
|
||||
}
|
||||
return Ok(MigrationScreenOutcome::Quit);
|
||||
}
|
||||
crate::layout_migration::finish_cache_rebuild(&meta_dir)?;
|
||||
}
|
||||
migration_completion_confirmation(terminal, app, &backup).await?;
|
||||
return Ok(MigrationScreenOutcome::Migrated);
|
||||
}
|
||||
Err(error) => {
|
||||
if !migration_retry_requested(terminal, app, &error.to_string()).await? {
|
||||
return Ok(MigrationScreenOutcome::Quit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn rebuild_runtime_cache_screen(
|
||||
terminal: &mut Tui,
|
||||
app: &mut app::App,
|
||||
instances_dir: &std::path::Path,
|
||||
meta_dir: &std::path::Path,
|
||||
) -> Result<(), String> {
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
let manager = crate::instance::InstanceManager::new(instances_dir, meta_dir);
|
||||
let instances = manager.load_all();
|
||||
let instance_total = instances.len() as u64;
|
||||
let instance_progress = Arc::new(Mutex::new((0_u64, String::new())));
|
||||
let task_progress = instance_progress.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
for (index, instance) in instances.iter().enumerate() {
|
||||
if let Ok(mut state) = task_progress.lock() {
|
||||
state.0 = index as u64;
|
||||
state.1 = instance.name.clone();
|
||||
}
|
||||
request_redraw();
|
||||
manager
|
||||
.repair_runtime_cache(instance)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
if let Ok(mut state) = task_progress.lock() {
|
||||
state.0 = instance_total;
|
||||
state.1.clear();
|
||||
}
|
||||
Ok::<(), String>(())
|
||||
});
|
||||
|
||||
while !task.is_finished() {
|
||||
let progress = crate::tui::progress::PROGRESS
|
||||
.lock()
|
||||
.ok()
|
||||
.map(|progress| progress.clone())
|
||||
.unwrap_or_default();
|
||||
let (instance_current, instance_name) = instance_progress
|
||||
.lock()
|
||||
.ok()
|
||||
.map(|state| state.clone())
|
||||
.unwrap_or_default();
|
||||
terminal
|
||||
.draw(|frame| {
|
||||
app.render_migration_frame(frame);
|
||||
let action = progress
|
||||
.current_action
|
||||
.as_deref()
|
||||
.unwrap_or("Checking cached runtime files");
|
||||
let detail = progress.sub_action.as_deref().unwrap_or("");
|
||||
let (current, total) = progress.progress.unwrap_or((0, 0));
|
||||
let instance_ratio = if instance_total == 0 {
|
||||
1.0
|
||||
} else {
|
||||
instance_current.min(instance_total) as f64 / instance_total as f64
|
||||
};
|
||||
let ratio = if total == 0 {
|
||||
instance_ratio
|
||||
} else {
|
||||
current.min(total) as f64 / total as f64
|
||||
};
|
||||
let action = if instance_name.is_empty() {
|
||||
action.to_owned()
|
||||
} else {
|
||||
format!("{action} — {instance_name}")
|
||||
};
|
||||
render_migration_progress_popup(frame, ratio, action, detail.to_owned());
|
||||
})
|
||||
.map_err(|error| error.to_string())?;
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
task.await.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
async fn migration_retry_requested(
|
||||
terminal: &mut Tui,
|
||||
app: &mut app::App,
|
||||
error: &str,
|
||||
) -> color_eyre::Result<bool> {
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crossterm::event::{Event, KeyCode};
|
||||
use ratatui::layout::{Constraint, Direction, Layout};
|
||||
use ratatui::style::Style;
|
||||
use ratatui::widgets::{Block, Paragraph, Wrap};
|
||||
use std::time::Duration;
|
||||
|
||||
loop {
|
||||
terminal.draw(|frame| {
|
||||
app.render_migration_frame(frame);
|
||||
let theme = THEME.as_ref();
|
||||
let rows = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Fill(1),
|
||||
Constraint::Length(9),
|
||||
Constraint::Fill(1),
|
||||
])
|
||||
.split(frame.area());
|
||||
let columns = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage(12),
|
||||
Constraint::Percentage(76),
|
||||
Constraint::Percentage(12),
|
||||
])
|
||||
.split(rows[1]);
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!(
|
||||
"Migration stopped safely:\n\n{error}\n\n[r] retry [q] quit"
|
||||
))
|
||||
.block(
|
||||
Block::bordered()
|
||||
.title(" Migration needs attention ")
|
||||
.border_type(BORDER_STYLE.to_border_type())
|
||||
.border_style(Style::default().fg(theme.error()))
|
||||
.style(Style::default().fg(theme.text()).bg(theme.surface())),
|
||||
)
|
||||
.wrap(Wrap { trim: false }),
|
||||
columns[1],
|
||||
);
|
||||
})?;
|
||||
if crossterm::event::poll(Duration::from_millis(100))?
|
||||
&& let Event::Key(key) = crossterm::event::read()?
|
||||
{
|
||||
match key.code {
|
||||
KeyCode::Char('r') => return Ok(true),
|
||||
KeyCode::Char('q') | KeyCode::Esc => return Ok(false),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn migration_completion_confirmation(
|
||||
terminal: &mut Tui,
|
||||
app: &mut app::App,
|
||||
backup: &std::path::Path,
|
||||
) -> color_eyre::Result<()> {
|
||||
use crate::config::theme::THEME;
|
||||
use crate::tui::widgets::popups::{base::PopupFrame, keybind_line};
|
||||
use crossterm::event::{Event, KeyCode};
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use ratatui::text::Line;
|
||||
use ratatui::widgets::{Paragraph, Widget, Wrap};
|
||||
use std::time::Duration;
|
||||
|
||||
loop {
|
||||
terminal.draw(|frame| {
|
||||
app.render_migration_frame(frame);
|
||||
let theme = THEME.as_ref();
|
||||
let backup = backup.display().to_string();
|
||||
frame.render_widget(
|
||||
PopupFrame {
|
||||
title: Line::from(" Migration finished ").style(
|
||||
Style::default()
|
||||
.fg(theme.success())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
border_color: theme.success(),
|
||||
bg: Some(theme.surface()),
|
||||
keybinds: Some(keybind_line(&[("Enter", " continue")])),
|
||||
search_line: None,
|
||||
content: Box::new(move |area, buffer| {
|
||||
Paragraph::new(format!("Backup:\n{backup}"))
|
||||
.style(Style::default().fg(theme.text()))
|
||||
.wrap(Wrap { trim: false })
|
||||
.render(area, buffer);
|
||||
}),
|
||||
},
|
||||
migration_popup_area(frame.area(), 6),
|
||||
);
|
||||
})?;
|
||||
if crossterm::event::poll(Duration::from_millis(100))?
|
||||
&& let Event::Key(key) = crossterm::event::read()?
|
||||
&& key.code == KeyCode::Enter
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_migration_progress_popup(
|
||||
frame: &mut ratatui::Frame,
|
||||
ratio: f64,
|
||||
action: String,
|
||||
detail: String,
|
||||
) {
|
||||
use crate::config::theme::THEME;
|
||||
use crate::tui::widgets::popups::base::PopupFrame;
|
||||
use ratatui::layout::{Constraint, Layout};
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use ratatui::text::Line;
|
||||
use ratatui::widgets::{Gauge, Paragraph, Widget};
|
||||
|
||||
let theme = THEME.as_ref();
|
||||
frame.render_widget(
|
||||
PopupFrame {
|
||||
title: Line::from(" Migration ").style(
|
||||
Style::default()
|
||||
.fg(theme.text_dim())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
border_color: theme.accent(),
|
||||
bg: Some(theme.surface()),
|
||||
keybinds: None,
|
||||
search_line: None,
|
||||
content: Box::new(move |area, buffer| {
|
||||
let rows = Layout::vertical([
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.split(area);
|
||||
Gauge::default()
|
||||
.gauge_style(
|
||||
Style::default()
|
||||
.fg(theme.success())
|
||||
.bg(theme.surface())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
)
|
||||
.percent((ratio.clamp(0.0, 1.0) * 100.0) as u16)
|
||||
.render(rows[0], buffer);
|
||||
Paragraph::new(action.as_str())
|
||||
.style(Style::default().fg(theme.text()))
|
||||
.render(rows[1], buffer);
|
||||
Paragraph::new(detail.as_str())
|
||||
.style(Style::default().fg(theme.text_dim()))
|
||||
.render(rows[2], buffer);
|
||||
}),
|
||||
},
|
||||
migration_popup_area(frame.area(), 5),
|
||||
);
|
||||
}
|
||||
|
||||
fn migration_popup_area(area: ratatui::layout::Rect, height: u16) -> ratatui::layout::Rect {
|
||||
use ratatui::layout::Constraint;
|
||||
|
||||
area.centered(
|
||||
Constraint::Length(area.width.saturating_sub(4).min(72)),
|
||||
Constraint::Length(area.height.saturating_sub(2).min(height)),
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
// global progress state shared between background tasks and the status bar widget.
|
||||
// background tasks set the action/progress, the render loop reads it every frame.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
@@ -9,15 +11,155 @@ pub struct ProgressState {
|
||||
pub current_action: Option<String>,
|
||||
pub progress: Option<(u64, u64)>,
|
||||
pub sub_action: Option<String>,
|
||||
tasks: BTreeMap<u64, TaskState>,
|
||||
legacy_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct TaskState {
|
||||
action: String,
|
||||
sub_action: Option<String>,
|
||||
progress: Option<(u64, u64)>,
|
||||
}
|
||||
|
||||
pub static PROGRESS: LazyLock<Arc<Mutex<ProgressState>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(ProgressState::default())));
|
||||
static NEXT_TASK_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
pub struct ProgressTask {
|
||||
id: u64,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ProgressTaskHandle {
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl ProgressTask {
|
||||
pub fn start(action: impl Into<String>) -> Self {
|
||||
let id = NEXT_TASK_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let action = action.into();
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
state.tasks.insert(
|
||||
id,
|
||||
TaskState {
|
||||
action: action.clone(),
|
||||
sub_action: None,
|
||||
progress: None,
|
||||
},
|
||||
);
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
tracing::info!("{}", action);
|
||||
crate::tui::request_redraw();
|
||||
Self {
|
||||
id,
|
||||
finished: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle(&self) -> ProgressTaskHandle {
|
||||
ProgressTaskHandle { id: self.id }
|
||||
}
|
||||
|
||||
pub fn set_action(&self, text: impl Into<String>) {
|
||||
update_task_action(self.id, text.into());
|
||||
}
|
||||
|
||||
pub fn set_sub_action(&self, text: impl Into<String>) {
|
||||
update_task_sub_action(self.id, text.into());
|
||||
}
|
||||
|
||||
pub fn set_progress(&self, current: u64, total: u64) {
|
||||
update_task_progress(self.id, current, total);
|
||||
}
|
||||
|
||||
pub fn finish(mut self) {
|
||||
self.remove();
|
||||
self.finished = true;
|
||||
}
|
||||
|
||||
pub fn fail(mut self, error: impl std::fmt::Display) {
|
||||
tracing::warn!("Progress task failed: {error}");
|
||||
self.remove();
|
||||
self.finished = true;
|
||||
}
|
||||
|
||||
fn remove(&self) {
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
state.tasks.remove(&self.id);
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
crate::tui::request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
impl ProgressTaskHandle {
|
||||
pub fn set_sub_action(&self, text: impl Into<String>) {
|
||||
update_task_sub_action(self.id, text.into());
|
||||
}
|
||||
|
||||
pub fn set_progress(&self, current: u64, total: u64) {
|
||||
update_task_progress(self.id, current, total);
|
||||
}
|
||||
}
|
||||
|
||||
fn update_task_action(id: u64, text: String) {
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
if let Some(task) = state.tasks.get_mut(&id) {
|
||||
task.action = text;
|
||||
}
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
crate::tui::request_redraw();
|
||||
}
|
||||
|
||||
fn update_task_sub_action(id: u64, text: String) {
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
if let Some(task) = state.tasks.get_mut(&id) {
|
||||
task.sub_action = Some(text);
|
||||
}
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
crate::tui::request_redraw();
|
||||
}
|
||||
|
||||
fn update_task_progress(id: u64, current: u64, total: u64) {
|
||||
if let Ok(mut state) = PROGRESS.lock() {
|
||||
if let Some(task) = state.tasks.get_mut(&id) {
|
||||
task.progress = Some((current, total));
|
||||
}
|
||||
refresh_visible(&mut state);
|
||||
}
|
||||
crate::tui::request_redraw();
|
||||
}
|
||||
|
||||
impl Drop for ProgressTask {
|
||||
fn drop(&mut self) {
|
||||
if !self.finished {
|
||||
self.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_visible(state: &mut ProgressState) {
|
||||
if let Some((_, task)) = state.tasks.last_key_value() {
|
||||
state.current_action = Some(task.action.clone());
|
||||
state.sub_action.clone_from(&task.sub_action);
|
||||
state.progress = task.progress;
|
||||
} else if !state.legacy_active {
|
||||
state.current_action = None;
|
||||
state.sub_action = None;
|
||||
state.progress = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_action(text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.legacy_active = true;
|
||||
state.current_action = Some(text.clone());
|
||||
crate::tui::request_redraw();
|
||||
}
|
||||
@@ -60,6 +202,8 @@ pub fn clear() {
|
||||
state.current_action = None;
|
||||
state.progress = None;
|
||||
state.sub_action = None;
|
||||
state.tasks.clear();
|
||||
state.legacy_active = false;
|
||||
crate::tui::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -68,6 +212,52 @@ pub fn clear() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
static TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[test]
|
||||
fn newest_task_is_visible_and_drop_restores_previous_task() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear();
|
||||
let first = ProgressTask::start("first");
|
||||
first.set_progress(1, 2);
|
||||
{
|
||||
let second = ProgressTask::start("second");
|
||||
second.set_sub_action("working");
|
||||
let state = PROGRESS.lock().unwrap();
|
||||
assert_eq!(state.current_action.as_deref(), Some("second"));
|
||||
assert_eq!(state.sub_action.as_deref(), Some("working"));
|
||||
}
|
||||
let state = PROGRESS.lock().unwrap();
|
||||
assert_eq!(state.current_action.as_deref(), Some("first"));
|
||||
assert_eq!(state.progress, Some((1, 2)));
|
||||
drop(state);
|
||||
first.finish();
|
||||
clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_phase_keeps_the_existing_progress_visible() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear();
|
||||
let task = ProgressTask::start("inventory");
|
||||
task.set_progress(4, 10);
|
||||
task.set_action("provider matching");
|
||||
|
||||
let state = PROGRESS.lock().unwrap();
|
||||
assert_eq!(state.current_action.as_deref(), Some("provider matching"));
|
||||
assert_eq!(state.progress, Some((4, 10)));
|
||||
drop(state);
|
||||
|
||||
task.finish();
|
||||
assert!(!is_active());
|
||||
clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active() -> bool {
|
||||
PROGRESS
|
||||
.lock()
|
||||
|
||||
+92
-19
@@ -19,6 +19,14 @@ use crate::tui::widgets::popups::error::{ErrorPopup, popup_area};
|
||||
|
||||
impl App {
|
||||
pub(super) fn render_frame(&mut self, frame: &mut Frame) {
|
||||
self.render_frame_with_content(frame, true);
|
||||
}
|
||||
|
||||
pub(super) fn render_migration_frame(&mut self, frame: &mut Frame) {
|
||||
self.render_frame_with_content(frame, false);
|
||||
}
|
||||
|
||||
fn render_frame_with_content(&mut self, frame: &mut Frame, load_content: bool) {
|
||||
use crate::config::theme::THEME;
|
||||
use ratatui::style::Style;
|
||||
use ratatui::widgets::Block;
|
||||
@@ -52,25 +60,34 @@ impl App {
|
||||
self.instances_state.selected_instance(),
|
||||
&mut self.throbber_state,
|
||||
);
|
||||
widgets::content::render(
|
||||
frame,
|
||||
main_chunks[1],
|
||||
self.focused,
|
||||
self.content_tab,
|
||||
self.content_mode,
|
||||
self.instances_state.selected_instance(),
|
||||
&mut self.mods_state,
|
||||
&mut self.mods_discovery_state,
|
||||
&mut self.resource_packs_state,
|
||||
&mut self.resource_packs_discovery_state,
|
||||
&mut self.shaders_state,
|
||||
&mut self.shaders_discovery_state,
|
||||
&mut self.worlds_state,
|
||||
&mut self.screenshots_state,
|
||||
&mut self.logs_state,
|
||||
&self.instance_manager.instances_dir,
|
||||
&self.picker,
|
||||
);
|
||||
if load_content {
|
||||
widgets::content::render(
|
||||
frame,
|
||||
main_chunks[1],
|
||||
self.focused,
|
||||
self.content_tab,
|
||||
self.content_mode,
|
||||
self.instances_state.selected_instance(),
|
||||
&mut self.mods_state,
|
||||
&mut self.mods_discovery_state,
|
||||
&mut self.resource_packs_state,
|
||||
&mut self.resource_packs_discovery_state,
|
||||
&mut self.shaders_state,
|
||||
&mut self.shaders_discovery_state,
|
||||
&mut self.worlds_state,
|
||||
&mut self.screenshots_state,
|
||||
&mut self.logs_state,
|
||||
&self.instance_manager.instances_dir,
|
||||
&self.picker,
|
||||
);
|
||||
} else {
|
||||
frame.render_widget(
|
||||
Block::bordered()
|
||||
.border_type(crate::config::theme::BORDER_STYLE.to_border_type())
|
||||
.border_style(Style::default().fg(theme.border())),
|
||||
main_chunks[1],
|
||||
);
|
||||
}
|
||||
|
||||
let bottom_chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
@@ -135,6 +152,10 @@ impl App {
|
||||
let area = confirm_popup_area(frame.area(), &target);
|
||||
frame.render_widget(ConfirmPopup::for_target(&target), area);
|
||||
}
|
||||
|
||||
if let Some(conflict) = &self.provider_conflict {
|
||||
render_provider_conflict(frame, conflict);
|
||||
}
|
||||
}
|
||||
|
||||
// full-screen log viewer with search highlighting and auto-scroll.
|
||||
@@ -331,3 +352,55 @@ impl App {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_provider_conflict(frame: &mut Frame, conflict: &super::app::ProviderConflictState) {
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use ratatui::{
|
||||
layout::{Constraint, Flex, Layout},
|
||||
style::{Modifier, Style},
|
||||
text::Line,
|
||||
widgets::{Block, Borders, Clear, List, ListItem, ListState},
|
||||
};
|
||||
|
||||
let theme = THEME.as_ref();
|
||||
let [area] = Layout::vertical([Constraint::Length(
|
||||
(conflict.candidates.len() as u16 + 4).min(frame.area().height.saturating_sub(2)),
|
||||
)])
|
||||
.flex(Flex::Center)
|
||||
.areas(frame.area());
|
||||
let [area] = Layout::horizontal([Constraint::Percentage(58)])
|
||||
.flex(Flex::Center)
|
||||
.areas(area);
|
||||
frame.render_widget(Clear, area);
|
||||
|
||||
let title = conflict
|
||||
.relative_path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("content file");
|
||||
let items = conflict.candidates.iter().map(|candidate| {
|
||||
ListItem::new(Line::from(format!(
|
||||
"{} {} {}",
|
||||
candidate.provider, candidate.project_id, candidate.version_id
|
||||
)))
|
||||
});
|
||||
let mut state = ListState::default().with_selected(Some(conflict.selected));
|
||||
let list = List::new(items)
|
||||
.block(
|
||||
Block::default()
|
||||
.title(Line::from(format!(" Choose provider for {title} ")))
|
||||
.title_bottom(Line::from(" [j/k] select [Enter] use [Esc] later "))
|
||||
.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.background()))
|
||||
.highlight_style(
|
||||
Style::default()
|
||||
.fg(theme.accent())
|
||||
.bg(theme.stripe())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
)
|
||||
.highlight_symbol("▌");
|
||||
frame.render_stateful_widget(list, area, &mut state);
|
||||
}
|
||||
@@ -74,6 +74,7 @@ pub struct VersionPopupState {
|
||||
pub versions: Vec<VersionInfo>,
|
||||
pub selected: usize,
|
||||
pub loading: bool,
|
||||
pub confirming: bool,
|
||||
pub installing: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
@@ -264,6 +265,7 @@ impl DiscoveryState {
|
||||
versions: Vec::new(),
|
||||
selected: 0,
|
||||
loading: true,
|
||||
confirming: false,
|
||||
installing: false,
|
||||
error: None,
|
||||
});
|
||||
@@ -274,13 +276,21 @@ impl DiscoveryState {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn refresh_installed_labels(&mut self, installed_entries: &[ContentEntry]) {
|
||||
pub fn refresh_installed_manifest(
|
||||
&mut self,
|
||||
manifest: &crate::instance::ContentManifest,
|
||||
minecraft_dir: &std::path::Path,
|
||||
) {
|
||||
let mut changed = false;
|
||||
for entry in &mut self.list.entries {
|
||||
let installed_path = entry
|
||||
.source_slug
|
||||
.as_deref()
|
||||
.and_then(|slug| installed_path_for_identity(&entry.name, slug, installed_entries));
|
||||
let Some(project) = entry.provider_project.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let installed_path = manifest.resolved_project_path(
|
||||
&project.provider,
|
||||
&project.project_id,
|
||||
minecraft_dir,
|
||||
);
|
||||
if entry.installed_path != installed_path {
|
||||
entry.title_suffix = installed_path.is_some().then(|| "Installed".to_owned());
|
||||
entry.installed_path = installed_path;
|
||||
@@ -294,7 +304,7 @@ impl DiscoveryState {
|
||||
|
||||
pub fn begin_install(&mut self) -> Option<InstallRequest> {
|
||||
let popup = self.version_popup.as_mut()?;
|
||||
if popup.loading || popup.installing {
|
||||
if popup.loading || popup.installing || !popup.confirming {
|
||||
return None;
|
||||
}
|
||||
let version = popup.versions.get(popup.selected)?.clone();
|
||||
@@ -309,6 +319,18 @@ impl DiscoveryState {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn begin_confirmation(&mut self) -> bool {
|
||||
let Some(popup) = self.version_popup.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
if popup.loading || popup.installing || popup.versions.get(popup.selected).is_none() {
|
||||
return false;
|
||||
}
|
||||
popup.confirming = true;
|
||||
popup.error = None;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn search_due(&self) -> bool {
|
||||
self.search_changed_at
|
||||
.is_some_and(|changed| changed.elapsed() >= SEARCH_DEBOUNCE)
|
||||
@@ -434,6 +456,7 @@ impl DiscoveryState {
|
||||
continue;
|
||||
};
|
||||
popup.installing = false;
|
||||
popup.confirming = false;
|
||||
match result {
|
||||
Ok(completion) => {
|
||||
if let Some(entry) = self
|
||||
@@ -501,12 +524,16 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut DiscoveryState) -> bool {
|
||||
if let Some(popup) = state.version_popup.as_mut() {
|
||||
match key_event.code {
|
||||
KeyCode::Esc if !popup.installing => state.version_popup = None,
|
||||
KeyCode::Char('j') | KeyCode::Down if !popup.loading && !popup.installing => {
|
||||
KeyCode::Char('j') | KeyCode::Down
|
||||
if !popup.loading && !popup.installing && !popup.confirming =>
|
||||
{
|
||||
if popup.selected + 1 < popup.versions.len() {
|
||||
popup.selected += 1;
|
||||
}
|
||||
}
|
||||
KeyCode::Char('k') | KeyCode::Up if !popup.loading && !popup.installing => {
|
||||
KeyCode::Char('k') | KeyCode::Up
|
||||
if !popup.loading && !popup.installing && !popup.confirming =>
|
||||
{
|
||||
popup.selected = popup.selected.saturating_sub(1);
|
||||
}
|
||||
_ => {}
|
||||
@@ -563,6 +590,11 @@ pub(crate) fn project_entry(
|
||||
name: project.title,
|
||||
source_slug: Some(project.slug),
|
||||
installed_path: installed_path.clone(),
|
||||
provider_project: Some(crate::instance::ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: project.id.clone(),
|
||||
version_id: String::new(),
|
||||
}),
|
||||
title_suffix: installed_path.is_some().then(|| "Installed".to_owned()),
|
||||
footer_label: Some(format!("{} downloads", format_downloads(project.downloads))),
|
||||
description: project.description,
|
||||
@@ -573,48 +605,6 @@ pub(crate) fn project_entry(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn installed_project_path(
|
||||
project: &DiscoveryProject,
|
||||
installed_entries: &[ContentEntry],
|
||||
) -> Option<PathBuf> {
|
||||
installed_path_for_identity(&project.title, &project.slug, installed_entries)
|
||||
}
|
||||
|
||||
fn installed_path_for_identity(
|
||||
title: &str,
|
||||
slug: &str,
|
||||
installed_entries: &[ContentEntry],
|
||||
) -> Option<PathBuf> {
|
||||
installed_entries.iter().find_map(|entry| {
|
||||
let matches = identity_matches(&entry.name, title)
|
||||
|| identity_matches(&entry.name, slug)
|
||||
|| filename_matches_project(&entry.file_stem, slug)
|
||||
|| filename_matches_project(&entry.file_stem, title);
|
||||
matches.then(|| entry.path.clone())
|
||||
})
|
||||
}
|
||||
|
||||
fn identity_matches(left: &str, right: &str) -> bool {
|
||||
let normalize = |value: &str| {
|
||||
value
|
||||
.chars()
|
||||
.filter(|character| character.is_alphanumeric())
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect::<String>()
|
||||
};
|
||||
let right = normalize(right);
|
||||
!right.is_empty() && normalize(left) == right
|
||||
}
|
||||
|
||||
fn filename_matches_project(file_stem: &str, project_name: &str) -> bool {
|
||||
let file_stem = file_stem.to_lowercase();
|
||||
let project_name = project_name.to_lowercase().replace(' ', "-");
|
||||
file_stem == project_name
|
||||
|| file_stem
|
||||
.strip_prefix(&project_name)
|
||||
.is_some_and(|suffix| suffix.starts_with(['-', '_', '.']))
|
||||
}
|
||||
|
||||
fn format_downloads(downloads: u64) -> String {
|
||||
match downloads {
|
||||
1_000_000.. => format!("{:.1}M", downloads as f64 / 1_000_000.0),
|
||||
@@ -649,6 +639,7 @@ mod tests {
|
||||
fn version(id: &str) -> VersionInfo {
|
||||
VersionInfo {
|
||||
id: id.to_owned(),
|
||||
project_id: "project".to_owned(),
|
||||
name: format!("Version {id}"),
|
||||
version_number: id.to_owned(),
|
||||
game_versions: vec!["1.21.1".to_owned()],
|
||||
@@ -685,33 +676,6 @@ mod tests {
|
||||
assert_eq!(entry.installed_path, Some(PathBuf::from("example.jar")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_projects_match_metadata_names_and_versioned_filenames() {
|
||||
let project = DiscoveryProject {
|
||||
id: "P7dR8mSH".to_owned(),
|
||||
slug: "fabric-api".to_owned(),
|
||||
title: "Fabric API".to_owned(),
|
||||
description: String::new(),
|
||||
downloads: 0,
|
||||
icon_url: None,
|
||||
icon_bytes: None,
|
||||
};
|
||||
let mut local = project_entry(project.clone(), None);
|
||||
local.name = "Fabric API".to_owned();
|
||||
local.file_stem = "unrelated-file".to_owned();
|
||||
assert!(installed_project_path(&project, &[local]).is_some());
|
||||
|
||||
let mut local = project_entry(project.clone(), None);
|
||||
local.name = "Unknown".to_owned();
|
||||
local.file_stem = "fabric-api-0.116.0+1.21.1".to_owned();
|
||||
assert!(installed_project_path(&project, &[local]).is_some());
|
||||
|
||||
let mut local = project_entry(project.clone(), None);
|
||||
local.name = "Fabric Language Kotlin".to_owned();
|
||||
local.file_stem = "fabric-language-kotlin".to_owned();
|
||||
assert!(installed_project_path(&project, &[local]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_and_change_version_popups_only_differ_in_title() {
|
||||
let project = DiscoveryProject {
|
||||
@@ -819,7 +783,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_labels_follow_the_current_instance_entries() {
|
||||
fn installed_labels_follow_exact_manifest_projects() {
|
||||
let project = DiscoveryProject {
|
||||
id: "project-id".to_owned(),
|
||||
slug: "example-project".to_owned(),
|
||||
@@ -832,15 +796,25 @@ mod tests {
|
||||
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
|
||||
state.list.entries.push(project_entry(project, None));
|
||||
|
||||
let mut installed = state.list.entries[0].clone();
|
||||
installed.name = "Example Project".to_owned();
|
||||
installed.file_stem = "example-project-1.0.0".to_owned();
|
||||
installed.path = PathBuf::from("first/mods/example-project-1.0.0.jar");
|
||||
installed.source_slug = None;
|
||||
installed.installed_path = None;
|
||||
installed.title_suffix = None;
|
||||
|
||||
state.refresh_installed_labels(&[installed]);
|
||||
let mut manifest = crate::instance::ContentManifest::default();
|
||||
manifest.upsert(crate::instance::ContentFileRecord {
|
||||
relative_path: PathBuf::from("mods/example-project-1.0.0.jar"),
|
||||
kind: crate::instance::ContentKind::Mod,
|
||||
enabled: true,
|
||||
fingerprint: crate::instance::FileFingerprint {
|
||||
size: 1,
|
||||
modified_ns: 1,
|
||||
hashes: Default::default(),
|
||||
},
|
||||
resolution: crate::instance::Resolution::Resolved {
|
||||
project: crate::instance::ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: "project-id".to_owned(),
|
||||
version_id: "version".to_owned(),
|
||||
},
|
||||
},
|
||||
});
|
||||
state.refresh_installed_manifest(&manifest, std::path::Path::new("first"));
|
||||
assert_eq!(
|
||||
state.list.entries[0].title_suffix.as_deref(),
|
||||
Some("Installed")
|
||||
@@ -850,7 +824,10 @@ mod tests {
|
||||
Some(PathBuf::from("first/mods/example-project-1.0.0.jar"))
|
||||
);
|
||||
|
||||
state.refresh_installed_labels(&[]);
|
||||
state.refresh_installed_manifest(
|
||||
&crate::instance::ContentManifest::default(),
|
||||
std::path::Path::new("first"),
|
||||
);
|
||||
assert_eq!(state.list.entries[0].title_suffix, None);
|
||||
assert_eq!(state.list.entries[0].installed_path, None);
|
||||
assert_eq!(state.list.entries[0].path, PathBuf::from("project-id"));
|
||||
|
||||
+306
-62
@@ -182,6 +182,54 @@ impl Default for ContentListState {
|
||||
}
|
||||
|
||||
impl ContentListState {
|
||||
pub fn apply_manifest(
|
||||
&mut self,
|
||||
manifest: &crate::instance::ContentManifest,
|
||||
minecraft_dir: &Path,
|
||||
kind: crate::instance::ContentKind,
|
||||
icons: &std::collections::HashMap<(String, String), Vec<u8>>,
|
||||
) {
|
||||
let mut changed = false;
|
||||
for entry in &mut self.entries {
|
||||
let Ok(relative_path) = entry.path.strip_prefix(minecraft_dir) else {
|
||||
continue;
|
||||
};
|
||||
let Some(record) = manifest
|
||||
.record(relative_path)
|
||||
.filter(|record| record.kind == kind)
|
||||
else {
|
||||
if entry.provider_project.take().is_some() {
|
||||
changed = true;
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let project = match &record.resolution {
|
||||
crate::instance::Resolution::Resolved { project } => Some(project.clone()),
|
||||
_ => None,
|
||||
};
|
||||
if entry.provider_project != project {
|
||||
entry.provider_project = project.clone();
|
||||
changed = true;
|
||||
}
|
||||
if entry.icon_bytes.is_none()
|
||||
&& let Some(project) = project
|
||||
&& let Some(bytes) =
|
||||
icons.get(&(project.provider.clone(), project.project_id.clone()))
|
||||
&& let Some(lines) = crate::instance::content::mods::make_icon_pixels(bytes, 6, 3)
|
||||
{
|
||||
entry.icon_bytes = Some(bytes.clone());
|
||||
entry.icon_lines = Some(lines);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.images_dirty = true;
|
||||
self.image_protocols.clear();
|
||||
self.requested_images.clear();
|
||||
crate::tui::request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_stream(&mut self, source: impl Into<String>) -> ContentStream {
|
||||
self.start_stream_with_order(source, ContentStreamOrder::Sorted)
|
||||
}
|
||||
@@ -319,9 +367,9 @@ impl ContentListState {
|
||||
|
||||
// drain streaming entries from the initial load. each entry arrives
|
||||
// individually and is inserted in sorted position for a smooth fill-in
|
||||
pub fn drain_pending(&mut self) {
|
||||
pub fn drain_pending(&mut self) -> bool {
|
||||
let Some(rx) = &self.stream_rx else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
|
||||
let mut received = false;
|
||||
@@ -370,6 +418,7 @@ impl ContentListState {
|
||||
}
|
||||
}
|
||||
Ok(ContentStreamUpdate::Retain(file_stems)) => {
|
||||
received = true;
|
||||
let selected_stem = self.selected_file_stem();
|
||||
self.entries
|
||||
.retain(|entry| file_stems.contains(&entry.file_stem));
|
||||
@@ -387,6 +436,7 @@ impl ContentListState {
|
||||
path,
|
||||
bytes,
|
||||
}) => {
|
||||
received = true;
|
||||
if let Some(entry) = self
|
||||
.entries
|
||||
.iter_mut()
|
||||
@@ -431,13 +481,14 @@ impl ContentListState {
|
||||
}
|
||||
self.update_scrollbar();
|
||||
}
|
||||
received || finished
|
||||
}
|
||||
|
||||
// pick up the precomputed diff from the notify watcher callback.
|
||||
// skip while streaming is in progress to avoid duplicate entries.
|
||||
pub fn drain_watcher(&mut self) {
|
||||
pub fn drain_watcher(&mut self) -> bool {
|
||||
if self.stream_rx.is_some() {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
let diff = match self.watcher_diff.lock() {
|
||||
@@ -446,7 +497,7 @@ impl ContentListState {
|
||||
};
|
||||
|
||||
let Some(diff) = diff else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
self.images_dirty = true;
|
||||
|
||||
@@ -495,6 +546,7 @@ impl ContentListState {
|
||||
}
|
||||
|
||||
self.update_scrollbar();
|
||||
true
|
||||
}
|
||||
|
||||
// starts a notify file watcher on the given directory. changes trigger
|
||||
@@ -510,10 +562,12 @@ impl ContentListState {
|
||||
let ext: &'static str = self.content_ext.unwrap_or(".jar");
|
||||
let scan_one = self.scan_one_fn;
|
||||
|
||||
let dirty = Arc::new(AtomicBool::new(false));
|
||||
let running = Arc::new(AtomicBool::new(false));
|
||||
let dirty_cb = dirty.clone();
|
||||
let running_cb = running.clone();
|
||||
let pending_paths = Arc::new(Mutex::new(HashSet::<std::path::PathBuf>::new()));
|
||||
let pending_paths_cb = pending_paths.clone();
|
||||
let needs_rescan = Arc::new(AtomicBool::new(false));
|
||||
let needs_rescan_cb = needs_rescan.clone();
|
||||
|
||||
// initialize known stems from the current directory state so existing
|
||||
// files are not treated as "new" on the first notify event
|
||||
@@ -521,28 +575,39 @@ impl ContentListState {
|
||||
|
||||
let watch_dir = dir.clone();
|
||||
let watcher = notify::recommended_watcher(move |res: Result<notify::Event, _>| {
|
||||
if let Err(e) = &res {
|
||||
tracing::warn!(
|
||||
"Content watcher event error for {}: {}",
|
||||
watch_dir.display(),
|
||||
e
|
||||
);
|
||||
return;
|
||||
let event_paths = match res {
|
||||
Ok(event) => match watcher_event_handling(&event.kind) {
|
||||
WatcherEventHandling::Ignore => return,
|
||||
WatcherEventHandling::Paths => event.paths,
|
||||
WatcherEventHandling::Rescan => {
|
||||
needs_rescan_cb.store(true, Ordering::Relaxed);
|
||||
event.paths
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"Content watcher event error for {}: {}",
|
||||
watch_dir.display(),
|
||||
e
|
||||
);
|
||||
needs_rescan_cb.store(true, Ordering::Relaxed);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
if let Ok(mut pending) = pending_paths_cb.lock() {
|
||||
pending.extend(event_paths);
|
||||
}
|
||||
|
||||
// mark dirty. if a thread is already running it will loop to
|
||||
// pick up the change after its current diff
|
||||
dirty_cb.store(true, Ordering::Relaxed);
|
||||
|
||||
if running_cb.swap(true, Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
let dir = watch_dir.clone();
|
||||
let diff_slot = watcher_diff.clone();
|
||||
let dirty = dirty_cb.clone();
|
||||
let running = running_cb.clone();
|
||||
let known = known_stems.clone();
|
||||
let pending_paths = pending_paths_cb.clone();
|
||||
let needs_rescan = needs_rescan_cb.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
// always clear `running` even if we panic
|
||||
@@ -552,56 +617,50 @@ impl ContentListState {
|
||||
self.0.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let _guard = ResetOnDrop(running);
|
||||
let _guard = ResetOnDrop(running.clone());
|
||||
|
||||
loop {
|
||||
dirty.store(false, Ordering::Relaxed);
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
|
||||
let result = (|| {
|
||||
let on_disk = read_dir_stems(&dir, ext);
|
||||
let mut known_map = known.lock().ok()?;
|
||||
|
||||
let mut toggled = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
let mut added = Vec::new();
|
||||
|
||||
for (stem, (old_path, old_enabled)) in known_map.iter() {
|
||||
if let Some((disk_path, disk_enabled)) = on_disk.get(stem) {
|
||||
if *disk_enabled != *old_enabled || *disk_path != *old_path {
|
||||
toggled.push((stem.clone(), *disk_enabled, disk_path.clone()));
|
||||
}
|
||||
} else {
|
||||
removed.push(stem.clone());
|
||||
}
|
||||
}
|
||||
|
||||
for (stem, (path, enabled)) in &on_disk {
|
||||
if !known_map.contains_key(stem)
|
||||
&& let Some(scan_one) = scan_one
|
||||
{
|
||||
added.push(scan_one(path, stem, *enabled));
|
||||
}
|
||||
}
|
||||
|
||||
*known_map = on_disk;
|
||||
|
||||
Some(WatcherDiff {
|
||||
toggled,
|
||||
removed,
|
||||
added,
|
||||
})
|
||||
})();
|
||||
let paths = pending_paths
|
||||
.lock()
|
||||
.ok()
|
||||
.map(|mut pending| pending.drain().collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
let full_rescan = needs_rescan.swap(false, Ordering::Relaxed);
|
||||
let result = if full_rescan {
|
||||
diff_directory(&dir, ext, scan_one, &known)
|
||||
} else {
|
||||
diff_event_paths(&dir, &paths, ext, scan_one, &known)
|
||||
};
|
||||
|
||||
if let Some(diff) = result
|
||||
&& let Ok(mut slot) = diff_slot.lock()
|
||||
{
|
||||
*slot = Some(diff);
|
||||
if let Some(pending) = slot.as_mut() {
|
||||
merge_watcher_diff(pending, diff);
|
||||
} else {
|
||||
*slot = Some(diff);
|
||||
}
|
||||
crate::tui::request_redraw();
|
||||
}
|
||||
|
||||
if !dirty.load(Ordering::Relaxed) {
|
||||
break;
|
||||
let no_pending = pending_paths.lock().is_ok_and(|pending| pending.is_empty());
|
||||
if no_pending && !needs_rescan.load(Ordering::Relaxed) {
|
||||
// Release ownership before the final check. An event
|
||||
// racing with this boundary either starts a new worker
|
||||
// or is observed here and kept by this worker.
|
||||
running.store(false, Ordering::Release);
|
||||
let still_empty =
|
||||
pending_paths.lock().is_ok_and(|pending| pending.is_empty());
|
||||
if still_empty && !needs_rescan.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
if running
|
||||
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1580,10 +1639,161 @@ fn square_icon_columns(rows: u16, font_size: (u16, u16)) -> u16 {
|
||||
((u32::from(rows) * height + width / 2) / width).max(1) as u16
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum WatcherEventHandling {
|
||||
Ignore,
|
||||
Paths,
|
||||
Rescan,
|
||||
}
|
||||
|
||||
fn watcher_event_handling(kind: ¬ify::EventKind) -> WatcherEventHandling {
|
||||
match kind {
|
||||
notify::EventKind::Access(_) => WatcherEventHandling::Ignore,
|
||||
notify::EventKind::Create(_)
|
||||
| notify::EventKind::Modify(_)
|
||||
| notify::EventKind::Remove(_) => WatcherEventHandling::Paths,
|
||||
notify::EventKind::Any | notify::EventKind::Other => WatcherEventHandling::Rescan,
|
||||
}
|
||||
}
|
||||
|
||||
// reads a content directory and builds a stem -> (path, enabled) map.
|
||||
// used both by watch_dir to initialize known state and by the watcher
|
||||
// thread to detect changes. when ext is empty (worlds), only directories
|
||||
// are included.
|
||||
fn diff_directory(
|
||||
dir: &std::path::Path,
|
||||
ext: &str,
|
||||
scan_one: Option<ScanOneFn>,
|
||||
known: &Arc<Mutex<HashMap<String, (std::path::PathBuf, bool)>>>,
|
||||
) -> Option<WatcherDiff> {
|
||||
let on_disk = read_dir_stems(dir, ext);
|
||||
let mut known_map = known.lock().ok()?;
|
||||
let mut toggled = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
let mut added = Vec::new();
|
||||
for (stem, (old_path, old_enabled)) in known_map.iter() {
|
||||
if let Some((disk_path, disk_enabled)) = on_disk.get(stem) {
|
||||
if disk_enabled != old_enabled || disk_path != old_path {
|
||||
toggled.push((stem.clone(), *disk_enabled, disk_path.clone()));
|
||||
}
|
||||
} else {
|
||||
removed.push(stem.clone());
|
||||
}
|
||||
}
|
||||
for (stem, (path, enabled)) in &on_disk {
|
||||
if !known_map.contains_key(stem)
|
||||
&& let Some(scan_one) = scan_one
|
||||
{
|
||||
added.push(scan_one(path, stem, *enabled));
|
||||
}
|
||||
}
|
||||
*known_map = on_disk;
|
||||
watcher_diff(toggled, removed, added)
|
||||
}
|
||||
|
||||
fn diff_event_paths(
|
||||
dir: &std::path::Path,
|
||||
paths: &[std::path::PathBuf],
|
||||
ext: &str,
|
||||
scan_one: Option<ScanOneFn>,
|
||||
known: &Arc<Mutex<HashMap<String, (std::path::PathBuf, bool)>>>,
|
||||
) -> Option<WatcherDiff> {
|
||||
let mut known_map = known.lock().ok()?;
|
||||
let mut toggled = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
let mut added = Vec::new();
|
||||
for path in paths {
|
||||
if path.parent() != Some(dir) {
|
||||
continue;
|
||||
}
|
||||
if path.exists() {
|
||||
let Some((stem, enabled)) = watched_stem(path, ext) else {
|
||||
continue;
|
||||
};
|
||||
match known_map.get(&stem) {
|
||||
Some((known_path, known_enabled))
|
||||
if known_path == path && *known_enabled == enabled =>
|
||||
{
|
||||
// A modify event still needs a rescan so changed archive
|
||||
// metadata and icons become visible.
|
||||
if let Some(scan_one) = scan_one {
|
||||
removed.push(stem.clone());
|
||||
added.push(scan_one(path, &stem, enabled));
|
||||
}
|
||||
}
|
||||
Some(_) => {
|
||||
toggled.push((stem.clone(), enabled, path.clone()));
|
||||
}
|
||||
None => {
|
||||
if let Some(scan_one) = scan_one {
|
||||
added.push(scan_one(path, &stem, enabled));
|
||||
}
|
||||
}
|
||||
}
|
||||
known_map.insert(stem, (path.clone(), enabled));
|
||||
} else {
|
||||
let removed_stems = known_map
|
||||
.iter()
|
||||
.filter_map(|(stem, (known_path, _))| (known_path == path).then(|| stem.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
for stem in removed_stems {
|
||||
known_map.remove(&stem);
|
||||
removed.push(stem);
|
||||
}
|
||||
}
|
||||
}
|
||||
watcher_diff(toggled, removed, added)
|
||||
}
|
||||
|
||||
fn watcher_diff(
|
||||
toggled: Vec<(String, bool, std::path::PathBuf)>,
|
||||
removed: Vec<String>,
|
||||
added: Vec<crate::instance::content::mods::ContentEntry>,
|
||||
) -> Option<WatcherDiff> {
|
||||
if toggled.is_empty() && removed.is_empty() && added.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(WatcherDiff {
|
||||
toggled,
|
||||
removed,
|
||||
added,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_watcher_diff(pending: &mut WatcherDiff, mut next: WatcherDiff) {
|
||||
pending.toggled.append(&mut next.toggled);
|
||||
pending.removed.append(&mut next.removed);
|
||||
pending.added.append(&mut next.added);
|
||||
|
||||
pending.toggled.reverse();
|
||||
pending.toggled.sort_by(|left, right| left.0.cmp(&right.0));
|
||||
pending.toggled.dedup_by(|left, right| left.0 == right.0);
|
||||
pending.removed.sort();
|
||||
pending.removed.dedup();
|
||||
pending.added.reverse();
|
||||
pending
|
||||
.added
|
||||
.sort_by(|left, right| left.file_stem.cmp(&right.file_stem));
|
||||
pending
|
||||
.added
|
||||
.dedup_by(|left, right| left.file_stem == right.file_stem);
|
||||
}
|
||||
|
||||
fn watched_stem(path: &std::path::Path, ext: &str) -> Option<(String, bool)> {
|
||||
let name = path.file_name()?.to_str()?;
|
||||
if path.is_dir() || ext.is_empty() {
|
||||
let (enabled, stem) = crate::instance::content::parse_enabled_stem_dir(name);
|
||||
return Some((stem, enabled));
|
||||
}
|
||||
let disabled_ext = format!("{ext}.disabled");
|
||||
if let Some(stem) = name.strip_suffix(&disabled_ext) {
|
||||
Some((stem.to_owned(), false))
|
||||
} else {
|
||||
name.strip_suffix(ext).map(|stem| (stem.to_owned(), true))
|
||||
}
|
||||
}
|
||||
|
||||
fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::path::PathBuf, bool)> {
|
||||
let mut map = HashMap::new();
|
||||
let Ok(read_dir) = std::fs::read_dir(dir) else {
|
||||
@@ -1620,7 +1830,11 @@ fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::pat
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{collections::HashSet, path::PathBuf};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::instance::content::mods::ContentEntry;
|
||||
use ratatui::{
|
||||
@@ -1632,8 +1846,9 @@ mod tests {
|
||||
};
|
||||
|
||||
use super::{
|
||||
ContentListState, available_description_width, description_text_width, ellipsize,
|
||||
right_aligned_footer_spans, square_icon_columns, title_suffix_spans,
|
||||
ContentListState, WatcherEventHandling, available_description_width,
|
||||
description_text_width, diff_event_paths, ellipsize, right_aligned_footer_spans,
|
||||
square_icon_columns, title_suffix_spans, watcher_event_handling,
|
||||
};
|
||||
|
||||
fn entry(name: &str) -> ContentEntry {
|
||||
@@ -1642,6 +1857,7 @@ mod tests {
|
||||
name: name.to_owned(),
|
||||
source_slug: None,
|
||||
installed_path: None,
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
description: String::new(),
|
||||
@@ -1652,6 +1868,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_watcher_ignores_file_access_events() {
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::EventKind::Access(notify::event::AccessKind::Any)),
|
||||
WatcherEventHandling::Ignore
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_watcher_handles_mutations_without_full_rescan() {
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::EventKind::Modify(notify::event::ModifyKind::Any)),
|
||||
WatcherEventHandling::Paths
|
||||
);
|
||||
assert_eq!(
|
||||
watcher_event_handling(¬ify::EventKind::Any),
|
||||
WatcherEventHandling::Rescan
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn irrelevant_watcher_paths_do_not_emit_an_empty_diff() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let known = Arc::new(Mutex::new(HashMap::new()));
|
||||
let paths = vec![temp.path().join("notes.txt")];
|
||||
assert!(diff_event_paths(temp.path(), &paths, ".jar", None, &known).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn square_columns_follow_terminal_cell_ratio() {
|
||||
assert_eq!(square_icon_columns(3, (8, 16)), 6);
|
||||
|
||||
@@ -306,7 +306,7 @@ pub fn render(
|
||||
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
let content_dir = instances_dir
|
||||
.join(&instance.name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("mods");
|
||||
mods_state.start_load(
|
||||
&content_dir,
|
||||
@@ -349,7 +349,7 @@ pub fn render(
|
||||
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
let content_dir = instances_dir
|
||||
.join(&instance.name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("resourcepacks");
|
||||
resource_packs_state.start_load(
|
||||
&content_dir,
|
||||
@@ -392,7 +392,7 @@ pub fn render(
|
||||
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
let content_dir = instances_dir
|
||||
.join(&instance.name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("shaderpacks");
|
||||
shaders_state.start_load(
|
||||
&content_dir,
|
||||
@@ -473,7 +473,7 @@ pub fn render(
|
||||
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
let content_dir = instances_dir
|
||||
.join(&instance.name)
|
||||
.join(".minecraft")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join("saves");
|
||||
worlds_state.start_load(
|
||||
&content_dir,
|
||||
@@ -547,8 +547,16 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
|
||||
let title = popup.title();
|
||||
let loading = popup.loading;
|
||||
let installing = popup.installing;
|
||||
let confirming = popup.confirming;
|
||||
let error = popup.error.clone();
|
||||
let selected = popup.selected;
|
||||
let selected_version = popup
|
||||
.versions
|
||||
.get(selected)
|
||||
.map(|version| version.version_number.clone())
|
||||
.unwrap_or_default();
|
||||
let project_title = popup.project_title.clone();
|
||||
let replacing = popup.installed_path.is_some();
|
||||
let items = popup
|
||||
.versions
|
||||
.iter()
|
||||
@@ -561,11 +569,15 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
|
||||
title: styled_title(&title, false),
|
||||
border_color: theme.accent(),
|
||||
bg: Some(theme.surface()),
|
||||
keybinds: Some(crate::tui::widgets::popups::keybind_line(&[
|
||||
("j/k", " navigate"),
|
||||
("Enter", " install"),
|
||||
("Esc", " close"),
|
||||
])),
|
||||
keybinds: Some(crate::tui::widgets::popups::keybind_line(if confirming {
|
||||
&[("Enter", " confirm"), ("Esc", " cancel")]
|
||||
} else {
|
||||
&[
|
||||
("j/k", " navigate"),
|
||||
("Enter", " continue"),
|
||||
("Esc", " close"),
|
||||
]
|
||||
})),
|
||||
search_line: None,
|
||||
content: Box::new(move |area, buffer| {
|
||||
if installing {
|
||||
@@ -581,6 +593,14 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
|
||||
.style(Style::default().fg(THEME.as_ref().error()))
|
||||
.wrap(Wrap { trim: true })
|
||||
.render(area, buffer);
|
||||
} else if confirming {
|
||||
let action = if replacing { "Change" } else { "Install" };
|
||||
Paragraph::new(format!(
|
||||
"{action} {project_title} version {selected_version}?\n\nThe file is changed only after the download succeeds."
|
||||
))
|
||||
.style(Style::default().fg(THEME.as_ref().text()))
|
||||
.wrap(Wrap { trim: true })
|
||||
.render(area, buffer);
|
||||
} else if items.is_empty() {
|
||||
Paragraph::new("No compatible versions found.")
|
||||
.style(Style::default().fg(THEME.as_ref().text_dim()))
|
||||
@@ -743,6 +763,7 @@ mod tests {
|
||||
fn discovery_version_rows_only_show_the_version_number() {
|
||||
let version = crate::net::modrinth::VersionInfo {
|
||||
id: "version-id".to_owned(),
|
||||
project_id: "project-id".to_owned(),
|
||||
name: "A descriptive release title".to_owned(),
|
||||
version_number: "3.2.4-fabric-26.1".to_owned(),
|
||||
game_versions: vec![],
|
||||
|
||||
@@ -296,6 +296,7 @@ mod tests {
|
||||
guard.versions = LoadState::Loaded(vec![
|
||||
VersionInfo {
|
||||
id: "v1".into(),
|
||||
project_id: "project".into(),
|
||||
name: "1.0.0".into(),
|
||||
version_number: "1.0.0".into(),
|
||||
game_versions: vec!["1.20.1".into()],
|
||||
@@ -304,6 +305,7 @@ mod tests {
|
||||
},
|
||||
VersionInfo {
|
||||
id: "v2".into(),
|
||||
project_id: "project".into(),
|
||||
name: "0.9.0".into(),
|
||||
version_number: "0.9.0".into(),
|
||||
game_versions: vec!["1.20.1".into()],
|
||||
|
||||
@@ -296,7 +296,7 @@ async fn resolve_version_id(
|
||||
match modrinth::fetch_version(client, version_id).await {
|
||||
Ok(version) => {
|
||||
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
||||
let tmp_dir = meta_dir.join("tmp");
|
||||
let tmp_dir = crate::storage::MetadataPaths::new(&meta_dir).temporary();
|
||||
if let Err(e) = tokio::fs::create_dir_all(&tmp_dir).await {
|
||||
set_error_and_back(
|
||||
&state_arc,
|
||||
@@ -368,7 +368,7 @@ fn start_version_download(state: &mut ImportWizardState) {
|
||||
tokio::spawn(async move {
|
||||
let client = crate::net::HttpClient::new();
|
||||
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
||||
let tmp_dir = meta_dir.join("tmp");
|
||||
let tmp_dir = crate::storage::MetadataPaths::new(&meta_dir).temporary();
|
||||
if let Err(e) = tokio::fs::create_dir_all(&tmp_dir).await {
|
||||
set_error_and_back(
|
||||
&state_arc,
|
||||
|
||||
Reference in new issue
Block a user