fix: reload editor saves and reject stale TUI actions
This commit is contained in:
1 parent
eb53c7164e
commit
9cd454cee2
33 files changed
+2297
-638
No files matched your search
@@ -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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn bundled_glfw_version(meta_dir: &Path, game_version: &str) -> Option<String> {
|
||||||
|
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<GlfwInstallation> {
|
||||||
|
discover_in(&discovery_directories(), std::env::consts::OS)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discovery_directories() -> Vec<PathBuf> {
|
||||||
|
let mut directories = Vec::<PathBuf>::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<GlfwInstallation> {
|
||||||
|
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<String> {
|
||||||
|
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))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
pub mod config_sync;
|
pub mod config_sync;
|
||||||
pub mod content;
|
pub mod content;
|
||||||
pub mod desktop;
|
pub mod desktop;
|
||||||
|
pub(crate) mod glfw;
|
||||||
pub mod import;
|
pub mod import;
|
||||||
pub mod java;
|
pub mod java;
|
||||||
pub mod launch;
|
pub mod launch;
|
||||||
|
|||||||
+6
-1
@@ -54,6 +54,7 @@ pub struct App {
|
|||||||
pub(super) throbber_tick: u8,
|
pub(super) throbber_tick: u8,
|
||||||
pub(super) error_effects: HashMap<u64, ErrorEffectState>,
|
pub(super) error_effects: HashMap<u64, ErrorEffectState>,
|
||||||
pub(super) pending_editor: Option<std::path::PathBuf>,
|
pub(super) pending_editor: Option<std::path::PathBuf>,
|
||||||
|
pub(super) edited_config_watches: Vec<super::event::EditedConfigWatch>,
|
||||||
pub(super) reconciliation_for: Option<(String, chrono::DateTime<chrono::Utc>)>,
|
pub(super) reconciliation_for: Option<(String, chrono::DateTime<chrono::Utc>)>,
|
||||||
pub(super) content_manifest: Option<(String, crate::instance::ContentManifest)>,
|
pub(super) content_manifest: Option<(String, crate::instance::ContentManifest)>,
|
||||||
pub(super) content_update_snapshot:
|
pub(super) content_update_snapshot:
|
||||||
@@ -129,7 +130,10 @@ impl App {
|
|||||||
crate::instance::import::refresh::recover_interrupted(&instances_dir);
|
crate::instance::import::refresh::recover_interrupted(&instances_dir);
|
||||||
|
|
||||||
let manager = InstanceManager::new(instances_dir, meta_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();
|
let instances = manager.load_all();
|
||||||
instances::spawn_modpack_update_checks(&instances);
|
instances::spawn_modpack_update_checks(&instances);
|
||||||
let instances_state = instances::State::with_instances(instances);
|
let instances_state = instances::State::with_instances(instances);
|
||||||
@@ -197,6 +201,7 @@ impl App {
|
|||||||
throbber_tick: 0,
|
throbber_tick: 0,
|
||||||
error_effects: HashMap::new(),
|
error_effects: HashMap::new(),
|
||||||
pending_editor: None,
|
pending_editor: None,
|
||||||
|
edited_config_watches: Vec::new(),
|
||||||
reconciliation_for: None,
|
reconciliation_for: None,
|
||||||
content_manifest: None,
|
content_manifest: None,
|
||||||
content_update_snapshot: None,
|
content_update_snapshot: None,
|
||||||
|
|||||||
+414
-46
@@ -2,7 +2,7 @@
|
|||||||
// SPDX-License-Identifier: GPL-3.0-only
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use color_eyre::eyre::Context;
|
use color_eyre::eyre::Context;
|
||||||
use crossterm::event::{self, Event};
|
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
buffer::{Buffer, CellDiffOption},
|
buffer::{Buffer, CellDiffOption},
|
||||||
crossterm::event::KeyEventKind,
|
crossterm::event::KeyEventKind,
|
||||||
@@ -29,6 +29,7 @@ impl App {
|
|||||||
let mut image_redraw_marker = false;
|
let mut image_redraw_marker = false;
|
||||||
while !self.exit {
|
while !self.exit {
|
||||||
let redraw_requested = crate::feedback::take_redraw_request();
|
let redraw_requested = crate::feedback::take_redraw_request();
|
||||||
|
let edited_config_changed = self.drain_edited_configs();
|
||||||
if let Some(params) = new_instance::take_result() {
|
if let Some(params) = new_instance::take_result() {
|
||||||
self.spawn_create(params);
|
self.spawn_create(params);
|
||||||
}
|
}
|
||||||
@@ -179,6 +180,7 @@ impl App {
|
|||||||
let continuously_animated = spinner_active || error_buffer::has_errors();
|
let continuously_animated = spinner_active || error_buffer::has_errors();
|
||||||
let safety_refresh = last_draw.elapsed() >= Duration::from_secs(1);
|
let safety_refresh = last_draw.elapsed() >= Duration::from_secs(1);
|
||||||
if input_changed
|
if input_changed
|
||||||
|
|| edited_config_changed
|
||||||
|| continuously_animated
|
|| continuously_animated
|
||||||
|| safety_refresh
|
|| safety_refresh
|
||||||
|| redraw_requested
|
|| redraw_requested
|
||||||
@@ -198,10 +200,8 @@ impl App {
|
|||||||
drawn_image_skips = image_skips;
|
drawn_image_skips = image_skips;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(path) = self.pending_editor.take()
|
if let Some(path) = self.pending_editor.take() {
|
||||||
&& Self::run_editor(terminal, &path)
|
self.run_editor(terminal, &path);
|
||||||
{
|
|
||||||
self.reload_edited_config(&path);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -259,15 +259,13 @@ impl App {
|
|||||||
crate::instance::ContentManifest::update(&paths.content_manifest(), |manifest| {
|
crate::instance::ContentManifest::update(&paths.content_manifest(), |manifest| {
|
||||||
let mut complete = true;
|
let mut complete = true;
|
||||||
for toggle in toggles {
|
for toggle in toggles {
|
||||||
let Ok(old_path) = toggle.old_path.strip_prefix(&minecraft_dir) else {
|
complete &= crate::instance::content::local::record_toggle(
|
||||||
complete = false;
|
manifest,
|
||||||
continue;
|
&minecraft_dir,
|
||||||
};
|
&toggle.old_path,
|
||||||
let Ok(new_path) = toggle.new_path.strip_prefix(&minecraft_dir) else {
|
&toggle.new_path,
|
||||||
complete = false;
|
toggle.enabled,
|
||||||
continue;
|
)?;
|
||||||
};
|
|
||||||
complete &= manifest.rename_record(old_path, new_path, toggle.enabled);
|
|
||||||
}
|
}
|
||||||
Ok((manifest.clone(), complete))
|
Ok((manifest.clone(), complete))
|
||||||
});
|
});
|
||||||
@@ -358,16 +356,33 @@ impl App {
|
|||||||
}
|
}
|
||||||
Err(_) => return,
|
Err(_) => return,
|
||||||
};
|
};
|
||||||
let Some(result) = result else {
|
let Some(mut result) = result else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
self.reconciliation_for = Some((result.instance_name.clone(), result.instance_created));
|
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!(
|
tracing::warn!(
|
||||||
"Content reconciliation for {} was incomplete: {}",
|
"Content reconciliation for {} was incomplete: {}",
|
||||||
result.instance_name,
|
result.instance_name,
|
||||||
error
|
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(
|
let minecraft_dir = crate::storage::InstancePaths::new(
|
||||||
self.instance_manager.instances_dir.join(&selected.name),
|
self.instance_manager.instances_dir.join(&selected.name),
|
||||||
@@ -551,16 +566,7 @@ impl App {
|
|||||||
fn handle_events(&mut self) -> color_eyre::Result<bool> {
|
fn handle_events(&mut self) -> color_eyre::Result<bool> {
|
||||||
match crossterm::event::poll(Duration::from_millis(16)) {
|
match crossterm::event::poll(Duration::from_millis(16)) {
|
||||||
Ok(true) => match event::read() {
|
Ok(true) => match event::read() {
|
||||||
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => {
|
Ok(event) => self.dispatch_event(event),
|
||||||
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),
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!("Event read error: {}", e);
|
tracing::error!("Event read error: {}", e);
|
||||||
Ok(false)
|
Ok(false)
|
||||||
@@ -574,6 +580,155 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn dispatch_event(&mut self, event: Event) -> color_eyre::Result<bool> {
|
||||||
|
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) {
|
fn spawn_create(&self, params: new_instance::WizardParams) {
|
||||||
let instances_dir = self.instance_manager.instances_dir.clone();
|
let instances_dir = self.instance_manager.instances_dir.clone();
|
||||||
let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
|
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)
|
// Terminal editors need the normal screen and input mode while they run.
|
||||||
// gotta leave the alternate screen and restore it after, otherwise the
|
fn run_editor(&mut self, terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) {
|
||||||
// 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 {
|
|
||||||
use ratatui::crossterm::{
|
use ratatui::crossterm::{
|
||||||
ExecutableCommand,
|
ExecutableCommand,
|
||||||
event::{DisableMouseCapture, EnableMouseCapture},
|
event::{DisableMouseCapture, EnableMouseCapture},
|
||||||
@@ -710,15 +863,28 @@ impl App {
|
|||||||
let editor = std::env::var("EDITOR")
|
let editor = std::env::var("EDITOR")
|
||||||
.or_else(|_| std::env::var("VISUAL"))
|
.or_else(|_| std::env::var("VISUAL"))
|
||||||
.unwrap_or_else(|_| default_editor.to_owned());
|
.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 {
|
let Some((program, args)) = parts.split_first() else {
|
||||||
tracing::error!("Editor command is empty");
|
tracing::error!("Editor command is empty");
|
||||||
return false;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let is_tui_editor = editor_runs_in_terminal(program);
|
let is_tui_editor = editor_runs_in_terminal(program);
|
||||||
|
|
||||||
if is_tui_editor {
|
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(DisableMouseCapture);
|
||||||
let _ = stdout().execute(LeaveAlternateScreen);
|
let _ = stdout().execute(LeaveAlternateScreen);
|
||||||
let _ = disable_raw_mode();
|
let _ = disable_raw_mode();
|
||||||
@@ -738,24 +904,62 @@ impl App {
|
|||||||
|
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
tracing::error!("Failed to open editor: {}", e);
|
tracing::error!("Failed to open editor: {}", e);
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
true
|
|
||||||
} else {
|
} else {
|
||||||
if let Err(e) = std::process::Command::new(program)
|
if let Err(e) = self.launch_gui_editor(
|
||||||
.args(args)
|
std::process::Command::new(program).args(args).arg(path),
|
||||||
.arg(path)
|
path,
|
||||||
.stdout(std::process::Stdio::null())
|
) {
|
||||||
.stderr(std::process::Stdio::null())
|
|
||||||
.spawn()
|
|
||||||
{
|
|
||||||
tracing::error!("Failed to open editor: {}", e);
|
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<std::thread::JoinHandle<()>> {
|
||||||
|
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::<Vec<_>>();
|
||||||
|
for path in &changed {
|
||||||
|
self.reload_edited_config(path);
|
||||||
|
}
|
||||||
|
!changed.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
fn reload_edited_config(&mut self, path: &std::path::Path) {
|
fn reload_edited_config(&mut self, path: &std::path::Path) {
|
||||||
match path.file_name().and_then(|name| name.to_str()) {
|
match path.file_name().and_then(|name| name.to_str()) {
|
||||||
Some("config.toml") => {
|
Some("config.toml") => {
|
||||||
@@ -1021,6 +1225,120 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) struct EditedConfigWatch {
|
||||||
|
path: std::path::PathBuf,
|
||||||
|
contents: Option<Vec<u8>>,
|
||||||
|
events: std::sync::mpsc::Receiver<notify::Result<notify::Event>>,
|
||||||
|
pending: Option<std::time::Instant>,
|
||||||
|
read_error: Option<std::io::ErrorKind>,
|
||||||
|
_watcher: notify::RecommendedWatcher,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EditedConfigWatch {
|
||||||
|
fn new(path: std::path::PathBuf) -> color_eyre::Result<Self> {
|
||||||
|
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(
|
async fn apply_instance_settings_update(
|
||||||
manager: &InstanceManager,
|
manager: &InstanceManager,
|
||||||
previous: &crate::instance::InstanceConfig,
|
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<Vec<String>> {
|
||||||
if std::path::Path::new(editor).is_file() {
|
if std::path::Path::new(editor).is_file() {
|
||||||
vec![editor]
|
Ok(vec![editor.to_owned()])
|
||||||
} else {
|
} else {
|
||||||
editor.split_whitespace().collect()
|
split_editor_command(editor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn split_editor_command(editor: &str) -> std::io::Result<Vec<String>> {
|
||||||
|
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<Vec<String>> {
|
||||||
|
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::<Vec<_>>();
|
||||||
|
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)]
|
#[cfg(test)]
|
||||||
#[path = "tests/event.rs"]
|
#[path = "tests/event.rs"]
|
||||||
mod tests;
|
mod tests;
|
||||||
+114
-166
@@ -50,10 +50,11 @@ impl App {
|
|||||||
let link = self
|
let link = self
|
||||||
.active_discovery_state_mut()
|
.active_discovery_state_mut()
|
||||||
.and_then(|state| state.project_link_at(event.column, event.row));
|
.and_then(|state| state.project_link_at(event.column, event.row));
|
||||||
if let Some(link) = link
|
if let Some(link) = link {
|
||||||
&& let Err(error) = open::that_detached(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 {link}: {error}");
|
tracing::warn!("Failed to open project link: {error}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,14 +106,29 @@ impl App {
|
|||||||
.map(|(_, candidate)| candidate.clone())
|
.map(|(_, candidate)| candidate.clone())
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
if let Some(project) = project
|
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),
|
self.instance_manager.instances_dir.join(instance_name),
|
||||||
)
|
);
|
||||||
.content_manifest();
|
let manifest_path = paths.content_manifest();
|
||||||
let updated =
|
let expected = cached.record(&relative_path).cloned();
|
||||||
crate::instance::ContentManifest::update(&manifest_path, |manifest| {
|
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
|
if let Some(record) = manifest
|
||||||
.files
|
.files
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
@@ -123,10 +139,18 @@ impl App {
|
|||||||
record.provider_aliases = aliases;
|
record.provider_aliases = aliases;
|
||||||
}
|
}
|
||||||
Ok(manifest.clone())
|
Ok(manifest.clone())
|
||||||
})?;
|
},
|
||||||
self.content_manifest = Some((instance_name.clone(), updated));
|
);
|
||||||
self.provider_conflict = None;
|
match updated {
|
||||||
self.reconciliation_for = None;
|
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 => {
|
KeyCode::Esc => {
|
||||||
@@ -270,11 +294,9 @@ impl App {
|
|||||||
FocusedArea::Settings
|
FocusedArea::Settings
|
||||||
}
|
}
|
||||||
Some(confirm_popup::ConfirmTarget::Content { name, path, .. }) => {
|
Some(confirm_popup::ConfirmTarget::Content { name, path, .. }) => {
|
||||||
let orphaned = self.orphan_dependencies_after_removing(&path);
|
match self.delete_content_path(&path, false) {
|
||||||
match delete_content_path(&path) {
|
Ok(orphaned) => {
|
||||||
Ok(()) => {
|
|
||||||
self.remove_content_path_from_states(&path);
|
self.remove_content_path_from_states(&path);
|
||||||
self.remove_content_path_from_manifest(&path);
|
|
||||||
if !orphaned.is_empty() {
|
if !orphaned.is_empty() {
|
||||||
confirm_popup::set_pending_orphan_dependencies(orphaned);
|
confirm_popup::set_pending_orphan_dependencies(orphaned);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -288,10 +310,9 @@ impl App {
|
|||||||
}
|
}
|
||||||
Some(confirm_popup::ConfirmTarget::OrphanDependencies { paths }) => {
|
Some(confirm_popup::ConfirmTarget::OrphanDependencies { paths }) => {
|
||||||
for path in paths {
|
for path in paths {
|
||||||
match delete_content_path(&path) {
|
match self.delete_content_path(&path, true) {
|
||||||
Ok(()) => {
|
Ok(_) => {
|
||||||
self.remove_content_path_from_states(&path);
|
self.remove_content_path_from_states(&path);
|
||||||
self.remove_content_path_from_manifest(&path);
|
|
||||||
}
|
}
|
||||||
Err(error) => tracing::error!(
|
Err(error) => tracing::error!(
|
||||||
"Failed to remove unused dependency '{}': {}",
|
"Failed to remove unused dependency '{}': {}",
|
||||||
@@ -534,16 +555,8 @@ impl App {
|
|||||||
if let Some(state) = self.active_discovery_state_mut() {
|
if let Some(state) = self.active_discovery_state_mut() {
|
||||||
state.begin_world_selection(worlds);
|
state.begin_world_selection(worlds);
|
||||||
}
|
}
|
||||||
} else if matches!(
|
} else {
|
||||||
kind,
|
|
||||||
Some(
|
|
||||||
crate::instance::ContentKind::Mod
|
|
||||||
| crate::instance::ContentKind::DataPack
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
self.spawn_active_discovery_dependencies();
|
self.spawn_active_discovery_dependencies();
|
||||||
} else if let Some(state) = self.active_discovery_state_mut() {
|
|
||||||
state.begin_confirmation();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -632,7 +645,10 @@ impl App {
|
|||||||
}
|
}
|
||||||
return Ok(());
|
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
|
self.open_world_datapacks = self
|
||||||
.worlds_state
|
.worlds_state
|
||||||
.selected_entry()
|
.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 {
|
match self.content_tab {
|
||||||
widgets::content::ContentTab::Mods => Some(&self.mods_discovery_state),
|
widgets::content::ContentTab::Mods => Some(&self.mods_discovery_state),
|
||||||
widgets::content::ContentTab::ResourcePacks => {
|
widgets::content::ContentTab::ResourcePacks => {
|
||||||
@@ -1917,96 +1935,25 @@ impl App {
|
|||||||
"Invalid datapack target world".to_owned(),
|
"Invalid datapack target world".to_owned(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
tokio::fs::create_dir_all(&destination)
|
|
||||||
.await
|
|
||||||
.map_err(crate::net::NetError::from)?;
|
|
||||||
let registry =
|
let registry =
|
||||||
crate::instance::content::provider::ProviderRegistry::configured(client);
|
crate::instance::content::provider::ProviderRegistry::configured(client);
|
||||||
if let Some(plan) = &request.dependency_plan {
|
let plan = request.dependency_plan.as_ref().ok_or_else(|| {
|
||||||
let installed = crate::instance::content::dependencies::install(
|
crate::net::NetError::Parse(
|
||||||
®istry,
|
"Installation has no resolved dependency plan".to_owned(),
|
||||||
&manifest_path,
|
|
||||||
&minecraft_dir,
|
|
||||||
plan,
|
|
||||||
)
|
)
|
||||||
.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
|
let installed = crate::instance::content::dependencies::install(
|
||||||
.download_version(
|
®istry,
|
||||||
&request.version,
|
&manifest_path,
|
||||||
&destination,
|
&minecraft_dir,
|
||||||
request.installed_path.as_deref(),
|
plan,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
let (path, skipped) = match outcome {
|
|
||||||
crate::net::modrinth::DownloadOutcome::Downloaded(path) => (path, false),
|
|
||||||
crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => (path, true),
|
|
||||||
};
|
|
||||||
let replaced = request.installed_path.is_some() && !skipped;
|
|
||||||
let 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)?;
|
|
||||||
}
|
|
||||||
Ok::<_, crate::net::NetError>(widgets::content::discovery::InstallCompletion {
|
Ok::<_, crate::net::NetError>(widgets::content::discovery::InstallCompletion {
|
||||||
path,
|
path: installed.root_path,
|
||||||
replaced,
|
replaced: installed.replaced,
|
||||||
skipped,
|
skipped: installed.skipped,
|
||||||
orphaned_dependencies: Vec::new(),
|
orphaned_dependencies: installed.orphaned_dependencies,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
@@ -2184,19 +2131,44 @@ impl App {
|
|||||||
self.focused = FocusedArea::ConfirmDelete;
|
self.focused = FocusedArea::ConfirmDelete;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn orphan_dependencies_after_removing(
|
fn delete_content_path(
|
||||||
&self,
|
&mut self,
|
||||||
path: &std::path::Path,
|
path: &std::path::Path,
|
||||||
) -> Vec<std::path::PathBuf> {
|
orphan_only: bool,
|
||||||
self.content_manifest_for_path(path)
|
) -> std::io::Result<Vec<std::path::PathBuf>> {
|
||||||
.map(|(manifest, relative_path, minecraft_dir)| {
|
let instance = self
|
||||||
manifest
|
.instances_state
|
||||||
.orphaned_dependencies_after_removing(&relative_path)
|
.selected_instance()
|
||||||
.into_iter()
|
.ok_or_else(|| std::io::Error::other("No instance is selected"))?;
|
||||||
.map(|relative| minecraft_dir.join(relative))
|
let name = instance.name.clone();
|
||||||
.collect()
|
let paths =
|
||||||
})
|
crate::storage::InstancePaths::new(self.instance_manager.instances_dir.join(&name));
|
||||||
.unwrap_or_default()
|
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::<Vec<_>>();
|
||||||
|
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(
|
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) {
|
fn open_instance_settings(&mut self, return_focus: FocusedArea) {
|
||||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||||
return;
|
return;
|
||||||
@@ -2284,6 +2225,10 @@ impl App {
|
|||||||
let mut state = widgets::popups::instance_settings::State::with_accounts(
|
let mut state = widgets::popups::instance_settings::State::with_accounts(
|
||||||
&instance,
|
&instance,
|
||||||
&self.instance_manager.meta_dir,
|
&self.instance_manager.meta_dir,
|
||||||
|
&crate::storage::InstancePaths::new(
|
||||||
|
self.instance_manager.instances_dir.join(&instance.name),
|
||||||
|
)
|
||||||
|
.minecraft(),
|
||||||
self.account_state.store.accounts.clone(),
|
self.account_state.store.accounts.clone(),
|
||||||
);
|
);
|
||||||
if self
|
if self
|
||||||
@@ -2440,11 +2385,14 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn delete_content_path(path: &std::path::Path) -> std::io::Result<()> {
|
pub(super) fn project_link_url(link: &str) -> std::io::Result<reqwest::Url> {
|
||||||
match std::fs::metadata(path) {
|
let url = reqwest::Url::parse(link)
|
||||||
Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(path),
|
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?;
|
||||||
Ok(_) => std::fs::remove_file(path),
|
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
return Err(std::io::Error::new(
|
||||||
Err(e) => Err(e),
|
std::io::ErrorKind::InvalidInput,
|
||||||
|
"Project links must use HTTP or HTTPS",
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
Ok(url)
|
||||||
}
|
}
|
||||||
+5
-18
@@ -15,7 +15,7 @@ use tracing_subscriber::{EnvFilter, Layer};
|
|||||||
|
|
||||||
use std::sync::LazyLock;
|
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 MINECRAFT_LOG_TARGET: &str = "mc_instance";
|
||||||
const DEFAULT_FILE_FILTER: &str = "warn,rmcl=trace";
|
const DEFAULT_FILE_FILTER: &str = "warn,rmcl=trace";
|
||||||
@@ -79,11 +79,9 @@ pub fn init() -> WorkerGuard {
|
|||||||
should_record_app_log(metadata.target(), *metadata.level())
|
should_record_app_log(metadata.target(), *metadata.level())
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
.with(
|
.with(StatusLayer.with_filter(filter_fn(|metadata| {
|
||||||
StatusLayer::new(error_buffer::ERROR_EVENTS.clone()).with_filter(filter_fn(
|
should_record_app_log(metadata.target(), *metadata.level())
|
||||||
|metadata| should_record_app_log(metadata.target(), *metadata.level()),
|
})))
|
||||||
)),
|
|
||||||
)
|
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
guard
|
guard
|
||||||
@@ -113,12 +111,6 @@ fn open_log_writer(log_dir: &Path) -> (NonBlocking, WorkerGuard) {
|
|||||||
|
|
||||||
struct StatusLayer;
|
struct StatusLayer;
|
||||||
|
|
||||||
impl StatusLayer {
|
|
||||||
fn new(_events: Arc<Mutex<std::collections::VecDeque<ErrorEvent>>>) -> Self {
|
|
||||||
Self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S: Subscriber> Layer<S> for StatusLayer {
|
impl<S: Subscriber> Layer<S> for StatusLayer {
|
||||||
fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
|
fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
|
||||||
let level = *event.metadata().level();
|
let level = *event.metadata().level();
|
||||||
@@ -140,12 +132,7 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if level <= Level::WARN && should_record_app_log(target, level) {
|
if level <= Level::WARN && should_record_app_log(target, level) {
|
||||||
error_buffer::push_error(ErrorEvent {
|
error_buffer::push_message(level, visitor.message);
|
||||||
id: 0,
|
|
||||||
level,
|
|
||||||
message: visitor.message,
|
|
||||||
pushed_at: std::time::Instant::now(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+580
-1
@@ -4,6 +4,555 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::tui::tests::harness::UiHarness;
|
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]
|
#[test]
|
||||||
fn edited_instance_config_reloads_into_the_ui() {
|
fn edited_instance_config_reloads_into_the_ui() {
|
||||||
let mut ui = UiHarness::new();
|
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("/usr/bin/nvim"));
|
||||||
assert!(editor_runs_in_terminal("nano"));
|
assert!(editor_runs_in_terminal("nano"));
|
||||||
assert!(!editor_runs_in_terminal("/usr/bin/code"));
|
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]
|
#[test]
|
||||||
|
|||||||
+109
-28
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
|
|||||||
use super::harness::UiHarness;
|
use super::harness::UiHarness;
|
||||||
use crate::instance::content::entry::ContentEntry;
|
use crate::instance::content::entry::ContentEntry;
|
||||||
use crate::instance::{
|
use crate::instance::{
|
||||||
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
|
ContentFileRecord, ContentKind, ContentManifest, ProviderProject, Resolution,
|
||||||
};
|
};
|
||||||
use crate::net::modrinth::DiscoveryProject;
|
use crate::net::modrinth::DiscoveryProject;
|
||||||
use crate::tui::{
|
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]
|
#[test]
|
||||||
fn global_navigation_returns_from_log_overlay() {
|
fn global_navigation_returns_from_log_overlay() {
|
||||||
let mut ui = UiHarness::new();
|
let mut ui = UiHarness::new();
|
||||||
@@ -72,13 +88,13 @@ fn installed_version_action_requires_selected_provider_match() {
|
|||||||
ui.add_instance("Unmatched");
|
ui.add_instance("Unmatched");
|
||||||
ui.app.focused = FocusedArea::Content;
|
ui.app.focused = FocusedArea::Content;
|
||||||
ui.app.content_tab = ContentTab::Mods;
|
ui.app.content_tab = ContentTab::Mods;
|
||||||
let path = ui
|
let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Unmatched")).minecraft();
|
||||||
.instance_path("Unmatched")
|
let path = minecraft.join("mods/unknown.jar");
|
||||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
.join("mods/unknown.jar");
|
std::fs::write(&path, b"unknown").unwrap();
|
||||||
ui.app.mods_state.entries = vec![content_entry("Unknown mod", path)];
|
ui.app.mods_state.entries = vec![content_entry("Unknown mod", path)];
|
||||||
ui.app.mods_state.list_state.selected = Some(0);
|
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();
|
let project = record.resolved_project().unwrap().clone();
|
||||||
ui.app.content_manifest = Some((
|
ui.app.content_manifest = Some((
|
||||||
"Unmatched".to_owned(),
|
"Unmatched".to_owned(),
|
||||||
@@ -102,13 +118,13 @@ fn installed_popup_navigation_preserves_local_filters() {
|
|||||||
ui.add_instance("Popup");
|
ui.add_instance("Popup");
|
||||||
ui.app.focused = FocusedArea::Content;
|
ui.app.focused = FocusedArea::Content;
|
||||||
ui.app.content_tab = ContentTab::Mods;
|
ui.app.content_tab = ContentTab::Mods;
|
||||||
let path = ui
|
let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Popup")).minecraft();
|
||||||
.instance_path("Popup")
|
let path = minecraft.join("mods/known.jar");
|
||||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
.join("mods/known.jar");
|
std::fs::write(&path, b"known").unwrap();
|
||||||
ui.app.mods_state.entries = vec![content_entry("Known mod", path)];
|
ui.app.mods_state.entries = vec![content_entry("Known mod", path)];
|
||||||
ui.app.mods_state.list_state.selected = Some(0);
|
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();
|
let project = record.resolved_project().unwrap().clone();
|
||||||
ui.app.content_manifest = Some((
|
ui.app.content_manifest = Some((
|
||||||
"Popup".to_owned(),
|
"Popup".to_owned(),
|
||||||
@@ -282,15 +298,16 @@ fn world_datapack_version_action_requires_selected_provider_match() {
|
|||||||
ui.add_instance("Datapacks");
|
ui.add_instance("Datapacks");
|
||||||
ui.app.focused = FocusedArea::Content;
|
ui.app.focused = FocusedArea::Content;
|
||||||
ui.app.content_tab = ContentTab::Worlds;
|
ui.app.content_tab = ContentTab::Worlds;
|
||||||
let world = ui
|
let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Datapacks")).minecraft();
|
||||||
.instance_path("Datapacks")
|
let world = minecraft.join("saves/World");
|
||||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
|
||||||
.join("saves/World");
|
|
||||||
let path = world.join("datapacks/unknown.zip");
|
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.entries = vec![content_entry("Unknown datapack", path)];
|
||||||
ui.app.world_datapacks_state.list_state.selected = Some(0);
|
ui.app.world_datapacks_state.list_state.selected = Some(0);
|
||||||
ui.app.open_world_datapacks = Some(("World".to_owned(), world));
|
ui.app.open_world_datapacks = Some(("World".to_owned(), world));
|
||||||
let mut record = managed_mod_record(
|
let mut record = managed_mod_record(
|
||||||
|
&minecraft,
|
||||||
"saves/World/datapacks/unknown.zip",
|
"saves/World/datapacks/unknown.zip",
|
||||||
"known",
|
"known",
|
||||||
false,
|
false,
|
||||||
@@ -482,6 +499,7 @@ fn confirmed_screenshot_delete_removes_state_and_file() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn managed_mod_record(
|
fn managed_mod_record(
|
||||||
|
minecraft: &Path,
|
||||||
path: &str,
|
path: &str,
|
||||||
project_id: &str,
|
project_id: &str,
|
||||||
automatic_dependency: bool,
|
automatic_dependency: bool,
|
||||||
@@ -491,11 +509,8 @@ fn managed_mod_record(
|
|||||||
relative_path: PathBuf::from(path),
|
relative_path: PathBuf::from(path),
|
||||||
kind: ContentKind::Mod,
|
kind: ContentKind::Mod,
|
||||||
enabled: true,
|
enabled: true,
|
||||||
fingerprint: FileFingerprint {
|
fingerprint: crate::instance::content::manifest::fingerprint(&minecraft.join(path))
|
||||||
size: 1,
|
.unwrap(),
|
||||||
modified_ns: 1,
|
|
||||||
hashes: Default::default(),
|
|
||||||
},
|
|
||||||
resolution: Resolution::Resolved {
|
resolution: Resolution::Resolved {
|
||||||
project: ProviderProject {
|
project: ProviderProject {
|
||||||
provider: "modrinth".to_owned(),
|
provider: "modrinth".to_owned(),
|
||||||
@@ -552,8 +567,8 @@ fn deleting_a_mod_offers_its_unused_dependency_chain() {
|
|||||||
ContentManifest {
|
ContentManifest {
|
||||||
version: 1,
|
version: 1,
|
||||||
files: vec![
|
files: vec![
|
||||||
managed_mod_record("mods/root.jar", "root", false, vec![dependency]),
|
managed_mod_record(&minecraft, "mods/root.jar", "root", false, vec![dependency]),
|
||||||
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("Dependencies")).content_manifest())
|
.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");
|
let library_path = minecraft.join("mods/library.jar");
|
||||||
std::fs::create_dir_all(library_path.parent().unwrap()).unwrap();
|
std::fs::create_dir_all(library_path.parent().unwrap()).unwrap();
|
||||||
std::fs::write(&library_path, b"l").unwrap();
|
std::fs::write(&library_path, b"l").unwrap();
|
||||||
|
std::fs::write(minecraft.join("mods/root.jar"), b"r").unwrap();
|
||||||
ContentManifest {
|
ContentManifest {
|
||||||
version: 1,
|
version: 1,
|
||||||
files: vec![
|
files: vec![
|
||||||
managed_mod_record(
|
managed_mod_record(
|
||||||
|
&minecraft,
|
||||||
"mods/root.jar",
|
"mods/root.jar",
|
||||||
"root",
|
"root",
|
||||||
false,
|
false,
|
||||||
@@ -609,7 +626,7 @@ fn deleting_a_required_library_warns_but_can_continue() {
|
|||||||
version_id: "library-version".to_owned(),
|
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())
|
.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());
|
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]
|
#[test]
|
||||||
fn confirmed_account_delete_updates_the_account_panel() {
|
fn confirmed_account_delete_updates_the_account_panel() {
|
||||||
let mut ui = UiHarness::new();
|
let mut ui = UiHarness::new();
|
||||||
@@ -1164,6 +1233,7 @@ fn instance_launch_options_autosave_through_the_editor() {
|
|||||||
fn settings_panel_keeps_direct_profile_management() {
|
fn settings_panel_keeps_direct_profile_management() {
|
||||||
let mut ui = UiHarness::new();
|
let mut ui = UiHarness::new();
|
||||||
ui.add_instance("profile-test");
|
ui.add_instance("profile-test");
|
||||||
|
std::fs::create_dir_all(ui.instance_path("profile-test").join("minecraft")).unwrap();
|
||||||
ui.app.focused = FocusedArea::Settings;
|
ui.app.focused = FocusedArea::Settings;
|
||||||
|
|
||||||
ui.key(KeyCode::Char('a'));
|
ui.key(KeyCode::Char('a'));
|
||||||
@@ -1249,6 +1319,11 @@ fn provider_conflict_selection_is_persisted() {
|
|||||||
let mut ui = UiHarness::new();
|
let mut ui = UiHarness::new();
|
||||||
ui.add_instance("Conflict");
|
ui.add_instance("Conflict");
|
||||||
let relative_path = std::path::PathBuf::from("mods/example.jar");
|
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![
|
let candidates = vec![
|
||||||
ProviderProject {
|
ProviderProject {
|
||||||
provider: "modrinth".to_owned(),
|
provider: "modrinth".to_owned(),
|
||||||
@@ -1267,11 +1342,7 @@ fn provider_conflict_selection_is_persisted() {
|
|||||||
relative_path: relative_path.clone(),
|
relative_path: relative_path.clone(),
|
||||||
kind: crate::instance::ContentKind::Mod,
|
kind: crate::instance::ContentKind::Mod,
|
||||||
enabled: true,
|
enabled: true,
|
||||||
fingerprint: crate::instance::FileFingerprint {
|
fingerprint: crate::instance::content::manifest::fingerprint(&file).unwrap(),
|
||||||
size: 1,
|
|
||||||
modified_ns: 0,
|
|
||||||
hashes: Default::default(),
|
|
||||||
},
|
|
||||||
resolution: crate::instance::Resolution::Ambiguous {
|
resolution: crate::instance::Resolution::Ambiguous {
|
||||||
candidates: candidates.clone(),
|
candidates: candidates.clone(),
|
||||||
},
|
},
|
||||||
@@ -1293,6 +1364,16 @@ fn provider_conflict_selection_is_persisted() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ui.key(KeyCode::Down);
|
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);
|
ui.key(KeyCode::Enter);
|
||||||
|
|
||||||
assert!(ui.app.provider_conflict.is_none());
|
assert!(ui.app.provider_conflict.is_none());
|
||||||
|
|||||||
+25
-13
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
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 ratatui::{Terminal, backend::TestBackend};
|
||||||
|
|
||||||
use crate::auth::{Account, AccountStore, AccountType};
|
use crate::auth::{Account, AccountStore, AccountType};
|
||||||
@@ -94,7 +94,10 @@ impl UiHarness {
|
|||||||
},
|
},
|
||||||
logs_state: widgets::logs_viewer::LogsState::default(),
|
logs_state: widgets::logs_viewer::LogsState::default(),
|
||||||
account_state,
|
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,
|
instance_settings: None,
|
||||||
pending_instance_settings_updates: Default::default(),
|
pending_instance_settings_updates: Default::default(),
|
||||||
global_settings: None,
|
global_settings: None,
|
||||||
@@ -109,6 +112,7 @@ impl UiHarness {
|
|||||||
throbber_tick: 0,
|
throbber_tick: 0,
|
||||||
error_effects: HashMap::new(),
|
error_effects: HashMap::new(),
|
||||||
pending_editor: None,
|
pending_editor: None,
|
||||||
|
edited_config_watches: Vec::new(),
|
||||||
reconciliation_for: None,
|
reconciliation_for: None,
|
||||||
content_manifest: None,
|
content_manifest: None,
|
||||||
content_update_snapshot: None,
|
content_update_snapshot: None,
|
||||||
@@ -164,15 +168,19 @@ impl UiHarness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_account(&mut self, username: &str) {
|
pub fn add_account(&mut self, username: &str) {
|
||||||
self.app.account_state.store.accounts.push(Account {
|
self.app
|
||||||
uuid: username.to_owned(),
|
.account_state
|
||||||
username: username.to_owned(),
|
.store
|
||||||
account_type: AccountType::Microsoft,
|
.add(Account {
|
||||||
active: true,
|
uuid: username.to_owned(),
|
||||||
refresh_token: Some("refresh".to_owned()),
|
username: username.to_owned(),
|
||||||
cached_mc_token: None,
|
account_type: AccountType::Microsoft,
|
||||||
cached_mc_token_expires_at: None,
|
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);
|
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) {
|
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();
|
let _runtime = self.runtime.enter();
|
||||||
self.app
|
self.app
|
||||||
.handle_key_event(KeyEvent::new(code, modifiers))
|
.dispatch_event(Event::Key(key))
|
||||||
.expect("handle key");
|
.expect("handle key")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mouse(&mut self, kind: MouseEventKind) {
|
pub fn mouse(&mut self, kind: MouseEventKind) {
|
||||||
|
|||||||
@@ -2,6 +2,18 @@
|
|||||||
// SPDX-License-Identifier: GPL-3.0-only
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use super::*;
|
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 crate::tests::TEST_LOCK;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use crossterm::event::KeyModifiers;
|
use crossterm::event::KeyModifiers;
|
||||||
@@ -1332,6 +1344,7 @@ fn dependency_resolution_opens_the_existing_confirmation() {
|
|||||||
title: "Project".to_owned(),
|
title: "Project".to_owned(),
|
||||||
version: root_version,
|
version: root_version,
|
||||||
installed_path: None,
|
installed_path: None,
|
||||||
|
expected_record: None,
|
||||||
kind: crate::instance::ContentKind::Mod,
|
kind: crate::instance::ContentKind::Mod,
|
||||||
destination: std::path::PathBuf::from("mods"),
|
destination: std::path::PathBuf::from("mods"),
|
||||||
provider_aliases: Vec::new(),
|
provider_aliases: Vec::new(),
|
||||||
@@ -1389,6 +1402,7 @@ fn confirming_state_with_plan() -> DiscoveryState {
|
|||||||
title: title.to_owned(),
|
title: title.to_owned(),
|
||||||
version,
|
version,
|
||||||
installed_path: None,
|
installed_path: None,
|
||||||
|
expected_record: None,
|
||||||
kind: crate::instance::ContentKind::Mod,
|
kind: crate::instance::ContentKind::Mod,
|
||||||
destination: std::path::PathBuf::from("mods"),
|
destination: std::path::PathBuf::from("mods"),
|
||||||
provider_aliases: Vec::new(),
|
provider_aliases: Vec::new(),
|
||||||
|
|||||||
@@ -8,6 +8,30 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::instance::content::entry::{ContentEntry, WorldDetails, WorldGameMode};
|
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::{
|
use ratatui::{
|
||||||
buffer::Buffer,
|
buffer::Buffer,
|
||||||
layout::Rect,
|
layout::Rect,
|
||||||
|
|||||||
@@ -185,6 +185,7 @@ fn skipped_dependencies_render_as_skipped_in_confirmation() {
|
|||||||
title: title.to_owned(),
|
title: title.to_owned(),
|
||||||
version,
|
version,
|
||||||
installed_path: None,
|
installed_path: None,
|
||||||
|
expected_record: None,
|
||||||
kind: ContentKind::Mod,
|
kind: ContentKind::Mod,
|
||||||
destination: std::path::PathBuf::from("mods"),
|
destination: std::path::PathBuf::from("mods"),
|
||||||
provider_aliases: Vec::new(),
|
provider_aliases: Vec::new(),
|
||||||
|
|||||||
@@ -48,3 +48,58 @@ fn list_and_viewer_navigation_loads_and_scrolls_the_selected_log() {
|
|||||||
assert!(handle_key(&key(KeyCode::Esc), &mut state));
|
assert!(handle_key(&key(KeyCode::Esc), &mut state));
|
||||||
assert!(!state.viewer_focused);
|
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::<String>();
|
||||||
|
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));
|
||||||
|
}
|
||||||
@@ -435,6 +435,18 @@ fn emphasis_next_to_html_tag_boundaries_does_not_leak_markers() {
|
|||||||
assert!(!rendered.contains('*'), "{rendered}");
|
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::<String>(),
|
||||||
|
"* and 2 ** 3 and *"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fenced_code_blocks_are_rendered_without_fences() {
|
fn fenced_code_blocks_are_rendered_without_fences() {
|
||||||
let text = formatted_text("```json5\n{\n \"enabled\": true\n}\n```", 24);
|
let text = formatted_text("```json5\n{\n \"enabled\": true\n}\n```", 24);
|
||||||
|
|||||||
@@ -16,6 +16,43 @@ fn key(code: KeyCode) -> KeyEvent {
|
|||||||
KeyEvent::new(code, KeyModifiers::NONE)
|
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 {
|
fn summary() -> ImportSummary {
|
||||||
ImportSummary {
|
ImportSummary {
|
||||||
name: "Test Pack".to_owned(),
|
name: "Test Pack".to_owned(),
|
||||||
|
|||||||
@@ -11,6 +11,61 @@ fn key(code: KeyCode) -> KeyEvent {
|
|||||||
KeyEvent::new(code, KeyModifiers::NONE)
|
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]
|
#[test]
|
||||||
fn filtered_vanilla_wizard_returns_the_displayed_version() {
|
fn filtered_vanilla_wizard_returns_the_displayed_version() {
|
||||||
let _guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
|
let _guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
|
||||||
|
|||||||
@@ -53,6 +53,32 @@ fn highlight_spans_marks_each_case_insensitive_match() {
|
|||||||
assert!(spans[2].style.add_modifier.contains(Modifier::UNDERLINED));
|
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::<String>(),
|
||||||
|
"İab"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
spans
|
||||||
|
.iter()
|
||||||
|
.filter(|span| span.style.add_modifier.contains(Modifier::UNDERLINED))
|
||||||
|
.map(|span| span.content.as_ref())
|
||||||
|
.collect::<String>(),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn ctrl_backspace_deletes_the_previous_word() {
|
fn ctrl_backspace_deletes_the_previous_word() {
|
||||||
let mut search = SearchState {
|
let mut search = SearchState {
|
||||||
|
|||||||
@@ -6,13 +6,21 @@ use super::*;
|
|||||||
#[test]
|
#[test]
|
||||||
fn narrow_settings_shows_the_selected_pane() {
|
fn narrow_settings_shows_the_selected_pane() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
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!({
|
let instance: InstanceConfig = serde_json::from_value(serde_json::json!({
|
||||||
"name": "Test", "game_version": "1.21", "loader": "vanilla",
|
"name": "Test", "game_version": "1.21", "loader": "vanilla",
|
||||||
"loader_version": null, "created": "2026-01-01T00:00:00Z", "java_path": "test-java"
|
"loader_version": null, "created": "2026-01-01T00:00:00Z", "java_path": "test-java"
|
||||||
}))
|
}))
|
||||||
.unwrap();
|
.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();
|
state.java_label = "jdk17".to_owned();
|
||||||
let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(35, 8)).unwrap();
|
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]
|
#[test]
|
||||||
fn removing_selected_last_profile_clamps_selection() {
|
fn removing_selected_last_profile_clamps_selection() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
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.profiles = vec!["first".to_string(), "second".to_string()];
|
||||||
state.active_profile = Some("second".to_string());
|
state.active_profile = Some("second".to_string());
|
||||||
state.list_state.selected = Some(2);
|
state.list_state.selected = Some(2);
|
||||||
@@ -77,7 +85,7 @@ fn removing_selected_last_profile_clamps_selection() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn info_pane_does_not_bind_desktop_toggle() {
|
fn info_pane_does_not_bind_desktop_toggle() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
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;
|
state.pane = SettingsPane::Info;
|
||||||
|
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
@@ -85,3 +93,45 @@ fn info_pane_does_not_bind_desktop_toggle() {
|
|||||||
SettingsAction::None
|
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");
|
||||||
|
}
|
||||||
@@ -1364,11 +1364,8 @@ impl DiscoveryState {
|
|||||||
|
|
||||||
pub(crate) fn set_filter_loader(&mut self, loader: ModLoader) {
|
pub(crate) fn set_filter_loader(&mut self, loader: ModLoader) {
|
||||||
if self.filter_loader != loader {
|
if self.filter_loader != loader {
|
||||||
*self
|
self.filter_game_versions =
|
||||||
.filter_game_versions
|
Arc::new(Mutex::new(crate::tui::widgets::popups::LoadState::Idle));
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner) =
|
|
||||||
crate::tui::widgets::popups::LoadState::Idle;
|
|
||||||
}
|
}
|
||||||
self.filter_loader = loader;
|
self.filter_loader = loader;
|
||||||
}
|
}
|
||||||
@@ -2645,6 +2642,21 @@ impl DiscoveryState {
|
|||||||
self.pending_orphan_cleanup.take()
|
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 {
|
fn should_load_more(&self) -> bool {
|
||||||
if self.page_loading
|
if self.page_loading
|
||||||
|| (self.preparing_list.is_some() && self.retry_page_at.is_none())
|
|| (self.preparing_list.is_some() && self.retry_page_at.is_none())
|
||||||
|
|||||||
@@ -578,7 +578,7 @@ impl ContentListState {
|
|||||||
&& !self
|
&& !self
|
||||||
.version_metadata
|
.version_metadata
|
||||||
.contains_key(&(project.provider.clone(), project.version_id.clone()));
|
.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;
|
continue;
|
||||||
}
|
}
|
||||||
let pending = self.pending_provider_icons.clone();
|
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 {
|
pub fn drain_pending(&mut self) -> bool {
|
||||||
let Some(rx) = &self.stream_rx else {
|
let Some(rx) = &self.stream_rx else {
|
||||||
return false;
|
return false;
|
||||||
@@ -1808,8 +1806,6 @@ impl ContentListState {
|
|||||||
.collect();
|
.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) {
|
pub fn toggle_selected(&mut self) {
|
||||||
let Some(index) = self.list_state.selected else {
|
let Some(index) = self.list_state.selected else {
|
||||||
return;
|
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(
|
fn icon_spans(
|
||||||
icon_pixels: Option<&Vec<Vec<IconCell>>>,
|
icon_pixels: Option<&Vec<Vec<IconCell>>>,
|
||||||
row: usize,
|
row: usize,
|
||||||
|
|||||||
@@ -597,7 +597,6 @@ pub fn render(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// lazy-load: only scan when switching to an instance that hasn't been loaded yet
|
|
||||||
match tab {
|
match tab {
|
||||||
ContentTab::Mods
|
ContentTab::Mods
|
||||||
| ContentTab::ResourcePacks
|
| ContentTab::ResourcePacks
|
||||||
@@ -643,8 +642,8 @@ pub fn render(
|
|||||||
}
|
}
|
||||||
ContentTab::Worlds => {
|
ContentTab::Worlds => {
|
||||||
if let Some(instance) = instance {
|
if let Some(instance) = instance {
|
||||||
if let Some((world_name, world_path)) = open_world_datapacks {
|
if let Some((_, world_path)) = open_world_datapacks {
|
||||||
let cache_key = format!("{}:{world_name}", instance.name);
|
let cache_key = format!("{}:{world_path:?}", instance.name);
|
||||||
let content_dir = world_path.join("datapacks");
|
let content_dir = world_path.join("datapacks");
|
||||||
if world_datapacks_state.loaded_for.as_deref() != Some(cache_key.as_str()) {
|
if world_datapacks_state.loaded_for.as_deref() != Some(cache_key.as_str()) {
|
||||||
world_datapacks_state.start_load(
|
world_datapacks_state.start_load(
|
||||||
|
|||||||
@@ -76,6 +76,7 @@ impl LogsState {
|
|||||||
self.viewer_scroll = 0;
|
self.viewer_scroll = 0;
|
||||||
self.viewer_focused = false;
|
self.viewer_focused = false;
|
||||||
self.selected_path = None;
|
self.selected_path = None;
|
||||||
|
self.was_live = false;
|
||||||
self.last_rescan = std::time::Instant::now();
|
self.last_rescan = std::time::Instant::now();
|
||||||
|
|
||||||
let dir = instances_dir.to_path_buf();
|
let dir = instances_dir.to_path_buf();
|
||||||
@@ -99,33 +100,38 @@ impl LogsState {
|
|||||||
|
|
||||||
pub fn drain_pending(&mut self) {
|
pub fn drain_pending(&mut self) {
|
||||||
let live_now = self.has_live();
|
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() {
|
let taken = match self.pending.lock() {
|
||||||
Ok(mut slot) => slot.take(),
|
Ok(mut slot) => slot.take(),
|
||||||
_ => None,
|
_ => 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)
|
&& self.loaded_for.as_deref() == Some(&instance_name)
|
||||||
{
|
{
|
||||||
let prev_selected = self.list_state.selected;
|
|
||||||
self.entries = entries;
|
self.entries = entries;
|
||||||
self.loading = false;
|
self.loading = false;
|
||||||
|
true
|
||||||
let display_count = self.display_count();
|
} else {
|
||||||
|
false
|
||||||
if display_count > 0 && prev_selected.is_none() {
|
};
|
||||||
self.list_state.selected = Some(0);
|
if updated || live_changed {
|
||||||
self.load_selected_content();
|
let previous = self.list_state.selected.unwrap_or(0);
|
||||||
} else if let Some(sel) = prev_selected
|
let indices = self.display_indices();
|
||||||
&& sel >= display_count
|
self.list_state.selected = indices
|
||||||
&& display_count > 0
|
.iter()
|
||||||
{
|
.position(|index| match index {
|
||||||
self.list_state.selected = Some(display_count - 1);
|
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.update_scrollbar();
|
||||||
|
self.load_selected_content();
|
||||||
}
|
}
|
||||||
|
self.was_live = live_now;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn try_rescan(&mut self) {
|
pub fn try_rescan(&mut self) {
|
||||||
@@ -448,7 +454,6 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused:
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let has_live = state.has_live();
|
|
||||||
let display_count = state.display_count();
|
let display_count = state.display_count();
|
||||||
|
|
||||||
if display_count == 0 {
|
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);
|
Layout::horizontal([Constraint::Length(30), Constraint::Min(0)]).areas(area);
|
||||||
|
|
||||||
render_list(frame, list_area, state, is_focused);
|
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) {
|
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(
|
fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) {
|
||||||
frame: &mut Frame,
|
|
||||||
area: Rect,
|
|
||||||
state: &mut LogsState,
|
|
||||||
_is_focused: bool,
|
|
||||||
has_live: bool,
|
|
||||||
) {
|
|
||||||
let theme = THEME.as_ref();
|
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<ViewerLine> = if is_live {
|
let all_lines: Vec<ViewerLine> = if is_live {
|
||||||
let name = state.loaded_for.as_deref().unwrap_or("");
|
let name = state.loaded_for.as_deref().unwrap_or("");
|
||||||
|
|||||||
@@ -335,6 +335,12 @@ fn normalize_html(source: &str) -> NormalizedDocument {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn convert_html_fragment(html: &str) -> Result<NormalizedDocument, String> {
|
fn convert_html_fragment(html: &str) -> Result<NormalizedDocument, String> {
|
||||||
|
// A closing emphasis delimiter after punctuation needs a word boundary.
|
||||||
|
static EMPHASIS_BOUNDARY: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
|
||||||
|
regex::Regex::new(r"(?i)(</(?:strong|b|em|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 image_alignments = Arc::new(Mutex::new(HashMap::new()));
|
||||||
let visitor: VisitorHandle = Arc::new(Mutex::new(ImageAlignmentVisitor {
|
let visitor: VisitorHandle = Arc::new(Mutex::new(ImageAlignmentVisitor {
|
||||||
centered: Vec::new(),
|
centered: Vec::new(),
|
||||||
@@ -617,17 +623,13 @@ fn external_markdown_text(source: &str, width: u16) -> (Text<'static>, Vec<LinkT
|
|||||||
line.style = line_style;
|
line.style = line_style;
|
||||||
line.spans.retain(|span| {
|
line.spans.retain(|span| {
|
||||||
let content = span.content.as_ref();
|
let content = span.content.as_ref();
|
||||||
content != "*"
|
!(span.style.add_modifier.contains(Modifier::UNDERLINED)
|
||||||
&& !(span.style.add_modifier.contains(Modifier::UNDERLINED)
|
&& content.starts_with("(http")
|
||||||
&& content.starts_with("(http")
|
&& content.ends_with(')'))
|
||||||
&& content.ends_with(')'))
|
|
||||||
});
|
});
|
||||||
remove_link_destination(line);
|
remove_link_destination(line);
|
||||||
for span in &mut line.spans {
|
for span in &mut line.spans {
|
||||||
span.style = line_style.patch(span.style);
|
span.style = line_style.patch(span.style);
|
||||||
if span.content.contains("**") {
|
|
||||||
span.content = span.content.replace("**", "").into();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
text.lines = wrap_tables(text.lines, width, table_separator_style)
|
text.lines = wrap_tables(text.lines, width, table_separator_style)
|
||||||
|
|||||||
@@ -20,8 +20,6 @@ pub mod search;
|
|||||||
pub mod settings;
|
pub mod settings;
|
||||||
pub mod status;
|
pub mod status;
|
||||||
|
|
||||||
// highlight the first character of a title with the accent color,
|
|
||||||
// gives the UI that "keyboard shortcut hint" look
|
|
||||||
pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
|
pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
|
||||||
let theme = THEME.as_ref();
|
let theme = THEME.as_ref();
|
||||||
if !highlight || title.is_empty() {
|
if !highlight || title.is_empty() {
|
||||||
|
|||||||
@@ -14,7 +14,10 @@ use ratatui_textarea::TextArea;
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
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},
|
theme::{BORDER_STYLE, BorderStyle, THEME, ThemeConfig},
|
||||||
},
|
},
|
||||||
instance::models::{memory_kib, normalize_memory_value, parse_resolution},
|
instance::models::{memory_kib, normalize_memory_value, parse_resolution},
|
||||||
@@ -22,10 +25,10 @@ use crate::{
|
|||||||
DisplayResolution, JavaChoice, JavaPicker, ResolutionChoice, ResolutionPickerAction,
|
DisplayResolution, JavaChoice, JavaPicker, ResolutionChoice, ResolutionPickerAction,
|
||||||
SettingsPicker, SettingsPickerAction, SettingsPickerOption, adjust_memory, auto_label,
|
SettingsPicker, SettingsPickerAction, SettingsPickerOption, adjust_memory, auto_label,
|
||||||
default_label, default_resolution, display_resolutions, environment_labels,
|
default_label, default_resolution, display_resolutions, environment_labels,
|
||||||
format_tag_values, handle_resolution_picker_key, handle_text_area_input,
|
handle_resolution_picker_key, handle_text_area_input, is_default_resolution,
|
||||||
is_default_resolution, parse_environment, parse_tag_values, render_memory_gauge,
|
parse_environment, render_memory_gauge, render_settings_picker, resolution_choices,
|
||||||
render_settings_picker, resolution_choices, resolution_items, settings_text_area,
|
resolution_items, settings_text_area, tagged_row_count, tagged_value_lines,
|
||||||
tagged_row_count, tagged_value_lines, toggle_window_mode, window_mode_title,
|
toggle_window_mode, window_mode_title,
|
||||||
},
|
},
|
||||||
tui::widgets::status_badge,
|
tui::widgets::status_badge,
|
||||||
};
|
};
|
||||||
@@ -96,8 +99,13 @@ impl State {
|
|||||||
let java_cache =
|
let java_cache =
|
||||||
crate::storage::MetadataPaths::new(runtime_config.paths.resolve_meta_dir())
|
crate::storage::MetadataPaths::new(runtime_config.paths.resolve_meta_dir())
|
||||||
.java_installations();
|
.java_installations();
|
||||||
let mut java_picker =
|
let cwd = std::env::current_dir().unwrap_or_default();
|
||||||
JavaPicker::with_cache(crate::instance::java::detect_java_path(), Some(java_cache));
|
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());
|
java_picker.set_current(config.paths.java_path.as_deref());
|
||||||
Self {
|
Self {
|
||||||
config,
|
config,
|
||||||
@@ -238,6 +246,7 @@ impl State {
|
|||||||
9 => match parse_environment(value) {
|
9 => match parse_environment(value) {
|
||||||
Ok(environment) => {
|
Ok(environment) => {
|
||||||
self.config.defaults.environment = environment;
|
self.config.defaults.environment = environment;
|
||||||
|
self.refresh_java_context();
|
||||||
self.save_pending = true;
|
self.save_pending = true;
|
||||||
}
|
}
|
||||||
Err(error) => invalid(self, error),
|
Err(error) => invalid(self, error),
|
||||||
@@ -563,7 +572,8 @@ impl State {
|
|||||||
.iter()
|
.iter()
|
||||||
.position(|mode| *mode == current);
|
.position(|mode| *mode == current);
|
||||||
let index = match (index, forward) {
|
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), true) => index + 1,
|
||||||
(Some(index), false) => index - 1,
|
(Some(index), false) => index - 1,
|
||||||
(None, true) => 0,
|
(None, true) => 0,
|
||||||
@@ -579,6 +589,7 @@ impl State {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn open_java_picker(&mut self) {
|
fn open_java_picker(&mut self) {
|
||||||
|
self.refresh_java_context();
|
||||||
self.java_picker
|
self.java_picker
|
||||||
.open(self.config.paths.java_path.as_deref());
|
.open(self.config.paths.java_path.as_deref());
|
||||||
self.java_picker.initialize();
|
self.java_picker.initialize();
|
||||||
@@ -586,6 +597,7 @@ impl State {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn toggle_auto_java(&mut self) -> Action {
|
fn toggle_auto_java(&mut self) -> Action {
|
||||||
|
self.refresh_java_context();
|
||||||
let Some(current) = self.config.paths.java_path.as_deref() else {
|
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.config.paths.java_path = Some(self.java_picker.detected_path().to_owned());
|
||||||
self.save_pending = true;
|
self.save_pending = true;
|
||||||
@@ -617,6 +629,17 @@ impl State {
|
|||||||
|
|
||||||
pub fn invalidate_java_cache(&mut self) {
|
pub fn invalidate_java_cache(&mut self) {
|
||||||
self.java_picker.invalidate_cache();
|
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) {
|
fn handle_java_picker_key(&mut self, key: &KeyEvent) {
|
||||||
@@ -687,6 +710,13 @@ impl State {
|
|||||||
self.error = None;
|
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 {
|
pub fn handle_key(&mut self, key: &KeyEvent) -> Action {
|
||||||
let action = self.handle_key_inner(key);
|
let action = self.handle_key_inner(key);
|
||||||
if !matches!(action, Action::None) {
|
if !matches!(action, Action::None) {
|
||||||
@@ -1318,6 +1348,88 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::instance::models::WindowMode;
|
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]
|
#[test]
|
||||||
fn launcher_memory_uses_slider_and_java_uses_picker() {
|
fn launcher_memory_uses_slider_and_java_uses_picker() {
|
||||||
let mut state = State::new();
|
let mut state = State::new();
|
||||||
@@ -1550,6 +1662,10 @@ mod tests {
|
|||||||
state.selected = 2;
|
state.selected = 2;
|
||||||
state.handle_key(&KeyEvent::from(KeyCode::Down));
|
state.handle_key(&KeyEvent::from(KeyCode::Down));
|
||||||
assert_eq!(state.selected, 24);
|
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!(
|
assert!(matches!(
|
||||||
state.handle_key(&KeyEvent::from(KeyCode::Right)),
|
state.handle_key(&KeyEvent::from(KeyCode::Right)),
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ mod state;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub use render::render;
|
pub use render::render;
|
||||||
pub use render::{popup_rect, render_with_picker};
|
pub use render::{popup_rect, render_with_picker};
|
||||||
|
pub(in crate::tui) use state::text_input_active;
|
||||||
pub use state::{
|
pub use state::{
|
||||||
ImportResult, ImportStep, ImportWizardState, discovery_activity, drain, handle_discovery_click,
|
ImportResult, ImportStep, ImportWizardState, discovery_activity, drain, handle_discovery_click,
|
||||||
handle_key, has_version_popup, open, take_result,
|
handle_key, has_version_popup, open, take_result,
|
||||||
|
|||||||
@@ -120,6 +120,23 @@ pub fn has_version_popup() -> bool {
|
|||||||
.is_ok_and(|state| state.version_popup.is_some())
|
.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> {
|
pub fn discovery_activity() -> Option<&'static str> {
|
||||||
let wizard = IMPORT_STATE.lock().ok()?;
|
let wizard = IMPORT_STATE.lock().ok()?;
|
||||||
let step = wizard.step.clone();
|
let step = wizard.step.clone();
|
||||||
|
|||||||
@@ -16,8 +16,10 @@ use crate::{
|
|||||||
auth::{Account, AccountType},
|
auth::{Account, AccountType},
|
||||||
config::{
|
config::{
|
||||||
SETTINGS,
|
SETTINGS,
|
||||||
|
settings::{format_tag_values, parse_tag_values},
|
||||||
theme::{BORDER_STYLE, THEME},
|
theme::{BORDER_STYLE, THEME},
|
||||||
},
|
},
|
||||||
|
instance::glfw::bundled_glfw_version,
|
||||||
instance::loader::GameVersion,
|
instance::loader::GameVersion,
|
||||||
instance::models::{
|
instance::models::{
|
||||||
InstanceConfig, LaunchCommand, ModLoader, memory_kib, normalize_memory_value,
|
InstanceConfig, LaunchCommand, ModLoader, memory_kib, normalize_memory_value,
|
||||||
@@ -30,12 +32,12 @@ use crate::{
|
|||||||
DisplayResolution, GlfwChoice, GlfwPicker, JavaChoice, JavaPicker,
|
DisplayResolution, GlfwChoice, GlfwPicker, JavaChoice, JavaPicker,
|
||||||
ResolutionChoice, ResolutionPickerAction, SettingsPicker, SettingsPickerAction,
|
ResolutionChoice, ResolutionPickerAction, SettingsPicker, SettingsPickerAction,
|
||||||
SettingsPickerBadge, SettingsPickerOption, adjust_memory, auto_label,
|
SettingsPickerBadge, SettingsPickerOption, adjust_memory, auto_label,
|
||||||
bundled_glfw_version, bundled_label as bundled_badge, default_label,
|
bundled_label as bundled_badge, default_label, default_resolution,
|
||||||
default_resolution, display_resolutions, environment_labels, format_tag_values,
|
display_resolutions, environment_labels, handle_resolution_picker_key,
|
||||||
handle_resolution_picker_key, handle_text_area_input, is_default_resolution,
|
handle_text_area_input, is_default_resolution, parse_environment,
|
||||||
parse_environment, parse_tag_values, render_memory_gauge, render_settings_picker,
|
render_memory_gauge, render_settings_picker, resolution_choices, resolution_items,
|
||||||
resolution_choices, resolution_items, settings_text_area, tagged_row_count,
|
settings_text_area, tagged_row_count, tagged_value_lines, toggle_window_mode,
|
||||||
tagged_value_lines, toggle_window_mode, window_mode_title,
|
window_mode_title,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
search::SearchState,
|
search::SearchState,
|
||||||
@@ -92,6 +94,7 @@ pub struct State {
|
|||||||
account_picker: SettingsPicker,
|
account_picker: SettingsPicker,
|
||||||
accounts: Vec<Account>,
|
accounts: Vec<Account>,
|
||||||
meta_dir: std::path::PathBuf,
|
meta_dir: std::path::PathBuf,
|
||||||
|
minecraft_dir: std::path::PathBuf,
|
||||||
display_resolutions: Vec<DisplayResolution>,
|
display_resolutions: Vec<DisplayResolution>,
|
||||||
runtime_update_pending: bool,
|
runtime_update_pending: bool,
|
||||||
save_retry_pending: bool,
|
save_retry_pending: bool,
|
||||||
@@ -111,9 +114,16 @@ pub enum Action {
|
|||||||
|
|
||||||
impl State {
|
impl State {
|
||||||
pub fn new(instance: &InstanceConfig, meta_dir: &std::path::Path) -> Self {
|
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(
|
Self::with_accounts(
|
||||||
instance,
|
instance,
|
||||||
meta_dir,
|
meta_dir,
|
||||||
|
&minecraft_dir,
|
||||||
crate::auth::AccountStore::load().accounts,
|
crate::auth::AccountStore::load().accounts,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -121,16 +131,24 @@ impl State {
|
|||||||
pub fn with_accounts(
|
pub fn with_accounts(
|
||||||
instance: &InstanceConfig,
|
instance: &InstanceConfig,
|
||||||
meta_dir: &std::path::Path,
|
meta_dir: &std::path::Path,
|
||||||
|
minecraft_dir: &std::path::Path,
|
||||||
accounts: Vec<Account>,
|
accounts: Vec<Account>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let auto_java_path = SETTINGS
|
let settings = SETTINGS.read();
|
||||||
.read()
|
let cwd = minecraft_dir.to_owned();
|
||||||
.paths
|
let environment = crate::instance::java::merge_environment(
|
||||||
.effective_java_path()
|
&settings.defaults.environment,
|
||||||
.map(str::to_owned)
|
&instance.environment,
|
||||||
.unwrap_or_else(crate::instance::java::detect_java_path);
|
);
|
||||||
|
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 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());
|
java_picker.set_current(instance.java_path.as_deref());
|
||||||
let desktop = crate::instance::desktop::exists(&instance.name);
|
let desktop = crate::instance::desktop::exists(&instance.name);
|
||||||
Self {
|
Self {
|
||||||
@@ -158,6 +176,7 @@ impl State {
|
|||||||
account_picker: SettingsPicker::default(),
|
account_picker: SettingsPicker::default(),
|
||||||
accounts,
|
accounts,
|
||||||
meta_dir: meta_dir.to_path_buf(),
|
meta_dir: meta_dir.to_path_buf(),
|
||||||
|
minecraft_dir: minecraft_dir.to_owned(),
|
||||||
display_resolutions: display_resolutions(),
|
display_resolutions: display_resolutions(),
|
||||||
runtime_update_pending: false,
|
runtime_update_pending: false,
|
||||||
save_retry_pending: false,
|
save_retry_pending: false,
|
||||||
@@ -405,6 +424,7 @@ impl State {
|
|||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
}
|
}
|
||||||
ChoicePicker::Java => {
|
ChoicePicker::Java => {
|
||||||
|
self.refresh_java_context();
|
||||||
self.java_picker.open(self.draft.java_path.as_deref());
|
self.java_picker.open(self.draft.java_path.as_deref());
|
||||||
self.java_picker.initialize();
|
self.java_picker.initialize();
|
||||||
}
|
}
|
||||||
@@ -770,6 +790,7 @@ impl State {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn toggle_auto_java(&mut self) -> Action {
|
fn toggle_auto_java(&mut self) -> Action {
|
||||||
|
self.refresh_java_context();
|
||||||
let Some(current) = self.draft.java_path.as_deref() else {
|
let Some(current) = self.draft.java_path.as_deref() else {
|
||||||
self.draft.java_path = Some(self.java_picker.detected_path().to_owned());
|
self.draft.java_path = Some(self.java_picker.detected_path().to_owned());
|
||||||
self.error = None;
|
self.error = None;
|
||||||
@@ -937,7 +958,10 @@ impl State {
|
|||||||
Err(error) => invalid(self, error),
|
Err(error) => invalid(self, error),
|
||||||
},
|
},
|
||||||
7 => match parse_environment(value) {
|
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),
|
Err(error) => invalid(self, error),
|
||||||
},
|
},
|
||||||
9 if value.is_empty() => {
|
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 {
|
pub fn handle_key(&mut self, key: &KeyEvent) -> Action {
|
||||||
if self.runtime_update_pending {
|
if self.runtime_update_pending {
|
||||||
return if key.code == KeyCode::Esc {
|
return if key.code == KeyCode::Esc {
|
||||||
@@ -1106,6 +1140,23 @@ impl State {
|
|||||||
|
|
||||||
pub fn invalidate_java_cache(&mut self) {
|
pub fn invalidate_java_cache(&mut self) {
|
||||||
self.java_picker.invalidate_cache();
|
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<InstanceConfig>, bool)> {
|
pub fn cancel_runtime_change(&mut self) -> Option<(Box<InstanceConfig>, bool)> {
|
||||||
@@ -1740,6 +1791,79 @@ mod tests {
|
|||||||
use crate::instance::WindowMode;
|
use crate::instance::WindowMode;
|
||||||
use chrono::Utc;
|
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 {
|
fn instance() -> InstanceConfig {
|
||||||
InstanceConfig {
|
InstanceConfig {
|
||||||
name: "test".to_owned(),
|
name: "test".to_owned(),
|
||||||
@@ -2231,6 +2355,15 @@ mod tests {
|
|||||||
assert!(lines.len() > 1);
|
assert!(lines.len() > 1);
|
||||||
assert_eq!(tagged_row_count(&state.draft.jvm_args, 48), lines.len());
|
assert_eq!(tagged_row_count(&state.draft.jvm_args, 48), lines.len());
|
||||||
assert!(lines.iter().any(|line| line.to_string().contains("second")));
|
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]
|
#[test]
|
||||||
@@ -2296,7 +2429,12 @@ mod tests {
|
|||||||
cached_mc_token: None,
|
cached_mc_token: None,
|
||||||
cached_mc_token_expires_at: 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.selected = 10;
|
||||||
state.begin_edit();
|
state.begin_edit();
|
||||||
assert_eq!(state.choice_index, 0);
|
assert_eq!(state.choice_index, 0);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ mod render;
|
|||||||
mod state;
|
mod state;
|
||||||
|
|
||||||
pub use render::{popup_rect, render};
|
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};
|
pub use state::{WizardParams, WizardState, WizardStep, handle_key, take_result};
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -116,6 +116,13 @@ pub fn take_result() -> Option<WizardParams> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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(
|
fn handle_name_key(
|
||||||
state: &mut WizardState,
|
state: &mut WizardState,
|
||||||
key_event: &KeyEvent,
|
key_event: &KeyEvent,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// SPDX-License-Identifier: GPL-3.0-only
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, BTreeSet},
|
collections::BTreeMap,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::{
|
sync::{
|
||||||
Arc, Mutex,
|
Arc, Mutex,
|
||||||
@@ -21,8 +21,12 @@ use ratatui::{
|
|||||||
use ratatui_textarea::{CursorMove, TextArea};
|
use ratatui_textarea::{CursorMove, TextArea};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{settings::DEFAULT_RESOLUTION, theme::THEME},
|
config::{
|
||||||
|
settings::{DEFAULT_RESOLUTION, parse_tag_values},
|
||||||
|
theme::THEME,
|
||||||
|
},
|
||||||
instance::{
|
instance::{
|
||||||
|
glfw::{GlfwInstallation, discover_glfw_installations, glfw_version_from_path},
|
||||||
java::JavaInstallation,
|
java::JavaInstallation,
|
||||||
models::{WindowMode, memory_kib},
|
models::{WindowMode, memory_kib},
|
||||||
},
|
},
|
||||||
@@ -204,6 +208,9 @@ pub(crate) struct JavaPicker {
|
|||||||
cache_path: Option<PathBuf>,
|
cache_path: Option<PathBuf>,
|
||||||
refresh_started: bool,
|
refresh_started: bool,
|
||||||
generation: Arc<AtomicU64>,
|
generation: Arc<AtomicU64>,
|
||||||
|
cwd: PathBuf,
|
||||||
|
environment: BTreeMap<String, String>,
|
||||||
|
context_key: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -225,12 +232,6 @@ pub(crate) enum GlfwChoice {
|
|||||||
System(String),
|
System(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
struct GlfwInstallation {
|
|
||||||
path: PathBuf,
|
|
||||||
version: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub(crate) struct DisplayResolution {
|
pub(crate) struct DisplayResolution {
|
||||||
pub width: u32,
|
pub width: u32,
|
||||||
@@ -298,13 +299,24 @@ impl JavaPicker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn with_auto_path(detected: String) -> Self {
|
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<PathBuf>) -> Self {
|
pub(crate) fn with_cache(
|
||||||
let cached = cache_path
|
detected: String,
|
||||||
.as_deref()
|
cache_path: Option<PathBuf>,
|
||||||
.and_then(crate::instance::java::load_installation_cache);
|
cwd: PathBuf,
|
||||||
|
environment: BTreeMap<String, String>,
|
||||||
|
) -> 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 {
|
Self {
|
||||||
load: Arc::new(Mutex::new(
|
load: Arc::new(Mutex::new(
|
||||||
cached.map_or(LoadState::Idle, LoadState::Loaded),
|
cached.map_or(LoadState::Idle, LoadState::Loaded),
|
||||||
@@ -315,6 +327,25 @@ impl JavaPicker {
|
|||||||
cache_path,
|
cache_path,
|
||||||
refresh_started: false,
|
refresh_started: false,
|
||||||
generation: Arc::new(AtomicU64::new(0)),
|
generation: Arc::new(AtomicU64::new(0)),
|
||||||
|
cwd,
|
||||||
|
environment,
|
||||||
|
context_key,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_context(
|
||||||
|
&mut self,
|
||||||
|
detected: String,
|
||||||
|
cwd: PathBuf,
|
||||||
|
environment: BTreeMap<String, String>,
|
||||||
|
) {
|
||||||
|
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 refresh_generation = self.generation.load(Ordering::Relaxed);
|
||||||
let generation = self.generation.clone();
|
let generation = self.generation.clone();
|
||||||
let selected_paths = [Some(self.detected.clone()), self.current.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 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() {
|
for path in selected_paths.into_iter().flatten() {
|
||||||
if installations.iter().any(|installation| {
|
if installations.iter().any(|installation| {
|
||||||
same_executable(&installation.path.to_string_lossy(), &path)
|
same_executable(&installation.path.to_string_lossy(), &path)
|
||||||
}) {
|
}) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Some(installation) =
|
if let Some(installation) = crate::instance::java::inspect_installation_in(
|
||||||
crate::instance::java::inspect_installation(Path::new(&path))
|
Path::new(&path),
|
||||||
{
|
&cwd,
|
||||||
|
&environment,
|
||||||
|
) {
|
||||||
installations.push(installation);
|
installations.push(installation);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -363,8 +399,12 @@ impl JavaPicker {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if let Some(cache_path) = cache_path
|
if let Some(cache_path) = cache_path
|
||||||
&& let Err(error) =
|
&& let Err(error) = crate::instance::java::save_installation_cache_in(
|
||||||
crate::instance::java::save_installation_cache(&cache_path, &installations)
|
&cache_path,
|
||||||
|
&installations,
|
||||||
|
&cwd,
|
||||||
|
&environment,
|
||||||
|
)
|
||||||
{
|
{
|
||||||
tracing::debug!("Could not cache Java installations: {error}");
|
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<String> {
|
|
||||||
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<GlfwInstallation> {
|
|
||||||
let mut directories = Vec::<PathBuf>::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<String> {
|
|
||||||
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 {
|
fn same_executable(left: &str, right: &str) -> bool {
|
||||||
if left == right {
|
if left == right {
|
||||||
return true;
|
return true;
|
||||||
@@ -995,76 +920,6 @@ pub(crate) fn settings_text_area(lines: Vec<String>) -> TextArea<'static> {
|
|||||||
editor
|
editor
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn parse_tag_values(input: &str) -> Result<Vec<String>, 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::<Vec<_>>()
|
|
||||||
.join(" ")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn parse_environment(value: &str) -> Result<BTreeMap<String, String>, String> {
|
pub(crate) fn parse_environment(value: &str) -> Result<BTreeMap<String, String>, String> {
|
||||||
let mut environment = BTreeMap::new();
|
let mut environment = BTreeMap::new();
|
||||||
for assignment in parse_tag_values(value)? {
|
for assignment in parse_tag_values(value)? {
|
||||||
@@ -1118,7 +973,7 @@ pub(crate) fn tagged_value_lines(
|
|||||||
let mut spans = prefix;
|
let mut spans = prefix;
|
||||||
let mut used = 0usize;
|
let mut used = 0usize;
|
||||||
for value in values {
|
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);
|
let separator = usize::from(used > 0);
|
||||||
if used > 0 && used + separator + badge_width > available {
|
if used > 0 && used + separator + badge_width > available {
|
||||||
lines.push(Line::from(spans));
|
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 {
|
pub(crate) fn tagged_row_count(values: &[String], width: u16) -> usize {
|
||||||
if values.is_empty() {
|
tagged_value_lines(Vec::new(), false, false, values, "", width).len()
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn auto_label() -> Span<'static> {
|
pub(crate) fn auto_label() -> Span<'static> {
|
||||||
@@ -1303,6 +1143,7 @@ pub(crate) fn resolution_items(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::config::settings::format_tag_values;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn memory_steps_move_and_clamp() {
|
fn memory_steps_move_and_clamp() {
|
||||||
@@ -1387,7 +1228,12 @@ mod tests {
|
|||||||
let cache = temp.path().join("cache/java/installations.json");
|
let cache = temp.path().join("cache/java/installations.json");
|
||||||
std::fs::create_dir_all(cache.parent().unwrap()).unwrap();
|
std::fs::create_dir_all(cache.parent().unwrap()).unwrap();
|
||||||
std::fs::write(&cache, "[]").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 {
|
*picker.load.lock().unwrap() = LoadState::Loaded(vec![JavaInstallation {
|
||||||
path: "/cached/java".into(),
|
path: "/cached/java".into(),
|
||||||
version: Some("21".to_owned()),
|
version: Some("21".to_owned()),
|
||||||
@@ -1401,6 +1247,48 @@ mod tests {
|
|||||||
assert!(matches!(*picker.load.lock().unwrap(), LoadState::Idle));
|
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]
|
#[test]
|
||||||
fn java_title_is_minimal_and_uses_the_major_version() {
|
fn java_title_is_minimal_and_uses_the_major_version() {
|
||||||
let picker = JavaPicker::with_auto_path("/opt/jdk-25/bin/java".to_owned());
|
let picker = JavaPicker::with_auto_path("/opt/jdk-25/bin/java".to_owned());
|
||||||
@@ -1483,7 +1371,7 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(
|
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")
|
Some("3.3.3")
|
||||||
);
|
);
|
||||||
let mut picker = GlfwPicker::with_bundled_version(Some("3.3.3".to_owned()));
|
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]
|
#[test]
|
||||||
fn settings_text_input_deletes_the_previous_word() {
|
fn settings_text_input_deletes_the_previous_word() {
|
||||||
let mut input = TextArea::from(["one two"]);
|
let mut input = TextArea::from(["one two"]);
|
||||||
@@ -1538,10 +1413,10 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn tag_values_drop_exact_duplicates_without_reordering() {
|
fn tag_values_preserve_repeated_options_and_their_operands() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parse_tag_values("-Xmx2G '-Dlabel=hello world' -Xmx2G").unwrap(),
|
parse_tag_values("--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED").unwrap(),
|
||||||
["-Xmx2G", "-Dlabel=hello world"]
|
["--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("=missing").is_err());
|
||||||
assert!(parse_environment("KEY=one KEY=two").is_err());
|
assert!(parse_environment("KEY=one KEY=two").is_err());
|
||||||
|
assert!(parse_environment("KEY=one KEY=one").is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -57,12 +57,21 @@ impl SearchState {
|
|||||||
|
|
||||||
let query_lower = self.query.to_lowercase();
|
let query_lower = self.query.to_lowercase();
|
||||||
let text_lower = text.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::<usize>();
|
||||||
|
original_ranges.extend(std::iter::repeat_n(
|
||||||
|
(start, start + character.len_utf8()),
|
||||||
|
lowercase_bytes,
|
||||||
|
));
|
||||||
|
}
|
||||||
let mut spans = Vec::new();
|
let mut spans = Vec::new();
|
||||||
let mut last = 0;
|
let mut last = 0;
|
||||||
|
|
||||||
for (start, _) in text_lower.match_indices(&query_lower) {
|
for (lower_start, _) in text_lower.match_indices(&query_lower) {
|
||||||
let end = start + query_lower.len();
|
let start = original_ranges[lower_start].0;
|
||||||
if !text.is_char_boundary(start) || !text.is_char_boundary(end) {
|
let end = original_ranges[lower_start + query_lower.len() - 1].1;
|
||||||
|
if start < last {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if start > last {
|
if start > last {
|
||||||
|
|||||||
+69
-46
@@ -44,14 +44,16 @@ pub struct SettingsState {
|
|||||||
pub add_mode: AddMode,
|
pub add_mode: AddMode,
|
||||||
pub pane: SettingsPane,
|
pub pane: SettingsPane,
|
||||||
meta_dir: PathBuf,
|
meta_dir: PathBuf,
|
||||||
|
instances_dir: PathBuf,
|
||||||
active_profile: Option<String>,
|
active_profile: Option<String>,
|
||||||
instance_name: Option<String>,
|
instance_name: Option<String>,
|
||||||
java_key: Option<String>,
|
java_key: Option<String>,
|
||||||
java_label: String,
|
java_label: String,
|
||||||
|
pending_java: std::sync::Arc<std::sync::Mutex<Option<String>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SettingsState {
|
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| {
|
let profiles = crate::instance::config_sync::list_profiles(&meta_dir).unwrap_or_else(|e| {
|
||||||
tracing::warn!("Failed to load config sync profiles: {}", e);
|
tracing::warn!("Failed to load config sync profiles: {}", e);
|
||||||
Vec::new()
|
Vec::new()
|
||||||
@@ -62,10 +64,12 @@ impl SettingsState {
|
|||||||
add_mode: AddMode::None,
|
add_mode: AddMode::None,
|
||||||
pane: SettingsPane::Profile,
|
pane: SettingsPane::Profile,
|
||||||
meta_dir,
|
meta_dir,
|
||||||
|
instances_dir,
|
||||||
active_profile: None,
|
active_profile: None,
|
||||||
instance_name: None,
|
instance_name: None,
|
||||||
java_key: None,
|
java_key: None,
|
||||||
java_label: "unknown".to_string(),
|
java_label: "unknown".to_string(),
|
||||||
|
pending_java: Default::default(),
|
||||||
};
|
};
|
||||||
state.select_active();
|
state.select_active();
|
||||||
state
|
state
|
||||||
@@ -116,15 +120,53 @@ impl SettingsState {
|
|||||||
self.select_active();
|
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 {
|
if self.java_key != java_key {
|
||||||
let java_source = instance.map(effective_java_path);
|
self.pending_java = Default::default();
|
||||||
self.java_label = java_source
|
self.java_label = "unknown".to_owned();
|
||||||
.as_deref()
|
if let Some((java, cwd, environment)) = context {
|
||||||
.map(java_version_label)
|
let pending = self.pending_java.clone();
|
||||||
.unwrap_or_else(|| "unknown".to_string());
|
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;
|
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<String>, active_profile: Option<&str>)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn java_path_key(instance: &InstanceConfig) -> String {
|
fn java_path_key(
|
||||||
instance
|
java: &str,
|
||||||
.java_path
|
cwd: &Path,
|
||||||
.as_deref()
|
environment: &std::collections::BTreeMap<String, String>,
|
||||||
.filter(|path| !path.is_empty())
|
) -> String {
|
||||||
.map(str::to_owned)
|
format!(
|
||||||
.or_else(|| {
|
"{java}:{}",
|
||||||
SETTINGS
|
crate::instance::java::probe_context_key(cwd, environment)
|
||||||
.read()
|
)
|
||||||
.paths
|
|
||||||
.effective_java_path()
|
|
||||||
.map(str::to_owned)
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| "<auto>".to_owned())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn effective_java_path(instance: &InstanceConfig) -> String {
|
fn java_version_label(
|
||||||
instance
|
java_path: &str,
|
||||||
.java_path
|
cwd: &Path,
|
||||||
.clone()
|
environment: &std::collections::BTreeMap<String, String>,
|
||||||
.or_else(|| {
|
) -> String {
|
||||||
SETTINGS
|
let Some(version) =
|
||||||
.read()
|
crate::instance::java::java_version_in(Path::new(java_path), cwd, environment)
|
||||||
.paths
|
else {
|
||||||
.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 {
|
|
||||||
return "unknown".to_string();
|
return "unknown".to_string();
|
||||||
};
|
};
|
||||||
let major = crate::instance::java::java_major(Some(&version));
|
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 {
|
fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
|
||||||
let area = frame.area();
|
frame
|
||||||
let x = area.x + (area.width.saturating_sub(width)) / 2;
|
.area()
|
||||||
let y = area.y + (area.height.saturating_sub(height)) / 2;
|
.centered(Constraint::Length(width), Constraint::Length(height))
|
||||||
Rect {
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
width: width.min(area.width),
|
|
||||||
height: height.min(area.height),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum SettingsAction {
|
pub enum SettingsAction {
|
||||||
|
|||||||
Reference in new issue
Block a user