From 9cd454cee261176f9d1b8018af3a0b010ea86a9c Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 23:25:43 +0200 Subject: [PATCH] fix: reload editor saves and reject stale TUI actions --- src/instance/glfw.rs | 213 +++++++ src/instance/mod.rs | 1 + src/tui/app.rs | 7 +- src/tui/event.rs | 460 ++++++++++++-- src/tui/input.rs | 280 ++++----- src/tui/logging.rs | 23 +- src/tui/tests/event.rs | 581 +++++++++++++++++- src/tui/tests/flows.rs | 137 ++++- src/tui/tests/harness.rs | 38 +- src/tui/tests/widgets/content/discovery.rs | 14 + src/tui/tests/widgets/content/list.rs | 24 + src/tui/tests/widgets/content/tabs.rs | 1 + src/tui/tests/widgets/logs_viewer.rs | 55 ++ src/tui/tests/widgets/markdown.rs | 12 + .../widgets/popups/import_modpack/state.rs | 37 ++ .../widgets/popups/new_instance/state.rs | 55 ++ src/tui/tests/widgets/search.rs | 26 + src/tui/tests/widgets/settings.rs | 58 +- src/tui/widgets/content/discovery.rs | 22 +- src/tui/widgets/content/list.rs | 9 +- src/tui/widgets/content/tabs.rs | 5 +- src/tui/widgets/logs_viewer.rs | 49 +- src/tui/widgets/markdown.rs | 16 +- src/tui/widgets/mod.rs | 2 - src/tui/widgets/popups/global_settings.rs | 132 +++- src/tui/widgets/popups/import_modpack/mod.rs | 1 + .../widgets/popups/import_modpack/state.rs | 17 + src/tui/widgets/popups/instance_settings.rs | 168 ++++- src/tui/widgets/popups/new_instance/mod.rs | 1 + src/tui/widgets/popups/new_instance/state.rs | 7 + src/tui/widgets/popups/settings_controls.rs | 354 ++++------- src/tui/widgets/search.rs | 15 +- src/tui/widgets/settings.rs | 115 ++-- 33 files changed, 2297 insertions(+), 638 deletions(-) create mode 100644 src/instance/glfw.rs diff --git a/src/instance/glfw.rs b/src/instance/glfw.rs new file mode 100644 index 0000000..dedba69 --- /dev/null +++ b/src/instance/glfw.rs @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Clone)] +pub(crate) struct GlfwInstallation { + pub path: PathBuf, + pub version: Option, +} + +pub(crate) fn bundled_glfw_version(meta_dir: &Path, game_version: &str) -> Option { + let path = crate::storage::MetadataPaths::new(meta_dir) + .versions() + .join(game_version) + .join("meta.json"); + let profile: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; + profile + .get("libraries")? + .as_array()? + .iter() + .filter_map(|library| library.get("name")?.as_str()) + .find_map(|coordinate| { + let mut parts = coordinate.split(':'); + match (parts.next(), parts.next(), parts.next()) { + (Some("org.lwjgl"), Some("lwjgl-glfw"), Some(version)) => Some(version.to_owned()), + _ => None, + } + }) +} + +pub(crate) fn discover_glfw_installations() -> Vec { + discover_in(&discovery_directories(), std::env::consts::OS) +} + +fn discovery_directories() -> Vec { + let mut directories = Vec::::new(); + let variables: &[&str] = match std::env::consts::OS { + "windows" => &["PATH"], + "macos" => &["DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH", "PATH"], + _ => &["LD_LIBRARY_PATH", "PATH"], + }; + for variable in variables { + if let Some(value) = std::env::var_os(variable) { + directories.extend(std::env::split_paths(&value)); + } + } + match std::env::consts::OS { + "windows" => { + if let Some(root) = std::env::var_os("SystemRoot") { + let root = PathBuf::from(root); + directories.extend([root.join("System32"), root.clone()]); + } + } + "macos" => { + directories.extend( + [ + "/usr/lib", + "/usr/local/lib", + "/opt/homebrew/lib", + "/opt/local/lib", + ] + .into_iter() + .map(PathBuf::from), + ); + if let Some(home) = dirs::home_dir() { + directories.push(home.join("lib")); + } + } + _ => { + directories.extend( + ["/usr/lib", "/usr/lib64", "/usr/local/lib", "/lib", "/lib64"] + .into_iter() + .map(PathBuf::from), + ); + if let Some(home) = dirs::home_dir() { + directories.push(home.join(".local/lib")); + } + } + } + if let Ok(executable) = std::env::current_exe() + && let Some(parent) = executable.parent() + { + directories.push(parent.to_owned()); + } + if let Ok(directory) = std::env::current_dir() { + directories.push(directory); + } + directories.sort(); + directories.dedup(); + directories +} + +fn discover_in(roots: &[PathBuf], os: &str) -> Vec { + let mut directories = roots.to_vec(); + let mut nested = Vec::new(); + for directory in &directories { + if let Ok(entries) = std::fs::read_dir(directory) { + nested.extend( + entries + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.is_dir()), + ); + } + } + directories.extend(nested); + let mut seen = BTreeSet::new(); + let mut installations = Vec::new(); + for directory in directories { + let Ok(entries) = std::fs::read_dir(directory) else { + continue; + }; + for path in entries.flatten().map(|entry| entry.path()) { + if !path.is_file() + || !path + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| is_glfw_library_name(name, os)) + { + continue; + } + let canonical = std::fs::canonicalize(&path).unwrap_or(path); + if seen.insert(canonical.clone()) { + installations.push(GlfwInstallation { + version: glfw_version_from_path(&canonical), + path: canonical, + }); + } + } + } + installations.sort_by(|left, right| left.path.cmp(&right.path)); + installations +} + +fn is_glfw_library_name(name: &str, os: &str) -> bool { + let name = name.to_ascii_lowercase(); + let versioned_so = name.strip_prefix("libglfw.so.").is_some_and(|version| { + version.split('.').all(|part| { + !part.is_empty() && part.chars().all(|character| character.is_ascii_digit()) + }) + }); + match os { + "windows" => name.starts_with("glfw") && name.ends_with(".dll"), + "macos" => name.starts_with("libglfw.") && name.ends_with(".dylib"), + _ => name == "libglfw.so" || versioned_so, + } +} + +pub(crate) fn glfw_version_from_path(path: &Path) -> Option { + let name = path.file_name()?.to_str()?.to_ascii_lowercase(); + if let Some((_, suffix)) = name.rsplit_once(".so.") { + return (!suffix.is_empty()).then(|| suffix.to_owned()); + } + let stem = name + .strip_prefix("libglfw.") + .and_then(|name| name.strip_suffix(".dylib")) + .or_else(|| { + name.strip_prefix("glfw") + .and_then(|name| name.strip_suffix(".dll")) + })?; + (!stem.is_empty()).then(|| stem.trim_start_matches(['-', '.']).to_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn library_names_are_recognized() { + assert!(is_glfw_library_name("libglfw.so.3", "linux")); + assert!(is_glfw_library_name("libglfw.3.dylib", "macos")); + assert!(is_glfw_library_name("glfw3.dll", "windows")); + assert!(!is_glfw_library_name("libglfw.so.backup", "linux")); + assert!(!is_glfw_library_name("libGL.so", "linux")); + assert_eq!( + glfw_version_from_path(Path::new("/usr/lib/libglfw.so.3.4")).as_deref(), + Some("3.4") + ); + } + + #[test] + fn each_platform_discovers_its_native_libraries_in_environment_and_nested_directories() { + let temp = tempfile::tempdir().unwrap(); + let nested = temp.path().join("native"); + std::fs::create_dir(&nested).unwrap(); + for name in ["libglfw.so.3.4", "libglfw.3.dylib", "GLFW3.DLL"] { + std::fs::write(temp.path().join(name), b"library").unwrap(); + std::fs::write(nested.join(name), b"library").unwrap(); + } + for (os, expected, version) in [ + ("linux", "libglfw.so.3.4", "3.4"), + ("macos", "libglfw.3.dylib", "3"), + ("windows", "GLFW3.DLL", "3"), + ] { + let found = discover_in(&[temp.path().to_owned(), temp.path().to_owned()], os); + assert_eq!(found.len(), 2, "{os}"); + assert!( + found + .iter() + .all(|installation| installation.path.file_name().unwrap() == expected) + ); + assert!( + found + .iter() + .all(|installation| installation.version.as_deref() == Some(version)) + ); + } + } +} diff --git a/src/instance/mod.rs b/src/instance/mod.rs index 8b73d8b..5e44a22 100644 --- a/src/instance/mod.rs +++ b/src/instance/mod.rs @@ -4,6 +4,7 @@ pub mod config_sync; pub mod content; pub mod desktop; +pub(crate) mod glfw; pub mod import; pub mod java; pub mod launch; diff --git a/src/tui/app.rs b/src/tui/app.rs index 3bce87c..8a13a47 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -54,6 +54,7 @@ pub struct App { pub(super) throbber_tick: u8, pub(super) error_effects: HashMap, pub(super) pending_editor: Option, + pub(super) edited_config_watches: Vec, pub(super) reconciliation_for: Option<(String, chrono::DateTime)>, pub(super) content_manifest: Option<(String, crate::instance::ContentManifest)>, pub(super) content_update_snapshot: @@ -129,7 +130,10 @@ impl App { crate::instance::import::refresh::recover_interrupted(&instances_dir); let manager = InstanceManager::new(instances_dir, meta_dir); - let settings_state = widgets::settings::SettingsState::new(manager.meta_dir.clone()); + let settings_state = widgets::settings::SettingsState::new( + manager.meta_dir.clone(), + manager.instances_dir.clone(), + ); let instances = manager.load_all(); instances::spawn_modpack_update_checks(&instances); let instances_state = instances::State::with_instances(instances); @@ -197,6 +201,7 @@ impl App { throbber_tick: 0, error_effects: HashMap::new(), pending_editor: None, + edited_config_watches: Vec::new(), reconciliation_for: None, content_manifest: None, content_update_snapshot: None, diff --git a/src/tui/event.rs b/src/tui/event.rs index a0245bd..b090ced 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only use color_eyre::eyre::Context; -use crossterm::event::{self, Event}; +use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers}; use ratatui::{ buffer::{Buffer, CellDiffOption}, crossterm::event::KeyEventKind, @@ -29,6 +29,7 @@ impl App { let mut image_redraw_marker = false; while !self.exit { let redraw_requested = crate::feedback::take_redraw_request(); + let edited_config_changed = self.drain_edited_configs(); if let Some(params) = new_instance::take_result() { self.spawn_create(params); } @@ -179,6 +180,7 @@ impl App { let continuously_animated = spinner_active || error_buffer::has_errors(); let safety_refresh = last_draw.elapsed() >= Duration::from_secs(1); if input_changed + || edited_config_changed || continuously_animated || safety_refresh || redraw_requested @@ -198,10 +200,8 @@ impl App { drawn_image_skips = image_skips; } - if let Some(path) = self.pending_editor.take() - && Self::run_editor(terminal, &path) - { - self.reload_edited_config(&path); + if let Some(path) = self.pending_editor.take() { + self.run_editor(terminal, &path); } } Ok(()) @@ -259,15 +259,13 @@ impl App { crate::instance::ContentManifest::update(&paths.content_manifest(), |manifest| { let mut complete = true; for toggle in toggles { - let Ok(old_path) = toggle.old_path.strip_prefix(&minecraft_dir) else { - complete = false; - continue; - }; - let Ok(new_path) = toggle.new_path.strip_prefix(&minecraft_dir) else { - complete = false; - continue; - }; - complete &= manifest.rename_record(old_path, new_path, toggle.enabled); + complete &= crate::instance::content::local::record_toggle( + manifest, + &minecraft_dir, + &toggle.old_path, + &toggle.new_path, + toggle.enabled, + )?; } Ok((manifest.clone(), complete)) }); @@ -358,16 +356,33 @@ impl App { } Err(_) => return, }; - let Some(result) = result else { + let Some(mut result) = result else { return; }; self.reconciliation_for = Some((result.instance_name.clone(), result.instance_created)); - if let Some(error) = result.error { + if let Some(error) = &result.error { tracing::warn!( "Content reconciliation for {} was incomplete: {}", result.instance_name, error ); + let path = crate::storage::InstancePaths::new( + self.instance_manager.instances_dir.join(&selected.name), + ) + .content_manifest(); + result.manifest = match crate::instance::ContentManifest::load(&path) { + Ok(manifest) => manifest, + Err(error) => { + tracing::error!("Could not reload content inventory: {error}"); + let Some((name, manifest)) = &self.content_manifest else { + return; + }; + if name != &selected.name { + return; + } + manifest.clone() + } + }; } let minecraft_dir = crate::storage::InstancePaths::new( self.instance_manager.instances_dir.join(&selected.name), @@ -551,16 +566,7 @@ impl App { fn handle_events(&mut self) -> color_eyre::Result { match crossterm::event::poll(Duration::from_millis(16)) { Ok(true) => match event::read() { - Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => { - self.handle_key_event(key_event) - .wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}"))?; - Ok(true) - } - Ok(Event::Mouse(mouse_event)) => { - self.handle_mouse_event(mouse_event); - Ok(true) - } - Ok(_) => Ok(true), + Ok(event) => self.dispatch_event(event), Err(e) => { tracing::error!("Event read error: {}", e); Ok(false) @@ -574,6 +580,155 @@ impl App { } } + pub(super) fn dispatch_event(&mut self, event: Event) -> color_eyre::Result { + match event { + Event::Key(key) + if key.kind == KeyEventKind::Press + || (key.kind == KeyEventKind::Repeat && self.key_repeat_allowed(&key)) => + { + self.handle_key_event(key) + .wrap_err_with(|| format!("handling key event failed:\n{key:#?}"))?; + Ok(true) + } + Event::Key(_) => Ok(false), + Event::Mouse(mouse) => { + self.handle_mouse_event(mouse); + Ok(true) + } + _ => Ok(true), + } + } + + fn key_repeat_allowed(&self, key: &KeyEvent) -> bool { + let vertical_navigation = matches!( + key.code, + KeyCode::Up | KeyCode::Down | KeyCode::Char('j' | 'k') + ); + // These overlays take input before the focused area underneath them. + if self + .content_update_popup + .as_ref() + .is_some_and(widgets::content::update::State::visible) + || self.modpack_update_popup.is_some() + || self.provider_conflict.is_some() + { + return vertical_navigation; + } + if let Some(state) = &self.modpack_versions_state { + return vertical_navigation || (state.text_input_active() && repeatable_text_key(key)); + } + if self.focused == FocusedArea::ConfirmDelete { + return false; + } + + let text_input_active = match self.focused { + FocusedArea::Instances => { + self.instances_state.renaming.is_some() || self.instances_state.search.active + } + FocusedArea::Popup => new_instance::text_input_active(), + FocusedArea::ImportPopup => import_modpack::text_input_active(), + FocusedArea::Account => matches!( + self.account_state.add_mode, + widgets::account::AddMode::OfflineNameInput(_) + ), + FocusedArea::Settings => matches!( + self.settings_state.add_mode, + widgets::settings::AddMode::ProfileName(_) + ), + FocusedArea::InstanceSettings => self + .instance_settings + .as_ref() + .is_some_and(widgets::popups::instance_settings::State::text_input_active), + FocusedArea::GlobalSettings => self + .global_settings + .as_ref() + .is_some_and(widgets::popups::global_settings::State::text_input_active), + FocusedArea::OverviewExpanded => self.log_overlay_search.active, + FocusedArea::Content => { + let discovery = self.active_discovery_state(); + if let Some(state) = discovery + && (self.content_mode == widgets::content::ContentMode::Discover + || state.version_popup.is_some() + || state.project_page_open() + || state.sort_panel_open) + { + state.text_input_active() + } else { + match self.content_tab { + widgets::content::ContentTab::Mods => self.mods_state.search.active, + widgets::content::ContentTab::ResourcePacks => { + self.resource_packs_state.search.active + } + widgets::content::ContentTab::Shaders => self.shaders_state.search.active, + widgets::content::ContentTab::Worlds + if self.open_world_datapacks.is_some() => + { + self.world_datapacks_state.search.active + } + widgets::content::ContentTab::Worlds => self.worlds_state.search.active, + widgets::content::ContentTab::Screenshots => { + self.screenshots_state.search.active + } + widgets::content::ContentTab::Logs if self.logs_state.viewer_focused => { + self.logs_state.viewer_search.active + } + widgets::content::ContentTab::Logs => self.logs_state.search.active, + _ => false, + } + } + } + _ => false, + }; + if text_input_active { + return repeatable_text_key(key); + } + if vertical_navigation { + return true; + } + match self.focused { + FocusedArea::OverviewExpanded => matches!(key.code, KeyCode::Char('g' | 'G')), + FocusedArea::Settings => matches!( + key.code, + KeyCode::Left | KeyCode::Right | KeyCode::Char('h' | 'l') + ), + FocusedArea::Content => { + if let Some(state) = self.active_discovery_state() { + if state.project_page_open() { + return matches!( + key.code, + KeyCode::PageUp + | KeyCode::PageDown + | KeyCode::Home + | KeyCode::End + | KeyCode::Char('g' | 'G' | 'd' | 'u') + ); + } + if state.version_popup.is_some() || state.sort_panel_open { + return false; + } + if self.content_mode == widgets::content::ContentMode::Discover + && widgets::content::discovery::page_key_direction(key).is_some() + { + return true; + } + } + if self.content_tab == widgets::content::ContentTab::Logs + && self.logs_state.viewer_focused + && matches!(key.code, KeyCode::Char('g' | 'G')) + { + return true; + } + matches!( + key.code, + KeyCode::Left | KeyCode::Right | KeyCode::Char('h' | 'l') + ) || (self.content_tab == widgets::content::ContentTab::Screenshots + && key.modifiers.contains(KeyModifiers::SHIFT) + && matches!(key.code, KeyCode::Char('H' | 'J' | 'K' | 'L'))) + } + _ => false, + } + } + fn spawn_create(&self, params: new_instance::WizardParams) { let instances_dir = self.instance_manager.instances_dir.clone(); let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); @@ -693,10 +848,8 @@ impl App { }); } - // spawns $EDITOR/$VISUAL to edit a file. for terminal editors (vim, nano, etc) - // gotta leave the alternate screen and restore it after, otherwise the - // editor fights with ratatui for the terminal. GUI editors just get spawned detached. - fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) -> bool { + // Terminal editors need the normal screen and input mode while they run. + fn run_editor(&mut self, terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) { use ratatui::crossterm::{ ExecutableCommand, event::{DisableMouseCapture, EnableMouseCapture}, @@ -710,15 +863,28 @@ impl App { let editor = std::env::var("EDITOR") .or_else(|_| std::env::var("VISUAL")) .unwrap_or_else(|_| default_editor.to_owned()); - let parts = editor_parts(&editor); + let parts = match editor_parts(&editor) { + Ok(parts) => parts, + Err(error) => { + tracing::error!("Cannot parse editor command: {error}"); + return; + } + }; let Some((program, args)) = parts.split_first() else { tracing::error!("Editor command is empty"); - return false; + return; }; let is_tui_editor = editor_runs_in_terminal(program); if is_tui_editor { + if let Err(error) = self.watch_edited_config(path) { + error_buffer::push_message( + tracing::Level::ERROR, + format!("Cannot watch edited file {}: {error}", path.display()), + ); + return; + } let _ = stdout().execute(DisableMouseCapture); let _ = stdout().execute(LeaveAlternateScreen); let _ = disable_raw_mode(); @@ -738,24 +904,62 @@ impl App { if let Err(e) = result { tracing::error!("Failed to open editor: {}", e); - return false; } - true } else { - if let Err(e) = std::process::Command::new(program) - .args(args) - .arg(path) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - { + if let Err(e) = self.launch_gui_editor( + std::process::Command::new(program).args(args).arg(path), + path, + ) { tracing::error!("Failed to open editor: {}", e); - return false; } - false } } + fn watch_edited_config(&mut self, path: &std::path::Path) -> color_eyre::Result<()> { + let path = std::path::absolute(path)?; + if !self + .edited_config_watches + .iter() + .any(|watch| watch.path == path) + { + self.edited_config_watches + .push(EditedConfigWatch::new(path)?); + } + Ok(()) + } + + fn launch_gui_editor( + &mut self, + command: &mut std::process::Command, + path: &std::path::Path, + ) -> color_eyre::Result> { + self.watch_edited_config(path)?; + let mut child = command + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn()?; + // A GUI launcher can exit after handing the file to an existing editor. + // Reap it without tying the file watch or Tokio shutdown to its lifetime. + Ok(std::thread::spawn(move || match child.wait() { + Ok(status) if !status.success() => tracing::warn!("Editor exited with {status}"), + Err(error) => tracing::error!("Failed to wait for editor: {error}"), + _ => {} + })) + } + + fn drain_edited_configs(&mut self) -> bool { + let changed = self + .edited_config_watches + .iter_mut() + .filter_map(|watch| watch.changed().then(|| watch.path.clone())) + .collect::>(); + for path in &changed { + self.reload_edited_config(path); + } + !changed.is_empty() + } + fn reload_edited_config(&mut self, path: &std::path::Path) { match path.file_name().and_then(|name| name.to_str()) { Some("config.toml") => { @@ -1021,6 +1225,120 @@ impl App { } } +pub(super) struct EditedConfigWatch { + path: std::path::PathBuf, + contents: Option>, + events: std::sync::mpsc::Receiver>, + pending: Option, + read_error: Option, + _watcher: notify::RecommendedWatcher, +} + +impl EditedConfigWatch { + fn new(path: std::path::PathBuf) -> color_eyre::Result { + use notify::Watcher; + + let (tx, events) = std::sync::mpsc::channel(); + let mut watcher = notify::recommended_watcher(move |event| { + let _ = tx.send(event); + })?; + let parent = path + .parent() + .ok_or_else(|| color_eyre::eyre::eyre!("File has no parent directory"))?; + watcher.watch(parent, notify::RecursiveMode::NonRecursive)?; + let contents = match std::fs::read(&path) { + Ok(contents) => Some(contents), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(error.into()), + }; + Ok(Self { + path, + contents, + events, + pending: None, + read_error: None, + _watcher: watcher, + }) + } + + fn changed(&mut self) -> bool { + for result in self.events.try_iter() { + match result { + Ok(event) + if matches!(event.kind, notify::EventKind::Access(_)) + && !matches!( + event.kind, + notify::EventKind::Access(notify::event::AccessKind::Close( + notify::event::AccessMode::Write + )) + ) => {} + Ok(event) + if event.need_rescan() + || event.paths.is_empty() + || event.paths.iter().any(|path| { + path.file_name().zip(self.path.file_name()).is_some_and( + |(changed, watched)| changed.eq_ignore_ascii_case(watched), + ) || Some(path.as_path()) == self.path.parent() + }) => + { + self.pending = Some(std::time::Instant::now()); + } + Ok(_) => {} + Err(error) => { + tracing::error!( + "Edited file watch for {} failed: {error}", + self.path.display() + ); + self.pending = Some(std::time::Instant::now()); + } + } + } + if self + .pending + .is_none_or(|pending| pending.elapsed() < Duration::from_millis(100)) + { + return false; + } + let contents = match std::fs::read(&self.path) { + Ok(contents) => contents, + Err(error) => { + if error.kind() != std::io::ErrorKind::NotFound + && self.read_error != Some(error.kind()) + { + tracing::warn!("Cannot read edited file {}: {error}", self.path.display()); + } + self.read_error = Some(error.kind()); + self.pending = Some(std::time::Instant::now()); + return false; + } + }; + self.pending = None; + self.read_error = None; + if self.contents.as_ref() == Some(&contents) { + return false; + } + self.contents = Some(contents); + true + } +} + +fn repeatable_text_key(key: &KeyEvent) -> bool { + matches!( + key.code, + KeyCode::Char(_) + | KeyCode::Backspace + | KeyCode::Delete + | KeyCode::Left + | KeyCode::Right + | KeyCode::Up + | KeyCode::Down + | KeyCode::Home + | KeyCode::End + | KeyCode::PageUp + | KeyCode::PageDown + ) +} + async fn apply_instance_settings_update( manager: &InstanceManager, previous: &crate::instance::InstanceConfig, @@ -1123,14 +1441,64 @@ fn editor_runs_in_terminal(editor: &str) -> bool { ) } -fn editor_parts(editor: &str) -> Vec<&str> { +fn editor_parts(editor: &str) -> std::io::Result> { if std::path::Path::new(editor).is_file() { - vec![editor] + Ok(vec![editor.to_owned()]) } else { - editor.split_whitespace().collect() + split_editor_command(editor) } } +#[cfg(unix)] +fn split_editor_command(editor: &str) -> std::io::Result> { + shlex::split(editor).ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "Unterminated editor quote or escape", + ) + }) +} + +#[cfg(windows)] +fn split_editor_command(editor: &str) -> std::io::Result> { + use windows_sys::Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW}; + if editor.trim().is_empty() { + return Ok(Vec::new()); + } + if editor.contains('\0') { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "Editor command contains a NUL", + )); + } + let command = editor + .trim() + .encode_utf16() + .chain(Some(0)) + .collect::>(); + let mut count = 0; + // The OS allocates the complete argument array; it remains valid until LocalFree below. + let args = unsafe { CommandLineToArgvW(command.as_ptr(), &mut count) }; + if args.is_null() { + return Err(std::io::Error::last_os_error()); + } + let mut parts = Vec::new(); + for index in 0..count as usize { + let arg = unsafe { *args.add(index) }; + let mut length = 0; + while unsafe { *arg.add(length) } != 0 { + length += 1; + } + parts.push(String::from_utf16_lossy(unsafe { + std::slice::from_raw_parts(arg, length) + })); + } + unsafe { + LocalFree(args.cast()); + } + Ok(parts) +} + #[cfg(test)] #[path = "tests/event.rs"] mod tests; diff --git a/src/tui/input.rs b/src/tui/input.rs index f8edec5..0c7380e 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -50,10 +50,11 @@ impl App { let link = self .active_discovery_state_mut() .and_then(|state| state.project_link_at(event.column, event.row)); - if let Some(link) = link - && let Err(error) = open::that_detached(link) - { - tracing::warn!("Failed to open project link {link}: {error}"); + if let Some(link) = link { + let result = project_link_url(link).and_then(|url| open::that_detached(url.as_str())); + if let Err(error) = result { + tracing::warn!("Failed to open project link: {error}"); + } } } @@ -105,14 +106,29 @@ impl App { .map(|(_, candidate)| candidate.clone()) .collect::>(); if let Some(project) = project - && let Some((instance_name, _)) = &self.content_manifest + && let Some((instance_name, cached)) = &self.content_manifest { - let manifest_path = crate::storage::InstancePaths::new( + let paths = crate::storage::InstancePaths::new( self.instance_manager.instances_dir.join(instance_name), - ) - .content_manifest(); - let updated = - crate::instance::ContentManifest::update(&manifest_path, |manifest| { + ); + let manifest_path = paths.content_manifest(); + let expected = cached.record(&relative_path).cloned(); + let updated = crate::instance::ContentManifest::update( + &manifest_path, + |manifest| { + if expected.is_none() + || manifest.record(&relative_path) != expected.as_ref() + { + return Err(crate::instance::content::manifest::ManifestError::InvalidPath( + format!("Ownership of '{}' changed; refresh before selecting a provider", relative_path.display()), + )); + } + if let Some(record) = &expected { + crate::instance::content::local::validate_record( + &paths.minecraft(), + record, + )?; + } if let Some(record) = manifest .files .iter_mut() @@ -123,10 +139,18 @@ impl App { record.provider_aliases = aliases; } Ok(manifest.clone()) - })?; - self.content_manifest = Some((instance_name.clone(), updated)); - self.provider_conflict = None; - self.reconciliation_for = None; + }, + ); + match updated { + Ok(updated) => { + self.content_manifest = Some((instance_name.clone(), updated)); + self.provider_conflict = None; + self.reconciliation_for = None; + } + Err(error) => { + tracing::error!("Could not save provider selection: {error}") + } + } } } KeyCode::Esc => { @@ -270,11 +294,9 @@ impl App { FocusedArea::Settings } Some(confirm_popup::ConfirmTarget::Content { name, path, .. }) => { - let orphaned = self.orphan_dependencies_after_removing(&path); - match delete_content_path(&path) { - Ok(()) => { + match self.delete_content_path(&path, false) { + Ok(orphaned) => { self.remove_content_path_from_states(&path); - self.remove_content_path_from_manifest(&path); if !orphaned.is_empty() { confirm_popup::set_pending_orphan_dependencies(orphaned); return Ok(()); @@ -288,10 +310,9 @@ impl App { } Some(confirm_popup::ConfirmTarget::OrphanDependencies { paths }) => { for path in paths { - match delete_content_path(&path) { - Ok(()) => { + match self.delete_content_path(&path, true) { + Ok(_) => { self.remove_content_path_from_states(&path); - self.remove_content_path_from_manifest(&path); } Err(error) => tracing::error!( "Failed to remove unused dependency '{}': {}", @@ -534,16 +555,8 @@ impl App { if let Some(state) = self.active_discovery_state_mut() { state.begin_world_selection(worlds); } - } else if matches!( - kind, - Some( - crate::instance::ContentKind::Mod - | crate::instance::ContentKind::DataPack - ) - ) { + } else { self.spawn_active_discovery_dependencies(); - } else if let Some(state) = self.active_discovery_state_mut() { - state.begin_confirmation(); } } return Ok(()); @@ -632,7 +645,10 @@ impl App { } return Ok(()); } - if key_event.code == KeyCode::Enter && !self.worlds_state.search.active { + if key_event.code == KeyCode::Enter + && !key_event.modifiers.contains(KeyModifiers::SHIFT) + && !self.worlds_state.search.active + { self.open_world_datapacks = self .worlds_state .selected_entry() @@ -1422,7 +1438,9 @@ impl App { } } - fn active_discovery_state(&self) -> Option<&widgets::content::discovery::DiscoveryState> { + pub(super) fn active_discovery_state( + &self, + ) -> Option<&widgets::content::discovery::DiscoveryState> { match self.content_tab { widgets::content::ContentTab::Mods => Some(&self.mods_discovery_state), widgets::content::ContentTab::ResourcePacks => { @@ -1917,96 +1935,25 @@ impl App { "Invalid datapack target world".to_owned(), )); } - tokio::fs::create_dir_all(&destination) - .await - .map_err(crate::net::NetError::from)?; let registry = crate::instance::content::provider::ProviderRegistry::configured(client); - if let Some(plan) = &request.dependency_plan { - let installed = crate::instance::content::dependencies::install( - ®istry, - &manifest_path, - &minecraft_dir, - plan, + let plan = request.dependency_plan.as_ref().ok_or_else(|| { + crate::net::NetError::Parse( + "Installation has no resolved dependency plan".to_owned(), ) - .await?; - return Ok::<_, crate::net::NetError>( - widgets::content::discovery::InstallCompletion { - path: installed.root_path, - replaced: installed.replaced, - skipped: installed.skipped, - orphaned_dependencies: installed.orphaned_dependencies, - }, - ); - } - let provider = registry.get(&request.provider).ok_or_else(|| { - crate::net::NetError::Parse(format!( - "{} content provider is unavailable", - request.provider - )) })?; - let outcome = provider - .download_version( - &request.version, - &destination, - request.installed_path.as_deref(), - ) - .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 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)?; - let record = crate::instance::ContentFileRecord { - relative_path, - 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: request.provider.clone(), - project_id: request.project_id.clone(), - version_id: request.version.id.clone(), - }, - }, - provider_aliases: Vec::new(), - provider_checks: vec![request.provider.clone()], - required_dependencies: Vec::new(), - automatic_dependency: false, - cleanup_eligible: false, - }; - crate::instance::ContentManifest::update(&manifest_path, |manifest| { - 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); - } - manifest.upsert(record); - Ok(()) - }) - .map_err(|error| crate::net::NetError::Parse(error.to_string()))?; - if !skipped - && let Some(old_path) = request - .installed_path - .as_ref() - .filter(|old_path| old_path.as_path() != path.as_path()) - { - delete_content_path(old_path).map_err(crate::net::NetError::from)?; - } + let installed = crate::instance::content::dependencies::install( + ®istry, + &manifest_path, + &minecraft_dir, + plan, + ) + .await?; Ok::<_, crate::net::NetError>(widgets::content::discovery::InstallCompletion { - path, - replaced, - skipped, - orphaned_dependencies: Vec::new(), + path: installed.root_path, + replaced: installed.replaced, + skipped: installed.skipped, + orphaned_dependencies: installed.orphaned_dependencies, }) } .await @@ -2184,19 +2131,44 @@ impl App { self.focused = FocusedArea::ConfirmDelete; } - fn orphan_dependencies_after_removing( - &self, + fn delete_content_path( + &mut self, path: &std::path::Path, - ) -> Vec { - self.content_manifest_for_path(path) - .map(|(manifest, relative_path, minecraft_dir)| { - manifest - .orphaned_dependencies_after_removing(&relative_path) - .into_iter() - .map(|relative| minecraft_dir.join(relative)) - .collect() - }) - .unwrap_or_default() + orphan_only: bool, + ) -> std::io::Result> { + let instance = self + .instances_state + .selected_instance() + .ok_or_else(|| std::io::Error::other("No instance is selected"))?; + let name = instance.name.clone(); + let paths = + crate::storage::InstancePaths::new(self.instance_manager.instances_dir.join(&name)); + let minecraft_dir = paths.minecraft(); + let relative = crate::instance::content::local::relative_path(&minecraft_dir, path)?; + let manifest = match self + .content_manifest + .as_ref() + .filter(|(cached_name, _)| cached_name == &name) + { + Some((_, manifest)) => manifest.clone(), + None => crate::instance::ContentManifest::load(&paths.content_manifest()) + .map_err(std::io::Error::other)?, + }; + let expected = manifest + .files + .iter() + .filter(|record| record.relative_path.starts_with(&relative)) + .cloned() + .collect::>(); + let (manifest, orphaned) = crate::instance::content::local::remove( + &paths.content_manifest(), + &minecraft_dir, + path, + &expected, + orphan_only, + )?; + self.content_manifest = Some((name, manifest)); + Ok(orphaned) } fn content_manifest_for_path( @@ -2246,37 +2218,6 @@ impl App { } } - fn remove_content_path_from_manifest(&mut self, path: &std::path::Path) { - let Some(instance) = self.instances_state.selected_instance() else { - return; - }; - let instance_paths = crate::storage::InstancePaths::new( - self.instance_manager.instances_dir.join(&instance.name), - ); - let minecraft_dir = instance_paths.minecraft(); - let Ok(relative_path) = path.strip_prefix(&minecraft_dir) else { - return; - }; - if let Some((instance_name, manifest)) = self.content_manifest.as_mut() - && *instance_name == instance.name - { - manifest.remove(relative_path); - } - if let Err(error) = crate::instance::ContentManifest::update( - &instance_paths.content_manifest(), - |manifest| { - manifest.remove(relative_path); - Ok(()) - }, - ) { - tracing::warn!( - "Failed to remove '{}' from the content manifest: {}", - relative_path.display(), - error - ); - } - } - fn open_instance_settings(&mut self, return_focus: FocusedArea) { let Some(instance) = self.instances_state.selected_instance().cloned() else { return; @@ -2284,6 +2225,10 @@ impl App { let mut state = widgets::popups::instance_settings::State::with_accounts( &instance, &self.instance_manager.meta_dir, + &crate::storage::InstancePaths::new( + self.instance_manager.instances_dir.join(&instance.name), + ) + .minecraft(), self.account_state.store.accounts.clone(), ); if self @@ -2440,11 +2385,14 @@ impl App { } } -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), - Ok(_) => std::fs::remove_file(path), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(e) => Err(e), +pub(super) fn project_link_url(link: &str) -> std::io::Result { + let url = reqwest::Url::parse(link) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?; + if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "Project links must use HTTP or HTTPS", + )); } + Ok(url) } diff --git a/src/tui/logging.rs b/src/tui/logging.rs index ad783f3..31eac30 100644 --- a/src/tui/logging.rs +++ b/src/tui/logging.rs @@ -15,7 +15,7 @@ use tracing_subscriber::{EnvFilter, Layer}; use std::sync::LazyLock; -use crate::feedback::errors::{self as error_buffer, ErrorEvent}; +use crate::feedback::errors as error_buffer; const MINECRAFT_LOG_TARGET: &str = "mc_instance"; const DEFAULT_FILE_FILTER: &str = "warn,rmcl=trace"; @@ -79,11 +79,9 @@ pub fn init() -> WorkerGuard { should_record_app_log(metadata.target(), *metadata.level()) })), ) - .with( - StatusLayer::new(error_buffer::ERROR_EVENTS.clone()).with_filter(filter_fn( - |metadata| should_record_app_log(metadata.target(), *metadata.level()), - )), - ) + .with(StatusLayer.with_filter(filter_fn(|metadata| { + should_record_app_log(metadata.target(), *metadata.level()) + }))) .init(); guard @@ -113,12 +111,6 @@ fn open_log_writer(log_dir: &Path) -> (NonBlocking, WorkerGuard) { struct StatusLayer; -impl StatusLayer { - fn new(_events: Arc>>) -> Self { - Self - } -} - impl Layer for StatusLayer { fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) { let level = *event.metadata().level(); @@ -140,12 +132,7 @@ impl Layer for StatusLayer { } if level <= Level::WARN && should_record_app_log(target, level) { - error_buffer::push_error(ErrorEvent { - id: 0, - level, - message: visitor.message, - pushed_at: std::time::Instant::now(), - }); + error_buffer::push_message(level, visitor.message); } } } diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index cd0e76b..56c0e3c 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -4,6 +4,555 @@ use super::*; use crate::tui::tests::harness::UiHarness; +fn key_kind(code: KeyCode, kind: KeyEventKind) -> KeyEvent { + KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind) +} + +#[test] +fn dispatch_repeats_navigation_but_not_launch_delete_or_confirmation() { + let mut ui = UiHarness::new(); + for name in ["First", "Second", "Third"] { + ui.add_instance(name); + } + ui.app.instances_state.list_state.selected = Some(0); + ui.draw(); + + assert!(ui.key_event(key_kind(KeyCode::Down, KeyEventKind::Press))); + assert_eq!(ui.app.instances_state.list_state.selected, Some(1)); + assert!(ui.key_event(key_kind(KeyCode::Down, KeyEventKind::Repeat))); + assert_eq!(ui.app.instances_state.list_state.selected, Some(2)); + assert!(!ui.key_event(key_kind(KeyCode::Up, KeyEventKind::Release))); + assert_eq!(ui.app.instances_state.list_state.selected, Some(2)); + + for code in [ + KeyCode::Char('l'), + KeyCode::Char('d'), + KeyCode::Char('u'), + KeyCode::Enter, + ] { + assert!(!ui.key_event(key_kind(code, KeyEventKind::Repeat))); + } + assert_eq!(ui.app.focused, FocusedArea::Instances); + assert!(crate::instance::runtime::get("Third").is_none()); + assert!(widgets::popups::confirm::pending_target().is_none()); + + ui.key(KeyCode::Char('d')); + assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete); + // A search behind the confirmation cannot turn its 'y' into repeatable text. + ui.app.instances_state.search.active = true; + for kind in [KeyEventKind::Repeat, KeyEventKind::Release] { + for code in [KeyCode::Enter, KeyCode::Char('y'), KeyCode::Char('n')] { + assert!(!ui.key_event(key_kind(code, kind))); + } + } + assert!(ui.instance_path("Third").exists()); + assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete); + ui.app.instances_state.search.active = false; + ui.key(KeyCode::Char('y')); + assert!(!ui.instance_path("Third").exists()); + assert!(!ui.key_event(key_kind(KeyCode::Char('y'), KeyEventKind::Repeat))); + assert_eq!(ui.app.instances_state.instances.len(), 2); +} + +#[test] +fn dispatch_repeats_text_and_backspace_in_search_rename_account_and_profile_inputs() { + let mut ui = UiHarness::new(); + ui.add_instance("Text Fields"); + + ui.app.instances_state.search.activate(); + ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Press)); + ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat)); + assert!(!ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Release))); + assert_eq!(ui.app.instances_state.search.query, "dd"); + assert!(ui.key_event(key_kind(KeyCode::Backspace, KeyEventKind::Repeat))); + assert_eq!(ui.app.instances_state.search.query, "d"); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(ui.app.instances_state.search.active); + ui.app.instances_state.search.deactivate(); + + ui.app.instances_state.renaming = Some(String::new()); + assert!(ui.key_event(key_kind(KeyCode::Char('l'), KeyEventKind::Repeat))); + assert_eq!(ui.app.instances_state.renaming.as_deref(), Some("l")); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(ui.instance_path("Text Fields").exists()); + ui.app.instances_state.renaming = None; + + ui.app.focused = FocusedArea::Account; + ui.app.account_state.add_mode = widgets::account::AddMode::OfflineNameInput(String::new()); + assert!(ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat))); + assert!( + matches!(&ui.app.account_state.add_mode, widgets::account::AddMode::OfflineNameInput(name) if name == "d") + ); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert_eq!(ui.app.focused, FocusedArea::Account); + + ui.app.focused = FocusedArea::Settings; + ui.app.settings_state.add_mode = widgets::settings::AddMode::ProfileName(String::new()); + assert!(ui.key_event(key_kind(KeyCode::Char('q'), KeyEventKind::Repeat))); + assert!( + matches!(&ui.app.settings_state.add_mode, widgets::settings::AddMode::ProfileName(name) if name == "q") + ); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(!ui.app.exit); +} + +#[test] +fn dispatch_does_not_repeat_content_toggles_or_install_confirmation() { + let mut ui = UiHarness::new(); + ui.add_instance("One Shot Content"); + let path = ui + .instance_path("One Shot Content") + .join(crate::storage::MINECRAFT_DIR_NAME) + .join("mods/test.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"mod").unwrap(); + ui.app.focused = FocusedArea::Content; + ui.app + .mods_state + .set_entries(vec![crate::instance::content::entry::ContentEntry { + file_stem: "test".to_owned(), + name: "Test Mod".to_owned(), + source_slug: None, + installed_path: None, + provider_project: None, + world_details: None, + title_suffix: None, + footer_label: None, + footer_change: None, + description: String::new(), + enabled: true, + icon_bytes: None, + provider_icon: false, + provider_description: false, + path: path.clone(), + icon_lines: None, + }]); + ui.app.mods_state.list_state.selected = Some(0); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(path.exists()); + ui.key(KeyCode::Enter); + assert!(!path.exists()); + assert!(path.with_extension("jar.disabled").exists()); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(!path.exists()); + + ui.app + .mods_discovery_state + .begin_managed_modpack_versions( + "Install", + crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "test".to_owned(), + version_id: "installed".to_owned(), + }, + ) + .unwrap(); + let popup = ui.app.mods_discovery_state.version_popup.as_mut().unwrap(); + popup.loading = false; + popup.confirming = true; + ui.app.mods_discovery_state.search.activate(); + for code in [KeyCode::Enter, KeyCode::Char('s'), KeyCode::Tab] { + assert!(!ui.key_event(key_kind(code, KeyEventKind::Repeat))); + } + let popup = ui.app.mods_discovery_state.version_popup.as_ref().unwrap(); + assert!(!popup.installing); + assert!(!popup.skip_dependencies); + + let popup = ui.app.mods_discovery_state.version_popup.as_mut().unwrap(); + popup.confirming = false; + popup.selecting_world = true; + popup.worlds.search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat))); + assert_eq!( + ui.app + .mods_discovery_state + .version_popup + .as_ref() + .unwrap() + .worlds + .search + .query, + "d" + ); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); +} + +#[test] +fn dispatch_repeats_only_the_visible_content_search() { + use widgets::content::{ContentMode, ContentTab}; + + let mut ui = UiHarness::new(); + ui.app.focused = FocusedArea::Content; + for tab in [ + ContentTab::Mods, + ContentTab::ResourcePacks, + ContentTab::Shaders, + ContentTab::Worlds, + ContentTab::Screenshots, + ContentTab::Logs, + ] { + ui.app.content_tab = tab; + ui.key(KeyCode::Char('/')); + assert!( + ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat)), + "{tab:?}" + ); + let query = match tab { + ContentTab::Mods => &ui.app.mods_state.search.query, + ContentTab::ResourcePacks => &ui.app.resource_packs_state.search.query, + ContentTab::Shaders => &ui.app.shaders_state.search.query, + ContentTab::Worlds => &ui.app.worlds_state.search.query, + ContentTab::Screenshots => &ui.app.screenshots_state.search.query, + ContentTab::Logs => &ui.app.logs_state.search.query, + _ => unreachable!(), + }; + assert_eq!(query, "d"); + assert!(!ui.key_event(key_kind(KeyCode::Tab, KeyEventKind::Repeat))); + ui.key(KeyCode::Esc); + } + ui.app.content_tab = ContentTab::Worlds; + ui.app.open_world_datapacks = Some(("World".to_owned(), std::path::PathBuf::from("World"))); + ui.app.world_datapacks_state.search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('u'), KeyEventKind::Repeat))); + assert_eq!(ui.app.world_datapacks_state.search.query, "u"); + ui.app.open_world_datapacks = None; + + ui.app.content_tab = ContentTab::Logs; + ui.app.logs_state.viewer_focused = true; + ui.app.logs_state.viewer_search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('G'), KeyEventKind::Repeat))); + assert_eq!(ui.app.logs_state.viewer_search.query, "G"); + + ui.app.content_tab = ContentTab::Mods; + ui.app.content_mode = ContentMode::Discover; + ui.app.mods_discovery_state.search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('v'), KeyEventKind::Repeat))); + assert_eq!(ui.app.mods_discovery_state.search.query, "v"); + assert!(ui.app.mods_discovery_state.version_popup.is_none()); + ui.app.mods_discovery_state.search.deactivate(); + ui.app.mods_discovery_state.sort_panel_open = true; + ui.app.mods_discovery_state.sort_panel_focused = true; + ui.app.mods_discovery_state.filter_version_picker_open = true; + ui.app.mods_discovery_state.filter_version_search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('s'), KeyEventKind::Repeat))); + assert_eq!(ui.app.mods_discovery_state.filter_version_search.query, "s"); + assert!(!ui.app.mods_discovery_state.filter_show_snapshots); +} + +#[test] +fn dispatch_repeats_instance_setting_text_but_not_picker_selection_or_toggles() { + let mut ui = UiHarness::new(); + ui.add_instance("Settings Text"); + ui.key(KeyCode::Char('E')); + for _ in 0..4 { + ui.key_event(key_kind(KeyCode::Down, KeyEventKind::Repeat)); + } + ui.key(KeyCode::Char('c')); + assert!( + ui.app + .instance_settings + .as_ref() + .unwrap() + .text_input_active() + ); + ui.key(KeyCode::Char('d')); + assert!(ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Release))); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + ui.key(KeyCode::Enter); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .java_path + .as_deref(), + Some("dd") + ); + assert!(!ui.key_event(key_kind(KeyCode::Right, KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Char('a'), KeyEventKind::Repeat))); + + ui.key(KeyCode::Esc); + ui.key(KeyCode::Char('E')); + ui.key(KeyCode::Down); + ui.key(KeyCode::Enter); + let loader = ui.app.instance_settings.as_ref().unwrap().draft.loader; + assert!(!ui.key_event(key_kind(KeyCode::Right, KeyEventKind::Repeat))); + assert_eq!( + ui.app.instance_settings.as_ref().unwrap().draft.loader, + loader + ); +} + +#[test] +fn dispatch_repeats_wizard_name_import_input_and_discovery_search() { + let mut ui = UiHarness::new(); + ui.key(KeyCode::Char('a')); + ui.key(KeyCode::Char('q')); + assert!(ui.key_event(key_kind(KeyCode::Char('q'), KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Char('q'), KeyEventKind::Release))); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + ui.draw(); + assert!(ui.screen().contains("qq")); + assert!(!ui.app.exit); + ui.key(KeyCode::Esc); + + ui.key(KeyCode::Char('m')); + ui.key(KeyCode::Char('i')); + ui.key(KeyCode::Char('q')); + assert!(ui.key_event(key_kind(KeyCode::Char('q'), KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + ui.draw(); + assert!(ui.screen().contains("qq")); + ui.key(KeyCode::Esc); + ui.key(KeyCode::Char('/')); + assert!(ui.key_event(key_kind(KeyCode::Char('v'), KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + ui.draw(); + assert!(ui.screen().contains("/ v")); +} + +#[test] +fn gui_editor_handoff_process() {} + +#[test] +fn unrelated_directory_events_do_not_postpone_an_edited_file_save() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("instance.json"); + std::fs::write(&path, b"old").unwrap(); + let mut watch = EditedConfigWatch::new(path.clone()).unwrap(); + let (sender, events) = std::sync::mpsc::channel(); + watch.events = events; + watch.pending = Some(std::time::Instant::now() - Duration::from_secs(1)); + std::fs::write(path, b"new").unwrap(); + sender + .send(Ok(notify::Event::new(notify::EventKind::Modify( + notify::event::ModifyKind::Any, + )) + .add_path(temp.path().join("other.json")))) + .unwrap(); + assert!(watch.changed()); + std::fs::write(temp.path().join("instance.json"), b"changed again").unwrap(); + sender + .send(Ok(notify::Event::new(notify::EventKind::Modify( + notify::event::ModifyKind::Any, + )) + .add_path(temp.path().join("INSTANCE.JSON")))) + .unwrap(); + assert!(!watch.changed()); + assert!(watch.pending.is_some()); + watch.pending = Some(std::time::Instant::now() - Duration::from_secs(1)); + assert!(watch.changed()); +} + +fn wait_for_edited_config(ui: &mut UiHarness, changed: bool) { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + let mut observed = false; + loop { + let reloaded = ui.app.drain_edited_configs(); + observed |= ui + .app + .edited_config_watches + .iter() + .any(|watch| watch.pending.is_some()); + if changed && reloaded { + return; + } + assert!(!reloaded, "unchanged bytes must not reload"); + if !changed + && observed + && ui + .app + .edited_config_watches + .iter() + .all(|watch| watch.pending.is_none()) + { + return; + } + assert!( + std::time::Instant::now() < deadline, + "edited file notification timed out" + ); + std::thread::sleep(Duration::from_millis(20)); + } +} + +#[test] +fn gui_editor_saves_reload_after_handoff_and_atomic_replacement_only_when_bytes_change() { + let mut ui = UiHarness::new(); + ui.add_instance("GUI Edited"); + let path = ui.instance_path("GUI Edited").join("instance.json"); + let mut config = ui.app.instances_state.selected_instance().unwrap().clone(); + config.memory_max = Some("4G".to_owned()); + ui.app.instance_manager.save(&config).unwrap(); + let original = std::fs::read(&path).unwrap(); + + let reaper = ui + .app + .launch_gui_editor( + std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "tui::event::tests::gui_editor_handoff_process"]), + &path, + ) + .unwrap(); + assert!(!ui.app.drain_edited_configs()); + reaper.join().unwrap(); + assert!(!ui.app.drain_edited_configs()); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max, + None + ); + ui.app.watch_edited_config(&path).unwrap(); + assert_eq!(ui.app.edited_config_watches.len(), 1); + + std::fs::write(&path, &original).unwrap(); + wait_for_edited_config(&mut ui, false); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max, + None + ); + + config.memory_max = Some("8G".to_owned()); + std::fs::write(&path, serde_json::to_vec(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("8G") + ); + + config.memory_max = Some("12G".to_owned()); + crate::storage::write_atomic(&path, &serde_json::to_vec(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("12G") + ); + + config.memory_max = Some("16G".to_owned()); + std::fs::write(&path, serde_json::to_vec(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("16G") + ); + + std::fs::write(&path, b"invalid instance config").unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("16G") + ); + assert!( + error_buffer::peek_error() + .unwrap() + .message + .contains("Failed to reload edited instance") + ); + config.memory_max = Some("20G".to_owned()); + crate::storage::write_atomic(&path, &serde_json::to_vec(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("20G") + ); +} + +#[cfg(unix)] +#[test] +fn launcher_config_save_process() { + if std::env::var_os("RMCL_EDITOR_CONFIG_TEST").is_none() { + return; + } + let mut ui = UiHarness::new(); + let config_path = crate::config::get_config_path().join("config.toml"); + let theme_path = crate::config::get_config_path().join("theme.toml"); + let mut theme = crate::config::theme::ThemeConfig::default(); + std::fs::write(&theme_path, toml::to_string(&theme).unwrap()).unwrap(); + ui.app.watch_edited_config(&config_path).unwrap(); + ui.app.watch_edited_config(&theme_path).unwrap(); + assert!(!ui.app.drain_edited_configs()); + + let mut config = crate::config::SETTINGS.read().clone(); + config.ui.error_auto_dismiss_ms += 1; + let timeout = config.ui.error_auto_dismiss_ms; + std::fs::write(&config_path, toml::to_string(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + crate::config::SETTINGS.read().ui.error_auto_dismiss_ms, + timeout + ); + + theme.theme = "dracula".to_owned(); + theme.border_style = crate::config::theme::BorderStyle::Thick; + crate::storage::write_atomic(&theme_path, toml::to_string(&theme).unwrap().as_bytes()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + crate::config::theme::current_theme_config().theme, + "dracula" + ); + assert_eq!( + crate::config::theme::BORDER_STYLE.current(), + crate::config::theme::BorderStyle::Thick + ); +} + +#[cfg(unix)] +#[test] +fn watched_launcher_config_and_theme_saves_update_cached_settings() { + let ui = UiHarness::new(); + let root = ui.app.instance_manager.instances_dir.parent().unwrap(); + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "tui::event::tests::launcher_config_save_process", + "--nocapture", + ]) + .env("RMCL_EDITOR_CONFIG_TEST", "1") + .env("HOME", root) + .env("XDG_CONFIG_HOME", root) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); +} + #[test] fn edited_instance_config_reloads_into_the_ui() { let mut ui = UiHarness::new(); @@ -363,7 +912,37 @@ fn editor_kind_is_detected_from_the_executable_name() { assert!(editor_runs_in_terminal("/usr/bin/nvim")); assert!(editor_runs_in_terminal("nano")); assert!(!editor_runs_in_terminal("/usr/bin/code")); - assert_eq!(editor_parts("nvim -u NONE"), ["nvim", "-u", "NONE"]); + assert_eq!( + editor_parts("nvim -u NONE").unwrap(), + ["nvim", "-u", "NONE"] + ); +} + +#[test] +fn editor_commands_preserve_quoted_paths_arguments_and_empty_arguments() { + assert_eq!( + editor_parts(r#""/path with spaces/editor" --wait "two words" """#).unwrap(), + ["/path with spaces/editor", "--wait", "two words", ""] + ); + let temp = tempfile::tempdir().unwrap(); + let executable = temp.path().join("editor with spaces"); + std::fs::write(&executable, b"executable").unwrap(); + assert_eq!( + editor_parts(executable.to_str().unwrap()).unwrap(), + [executable.to_string_lossy().into_owned()] + ); + #[cfg(unix)] + assert!(editor_parts("editor 'unterminated").is_err()); + #[cfg(windows)] + assert_eq!( + editor_parts(r#""C:\Program Files\editor.exe" --wait "C:\folder with spaces\file.txt""#) + .unwrap(), + [ + r"C:\Program Files\editor.exe", + "--wait", + r"C:\folder with spaces\file.txt" + ] + ); } #[test] diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index b524704..61949c1 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use super::harness::UiHarness; use crate::instance::content::entry::ContentEntry; use crate::instance::{ - ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution, + ContentFileRecord, ContentKind, ContentManifest, ProviderProject, Resolution, }; use crate::net::modrinth::DiscoveryProject; use crate::tui::{ @@ -18,6 +18,22 @@ use crate::tui::{ }, }; +#[test] +fn remote_project_links_use_http_urls_and_encode_shell_metacharacters() { + let url = + crate::tui::input::project_link_url(r#"https://example.com/"&%USERNAME%?q=a b"#).unwrap(); + assert_eq!(url.as_str(), "https://example.com/%22&%USERNAME%?q=a%20b"); + for link in [ + "file:///C:/Windows/notepad.exe", + "javascript:alert(1)", + "shell:AppsFolder", + r"C:\folder\file", + "not a url", + ] { + assert!(crate::tui::input::project_link_url(link).is_err(), "{link}"); + } +} + #[test] fn global_navigation_returns_from_log_overlay() { let mut ui = UiHarness::new(); @@ -72,13 +88,13 @@ fn installed_version_action_requires_selected_provider_match() { ui.add_instance("Unmatched"); ui.app.focused = FocusedArea::Content; ui.app.content_tab = ContentTab::Mods; - let path = ui - .instance_path("Unmatched") - .join(crate::storage::MINECRAFT_DIR_NAME) - .join("mods/unknown.jar"); + let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Unmatched")).minecraft(); + let path = minecraft.join("mods/unknown.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"unknown").unwrap(); ui.app.mods_state.entries = vec![content_entry("Unknown mod", path)]; ui.app.mods_state.list_state.selected = Some(0); - let record = managed_mod_record("mods/unknown.jar", "known", false, Vec::new()); + let record = managed_mod_record(&minecraft, "mods/unknown.jar", "known", false, Vec::new()); let project = record.resolved_project().unwrap().clone(); ui.app.content_manifest = Some(( "Unmatched".to_owned(), @@ -102,13 +118,13 @@ fn installed_popup_navigation_preserves_local_filters() { ui.add_instance("Popup"); ui.app.focused = FocusedArea::Content; ui.app.content_tab = ContentTab::Mods; - let path = ui - .instance_path("Popup") - .join(crate::storage::MINECRAFT_DIR_NAME) - .join("mods/known.jar"); + let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Popup")).minecraft(); + let path = minecraft.join("mods/known.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"known").unwrap(); ui.app.mods_state.entries = vec![content_entry("Known mod", path)]; ui.app.mods_state.list_state.selected = Some(0); - let record = managed_mod_record("mods/known.jar", "known", false, Vec::new()); + let record = managed_mod_record(&minecraft, "mods/known.jar", "known", false, Vec::new()); let project = record.resolved_project().unwrap().clone(); ui.app.content_manifest = Some(( "Popup".to_owned(), @@ -282,15 +298,16 @@ fn world_datapack_version_action_requires_selected_provider_match() { ui.add_instance("Datapacks"); ui.app.focused = FocusedArea::Content; ui.app.content_tab = ContentTab::Worlds; - let world = ui - .instance_path("Datapacks") - .join(crate::storage::MINECRAFT_DIR_NAME) - .join("saves/World"); + let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Datapacks")).minecraft(); + let world = minecraft.join("saves/World"); let path = world.join("datapacks/unknown.zip"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"pack").unwrap(); ui.app.world_datapacks_state.entries = vec![content_entry("Unknown datapack", path)]; ui.app.world_datapacks_state.list_state.selected = Some(0); ui.app.open_world_datapacks = Some(("World".to_owned(), world)); let mut record = managed_mod_record( + &minecraft, "saves/World/datapacks/unknown.zip", "known", false, @@ -482,6 +499,7 @@ fn confirmed_screenshot_delete_removes_state_and_file() { } fn managed_mod_record( + minecraft: &Path, path: &str, project_id: &str, automatic_dependency: bool, @@ -491,11 +509,8 @@ fn managed_mod_record( relative_path: PathBuf::from(path), kind: ContentKind::Mod, enabled: true, - fingerprint: FileFingerprint { - size: 1, - modified_ns: 1, - hashes: Default::default(), - }, + fingerprint: crate::instance::content::manifest::fingerprint(&minecraft.join(path)) + .unwrap(), resolution: Resolution::Resolved { project: ProviderProject { provider: "modrinth".to_owned(), @@ -552,8 +567,8 @@ fn deleting_a_mod_offers_its_unused_dependency_chain() { ContentManifest { version: 1, files: vec![ - managed_mod_record("mods/root.jar", "root", false, vec![dependency]), - managed_mod_record("mods/library.jar", "library", true, Vec::new()), + managed_mod_record(&minecraft, "mods/root.jar", "root", false, vec![dependency]), + managed_mod_record(&minecraft, "mods/library.jar", "library", true, Vec::new()), ], } .save(&crate::storage::InstancePaths::new(ui.instance_path("Dependencies")).content_manifest()) @@ -596,10 +611,12 @@ fn deleting_a_required_library_warns_but_can_continue() { let library_path = minecraft.join("mods/library.jar"); std::fs::create_dir_all(library_path.parent().unwrap()).unwrap(); std::fs::write(&library_path, b"l").unwrap(); + std::fs::write(minecraft.join("mods/root.jar"), b"r").unwrap(); ContentManifest { version: 1, files: vec![ managed_mod_record( + &minecraft, "mods/root.jar", "root", false, @@ -609,7 +626,7 @@ fn deleting_a_required_library_warns_but_can_continue() { version_id: "library-version".to_owned(), }], ), - managed_mod_record("mods/library.jar", "library", true, Vec::new()), + managed_mod_record(&minecraft, "mods/library.jar", "library", true, Vec::new()), ], } .save(&crate::storage::InstancePaths::new(ui.instance_path("Required")).content_manifest()) @@ -630,6 +647,58 @@ fn deleting_a_required_library_warns_but_can_continue() { assert!(!Path::new(&library_path).exists()); } +#[test] +fn content_delete_rejects_ownership_changed_after_confirmation_opened() { + let mut ui = UiHarness::new(); + ui.add_instance("ChangedOwner"); + let paths = crate::storage::InstancePaths::new(ui.instance_path("ChangedOwner")); + let minecraft = paths.minecraft(); + let path = minecraft.join("mods/root.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"original").unwrap(); + let manifest = ContentManifest { + version: 1, + files: vec![managed_mod_record( + &minecraft, + "mods/root.jar", + "root", + false, + Vec::new(), + )], + }; + manifest.save(&paths.content_manifest()).unwrap(); + ui.app.content_manifest = Some(("ChangedOwner".to_owned(), manifest)); + ui.app.mods_state.entries = vec![content_entry("Root", path.clone())]; + ui.app.mods_state.list_state.selected = Some(0); + ui.app.focused = FocusedArea::Content; + ui.app.content_tab = ContentTab::Mods; + ui.key(KeyCode::Char('d')); + + let new_owner = ProviderProject { + provider: "curseforge".to_owned(), + project_id: "new-owner".to_owned(), + version_id: "new".to_owned(), + }; + ContentManifest::update(&paths.content_manifest(), |manifest| { + manifest.files[0].resolution = Resolution::Resolved { + project: new_owner.clone(), + }; + Ok(()) + }) + .unwrap(); + ui.key(KeyCode::Enter); + + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + assert_eq!(ui.app.mods_state.entries[0].path, path); + assert_eq!( + ContentManifest::load(&paths.content_manifest()) + .unwrap() + .files[0] + .resolved_project(), + Some(&new_owner) + ); +} + #[test] fn confirmed_account_delete_updates_the_account_panel() { let mut ui = UiHarness::new(); @@ -1164,6 +1233,7 @@ fn instance_launch_options_autosave_through_the_editor() { fn settings_panel_keeps_direct_profile_management() { let mut ui = UiHarness::new(); ui.add_instance("profile-test"); + std::fs::create_dir_all(ui.instance_path("profile-test").join("minecraft")).unwrap(); ui.app.focused = FocusedArea::Settings; ui.key(KeyCode::Char('a')); @@ -1249,6 +1319,11 @@ fn provider_conflict_selection_is_persisted() { let mut ui = UiHarness::new(); ui.add_instance("Conflict"); let relative_path = std::path::PathBuf::from("mods/example.jar"); + let file = crate::storage::InstancePaths::new(ui.instance_path("Conflict")) + .minecraft() + .join(&relative_path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, b"example").unwrap(); let candidates = vec![ ProviderProject { provider: "modrinth".to_owned(), @@ -1267,11 +1342,7 @@ fn provider_conflict_selection_is_persisted() { relative_path: relative_path.clone(), kind: crate::instance::ContentKind::Mod, enabled: true, - fingerprint: crate::instance::FileFingerprint { - size: 1, - modified_ns: 0, - hashes: Default::default(), - }, + fingerprint: crate::instance::content::manifest::fingerprint(&file).unwrap(), resolution: crate::instance::Resolution::Ambiguous { candidates: candidates.clone(), }, @@ -1293,6 +1364,16 @@ fn provider_conflict_selection_is_persisted() { }); ui.key(KeyCode::Down); + std::fs::write(&manifest_path, b"invalid").unwrap(); + ui.key(KeyCode::Enter); + assert_eq!(ui.app.provider_conflict.as_ref().unwrap().selected, 1); + ui.app + .content_manifest + .as_ref() + .unwrap() + .1 + .save(&manifest_path) + .unwrap(); ui.key(KeyCode::Enter); assert!(ui.app.provider_conflict.is_none()); diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 3f3753a..88b6406 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet}; -use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind}; +use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind}; use ratatui::{Terminal, backend::TestBackend}; use crate::auth::{Account, AccountStore, AccountType}; @@ -94,7 +94,10 @@ impl UiHarness { }, logs_state: widgets::logs_viewer::LogsState::default(), account_state, - settings_state: widgets::settings::SettingsState::new(meta_dir), + settings_state: widgets::settings::SettingsState::new( + meta_dir, + instance_manager.instances_dir.clone(), + ), instance_settings: None, pending_instance_settings_updates: Default::default(), global_settings: None, @@ -109,6 +112,7 @@ impl UiHarness { throbber_tick: 0, error_effects: HashMap::new(), pending_editor: None, + edited_config_watches: Vec::new(), reconciliation_for: None, content_manifest: None, content_update_snapshot: None, @@ -164,15 +168,19 @@ impl UiHarness { } pub fn add_account(&mut self, username: &str) { - self.app.account_state.store.accounts.push(Account { - uuid: username.to_owned(), - username: username.to_owned(), - account_type: AccountType::Microsoft, - active: true, - refresh_token: Some("refresh".to_owned()), - cached_mc_token: None, - cached_mc_token_expires_at: None, - }); + self.app + .account_state + .store + .add(Account { + uuid: username.to_owned(), + username: username.to_owned(), + account_type: AccountType::Microsoft, + active: true, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, + }) + .expect("persist test account"); self.app.account_state.list_state.selected = Some(0); } @@ -185,10 +193,14 @@ impl UiHarness { } pub fn key_with(&mut self, code: KeyCode, modifiers: KeyModifiers) { + self.key_event(KeyEvent::new(code, modifiers)); + } + + pub fn key_event(&mut self, key: KeyEvent) -> bool { let _runtime = self.runtime.enter(); self.app - .handle_key_event(KeyEvent::new(code, modifiers)) - .expect("handle key"); + .dispatch_event(Event::Key(key)) + .expect("handle key") } pub fn mouse(&mut self, kind: MouseEventKind) { diff --git a/src/tui/tests/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index 6d811a5..69558c5 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -2,6 +2,18 @@ // SPDX-License-Identifier: GPL-3.0-only use super::*; + +#[test] +fn changing_loader_isolates_pending_filter_versions() { + let mut state = DiscoveryState::new(ContentKind::Mod); + let previous = state.filter_game_versions.clone(); + state.set_filter_loader(ModLoader::Fabric); + *previous.lock().unwrap() = crate::tui::widgets::popups::LoadState::Error("stale".to_owned()); + assert!(matches!( + *state.filter_game_versions.lock().unwrap(), + crate::tui::widgets::popups::LoadState::Idle + )); +} use crate::tests::TEST_LOCK; use chrono::Utc; use crossterm::event::KeyModifiers; @@ -1332,6 +1344,7 @@ fn dependency_resolution_opens_the_existing_confirmation() { title: "Project".to_owned(), version: root_version, installed_path: None, + expected_record: None, kind: crate::instance::ContentKind::Mod, destination: std::path::PathBuf::from("mods"), provider_aliases: Vec::new(), @@ -1389,6 +1402,7 @@ fn confirming_state_with_plan() -> DiscoveryState { title: title.to_owned(), version, installed_path: None, + expected_record: None, kind: crate::instance::ContentKind::Mod, destination: std::path::PathBuf::from("mods"), provider_aliases: Vec::new(), diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index 78b55f4..c3b1d6e 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -8,6 +8,30 @@ use std::{ }; use crate::instance::content::entry::{ContentEntry, WorldDetails, WorldGameMode}; + +#[tokio::test] +async fn pending_version_metadata_does_not_queue_another_request_each_redraw() { + let temp = tempfile::tempdir().unwrap(); + let mut state = ContentListState { + provider_icon_meta_dir: Some(temp.path().to_owned()), + provider_icon_client: Some(crate::net::HttpClient::new()), + local_game_version: "1.21".to_owned(), + ..ContentListState::default() + }; + let mut entry = entry("project"); + entry.provider_project = Some(crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "project".to_owned(), + version_id: "version".to_owned(), + }); + state.entries.push(entry); + state.request_visible_provider_icons(&[0], 10); + let pending = Arc::strong_count(&state.pending_provider_icons); + for _ in 0..10 { + state.request_visible_provider_icons(&[0], 10); + } + assert_eq!(Arc::strong_count(&state.pending_provider_icons), pending); +} use ratatui::{ buffer::Buffer, layout::Rect, diff --git a/src/tui/tests/widgets/content/tabs.rs b/src/tui/tests/widgets/content/tabs.rs index d4a0a12..0b7df30 100644 --- a/src/tui/tests/widgets/content/tabs.rs +++ b/src/tui/tests/widgets/content/tabs.rs @@ -185,6 +185,7 @@ fn skipped_dependencies_render_as_skipped_in_confirmation() { title: title.to_owned(), version, installed_path: None, + expected_record: None, kind: ContentKind::Mod, destination: std::path::PathBuf::from("mods"), provider_aliases: Vec::new(), diff --git a/src/tui/tests/widgets/logs_viewer.rs b/src/tui/tests/widgets/logs_viewer.rs index 179c39a..e227dea 100644 --- a/src/tui/tests/widgets/logs_viewer.rs +++ b/src/tui/tests/widgets/logs_viewer.rs @@ -48,3 +48,58 @@ fn list_and_viewer_navigation_loads_and_scrolls_the_selected_log() { assert!(handle_key(&key(KeyCode::Esc), &mut state)); assert!(!state.viewer_focused); } + +#[test] +fn rescans_and_runtime_changes_keep_the_selected_log_and_viewer_in_sync() { + let temp = tempfile::tempdir().unwrap(); + let older = LogFileEntry { + name: "older.log".to_owned(), + path: temp.path().join("older.log"), + }; + let newer = LogFileEntry { + name: "newer.log".to_owned(), + path: temp.path().join("newer.log"), + }; + std::fs::write(&older.path, "older content").unwrap(); + std::fs::write(&newer.path, "newer content").unwrap(); + let name = "logs-rescan-identity"; + let mut state = LogsState { + loaded_for: Some(name.to_owned()), + entries: vec![older.clone()], + ..Default::default() + }; + state.list_state.selected = Some(0); + state.load_selected_content(); + *state.pending.lock().unwrap() = Some((name.to_owned(), vec![newer.clone(), older.clone()])); + state.drain_pending(); + assert_eq!(state.list_state.selected, Some(1)); + assert_eq!(state.viewer_lines, ["older content"]); + + crate::instance::runtime::set_state(name, crate::instance::runtime::RunState::Running); + state.drain_pending(); + assert_eq!(state.list_state.selected, Some(2)); + state.search.query = "older".to_owned(); + state.list_state.selected = Some(0); + state.load_selected_content(); + assert!(!state.is_live_selected()); + let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 4)).unwrap(); + terminal + .draw(|frame| render_viewer(frame, frame.area(), &mut state)) + .unwrap(); + let rendered = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(rendered.contains("older content")); + + state.search.query.clear(); + state.list_state.selected = Some(0); + state.load_selected_content(); + crate::instance::runtime::remove(name); + state.drain_pending(); + assert_eq!(state.viewer_lines, ["newer content"]); + assert_eq!(state.selected_path, Some(newer.path)); +} diff --git a/src/tui/tests/widgets/markdown.rs b/src/tui/tests/widgets/markdown.rs index ac13d31..9ecd9dc 100644 --- a/src/tui/tests/widgets/markdown.rs +++ b/src/tui/tests/widgets/markdown.rs @@ -435,6 +435,18 @@ fn emphasis_next_to_html_tag_boundaries_does_not_leak_markers() { assert!(!rendered.contains('*'), "{rendered}"); } +#[test] +fn literal_stars_and_code_operators_are_preserved() { + let text = formatted_text("`*` and `2 ** 3` and \\*", 80); + assert_eq!( + text.lines + .iter() + .map(ToString::to_string) + .collect::(), + "* and 2 ** 3 and *" + ); +} + #[test] fn fenced_code_blocks_are_rendered_without_fences() { let text = formatted_text("```json5\n{\n \"enabled\": true\n}\n```", 24); diff --git a/src/tui/tests/widgets/popups/import_modpack/state.rs b/src/tui/tests/widgets/popups/import_modpack/state.rs index 654c5a7..01b48ae 100644 --- a/src/tui/tests/widgets/popups/import_modpack/state.rs +++ b/src/tui/tests/widgets/popups/import_modpack/state.rs @@ -16,6 +16,43 @@ fn key(code: KeyCode) -> KeyEvent { KeyEvent::new(code, KeyModifiers::NONE) } +#[test] +fn dispatch_repeats_import_version_search_but_not_import_confirmation() { + use crate::tui::{app::FocusedArea, tests::harness::UiHarness}; + use crossterm::event::KeyEventKind; + + let mut ui = UiHarness::new(); + ui.app.focused = FocusedArea::ImportPopup; + ui.app.instances_state.show_import_popup = true; + IMPORT_STATE.lock().unwrap().step = ImportStep::Version; + IMPORT_STATE.lock().unwrap().version_search.activate(); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('i'), + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!(IMPORT_STATE.lock().unwrap().version_search.query, "i"); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + { + let mut state = IMPORT_STATE.lock().unwrap(); + state.step = ImportStep::Confirm; + state.summary = Some(summary()); + } + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(take_result().is_none()); + assert!(ui.app.instances_state.show_import_popup); + ui.key(KeyCode::Enter); + assert_eq!(take_result().unwrap().summary.name, "Test Pack"); +} + fn summary() -> ImportSummary { ImportSummary { name: "Test Pack".to_owned(), diff --git a/src/tui/tests/widgets/popups/new_instance/state.rs b/src/tui/tests/widgets/popups/new_instance/state.rs index 3638f47..42d73f3 100644 --- a/src/tui/tests/widgets/popups/new_instance/state.rs +++ b/src/tui/tests/widgets/popups/new_instance/state.rs @@ -11,6 +11,61 @@ fn key(code: KeyCode) -> KeyEvent { KeyEvent::new(code, KeyModifiers::NONE) } +#[test] +fn dispatch_repeats_version_search_but_not_snapshot_toggle_or_creation() { + use crate::tui::{app::FocusedArea, tests::harness::UiHarness}; + use crossterm::event::KeyEventKind; + + let mut ui = UiHarness::new(); + ui.app.focused = FocusedArea::Popup; + ui.app.instances_state.show_popup = true; + { + let mut state = WIZARD_STATE.lock().unwrap(); + state.step = WizardStep::Version; + state.versions = LoadState::Loaded(vec![GameVersion { + id: "1.21.1".to_owned(), + stable: true, + }]); + state.version_search.activate(); + } + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('s'), + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + { + let state = WIZARD_STATE.lock().unwrap(); + assert_eq!(state.version_search.query, "s"); + assert!(!state.show_snapshots); + } + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + { + let mut state = WIZARD_STATE.lock().unwrap(); + state.step = WizardStep::Confirm; + state.name_state = TextState::new().with_value("Held Confirm"); + state.version_search.deactivate(); + } + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(take_result().is_none()); + assert!(ui.app.instances_state.show_popup); + ui.key(KeyCode::Enter); + assert_eq!(take_result().unwrap().name, "Held Confirm"); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!(ui.app.focused, FocusedArea::Instances); +} + #[test] fn filtered_vanilla_wizard_returns_the_displayed_version() { let _guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); diff --git a/src/tui/tests/widgets/search.rs b/src/tui/tests/widgets/search.rs index a6e328a..77774f3 100644 --- a/src/tui/tests/widgets/search.rs +++ b/src/tui/tests/widgets/search.rs @@ -53,6 +53,32 @@ fn highlight_spans_marks_each_case_insensitive_match() { assert!(spans[2].style.add_modifier.contains(Modifier::UNDERLINED)); } +#[test] +fn highlighting_maps_expanding_lowercase_back_to_the_original_character() { + for (query, expected) in [("a", "a"), ("i", "İ"), ("\u{307}", "İ")] { + let search = SearchState { + query: query.to_owned(), + ..Default::default() + }; + let spans = search.highlight_spans("İab", Style::default()); + assert_eq!( + spans + .iter() + .map(|span| span.content.as_ref()) + .collect::(), + "İab" + ); + assert_eq!( + spans + .iter() + .filter(|span| span.style.add_modifier.contains(Modifier::UNDERLINED)) + .map(|span| span.content.as_ref()) + .collect::(), + expected + ); + } +} + #[test] fn ctrl_backspace_deletes_the_previous_word() { let mut search = SearchState { diff --git a/src/tui/tests/widgets/settings.rs b/src/tui/tests/widgets/settings.rs index 58d1070..2972bba 100644 --- a/src/tui/tests/widgets/settings.rs +++ b/src/tui/tests/widgets/settings.rs @@ -6,13 +6,21 @@ use super::*; #[test] fn narrow_settings_shows_the_selected_pane() { let tmp = tempfile::tempdir().unwrap(); - let mut state = SettingsState::new(tmp.path().to_path_buf()); + let mut state = SettingsState::new(tmp.path().to_path_buf(), tmp.path().join("instances")); let instance: InstanceConfig = serde_json::from_value(serde_json::json!({ "name": "Test", "game_version": "1.21", "loader": "vanilla", "loader_version": null, "created": "2026-01-01T00:00:00Z", "java_path": "test-java" })) .unwrap(); - state.java_key = Some("test-java".to_owned()); + let environment = crate::instance::java::merge_environment( + &SETTINGS.read().defaults.environment, + &instance.environment, + ); + state.java_key = Some(java_path_key( + "test-java", + &state.instances_dir.join("Test/minecraft"), + &environment, + )); state.java_label = "jdk17".to_owned(); let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(35, 8)).unwrap(); @@ -62,7 +70,7 @@ fn narrow_settings_shows_the_selected_pane() { #[test] fn removing_selected_last_profile_clamps_selection() { let tmp = tempfile::tempdir().unwrap(); - let mut state = SettingsState::new(tmp.path().to_path_buf()); + let mut state = SettingsState::new(tmp.path().to_path_buf(), tmp.path().join("instances")); state.profiles = vec!["first".to_string(), "second".to_string()]; state.active_profile = Some("second".to_string()); state.list_state.selected = Some(2); @@ -77,7 +85,7 @@ fn removing_selected_last_profile_clamps_selection() { #[test] fn info_pane_does_not_bind_desktop_toggle() { let tmp = tempfile::tempdir().unwrap(); - let mut state = SettingsState::new(tmp.path().to_path_buf()); + let mut state = SettingsState::new(tmp.path().to_path_buf(), tmp.path().join("instances")); state.pane = SettingsPane::Info; assert!(matches!( @@ -85,3 +93,45 @@ fn info_pane_does_not_bind_desktop_toggle() { SettingsAction::None )); } + +#[cfg(unix)] +#[test] +fn instance_java_labels_use_their_cwd_and_environment_and_discard_previous_results() { + use std::os::unix::fs::PermissionsExt; + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let java = temp.path().join("selected-java"); + std::fs::write(&java, b"#!/bin/sh\nread -r expected < marker || exit 1\n[ \"$RMCL_TEST_JAVA_VERSION\" = \"$expected\" ] || exit 1\nprintf 'java.version = %s\\n' \"$expected\"\n").unwrap(); + std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut state = SettingsState::new(temp.path().join("meta"), instances.clone()); + let instance = |name: &str, version: &str| -> InstanceConfig { + let minecraft = instances.join(name).join("minecraft"); + std::fs::create_dir_all(&minecraft).unwrap(); + std::fs::write(minecraft.join("marker"), format!("{version}\n")).unwrap(); + serde_json::from_value(serde_json::json!({ + "name": name, "game_version": "1.21", "loader": "vanilla", "created": "2026-01-01T00:00:00Z", + "java_path": java, "environment": {"RMCL_TEST_JAVA_VERSION": version} + })).unwrap() + }; + fn wait_for_label(state: &mut SettingsState, instance: &InstanceConfig, expected: &str) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while std::time::Instant::now() < deadline { + state.update_for_instance(Some(instance)); + if state.java_label == expected { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("Expected {expected}, found {}", state.java_label); + } + let first = instance("first", "21"); + wait_for_label(&mut state, &first, "jdk21"); + let old_pending = state.pending_java.clone(); + let second = instance("second", "25"); + state.update_for_instance(Some(&second)); + *old_pending.lock().unwrap() = Some("stale label".to_owned()); + wait_for_label(&mut state, &second, "jdk25"); +} diff --git a/src/tui/widgets/content/discovery.rs b/src/tui/widgets/content/discovery.rs index 7308867..3326070 100644 --- a/src/tui/widgets/content/discovery.rs +++ b/src/tui/widgets/content/discovery.rs @@ -1364,11 +1364,8 @@ impl DiscoveryState { pub(crate) fn set_filter_loader(&mut self, loader: ModLoader) { if self.filter_loader != loader { - *self - .filter_game_versions - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = - crate::tui::widgets::popups::LoadState::Idle; + self.filter_game_versions = + Arc::new(Mutex::new(crate::tui::widgets::popups::LoadState::Idle)); } self.filter_loader = loader; } @@ -2645,6 +2642,21 @@ impl DiscoveryState { self.pending_orphan_cleanup.take() } + pub(in crate::tui) fn text_input_active(&self) -> bool { + if let Some(popup) = &self.version_popup { + return popup.selecting_world && !popup.confirming && popup.worlds.search.active; + } + if self.project_page_open() { + return false; + } + if self.sort_panel_open && !self.search.active { + return self.sort_panel_focused + && self.filter_version_picker_open + && self.filter_version_search.active; + } + self.search.active + } + fn should_load_more(&self) -> bool { if self.page_loading || (self.preparing_list.is_some() && self.retry_page_at.is_none()) diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index dc175fc..888e624 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -578,7 +578,7 @@ impl ContentListState { && !self .version_metadata .contains_key(&(project.provider.clone(), project.version_id.clone())); - if !self.requested_provider_icons.insert(key) && !missing_version { + if !self.requested_provider_icons.insert(key) { continue; } let pending = self.pending_provider_icons.clone(); @@ -875,8 +875,6 @@ 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) -> bool { let Some(rx) = &self.stream_rx else { return false; @@ -1808,8 +1806,6 @@ impl ContentListState { .collect(); } - // enable/disable by renaming the file with/without .disabled extension. - // this is how most minecraft launchers handle it pub fn toggle_selected(&mut self) { let Some(index) = self.list_state.selected else { return; @@ -2694,9 +2690,6 @@ fn preserve_visual_metadata(entry: &mut ContentEntry, previous: &mut ContentEntr } } -// renders one row of a mod icon using half-block characters (U+2584). -// each cell packs two vertical pixels via fg/bg colors, giving -// double the vertical resolution out of the terminal fn icon_spans( icon_pixels: Option<&Vec>>, row: usize, diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index 6e49e07..6c099bf 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -597,7 +597,6 @@ pub fn render( return; } - // lazy-load: only scan when switching to an instance that hasn't been loaded yet match tab { ContentTab::Mods | ContentTab::ResourcePacks @@ -643,8 +642,8 @@ pub fn render( } ContentTab::Worlds => { if let Some(instance) = instance { - if let Some((world_name, world_path)) = open_world_datapacks { - let cache_key = format!("{}:{world_name}", instance.name); + if let Some((_, world_path)) = open_world_datapacks { + let cache_key = format!("{}:{world_path:?}", instance.name); let content_dir = world_path.join("datapacks"); if world_datapacks_state.loaded_for.as_deref() != Some(cache_key.as_str()) { world_datapacks_state.start_load( diff --git a/src/tui/widgets/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index acf5633..571d4f2 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -76,6 +76,7 @@ impl LogsState { self.viewer_scroll = 0; self.viewer_focused = false; self.selected_path = None; + self.was_live = false; self.last_rescan = std::time::Instant::now(); let dir = instances_dir.to_path_buf(); @@ -99,33 +100,38 @@ impl LogsState { pub fn drain_pending(&mut self) { let live_now = self.has_live(); - self.was_live = live_now; + let live_changed = live_now != self.was_live; + let selected_live = + self.was_live && self.selected_path.is_none() && self.list_state.selected.is_some(); let taken = match self.pending.lock() { Ok(mut slot) => slot.take(), _ => None, }; - if let Some((instance_name, entries)) = taken + let updated = if let Some((instance_name, entries)) = taken && self.loaded_for.as_deref() == Some(&instance_name) { - let prev_selected = self.list_state.selected; self.entries = entries; self.loading = false; - - let display_count = self.display_count(); - - if display_count > 0 && prev_selected.is_none() { - self.list_state.selected = Some(0); - self.load_selected_content(); - } else if let Some(sel) = prev_selected - && sel >= display_count - && display_count > 0 - { - self.list_state.selected = Some(display_count - 1); - } + true + } else { + false + }; + if updated || live_changed { + let previous = self.list_state.selected.unwrap_or(0); + let indices = self.display_indices(); + self.list_state.selected = indices + .iter() + .position(|index| match index { + None => selected_live, + Some(index) => self.selected_path.as_ref() == Some(&self.entries[*index].path), + }) + .or_else(|| (!indices.is_empty()).then(|| previous.min(indices.len() - 1))); self.update_scrollbar(); + self.load_selected_content(); } + self.was_live = live_now; } pub fn try_rescan(&mut self) { @@ -448,7 +454,6 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: return; } - let has_live = state.has_live(); let display_count = state.display_count(); if display_count == 0 { @@ -468,7 +473,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: Layout::horizontal([Constraint::Length(30), Constraint::Min(0)]).areas(area); render_list(frame, list_area, state, is_focused); - render_viewer(frame, viewer_area, state, is_focused, has_live); + render_viewer(frame, viewer_area, state); } fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: bool) { @@ -558,15 +563,9 @@ fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: ); } -fn render_viewer( - frame: &mut Frame, - area: Rect, - state: &mut LogsState, - _is_focused: bool, - has_live: bool, -) { +fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) { let theme = THEME.as_ref(); - let is_live = has_live && state.list_state.selected == Some(0); + let is_live = state.is_live_selected(); let all_lines: Vec = if is_live { let name = state.loaded_for.as_deref().unwrap_or(""); diff --git a/src/tui/widgets/markdown.rs b/src/tui/widgets/markdown.rs index 001c08a..0237049 100644 --- a/src/tui/widgets/markdown.rs +++ b/src/tui/widgets/markdown.rs @@ -335,6 +335,12 @@ fn normalize_html(source: &str) -> NormalizedDocument { } fn convert_html_fragment(html: &str) -> Result { + // A closing emphasis delimiter after punctuation needs a word boundary. + static EMPHASIS_BOUNDARY: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r"(?i)()([\p{L}\p{N}])") + .expect("valid emphasis boundary regex") + }); + let html = EMPHASIS_BOUNDARY.replace_all(html, "$1 $2"); let image_alignments = Arc::new(Mutex::new(HashMap::new())); let visitor: VisitorHandle = Arc::new(Mutex::new(ImageAlignmentVisitor { centered: Vec::new(), @@ -617,17 +623,13 @@ fn external_markdown_text(source: &str, width: u16) -> (Text<'static>, Vec Line<'_> { let theme = THEME.as_ref(); if !highlight || title.is_empty() { diff --git a/src/tui/widgets/popups/global_settings.rs b/src/tui/widgets/popups/global_settings.rs index 3dcb2c8..4a14c86 100644 --- a/src/tui/widgets/popups/global_settings.rs +++ b/src/tui/widgets/popups/global_settings.rs @@ -14,7 +14,10 @@ use ratatui_textarea::TextArea; use crate::{ config::{ Config, - settings::{ContentProvider, DEFAULT_RESOLUTION, ImageProtocol, ShortcutHintScope}, + settings::{ + ContentProvider, DEFAULT_RESOLUTION, ImageProtocol, ShortcutHintScope, + format_tag_values, parse_tag_values, + }, theme::{BORDER_STYLE, BorderStyle, THEME, ThemeConfig}, }, instance::models::{memory_kib, normalize_memory_value, parse_resolution}, @@ -22,10 +25,10 @@ use crate::{ DisplayResolution, JavaChoice, JavaPicker, ResolutionChoice, ResolutionPickerAction, SettingsPicker, SettingsPickerAction, SettingsPickerOption, adjust_memory, auto_label, default_label, default_resolution, display_resolutions, environment_labels, - format_tag_values, handle_resolution_picker_key, handle_text_area_input, - is_default_resolution, parse_environment, parse_tag_values, render_memory_gauge, - render_settings_picker, resolution_choices, resolution_items, settings_text_area, - tagged_row_count, tagged_value_lines, toggle_window_mode, window_mode_title, + handle_resolution_picker_key, handle_text_area_input, is_default_resolution, + parse_environment, render_memory_gauge, render_settings_picker, resolution_choices, + resolution_items, settings_text_area, tagged_row_count, tagged_value_lines, + toggle_window_mode, window_mode_title, }, tui::widgets::status_badge, }; @@ -96,8 +99,13 @@ impl State { let java_cache = crate::storage::MetadataPaths::new(runtime_config.paths.resolve_meta_dir()) .java_installations(); - let mut java_picker = - JavaPicker::with_cache(crate::instance::java::detect_java_path(), Some(java_cache)); + let cwd = std::env::current_dir().unwrap_or_default(); + let environment = crate::instance::java::merge_environment( + &config.defaults.environment, + &Default::default(), + ); + let detected = crate::instance::java::resolve_java_path_in(None, &cwd, &environment); + let mut java_picker = JavaPicker::with_cache(detected, Some(java_cache), cwd, environment); java_picker.set_current(config.paths.java_path.as_deref()); Self { config, @@ -238,6 +246,7 @@ impl State { 9 => match parse_environment(value) { Ok(environment) => { self.config.defaults.environment = environment; + self.refresh_java_context(); self.save_pending = true; } Err(error) => invalid(self, error), @@ -563,7 +572,8 @@ impl State { .iter() .position(|mode| *mode == current); let index = match (index, forward) { - (Some(2), true) | (Some(0), false) => 0, + (Some(2), true) => 0, + (Some(0), false) => 2, (Some(index), true) => index + 1, (Some(index), false) => index - 1, (None, true) => 0, @@ -579,6 +589,7 @@ impl State { } fn open_java_picker(&mut self) { + self.refresh_java_context(); self.java_picker .open(self.config.paths.java_path.as_deref()); self.java_picker.initialize(); @@ -586,6 +597,7 @@ impl State { } fn toggle_auto_java(&mut self) -> Action { + self.refresh_java_context(); let Some(current) = self.config.paths.java_path.as_deref() else { self.config.paths.java_path = Some(self.java_picker.detected_path().to_owned()); self.save_pending = true; @@ -617,6 +629,17 @@ impl State { pub fn invalidate_java_cache(&mut self) { self.java_picker.invalidate_cache(); + self.refresh_java_context(); + } + + fn refresh_java_context(&mut self) { + let cwd = std::env::current_dir().unwrap_or_default(); + let environment = crate::instance::java::merge_environment( + &self.config.defaults.environment, + &Default::default(), + ); + let detected = crate::instance::java::resolve_java_path_in(None, &cwd, &environment); + self.java_picker.set_context(detected, cwd, environment); } fn handle_java_picker_key(&mut self, key: &KeyEvent) { @@ -687,6 +710,13 @@ impl State { self.error = None; } + pub(in crate::tui) fn text_input_active(&self) -> bool { + self.choice_picker.is_none() + && !self.java_picker_open + && !self.theme_picker + && self.editing.is_some() + } + pub fn handle_key(&mut self, key: &KeyEvent) -> Action { let action = self.handle_key_inner(key); if !matches!(action, Action::None) { @@ -1318,6 +1348,88 @@ mod tests { use super::*; use crate::instance::models::WindowMode; + #[test] + fn dispatch_repeats_launcher_text_but_not_setting_toggles() { + use crate::tui::{app::FocusedArea, tests::harness::UiHarness}; + use crossterm::event::{KeyEventKind, KeyModifiers}; + + let mut ui = UiHarness::new(); + let mut state = State::new(); + state.selected = 6; + let mode = state.config.defaults.window_mode; + ui.app.global_settings = Some(state); + ui.app.focused = FocusedArea::GlobalSettings; + for code in [KeyCode::Right, KeyCode::Char('l'), KeyCode::Enter] { + assert!(!ui.key_event(KeyEvent::new_with_kind( + code, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + } + assert_eq!( + ui.app + .global_settings + .as_ref() + .unwrap() + .config + .defaults + .window_mode, + mode + ); + + ui.app.global_settings.as_mut().unwrap().editing = + Some(settings_text_area(vec![String::new()])); + ui.key(KeyCode::Char('l')); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('l'), + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('l'), + KeyModifiers::NONE, + KeyEventKind::Release + ))); + assert_eq!( + ui.app + .global_settings + .as_ref() + .unwrap() + .editing + .as_ref() + .unwrap() + .lines(), + &["ll"] + ); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Left, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Delete, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!( + ui.app + .global_settings + .as_ref() + .unwrap() + .editing + .as_ref() + .unwrap() + .lines(), + &["l"] + ); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(ui.app.global_settings.as_ref().unwrap().editing.is_some()); + } + #[test] fn launcher_memory_uses_slider_and_java_uses_picker() { let mut state = State::new(); @@ -1550,6 +1662,10 @@ mod tests { state.selected = 2; state.handle_key(&KeyEvent::from(KeyCode::Down)); assert_eq!(state.selected, 24); + state.cycle_shortcut_hints(false); + assert_eq!(shortcut_hint_mode(&state.config.ui), "Hidden"); + state.cycle_shortcut_hints(true); + assert_eq!(shortcut_hint_mode(&state.config.ui), "All"); assert!(matches!( state.handle_key(&KeyEvent::from(KeyCode::Right)), diff --git a/src/tui/widgets/popups/import_modpack/mod.rs b/src/tui/widgets/popups/import_modpack/mod.rs index 4bedbe9..17f5fea 100644 --- a/src/tui/widgets/popups/import_modpack/mod.rs +++ b/src/tui/widgets/popups/import_modpack/mod.rs @@ -7,6 +7,7 @@ mod state; #[cfg(test)] pub use render::render; pub use render::{popup_rect, render_with_picker}; +pub(in crate::tui) use state::text_input_active; pub use state::{ ImportResult, ImportStep, ImportWizardState, discovery_activity, drain, handle_discovery_click, handle_key, has_version_popup, open, take_result, diff --git a/src/tui/widgets/popups/import_modpack/state.rs b/src/tui/widgets/popups/import_modpack/state.rs index a49167a..921a1c3 100644 --- a/src/tui/widgets/popups/import_modpack/state.rs +++ b/src/tui/widgets/popups/import_modpack/state.rs @@ -120,6 +120,23 @@ pub fn has_version_popup() -> bool { .is_ok_and(|state| state.version_popup.is_some()) } +pub(in crate::tui) fn text_input_active() -> bool { + let Ok(state) = IMPORT_STATE.lock() else { + return false; + }; + match state.step { + ImportStep::Input => true, + ImportStep::Version => state.version_search.active, + ImportStep::Discover => { + drop(state); + DISCOVERY_STATE + .lock() + .is_ok_and(|discovery| discovery.text_input_active()) + } + _ => false, + } +} + pub fn discovery_activity() -> Option<&'static str> { let wizard = IMPORT_STATE.lock().ok()?; let step = wizard.step.clone(); diff --git a/src/tui/widgets/popups/instance_settings.rs b/src/tui/widgets/popups/instance_settings.rs index 249dad8..f18e476 100644 --- a/src/tui/widgets/popups/instance_settings.rs +++ b/src/tui/widgets/popups/instance_settings.rs @@ -16,8 +16,10 @@ use crate::{ auth::{Account, AccountType}, config::{ SETTINGS, + settings::{format_tag_values, parse_tag_values}, theme::{BORDER_STYLE, THEME}, }, + instance::glfw::bundled_glfw_version, instance::loader::GameVersion, instance::models::{ InstanceConfig, LaunchCommand, ModLoader, memory_kib, normalize_memory_value, @@ -30,12 +32,12 @@ use crate::{ DisplayResolution, GlfwChoice, GlfwPicker, JavaChoice, JavaPicker, ResolutionChoice, ResolutionPickerAction, SettingsPicker, SettingsPickerAction, SettingsPickerBadge, SettingsPickerOption, adjust_memory, auto_label, - bundled_glfw_version, bundled_label as bundled_badge, default_label, - default_resolution, display_resolutions, environment_labels, format_tag_values, - handle_resolution_picker_key, handle_text_area_input, is_default_resolution, - parse_environment, parse_tag_values, render_memory_gauge, render_settings_picker, - resolution_choices, resolution_items, settings_text_area, tagged_row_count, - tagged_value_lines, toggle_window_mode, window_mode_title, + bundled_label as bundled_badge, default_label, default_resolution, + display_resolutions, environment_labels, handle_resolution_picker_key, + handle_text_area_input, is_default_resolution, parse_environment, + render_memory_gauge, render_settings_picker, resolution_choices, resolution_items, + settings_text_area, tagged_row_count, tagged_value_lines, toggle_window_mode, + window_mode_title, }, }, search::SearchState, @@ -92,6 +94,7 @@ pub struct State { account_picker: SettingsPicker, accounts: Vec, meta_dir: std::path::PathBuf, + minecraft_dir: std::path::PathBuf, display_resolutions: Vec, runtime_update_pending: bool, save_retry_pending: bool, @@ -111,9 +114,16 @@ pub enum Action { impl State { pub fn new(instance: &InstanceConfig, meta_dir: &std::path::Path) -> Self { + let minecraft_dir = crate::config::SETTINGS + .read() + .paths + .resolve_instances_dir() + .join(&instance.name) + .join(crate::storage::MINECRAFT_DIR_NAME); Self::with_accounts( instance, meta_dir, + &minecraft_dir, crate::auth::AccountStore::load().accounts, ) } @@ -121,16 +131,24 @@ impl State { pub fn with_accounts( instance: &InstanceConfig, meta_dir: &std::path::Path, + minecraft_dir: &std::path::Path, accounts: Vec, ) -> Self { - let auto_java_path = SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - .unwrap_or_else(crate::instance::java::detect_java_path); + let settings = SETTINGS.read(); + let cwd = minecraft_dir.to_owned(); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &instance.environment, + ); + let auto_java_path = crate::instance::java::resolve_java_path_in( + settings.paths.effective_java_path(), + &cwd, + &environment, + ); + drop(settings); let java_cache = crate::storage::MetadataPaths::new(meta_dir).java_installations(); - let mut java_picker = JavaPicker::with_cache(auto_java_path, Some(java_cache)); + let mut java_picker = + JavaPicker::with_cache(auto_java_path, Some(java_cache), cwd, environment); java_picker.set_current(instance.java_path.as_deref()); let desktop = crate::instance::desktop::exists(&instance.name); Self { @@ -158,6 +176,7 @@ impl State { account_picker: SettingsPicker::default(), accounts, meta_dir: meta_dir.to_path_buf(), + minecraft_dir: minecraft_dir.to_owned(), display_resolutions: display_resolutions(), runtime_update_pending: false, save_retry_pending: false, @@ -405,6 +424,7 @@ impl State { .unwrap_or(0); } ChoicePicker::Java => { + self.refresh_java_context(); self.java_picker.open(self.draft.java_path.as_deref()); self.java_picker.initialize(); } @@ -770,6 +790,7 @@ impl State { } fn toggle_auto_java(&mut self) -> Action { + self.refresh_java_context(); let Some(current) = self.draft.java_path.as_deref() else { self.draft.java_path = Some(self.java_picker.detected_path().to_owned()); self.error = None; @@ -937,7 +958,10 @@ impl State { Err(error) => invalid(self, error), }, 7 => match parse_environment(value) { - Ok(environment) => self.draft.environment = environment, + Ok(environment) => { + self.draft.environment = environment; + self.refresh_java_context(); + } Err(error) => invalid(self, error), }, 9 if value.is_empty() => { @@ -964,6 +988,16 @@ impl State { } } + pub(in crate::tui) fn text_input_active(&self) -> bool { + !self.runtime_update_pending + && self.choice_picker.is_none() + && if self.picker.is_some() { + self.picker_search.active + } else { + self.editing.is_some() + } + } + pub fn handle_key(&mut self, key: &KeyEvent) -> Action { if self.runtime_update_pending { return if key.code == KeyCode::Esc { @@ -1106,6 +1140,23 @@ impl State { pub fn invalidate_java_cache(&mut self) { self.java_picker.invalidate_cache(); + self.refresh_java_context(); + } + + fn refresh_java_context(&mut self) { + let settings = SETTINGS.read(); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &self.draft.environment, + ); + let detected = crate::instance::java::resolve_java_path_in( + settings.paths.effective_java_path(), + &self.minecraft_dir, + &environment, + ); + drop(settings); + self.java_picker + .set_context(detected, self.minecraft_dir.clone(), environment); } pub fn cancel_runtime_change(&mut self) -> Option<(Box, bool)> { @@ -1740,6 +1791,79 @@ mod tests { use crate::instance::WindowMode; use chrono::Utc; + #[test] + fn dispatch_repeats_picker_search_without_snapshot_toggle_or_selection() { + use crate::tui::{app::FocusedArea, tests::harness::UiHarness}; + use crossterm::event::{KeyEventKind, KeyModifiers}; + + let mut ui = UiHarness::new(); + ui.add_instance("Picker Search"); + let config = ui.app.instances_state.selected_instance().unwrap(); + let mut state = State::with_accounts( + config, + &ui.app.instance_manager.meta_dir, + &ui.instance_path(&config.name).join("minecraft"), + Vec::new(), + ); + state.picker = Some(VersionPicker::Game); + state.game_versions = Arc::new(Mutex::new(LoadState::Loaded(vec![GameVersion { + id: "1.21.1".to_owned(), + stable: true, + }]))); + state.picker_search.activate(); + ui.app.instance_settings = Some(state); + ui.app.focused = FocusedArea::InstanceSettings; + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('s'), + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + let state = ui.app.instance_settings.as_ref().unwrap(); + assert_eq!(state.picker_search.query, "s"); + assert!(!state.show_snapshots); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!( + ui.app.instance_settings.as_ref().unwrap().picker, + Some(VersionPicker::Game) + ); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Backspace, + KeyModifiers::CONTROL, + KeyEventKind::Repeat + ))); + assert!( + ui.app + .instance_settings + .as_ref() + .unwrap() + .picker_search + .query + .is_empty() + ); + ui.key(KeyCode::Enter); + assert!( + !ui.app + .instance_settings + .as_ref() + .unwrap() + .picker_search + .active + ); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Right, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!( + ui.app.instance_settings.as_ref().unwrap().picker, + Some(VersionPicker::Game) + ); + } + fn instance() -> InstanceConfig { InstanceConfig { name: "test".to_owned(), @@ -2231,6 +2355,15 @@ mod tests { assert!(lines.len() > 1); assert_eq!(tagged_row_count(&state.draft.jvm_args, 48), lines.len()); assert!(lines.iter().any(|line| line.to_string().contains("second"))); + let values = vec![ + "界界界界界".to_owned(), + "abcdefghijklmn".to_owned(), + "e\u{301}".to_owned(), + ]; + let lines = tagged_field_lines(&state, 6, "JVM args", &values, "", 48); + assert_eq!(lines.len(), 2); + assert_eq!(tagged_row_count(&values, 48), lines.len()); + assert!(lines.iter().all(|line| line.width() <= 48)); } #[test] @@ -2296,7 +2429,12 @@ mod tests { cached_mc_token: None, cached_mc_token_expires_at: None, }]; - let mut state = State::with_accounts(&instance(), temp.path(), accounts); + let mut state = State::with_accounts( + &instance(), + temp.path(), + &temp.path().join("minecraft"), + accounts, + ); state.selected = 10; state.begin_edit(); assert_eq!(state.choice_index, 0); diff --git a/src/tui/widgets/popups/new_instance/mod.rs b/src/tui/widgets/popups/new_instance/mod.rs index 97f7535..e422e09 100644 --- a/src/tui/widgets/popups/new_instance/mod.rs +++ b/src/tui/widgets/popups/new_instance/mod.rs @@ -5,6 +5,7 @@ mod render; mod state; pub use render::{popup_rect, render}; +pub(in crate::tui) use state::text_input_active; pub use state::{WizardParams, WizardState, WizardStep, handle_key, take_result}; #[cfg(test)] diff --git a/src/tui/widgets/popups/new_instance/state.rs b/src/tui/widgets/popups/new_instance/state.rs index 9a69cfe..c2255dd 100644 --- a/src/tui/widgets/popups/new_instance/state.rs +++ b/src/tui/widgets/popups/new_instance/state.rs @@ -116,6 +116,13 @@ pub fn take_result() -> Option { } } +pub(in crate::tui) fn text_input_active() -> bool { + WIZARD_STATE.lock().is_ok_and(|state| { + state.step == WizardStep::Name + || (state.step == WizardStep::Version && state.version_search.active) + }) +} + fn handle_name_key( state: &mut WizardState, key_event: &KeyEvent, diff --git a/src/tui/widgets/popups/settings_controls.rs b/src/tui/widgets/popups/settings_controls.rs index 921e33a..92b04b2 100644 --- a/src/tui/widgets/popups/settings_controls.rs +++ b/src/tui/widgets/popups/settings_controls.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only use std::{ - collections::{BTreeMap, BTreeSet}, + collections::BTreeMap, path::{Path, PathBuf}, sync::{ Arc, Mutex, @@ -21,8 +21,12 @@ use ratatui::{ use ratatui_textarea::{CursorMove, TextArea}; use crate::{ - config::{settings::DEFAULT_RESOLUTION, theme::THEME}, + config::{ + settings::{DEFAULT_RESOLUTION, parse_tag_values}, + theme::THEME, + }, instance::{ + glfw::{GlfwInstallation, discover_glfw_installations, glfw_version_from_path}, java::JavaInstallation, models::{WindowMode, memory_kib}, }, @@ -204,6 +208,9 @@ pub(crate) struct JavaPicker { cache_path: Option, refresh_started: bool, generation: Arc, + cwd: PathBuf, + environment: BTreeMap, + context_key: String, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -225,12 +232,6 @@ pub(crate) enum GlfwChoice { System(String), } -#[derive(Debug, Clone)] -struct GlfwInstallation { - path: PathBuf, - version: Option, -} - #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct DisplayResolution { pub width: u32, @@ -298,13 +299,24 @@ impl JavaPicker { } pub(crate) fn with_auto_path(detected: String) -> Self { - Self::with_cache(detected, None) + let cwd = std::env::current_dir().unwrap_or_default(); + let environment = crate::instance::java::merge_environment( + &crate::config::SETTINGS.read().defaults.environment, + &BTreeMap::new(), + ); + Self::with_cache(detected, None, cwd, environment) } - pub(crate) fn with_cache(detected: String, cache_path: Option) -> Self { - let cached = cache_path - .as_deref() - .and_then(crate::instance::java::load_installation_cache); + pub(crate) fn with_cache( + detected: String, + cache_path: Option, + cwd: PathBuf, + environment: BTreeMap, + ) -> Self { + let cached = cache_path.as_deref().and_then(|path| { + crate::instance::java::load_installation_cache_in(path, &cwd, &environment) + }); + let context_key = crate::instance::java::probe_context_key(&cwd, &environment); Self { load: Arc::new(Mutex::new( cached.map_or(LoadState::Idle, LoadState::Loaded), @@ -315,6 +327,25 @@ impl JavaPicker { cache_path, refresh_started: false, generation: Arc::new(AtomicU64::new(0)), + cwd, + environment, + context_key, + } + } + + pub(crate) fn set_context( + &mut self, + detected: String, + cwd: PathBuf, + environment: BTreeMap, + ) { + let key = crate::instance::java::probe_context_key(&cwd, &environment); + if key != self.context_key || detected != self.detected { + self.invalidate_cache(); + self.detected = detected; + self.cwd = cwd; + self.environment = environment; + self.context_key = key; } } @@ -342,17 +373,22 @@ impl JavaPicker { let refresh_generation = self.generation.load(Ordering::Relaxed); let generation = self.generation.clone(); let selected_paths = [Some(self.detected.clone()), self.current.clone()]; + let cwd = self.cwd.clone(); + let environment = self.environment.clone(); let discover = move || { - let mut installations = crate::instance::java::discover_installations(); + let mut installations = + crate::instance::java::discover_installations_in(&cwd, &environment); for path in selected_paths.into_iter().flatten() { if installations.iter().any(|installation| { same_executable(&installation.path.to_string_lossy(), &path) }) { continue; } - if let Some(installation) = - crate::instance::java::inspect_installation(Path::new(&path)) - { + if let Some(installation) = crate::instance::java::inspect_installation_in( + Path::new(&path), + &cwd, + &environment, + ) { installations.push(installation); } } @@ -363,8 +399,12 @@ impl JavaPicker { return; } if let Some(cache_path) = cache_path - && let Err(error) = - crate::instance::java::save_installation_cache(&cache_path, &installations) + && let Err(error) = crate::instance::java::save_installation_cache_in( + &cache_path, + &installations, + &cwd, + &environment, + ) { tracing::debug!("Could not cache Java installations: {error}"); } @@ -737,121 +777,6 @@ impl Default for GlfwPicker { } } -pub(crate) fn bundled_glfw_version(meta_dir: &Path, game_version: &str) -> Option { - let path = crate::storage::MetadataPaths::new(meta_dir) - .versions() - .join(game_version) - .join("meta.json"); - let profile: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; - profile - .get("libraries")? - .as_array()? - .iter() - .filter_map(|library| library.get("name")?.as_str()) - .find_map(|coordinate| { - let mut parts = coordinate.split(':'); - match (parts.next(), parts.next(), parts.next()) { - (Some("org.lwjgl"), Some("lwjgl-glfw"), Some(version)) => Some(version.to_owned()), - _ => None, - } - }) -} - -fn discover_glfw_installations() -> Vec { - let mut directories = Vec::::new(); - for variable in ["LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "PATH"] { - if let Some(value) = std::env::var_os(variable) { - directories.extend(std::env::split_paths(&value)); - } - } - directories.extend( - [ - "/usr/lib", - "/usr/lib64", - "/usr/local/lib", - "/lib", - "/lib64", - "/opt/homebrew/lib", - "/opt/local/lib", - ] - .into_iter() - .map(PathBuf::from), - ); - - let mut nested = Vec::new(); - for directory in &directories { - if let Ok(entries) = std::fs::read_dir(directory) { - nested.extend( - entries - .flatten() - .map(|entry| entry.path()) - .filter(|path| path.is_dir()), - ); - } - } - directories.extend(nested); - - let mut seen = BTreeSet::new(); - let mut installations = Vec::new(); - for directory in directories { - let Ok(entries) = std::fs::read_dir(directory) else { - continue; - }; - for path in entries.flatten().map(|entry| entry.path()) { - if !is_glfw_library(&path) { - continue; - } - let canonical = std::fs::canonicalize(&path).unwrap_or(path); - if seen.insert(canonical.clone()) { - installations.push(GlfwInstallation { - version: glfw_version_from_path(&canonical), - path: canonical, - }); - } - } - } - installations.sort_by(|left, right| left.path.cmp(&right.path)); - installations -} - -fn is_glfw_library(path: &Path) -> bool { - if !path.is_file() { - return false; - } - let Some(name) = path.file_name().and_then(|name| name.to_str()) else { - return false; - }; - is_glfw_library_name(name) -} - -fn is_glfw_library_name(name: &str) -> bool { - let name = name.to_ascii_lowercase(); - let versioned_so = name.strip_prefix("libglfw.so.").is_some_and(|version| { - version.split('.').all(|part| { - !part.is_empty() && part.chars().all(|character| character.is_ascii_digit()) - }) - }); - name == "libglfw.so" - || versioned_so - || name.starts_with("libglfw.") && name.ends_with(".dylib") - || name.starts_with("glfw") && name.ends_with(".dll") -} - -fn glfw_version_from_path(path: &Path) -> Option { - let name = path.file_name()?.to_str()?.to_ascii_lowercase(); - if let Some((_, suffix)) = name.rsplit_once(".so.") { - return (!suffix.is_empty()).then(|| suffix.to_owned()); - } - let stem = name - .strip_prefix("libglfw.") - .and_then(|name| name.strip_suffix(".dylib")) - .or_else(|| { - name.strip_prefix("glfw") - .and_then(|name| name.strip_suffix(".dll")) - })?; - (!stem.is_empty()).then(|| stem.trim_start_matches(['-', '.']).to_owned()) -} - fn same_executable(left: &str, right: &str) -> bool { if left == right { return true; @@ -995,76 +920,6 @@ pub(crate) fn settings_text_area(lines: Vec) -> TextArea<'static> { editor } -pub(crate) fn parse_tag_values(input: &str) -> Result, String> { - #[derive(Clone, Copy, PartialEq, Eq)] - enum Quote { - None, - Single, - Double, - } - - let mut values = Vec::new(); - let mut current = String::new(); - let mut quote = Quote::None; - let mut started = false; - let mut characters = input.chars().peekable(); - while let Some(character) = characters.next() { - match (quote, character) { - (Quote::None, character) if character.is_whitespace() => { - if started { - values.push(std::mem::take(&mut current)); - started = false; - } - } - (Quote::None, '\'') => { - quote = Quote::Single; - started = true; - } - (Quote::None, '"') => { - quote = Quote::Double; - started = true; - } - (Quote::Single, '\'') => quote = Quote::None, - (Quote::Double, '"') => quote = Quote::None, - (Quote::Double, '\\') if matches!(characters.peek(), Some('"' | '\\')) => { - current.push(characters.next().unwrap_or_default()); - started = true; - } - (_, character) => { - current.push(character); - started = true; - } - } - } - if quote != Quote::None { - return Err("Quoted value is missing its closing quote.".to_owned()); - } - if started { - values.push(current); - } - let mut seen = BTreeSet::new(); - values.retain(|value| seen.insert(value.clone())); - Ok(values) -} - -pub(crate) fn format_tag_values(values: &[String]) -> String { - values - .iter() - .map(|value| { - if !value.is_empty() - && !value - .chars() - .any(|character| character.is_whitespace() || matches!(character, '\'' | '"')) - { - value.clone() - } else { - format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) - } - }) - .collect::>() - .join(" ") -} - pub(crate) fn parse_environment(value: &str) -> Result, String> { let mut environment = BTreeMap::new(); for assignment in parse_tag_values(value)? { @@ -1118,7 +973,7 @@ pub(crate) fn tagged_value_lines( let mut spans = prefix; let mut used = 0usize; for value in values { - let badge_width = value.chars().count() + 2; + let badge_width = Span::raw(value).width() + 2; let separator = usize::from(used > 0); if used > 0 && used + separator + badge_width > available { lines.push(Line::from(spans)); @@ -1147,22 +1002,7 @@ pub(crate) fn tagged_value_lines( } pub(crate) fn tagged_row_count(values: &[String], width: u16) -> usize { - if values.is_empty() { - return 1; - } - let available = width.saturating_sub(20) as usize; - let mut rows = 1; - let mut used = 0usize; - for value in values { - let badge_width = value.chars().count() + 2; - let separator = usize::from(used > 0); - if used > 0 && used + separator + badge_width > available { - rows += 1; - used = 0; - } - used += usize::from(used > 0) + badge_width; - } - rows + tagged_value_lines(Vec::new(), false, false, values, "", width).len() } pub(crate) fn auto_label() -> Span<'static> { @@ -1303,6 +1143,7 @@ pub(crate) fn resolution_items( #[cfg(test)] mod tests { use super::*; + use crate::config::settings::format_tag_values; #[test] fn memory_steps_move_and_clamp() { @@ -1387,7 +1228,12 @@ mod tests { let cache = temp.path().join("cache/java/installations.json"); std::fs::create_dir_all(cache.parent().unwrap()).unwrap(); std::fs::write(&cache, "[]").unwrap(); - let mut picker = JavaPicker::with_cache("/auto/java".to_owned(), Some(cache.clone())); + let mut picker = JavaPicker::with_cache( + "/auto/java".to_owned(), + Some(cache.clone()), + temp.path().to_owned(), + BTreeMap::new(), + ); *picker.load.lock().unwrap() = LoadState::Loaded(vec![JavaInstallation { path: "/cached/java".into(), version: Some("21".to_owned()), @@ -1401,6 +1247,48 @@ mod tests { assert!(matches!(*picker.load.lock().unwrap(), LoadState::Idle)); } + #[test] + fn java_picker_cache_and_workers_are_bound_to_the_captured_context() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("java"); + std::fs::write(&path, b"java").unwrap(); + let cache = temp.path().join("installations.json"); + let environment = BTreeMap::from([("JAVA_TEST_CONTEXT".to_owned(), "first".to_owned())]); + let installations = vec![JavaInstallation { + path: path.clone(), + version: Some("21".to_owned()), + }]; + crate::instance::java::save_installation_cache_in( + &cache, + &installations, + temp.path(), + &environment, + ) + .unwrap(); + let detected = path.to_string_lossy().into_owned(); + let mut picker = JavaPicker::with_cache( + detected.clone(), + Some(cache.clone()), + temp.path().to_owned(), + environment.clone(), + ); + assert!( + matches!(&*picker.load.lock().unwrap(), LoadState::Loaded(found) if *found == installations) + ); + picker.refresh_started = true; + let generation = picker.generation.load(Ordering::Relaxed); + picker.set_context(detected.clone(), temp.path().to_owned(), environment); + assert_eq!(picker.generation.load(Ordering::Relaxed), generation); + let changed = BTreeMap::from([("JAVA_TEST_CONTEXT".to_owned(), "second".to_owned())]); + picker.set_context(detected, temp.path().join("other"), changed.clone()); + assert_eq!(picker.generation.load(Ordering::Relaxed), generation + 1); + assert!(!picker.refresh_started); + assert!(matches!(*picker.load.lock().unwrap(), LoadState::Idle)); + assert!(!cache.exists()); + assert_eq!(picker.cwd, temp.path().join("other")); + assert_eq!(picker.environment, changed); + } + #[test] fn java_title_is_minimal_and_uses_the_major_version() { let picker = JavaPicker::with_auto_path("/opt/jdk-25/bin/java".to_owned()); @@ -1483,7 +1371,7 @@ mod tests { .unwrap(); assert_eq!( - bundled_glfw_version(temp.path(), "1.21.1").as_deref(), + crate::instance::glfw::bundled_glfw_version(temp.path(), "1.21.1").as_deref(), Some("3.3.3") ); let mut picker = GlfwPicker::with_bundled_version(Some("3.3.3".to_owned())); @@ -1495,19 +1383,6 @@ mod tests { ); } - #[test] - fn glfw_library_names_are_recognized() { - assert!(is_glfw_library_name("libglfw.so.3")); - assert!(is_glfw_library_name("libglfw.3.dylib")); - assert!(is_glfw_library_name("glfw3.dll")); - assert!(!is_glfw_library_name("libglfw.so.backup")); - assert!(!is_glfw_library_name("libGL.so")); - assert_eq!( - glfw_version_from_path(Path::new("/usr/lib/libglfw.so.3.4")).as_deref(), - Some("3.4") - ); - } - #[test] fn settings_text_input_deletes_the_previous_word() { let mut input = TextArea::from(["one two"]); @@ -1538,10 +1413,10 @@ mod tests { } #[test] - fn tag_values_drop_exact_duplicates_without_reordering() { + fn tag_values_preserve_repeated_options_and_their_operands() { assert_eq!( - parse_tag_values("-Xmx2G '-Dlabel=hello world' -Xmx2G").unwrap(), - ["-Xmx2G", "-Dlabel=hello world"] + parse_tag_values("--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED").unwrap(), + ["--add-opens", "java.base/java.lang=ALL-UNNAMED", "--add-opens", "java.base/java.util=ALL-UNNAMED"] ); } @@ -1560,6 +1435,7 @@ mod tests { ); assert!(parse_environment("=missing").is_err()); assert!(parse_environment("KEY=one KEY=two").is_err()); + assert!(parse_environment("KEY=one KEY=one").is_err()); } #[test] diff --git a/src/tui/widgets/search.rs b/src/tui/widgets/search.rs index 4b54685..3f93e7e 100644 --- a/src/tui/widgets/search.rs +++ b/src/tui/widgets/search.rs @@ -57,12 +57,21 @@ impl SearchState { let query_lower = self.query.to_lowercase(); let text_lower = text.to_lowercase(); + let mut original_ranges = Vec::with_capacity(text_lower.len()); + for (start, character) in text.char_indices() { + let lowercase_bytes = character.to_lowercase().map(char::len_utf8).sum::(); + original_ranges.extend(std::iter::repeat_n( + (start, start + character.len_utf8()), + lowercase_bytes, + )); + } let mut spans = Vec::new(); let mut last = 0; - for (start, _) in text_lower.match_indices(&query_lower) { - let end = start + query_lower.len(); - if !text.is_char_boundary(start) || !text.is_char_boundary(end) { + for (lower_start, _) in text_lower.match_indices(&query_lower) { + let start = original_ranges[lower_start].0; + let end = original_ranges[lower_start + query_lower.len() - 1].1; + if start < last { continue; } if start > last { diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs index 0458e6e..2e3baa8 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -44,14 +44,16 @@ pub struct SettingsState { pub add_mode: AddMode, pub pane: SettingsPane, meta_dir: PathBuf, + instances_dir: PathBuf, active_profile: Option, instance_name: Option, java_key: Option, java_label: String, + pending_java: std::sync::Arc>>, } impl SettingsState { - pub fn new(meta_dir: PathBuf) -> Self { + pub fn new(meta_dir: PathBuf, instances_dir: PathBuf) -> Self { let profiles = crate::instance::config_sync::list_profiles(&meta_dir).unwrap_or_else(|e| { tracing::warn!("Failed to load config sync profiles: {}", e); Vec::new() @@ -62,10 +64,12 @@ impl SettingsState { add_mode: AddMode::None, pane: SettingsPane::Profile, meta_dir, + instances_dir, active_profile: None, instance_name: None, java_key: None, java_label: "unknown".to_string(), + pending_java: Default::default(), }; state.select_active(); state @@ -116,15 +120,53 @@ impl SettingsState { self.select_active(); } - let java_key = instance.map(java_path_key); + let context = instance.map(|instance| { + let settings = SETTINGS.read(); + let cwd = self + .instances_dir + .join(&instance.name) + .join(crate::storage::MINECRAFT_DIR_NAME); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &instance.environment, + ); + let java = crate::instance::java::resolve_java_path_in( + instance + .java_path + .as_deref() + .filter(|path| !path.is_empty()) + .or(settings.paths.effective_java_path()), + &cwd, + &environment, + ); + (java, cwd, environment) + }); + let java_key = context + .as_ref() + .map(|(java, cwd, environment)| java_path_key(java, cwd, environment)); if self.java_key != java_key { - let java_source = instance.map(effective_java_path); - self.java_label = java_source - .as_deref() - .map(java_version_label) - .unwrap_or_else(|| "unknown".to_string()); + self.pending_java = Default::default(); + self.java_label = "unknown".to_owned(); + if let Some((java, cwd, environment)) = context { + let pending = self.pending_java.clone(); + std::thread::spawn(move || { + let label = java_version_label(&java, &cwd, &environment); + *pending + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(label); + crate::feedback::request_redraw(); + }); + } self.java_key = java_key; } + if let Some(label) = self + .pending_java + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + { + self.java_label = label; + } } } @@ -137,38 +179,25 @@ fn add_active_profile(profiles: &mut Vec, active_profile: Option<&str>) } } -fn java_path_key(instance: &InstanceConfig) -> String { - instance - .java_path - .as_deref() - .filter(|path| !path.is_empty()) - .map(str::to_owned) - .or_else(|| { - SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - }) - .unwrap_or_else(|| "".to_owned()) +fn java_path_key( + java: &str, + cwd: &Path, + environment: &std::collections::BTreeMap, +) -> String { + format!( + "{java}:{}", + crate::instance::java::probe_context_key(cwd, environment) + ) } -fn effective_java_path(instance: &InstanceConfig) -> String { - instance - .java_path - .clone() - .or_else(|| { - SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - }) - .unwrap_or_else(crate::instance::java::detect_java_path) -} - -fn java_version_label(java_path: &str) -> String { - let Some(version) = crate::instance::java::java_version(Path::new(java_path)) else { +fn java_version_label( + java_path: &str, + cwd: &Path, + environment: &std::collections::BTreeMap, +) -> String { + let Some(version) = + crate::instance::java::java_version_in(Path::new(java_path), cwd, environment) + else { return "unknown".to_string(); }; let major = crate::instance::java::java_major(Some(&version)); @@ -445,15 +474,9 @@ fn render_add_profile_popup(frame: &mut Frame, name: &str) { } fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect { - let area = frame.area(); - let x = area.x + (area.width.saturating_sub(width)) / 2; - let y = area.y + (area.height.saturating_sub(height)) / 2; - Rect { - x, - y, - width: width.min(area.width), - height: height.min(area.height), - } + frame + .area() + .centered(Constraint::Length(width), Constraint::Length(height)) } pub enum SettingsAction {