fix(settings): keep editor updates consistent

This commit is contained in:
objz committed 2026-09-04 23:54:38 +02:00
1 parent ccc09419fb
commit 31edc0dbf8
13 files changed
+743 -248

No files matched your search

+73 -41
View File
@@ -19,15 +19,15 @@ use crate::{
settings::{ContentProvider, DEFAULT_RESOLUTION, ImageProtocol},
theme::{BORDER_STYLE, BorderStyle, THEME, ThemeConfig},
},
instance::models::{WindowMode, normalize_memory_value, parse_resolution},
instance::models::{memory_kib, normalize_memory_value, parse_resolution},
tui::widgets::popups::settings_controls::{
DisplayResolution, JavaChoice, JavaPicker, ResolutionChoice, ResolutionPickerAction,
SettingsPicker, SettingsPickerAction, SettingsPickerOption, adjust_memory, auto_label,
default_label, default_resolution, display_resolutions, environment_labels,
handle_resolution_picker_key, handle_text_area_input, is_default_resolution, memory_kib,
parse_environment, render_memory_gauge, render_settings_picker, resolution_choices,
resolution_items, settings_text_area, tagged_row_count, tagged_value_lines,
toggle_window_mode,
format_tag_values, handle_resolution_picker_key, handle_text_area_input,
is_default_resolution, parse_environment, parse_tag_values, render_memory_gauge,
render_settings_picker, resolution_choices, resolution_items, settings_text_area,
tagged_row_count, tagged_value_lines, toggle_window_mode, window_mode_title,
},
tui::widgets::status_badge,
};
@@ -64,7 +64,7 @@ pub struct State {
pub enum Action {
None,
Save(Box<Config>, String, BorderStyle),
Save(Box<Config>),
Error(String),
ConfirmJavaAuto,
ClearCache,
@@ -97,7 +97,7 @@ impl State {
.java_installations();
let mut java_picker =
JavaPicker::with_cache(crate::instance::java::detect_java_path(), Some(java_cache));
java_picker.open(config.paths.java_path.as_deref());
java_picker.set_current(config.paths.java_path.as_deref());
Self {
config,
theme,
@@ -138,8 +138,8 @@ impl State {
.resolution
.map(|(width, height)| format!("{width}x{height}"))
.unwrap_or_default(),
8 => self.config.defaults.jvm_args.join(" "),
9 => environment_labels(&self.config.defaults.environment).join(" "),
8 => format_tag_values(&self.config.defaults.jvm_args),
9 => format_tag_values(&environment_labels(&self.config.defaults.environment)),
10 => self.config.content.preferred_provider.to_string(),
11 => status(self.config.content.preferred_provider_only),
12 => status(self.config.content.ask_on_provider_conflict),
@@ -226,11 +226,13 @@ impl State {
}
Err(error) => invalid(self, error),
},
8 => {
self.config.defaults.jvm_args =
value.split_whitespace().map(str::to_owned).collect();
self.save_pending = true;
}
8 => match parse_tag_values(value) {
Ok(arguments) => {
self.config.defaults.jvm_args = arguments;
self.save_pending = true;
}
Err(error) => invalid(self, error),
},
9 => match parse_environment(value) {
Ok(environment) => {
self.config.defaults.environment = environment;
@@ -290,14 +292,20 @@ impl State {
let previous = self.theme.theme.clone();
self.theme.theme = self.themes[self.theme_index].clone();
self.error = None;
if self.theme.theme == previous {
return;
}
if let Err(error) = crate::config::theme::apply_theme(
self.theme.theme.clone(),
self.theme.border_style.clone(),
) {
self.error = Some(error.to_string());
self.theme.theme = previous;
} else if self.theme.theme != previous {
self.save_pending = true;
self.theme_index = self
.themes
.iter()
.position(|candidate| candidate == &self.theme.theme)
.unwrap_or(0);
}
}
@@ -317,7 +325,14 @@ impl State {
fn handle_theme_picker_key(&mut self, key: &KeyEvent) {
match key.code {
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => self.theme_picker = false,
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => {
self.theme_picker = false;
self.theme_index = self
.themes
.iter()
.position(|candidate| candidate == &self.theme.theme)
.unwrap_or(0);
}
KeyCode::Char('j') | KeyCode::Down => {
self.theme_index = (self.theme_index + 1).min(self.themes.len() - 1);
}
@@ -349,8 +364,6 @@ impl State {
) {
self.error = Some(error.to_string());
self.theme.border_style = previous;
} else if self.theme.border_style != previous {
self.save_pending = true;
}
}
@@ -423,6 +436,7 @@ impl State {
.resolution_choices()
.get(self.choice_index)
.and_then(|choice| choice.resolution())
&& self.config.defaults.resolution != Some(resolution)
{
self.config.defaults.resolution = Some(resolution);
self.save_pending = true;
@@ -443,15 +457,18 @@ impl State {
return;
};
if picker == ChoicePicker::ImageProtocol {
self.config.ui.image_protocol = match value.as_str() {
let protocol = match value.as_str() {
"kitty" => ImageProtocol::Kitty,
"iterm2" => ImageProtocol::Iterm2,
"quadrants" => ImageProtocol::Quadrants,
"halfblocks" => ImageProtocol::Halfblocks,
_ => ImageProtocol::Kitty,
};
if self.config.ui.image_protocol != protocol {
self.config.ui.image_protocol = protocol;
self.save_pending = true;
}
}
self.save_pending = true;
self.choice_picker = None;
}
SettingsPickerAction::None => {}
@@ -463,8 +480,11 @@ impl State {
}
fn apply_default_resolution(&mut self) {
self.config.defaults.resolution = Some(default_resolution());
self.save_pending = true;
let resolution = Some(default_resolution());
if self.config.defaults.resolution != resolution {
self.config.defaults.resolution = resolution;
self.save_pending = true;
}
self.error = None;
}
@@ -521,11 +541,15 @@ impl State {
pub fn confirm_auto_java(&mut self) -> Action {
self.enable_auto_java();
self.save_pending = false;
Action::Save(
Box::new(self.config.clone()),
self.theme.theme.clone(),
self.theme.border_style.clone(),
)
Action::Save(Box::new(self.config.clone()))
}
pub fn mark_save_failed(&mut self) {
self.save_pending = true;
}
pub fn invalidate_java_cache(&mut self) {
self.java_picker.invalidate_cache();
}
fn handle_java_picker_key(&mut self, key: &KeyEvent) {
@@ -548,6 +572,8 @@ impl State {
}
fn adjust_selected_memory(&mut self, forward: bool) {
let previous_min = self.config.defaults.memory_min.clone();
let previous_max = self.config.defaults.memory_max.clone();
let value = if self.selected == 3 {
&self.config.defaults.memory_min
} else {
@@ -565,7 +591,8 @@ impl State {
self.config.defaults.memory_min = value;
}
}
self.save_pending = true;
self.save_pending |= self.config.defaults.memory_min != previous_min
|| self.config.defaults.memory_max != previous_max;
self.error = None;
}
@@ -604,11 +631,7 @@ impl State {
if self.save_pending && self.editing.is_none() {
self.save_pending = false;
self.config = self.config.clone().normalize();
return Action::Save(
Box::new(self.config.clone()),
self.theme.theme.clone(),
self.theme.border_style.clone(),
);
return Action::Save(Box::new(self.config.clone()));
}
Action::None
}
@@ -1171,13 +1194,6 @@ fn image_protocol_title(protocol: ImageProtocol) -> &'static str {
}
}
fn window_mode_title(mode: WindowMode) -> &'static str {
match mode {
WindowMode::Windowed => "Windowed",
WindowMode::Fullscreen => "Fullscreen",
}
}
fn restart_required_for(state: &State, index: usize) -> bool {
let current = crate::config::SETTINGS.read();
match index {
@@ -1195,6 +1211,7 @@ fn status(enabled: bool) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::instance::models::WindowMode;
#[test]
fn launcher_memory_uses_slider_and_java_uses_picker() {
@@ -1413,8 +1430,23 @@ mod tests {
state.selected = 0;
state.handle_key(&KeyEvent::from(KeyCode::Enter));
assert!(state.theme_picker);
let active_theme = state.theme.theme.clone();
state.handle_key(&KeyEvent::from(KeyCode::Down));
state.handle_key(&KeyEvent::from(KeyCode::Esc));
assert!(!state.theme_picker);
assert_eq!(state.themes[state.theme_index], active_theme);
}
#[test]
fn failed_launcher_save_remains_pending() {
let mut state = State::new();
state.config.defaults.jvm_args.push("-Xretry".to_owned());
state.mark_save_failed();
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Down)),
Action::Save(..)
));
}
#[test]
+102 -45
View File
@@ -22,7 +22,8 @@ use crate::{
},
instance::loader::GameVersion,
instance::models::{
InstanceConfig, LaunchCommand, ModLoader, normalize_memory_value, parse_resolution,
InstanceConfig, LaunchCommand, ModLoader, memory_kib, normalize_memory_value,
parse_resolution,
},
tui::widgets::{
popups::{
@@ -32,11 +33,11 @@ use crate::{
ResolutionChoice, ResolutionPickerAction, SettingsPicker, SettingsPickerAction,
SettingsPickerBadge, SettingsPickerOption, adjust_memory, auto_label,
bundled_glfw_version, bundled_label as bundled_badge, default_label,
default_resolution, display_resolutions, environment_labels,
default_resolution, display_resolutions, environment_labels, format_tag_values,
handle_resolution_picker_key, handle_text_area_input, is_default_resolution,
memory_kib, parse_environment, render_memory_gauge, render_settings_picker,
parse_environment, parse_tag_values, render_memory_gauge, render_settings_picker,
resolution_choices, resolution_items, settings_text_area, tagged_row_count,
tagged_value_lines, toggle_window_mode,
tagged_value_lines, toggle_window_mode, window_mode_title,
},
},
search::SearchState,
@@ -95,6 +96,7 @@ pub struct State {
meta_dir: std::path::PathBuf,
display_resolutions: Vec<DisplayResolution>,
runtime_update_pending: bool,
save_retry_pending: bool,
}
pub enum Action {
@@ -131,14 +133,15 @@ impl State {
.unwrap_or_else(crate::instance::java::detect_java_path);
let java_cache = crate::storage::MetadataPaths::new(meta_dir).java_installations();
let mut java_picker = JavaPicker::with_cache(auto_java_path, Some(java_cache));
java_picker.open(instance.java_path.as_deref());
java_picker.set_current(instance.java_path.as_deref());
let desktop = crate::instance::desktop::exists(&instance.name);
Self {
original: instance.clone(),
draft: instance.clone(),
selected: 0,
editing: None,
desktop: crate::instance::desktop::exists(&instance.name),
original_desktop: crate::instance::desktop::exists(&instance.name),
desktop,
original_desktop: desktop,
error: None,
picker: None,
picker_index: 0,
@@ -159,6 +162,7 @@ impl State {
meta_dir: meta_dir.to_path_buf(),
display_resolutions: display_resolutions(),
runtime_update_pending: false,
save_retry_pending: false,
}
}
@@ -221,18 +225,13 @@ impl State {
3 => self.draft.java_path.clone().unwrap_or_default(),
4 => self.draft.memory_min.clone().unwrap_or_default(),
5 => self.draft.memory_max.clone().unwrap_or_default(),
6 => self.draft.jvm_args.join(" "),
7 => self
.draft
.environment
.iter()
.map(|(key, value)| format!("{key}={value}"))
.collect::<Vec<_>>()
.join(" "),
8 => self
.draft
.effective_window_mode(SETTINGS.read().defaults.window_mode)
.to_string(),
6 => format_tag_values(&self.draft.jvm_args),
7 => format_tag_values(&environment_labels(&self.draft.environment)),
8 => window_mode_title(
self.draft
.effective_window_mode(SETTINGS.read().defaults.window_mode),
)
.to_owned(),
9 => self
.draft
.effective_resolution(SETTINGS.read().defaults.resolution)
@@ -494,7 +493,7 @@ impl State {
let count = self.choice_values().len();
match key.code {
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => self.choice_picker = None,
KeyCode::Char('j') | KeyCode::Down | KeyCode::Right if count > 0 => {
KeyCode::Char('j') | KeyCode::Down if count > 0 => {
self.choice_index = (self.choice_index + 1).min(count - 1);
}
KeyCode::Char('k') | KeyCode::Up => {
@@ -526,8 +525,7 @@ impl State {
let selected = self
.resolution_choices()
.get(self.choice_index)
.cloned()
.and_then(|choice| choice.resolution());
.and_then(ResolutionChoice::resolution);
if let Some(resolution) = selected {
self.draft.resolution = Some(resolution);
self.draft.inherit_resolution = false;
@@ -564,22 +562,26 @@ impl State {
*load = LoadState::Loading;
let target = self.game_versions.clone();
let loader = self.draft.loader;
tokio::spawn(async move {
let result = super::version_lists::game_versions(loader).await;
*target
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = match result {
Ok(versions) => LoadState::Loaded(versions),
Err(error) => {
crate::feedback::errors::push_message(
tracing::Level::ERROR,
format!("Failed to load game versions: {error}"),
);
LoadState::Error(error)
}
};
crate::feedback::request_redraw();
});
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn(async move {
let result = super::version_lists::game_versions(loader).await;
*target
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = match result {
Ok(versions) => LoadState::Loaded(versions),
Err(error) => {
crate::feedback::errors::push_message(
tracing::Level::ERROR,
format!("Failed to load game versions: {error}"),
);
LoadState::Error(error)
}
};
crate::feedback::request_redraw();
});
} else {
*load = LoadState::Idle;
}
}
}
@@ -830,7 +832,7 @@ impl State {
self.picker = None;
self.picker_search.deactivate();
if cancel_runtime_change {
self.cancel_runtime_change();
let _ = self.cancel_runtime_change();
}
}
@@ -932,9 +934,10 @@ impl State {
),
4 => self.set_memory(4, normalize_memory_value(value)),
5 => self.set_memory(5, normalize_memory_value(value)),
6 => {
self.draft.jvm_args = value.split_whitespace().map(str::to_owned).collect();
}
6 => match parse_tag_values(value) {
Ok(arguments) => self.draft.jvm_args = arguments,
Err(error) => invalid(self, error),
},
7 => match parse_environment(value) {
Ok(environment) => self.draft.environment = environment,
Err(error) => invalid(self, error),
@@ -980,7 +983,9 @@ impl State {
if let Some(error) = self.error.take() {
return Action::Error(error);
}
if before == self.draft && desktop_before == self.desktop || !self.dirty() {
if (before == self.draft && desktop_before == self.desktop && !self.save_retry_pending)
|| !self.dirty()
{
return Action::None;
}
if self.runtime_changed() {
@@ -1005,6 +1010,7 @@ impl State {
};
}
if self.validate_before_save() {
self.save_retry_pending = false;
Action::Save(Box::new(self.draft.clone()), self.desktop)
} else {
Action::Error(
@@ -1092,10 +1098,19 @@ impl State {
self.glfw_picker
.set_bundled_version(bundled_glfw_version(&self.meta_dir, &saved.game_version));
self.runtime_update_pending = false;
self.save_retry_pending = false;
self.error = None;
}
pub fn cancel_runtime_change(&mut self) {
pub fn mark_save_failed(&mut self) {
self.save_retry_pending = true;
}
pub fn invalidate_java_cache(&mut self) {
self.java_picker.invalidate_cache();
}
pub fn cancel_runtime_change(&mut self) -> Option<(Box<InstanceConfig>, bool)> {
self.draft.game_version = self.original.game_version.clone();
self.draft.loader = self.original.loader;
self.draft.loader_version = self.original.loader_version.clone();
@@ -1104,6 +1119,8 @@ impl State {
self.picker_initialized = false;
self.runtime_update_pending = false;
self.error = None;
(self.dirty() && self.validate_before_save())
.then(|| (Box::new(self.draft.clone()), self.desktop))
}
}
@@ -1964,6 +1981,46 @@ mod tests {
assert!(state.editing.is_some());
}
#[test]
fn right_arrow_selects_loader_without_moving_down() {
let temp = tempfile::tempdir().unwrap();
let mut state = State::new(&instance(), temp.path());
state.selected = 1;
state.handle_key(&KeyEvent::from(KeyCode::Enter));
assert_eq!(state.choice_picker, Some(ChoicePicker::Loader));
state.handle_key(&KeyEvent::from(KeyCode::Right));
assert!(state.choice_picker.is_none());
assert_eq!(state.draft.loader, ModLoader::Fabric);
}
#[test]
fn failed_instance_save_retries_without_another_edit() {
let temp = tempfile::tempdir().unwrap();
let mut state = State::new(&instance(), temp.path());
state.draft.jvm_args.push("-Xretry".to_owned());
state.mark_save_failed();
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Down)),
Action::Save(..)
));
}
#[test]
fn cancelling_runtime_change_keeps_other_edits_ready_to_save() {
let temp = tempfile::tempdir().unwrap();
let mut state = State::new(&instance(), temp.path());
state.draft.game_version = "1.21.2".to_owned();
state.draft.jvm_args.push("-Xkeep".to_owned());
let (saved, _) = state.cancel_runtime_change().expect("remaining edit");
assert_eq!(saved.game_version, state.original.game_version);
assert_eq!(saved.jvm_args, ["-Xkeep"]);
}
#[test]
fn java_and_resolution_defaults_are_direct_actions_not_list_rows() {
let temp = tempfile::tempdir().unwrap();
@@ -2093,7 +2150,7 @@ mod tests {
assert!(state.draft.inherit_window_mode);
assert_eq!(
state.display_value(8),
SETTINGS.read().defaults.window_mode.to_string()
window_mode_title(SETTINGS.read().defaults.window_mode)
);
state.selected = 9;
@@ -4,7 +4,6 @@
mod render;
mod state;
pub use super::LoadState;
pub use render::{popup_rect, render};
pub use state::{WizardParams, WizardState, WizardStep, handle_key, take_result};
+259 -28
View File
@@ -6,7 +6,10 @@
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
sync::{Arc, Mutex},
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
@@ -21,7 +24,10 @@ use ratatui_textarea::{CursorMove, TextArea};
use crate::{
config::{settings::DEFAULT_RESOLUTION, theme::THEME},
instance::{WindowMode, java::JavaInstallation},
instance::{
java::JavaInstallation,
models::{WindowMode, memory_kib},
},
tui::widgets::{popups::LoadState, status_badge},
};
@@ -36,6 +42,13 @@ pub(crate) fn toggle_window_mode(mode: WindowMode) -> WindowMode {
}
}
pub(crate) fn window_mode_title(mode: WindowMode) -> &'static str {
match mode {
WindowMode::Windowed => "Windowed",
WindowMode::Fullscreen => "Fullscreen",
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SettingsPickerBadge {
Auto,
@@ -192,6 +205,7 @@ pub(crate) struct JavaPicker {
picker: SettingsPicker,
cache_path: Option<PathBuf>,
refresh_started: bool,
generation: Arc<AtomicU64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -250,7 +264,7 @@ pub(crate) fn handle_resolution_picker_key(
match key.code {
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => ResolutionPickerAction::Back,
KeyCode::Char('d') => ResolutionPickerAction::Default,
KeyCode::Char('j') | KeyCode::Down | KeyCode::Right if count > 0 => {
KeyCode::Char('j') | KeyCode::Down if count > 0 => {
*selected = (*selected + 1).min(count - 1);
ResolutionPickerAction::None
}
@@ -302,12 +316,17 @@ impl JavaPicker {
picker: SettingsPicker::default(),
cache_path,
refresh_started: false,
generation: Arc::new(AtomicU64::new(0)),
}
}
pub(crate) fn open(&mut self, current: Option<&str>) {
pub(crate) fn set_current(&mut self, current: Option<&str>) {
self.current = current.map(str::to_owned);
self.picker.reset();
}
pub(crate) fn open(&mut self, current: Option<&str>) {
self.set_current(current);
if self.refresh_started {
return;
}
@@ -322,6 +341,8 @@ impl JavaPicker {
drop(load);
let target = self.load.clone();
let cache_path = self.cache_path.clone();
let refresh_generation = self.generation.load(Ordering::Relaxed);
let generation = self.generation.clone();
let selected_paths = [Some(self.detected.clone()), self.current.clone()];
let discover = move || {
let mut installations = crate::instance::java::discover_installations();
@@ -337,22 +358,33 @@ impl JavaPicker {
installations.push(installation);
}
}
let mut load = target
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if generation.load(Ordering::Relaxed) != refresh_generation {
return;
}
if let Some(cache_path) = cache_path
&& let Err(error) =
crate::instance::java::save_installation_cache(&cache_path, &installations)
{
tracing::debug!("Could not cache Java installations: {error}");
}
*target
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
LoadState::Loaded(installations);
*load = LoadState::Loaded(installations);
drop(load);
crate::feedback::request_redraw();
};
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn_blocking(discover);
} else {
self.refresh_started = false;
let mut load = self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if matches!(*load, LoadState::Loading) {
*load = LoadState::Idle;
}
}
}
@@ -493,6 +525,20 @@ impl JavaPicker {
pub(crate) fn automatic_change(&self, current: &str) -> bool {
!same_executable(current, &self.detected)
}
pub(crate) fn invalidate_cache(&mut self) {
self.generation.fetch_add(1, Ordering::Relaxed);
let mut load = self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(cache_path) = &self.cache_path {
let _ = std::fs::remove_file(cache_path);
}
*load = LoadState::Idle;
self.picker.reset();
self.refresh_started = false;
}
}
impl Default for JavaPicker {
@@ -542,7 +588,7 @@ impl GlfwPicker {
*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = LoadState::Loaded(Vec::new());
.unwrap_or_else(std::sync::PoisonError::into_inner) = LoadState::Idle;
}
}
@@ -607,7 +653,7 @@ impl GlfwPicker {
{
LoadState::Loaded(installations) => installations
.iter()
.find(|installation| installation.path.to_string_lossy() == path)
.find(|installation| same_executable(&installation.path.to_string_lossy(), path))
.and_then(|installation| installation.version.clone()),
_ => None,
};
@@ -771,11 +817,25 @@ fn discover_glfw_installations() -> Vec<GlfwInstallation> {
}
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();
name.starts_with("libglfw") && (name.contains(".so") || name.ends_with(".dylib"))
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")
}
@@ -812,18 +872,12 @@ fn java_runtime_label(path: &str, version: Option<&str>) -> String {
}
fn java_title(version: &str) -> String {
let mut parts = version.split(['.', '_']);
let first = parts.next().unwrap_or(version);
let major = if first == "1" {
parts.next().unwrap_or(first)
let major = crate::instance::java::java_major(Some(version));
if major == 0 {
"Java".to_owned()
} else {
first
};
format!("Java {major}")
}
pub(crate) fn memory_kib(value: &str) -> Option<u64> {
crate::instance::models::memory_kib(value)
format!("Java {major}")
}
}
pub(crate) fn adjust_memory(value: &str, forward: bool) -> String {
@@ -926,6 +980,10 @@ pub(crate) fn handle_text_area_input(input: &mut TextArea<'_>, key: &KeyEvent) {
pub(crate) fn settings_text_area(lines: Vec<String>) -> TextArea<'static> {
let theme = THEME.as_ref();
let lines = lines
.into_iter()
.flat_map(|line| line.split('\n').map(str::to_owned).collect::<Vec<String>>())
.collect::<Vec<_>>();
let mut editor = TextArea::new(if lines.is_empty() {
vec![String::new()]
} else {
@@ -939,9 +997,79 @@ pub(crate) fn settings_text_area(lines: Vec<String>) -> TextArea<'static> {
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> {
let mut environment = BTreeMap::new();
for assignment in value.split_whitespace() {
for assignment in parse_tag_values(value)? {
let Some((key, value)) = assignment.split_once('=') else {
return Err(format!(
"Environment variable '{assignment}' must use KEY=value."
@@ -1099,7 +1227,7 @@ pub(crate) fn resolution_choices(
let mut choices = Vec::new();
choices.extend(displays.iter().cloned().map(ResolutionChoice::Display));
for (width, height) in [
(854, 480),
DEFAULT_RESOLUTION,
(1280, 720),
(1600, 900),
(1920, 1080),
@@ -1229,6 +1357,52 @@ mod tests {
);
}
#[test]
fn setting_java_value_does_not_start_discovery() {
let mut picker = JavaPicker::with_auto_path("/auto/java".to_owned());
picker.set_current(Some("/custom/java"));
assert!(!picker.refresh_started);
assert!(matches!(
*picker
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
LoadState::Idle
));
picker.open(Some("/custom/java"));
assert!(!picker.refresh_started);
assert!(matches!(
*picker
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
LoadState::Idle
));
}
#[test]
fn invalidating_java_picker_drops_memory_and_disk_cache() {
let temp = tempfile::tempdir().unwrap();
let cache = temp.path().join("cache/java/installations.json");
std::fs::create_dir_all(cache.parent().unwrap()).unwrap();
std::fs::write(&cache, "[]").unwrap();
let mut picker = JavaPicker::with_cache("/auto/java".to_owned(), Some(cache.clone()));
*picker.load.lock().unwrap() = LoadState::Loaded(vec![JavaInstallation {
path: "/cached/java".into(),
version: Some("21".to_owned()),
}]);
picker.refresh_started = true;
picker.invalidate_cache();
assert!(!cache.exists());
assert!(!picker.refresh_started);
assert!(matches!(*picker.load.lock().unwrap(), LoadState::Idle));
}
#[test]
fn java_title_is_minimal_and_uses_the_major_version() {
let picker = JavaPicker::with_auto_path("/opt/jdk-25/bin/java".to_owned());
@@ -1245,6 +1419,7 @@ mod tests {
"Java 25 /opt/jdk-25/bin/java"
);
assert_eq!(java_title("1.8.0_412"), "Java 8");
assert_eq!(java_title("21-ea"), "Java 21");
}
#[test]
@@ -1282,6 +1457,20 @@ mod tests {
picker.handle_key(&KeyEvent::from(KeyCode::Enter)),
SettingsPickerAction::Select
);
assert_eq!(
picker.handle_key(&KeyEvent::from(KeyCode::Right)),
SettingsPickerAction::Select
);
}
#[test]
fn right_arrow_selects_resolution_instead_of_moving_down() {
let mut selected = 0;
assert_eq!(
handle_resolution_picker_key(&mut selected, 3, &KeyEvent::from(KeyCode::Right)),
ResolutionPickerAction::Select
);
assert_eq!(selected, 0);
}
#[test]
@@ -1310,10 +1499,11 @@ mod tests {
#[test]
fn glfw_library_names_are_recognized() {
assert!(is_glfw_library(Path::new("/usr/lib/libglfw.so.3")));
assert!(is_glfw_library(Path::new("/usr/lib/libglfw.3.dylib")));
assert!(is_glfw_library(Path::new("C:/bin/glfw3.dll")));
assert!(!is_glfw_library(Path::new("/usr/lib/libGL.so")));
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")
@@ -1333,6 +1523,47 @@ mod tests {
assert_eq!(input.lines(), ["one "]);
}
#[test]
fn tag_values_with_spaces_and_quotes_round_trip() {
let values = vec![
"-Xmx2G".to_owned(),
"-Dlabel=hello world".to_owned(),
r"C:\Program Files\Java".to_owned(),
"-Dquote=\"value\"".to_owned(),
String::new(),
];
let formatted = format_tag_values(&values);
assert_eq!(parse_tag_values(&formatted).unwrap(), values);
assert!(parse_tag_values("\"unterminated").is_err());
}
#[test]
fn tag_values_drop_exact_duplicates_without_reordering() {
assert_eq!(
parse_tag_values("-Xmx2G '-Dlabel=hello world' -Xmx2G").unwrap(),
["-Xmx2G", "-Dlabel=hello world"]
);
}
#[test]
fn environment_values_can_contain_spaces() {
let environment =
parse_environment(r#"LABEL="hello world" PATH="C:\Program Files""#).unwrap();
assert_eq!(
environment.get("LABEL").map(String::as_str),
Some("hello world")
);
assert_eq!(
environment.get("PATH").map(String::as_str),
Some(r"C:\Program Files")
);
assert!(parse_environment("=missing").is_err());
assert!(parse_environment("KEY=one KEY=two").is_err());
}
#[test]
fn memory_thumb_clears_the_first_unfilled_cell() {
let backend = ratatui::backend::TestBackend::new(40, 1);
+4 -21
View File
@@ -4,7 +4,7 @@
// settings panel: manages config profiles and shows compact instance info.
// detailed instance and launcher configuration opens in the TUI popups.
use std::{path::PathBuf, process::Command};
use std::path::{Path, PathBuf};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
@@ -50,7 +50,6 @@ pub struct SettingsState {
active_profile: Option<String>,
instance_name: Option<String>,
java_key: Option<String>,
java_source: Option<String>,
java_label: String,
}
@@ -69,7 +68,6 @@ impl SettingsState {
active_profile: None,
instance_name: None,
java_key: None,
java_source: None,
java_label: "unknown".to_string(),
};
state.select_active();
@@ -129,7 +127,6 @@ impl SettingsState {
.map(java_version_label)
.unwrap_or_else(|| "unknown".to_string());
self.java_key = java_key;
self.java_source = java_source;
}
}
}
@@ -174,25 +171,11 @@ fn effective_java_path(instance: &InstanceConfig) -> String {
}
fn java_version_label(java_path: &str) -> String {
let output = Command::new(java_path).arg("-version").output();
let Ok(output) = output else {
let Some(version) = crate::instance::java::java_version(Path::new(java_path)) else {
return "unknown".to_string();
};
let raw = String::from_utf8_lossy(if output.stderr.is_empty() {
&output.stdout
} else {
&output.stderr
});
let first_line = raw.lines().next().unwrap_or_default();
let Some(version) = first_line.split('"').nth(1) else {
return "unknown".to_string();
};
let major = if let Some(stripped) = version.strip_prefix("1.") {
stripped.split('.').next().unwrap_or(stripped)
} else {
version.split('.').next().unwrap_or(version)
};
if major.is_empty() {
let major = crate::instance::java::java_major(Some(&version));
if major == 0 {
"unknown".to_string()
} else {
format!("jdk{major}")