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
@@ -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