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

+3
View File
@@ -19,8 +19,11 @@ use crate::instance::{InstanceConfig, InstanceManager};
// so the main loop can pick them up without blocking
pub(super) static PENDING_INSTANCES: LazyLock<Arc<Mutex<Vec<InstanceConfig>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
pub(super) static COMPLETED_INSTANCE_SETTINGS_UPDATES: LazyLock<Arc<Mutex<Vec<InstanceConfig>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
pub(super) static FAILED_INSTANCE_SETTINGS_UPDATES: LazyLock<Arc<Mutex<Vec<String>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
pub(super) const RUNTIME_UPDATE_PENDING_MESSAGE: &str = "Wait for the runtime update to finish";
pub struct App {
pub(super) exit: bool,
+115 -62
View File
@@ -10,7 +10,10 @@ use ratatui::{
use std::time::Duration;
use super::Tui;
use super::app::{App, FAILED_INSTANCE_SETTINGS_UPDATES, FocusedArea, PENDING_INSTANCES};
use super::app::{
App, COMPLETED_INSTANCE_SETTINGS_UPDATES, FAILED_INSTANCE_SETTINGS_UPDATES, FocusedArea,
PENDING_INSTANCES, RUNTIME_UPDATE_PENDING_MESSAGE,
};
use super::widgets::{self, popups::import_modpack, popups::new_instance};
use crate::feedback::errors as error_buffer;
use crate::feedback::progress;
@@ -43,6 +46,7 @@ impl App {
// every content type has its own pending queue because they each
// get scanned/loaded on separate tokio tasks
self.drain_pending_instances();
self.drain_completed_instance_settings_updates();
self.drain_failed_instance_settings_updates();
self.instances_state.drain_modpack_updates();
self.drain_pending_last_played();
@@ -619,7 +623,7 @@ impl App {
) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = self.instance_manager.meta_dir.clone();
let pending_instances = PENDING_INSTANCES.clone();
let completed_updates = COMPLETED_INSTANCE_SETTINGS_UPDATES.clone();
tokio::spawn(async move {
progress::set_action(format!("Updating instance '{}'...", updated.name));
@@ -642,11 +646,7 @@ impl App {
}
};
let shortcut_result = if desktop {
crate::instance::desktop::create(&updated).map(|_| ())
} else {
crate::instance::desktop::remove(&updated.name)
};
let shortcut_result = crate::instance::desktop::set_enabled(&updated, desktop);
if let Err(error) = shortcut_result {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
@@ -655,7 +655,7 @@ impl App {
pushed_at: std::time::Instant::now(),
});
}
if let Ok(mut pending) = pending_instances.lock() {
if let Ok(mut pending) = completed_updates.lock() {
pending.push(updated);
}
progress::clear();
@@ -834,6 +834,14 @@ impl App {
use crate::instance::launch;
use crate::instance::runtime;
if self
.pending_instance_settings_updates
.contains(&instance.name)
{
error_buffer::push_message(tracing::Level::WARN, RUNTIME_UPDATE_PENDING_MESSAGE);
return;
}
let instance = match self.instance_manager.load_one(&instance.name) {
Ok(config) => config,
Err(e) => {
@@ -895,42 +903,73 @@ impl App {
}
fn drain_pending_instances(&mut self) {
if let Ok(mut pending) = PENDING_INSTANCES.lock() {
for config in pending.drain(..) {
let settings_update = self.pending_instance_settings_updates.remove(&config.name);
if settings_update
&& let Some(state) = self.instance_settings.as_mut()
&& state.runtime_update_pending_for(&config.name)
{
let desktop = crate::instance::desktop::exists(&config.name);
state.mark_saved(&config, desktop);
}
self.forget_instance_content(&config.name);
widgets::instances::spawn_modpack_update_check(&config);
if self
.instances_state
.instances
.iter()
.any(|instance| instance.name == config.name)
{
let name = config.name.clone();
self.instances_state.replace_instance(&name, config);
} else {
self.instances_state.add_instance(config);
}
let pending = PENDING_INSTANCES
.lock()
.map(|mut pending| pending.drain(..).collect::<Vec<_>>())
.unwrap_or_default();
for config in pending {
self.apply_pending_instance(config, false);
}
}
fn drain_completed_instance_settings_updates(&mut self) {
let completed = COMPLETED_INSTANCE_SETTINGS_UPDATES
.lock()
.map(|mut pending| pending.drain(..).collect::<Vec<_>>())
.unwrap_or_default();
for config in completed {
self.apply_pending_instance(config, true);
}
}
fn apply_pending_instance(
&mut self,
config: crate::instance::InstanceConfig,
settings_update: bool,
) {
let config = self
.instance_manager
.load_one(&config.name)
.unwrap_or(config);
if settings_update {
self.pending_instance_settings_updates.remove(&config.name);
if let Some(state) = self.instance_settings.as_mut()
&& state.runtime_update_pending_for(&config.name)
{
let desktop = crate::instance::desktop::exists(&config.name);
state.mark_saved(&config, desktop);
}
}
self.forget_instance_content(&config.name);
widgets::instances::spawn_modpack_update_check(&config);
if self
.instances_state
.instances
.iter()
.any(|instance| instance.name == config.name)
{
let name = config.name.clone();
self.instances_state.replace_instance(&name, config);
} else {
self.instances_state.add_instance(config);
}
}
fn drain_failed_instance_settings_updates(&mut self) {
if let Ok(mut failed) = FAILED_INSTANCE_SETTINGS_UPDATES.lock() {
for name in failed.drain(..) {
self.pending_instance_settings_updates.remove(&name);
if let Some(state) = self.instance_settings.as_mut()
&& state.runtime_update_pending_for(&name)
{
state.cancel_runtime_change();
}
let failed = FAILED_INSTANCE_SETTINGS_UPDATES
.lock()
.map(|mut failed| failed.drain(..).collect::<Vec<_>>())
.unwrap_or_default();
for name in failed {
self.pending_instance_settings_updates.remove(&name);
let remaining = self.instance_settings.as_mut().and_then(|state| {
state
.runtime_update_pending_for(&name)
.then(|| state.cancel_runtime_change())
.flatten()
});
if let Some((updated, desktop)) = remaining {
self.apply_instance_settings(*updated, desktop);
}
}
}
@@ -987,35 +1026,49 @@ async fn apply_instance_settings_update(
) -> color_eyre::Result<crate::instance::InstanceConfig> {
manager.repair_runtime_cache(&updated).await?;
let profile_changed = previous.config_sync_profile != updated.config_sync_profile;
if profile_changed {
updated.config_sync_profile = crate::instance::config_sync::switch_profile(
&previous.name,
previous.config_sync_profile.as_deref(),
updated.config_sync_profile.as_deref(),
&manager.meta_dir,
&manager.instances_dir.join(&previous.name),
)?;
if crate::instance::runtime::is_active(&previous.name) {
color_eyre::eyre::bail!("instance started while its runtime was being updated");
}
if let Err(error) = manager.save(&updated) {
if profile_changed
&& let Err(rollback_error) = crate::instance::config_sync::switch_profile(
&previous.name,
updated.config_sync_profile.as_deref(),
previous.config_sync_profile.as_deref(),
&manager.meta_dir,
&manager.instances_dir.join(&previous.name),
)
{
tracing::error!("Failed to roll back config profile: {rollback_error}");
}
return Err(error.into());
}
let current = manager.load_one(&previous.name)?;
updated = merge_instance_settings(previous, &updated, current);
manager.save(&updated)?;
Ok(updated)
}
pub(super) fn merge_instance_settings(
previous: &crate::instance::InstanceConfig,
updated: &crate::instance::InstanceConfig,
mut current: crate::instance::InstanceConfig,
) -> crate::instance::InstanceConfig {
macro_rules! apply_changed {
($field:ident) => {
if previous.$field != updated.$field {
current.$field.clone_from(&updated.$field);
}
};
}
apply_changed!(game_version);
apply_changed!(loader);
apply_changed!(loader_version);
apply_changed!(java_path);
apply_changed!(memory_max);
apply_changed!(memory_min);
apply_changed!(jvm_args);
apply_changed!(environment);
apply_changed!(window_mode);
apply_changed!(inherit_window_mode);
apply_changed!(resolution);
apply_changed!(inherit_resolution);
apply_changed!(preferred_account);
apply_changed!(pre_launch_command);
apply_changed!(post_exit_command);
apply_changed!(glfw_path);
current
}
fn mark_terminal_images(buffer: &mut Buffer, alternate: bool) {
// toggling an invisible suffix lets the normal cell diff redraw exposed
// images before later popup cells, without clearing or repainting the screen
+107 -37
View File
@@ -217,8 +217,9 @@ impl App {
if instance.preferred_account.as_deref()
== Some(removed_uuid.as_str())
{
instance.preferred_account = None;
if let Err(error) = self.instance_manager.save(instance) {
let mut updated = instance.clone();
updated.preferred_account = None;
if let Err(error) = self.instance_manager.save(&updated) {
error_buffer::push_message(
tracing::Level::ERROR,
format!(
@@ -226,6 +227,8 @@ impl App {
instance.name
),
);
} else {
*instance = updated;
}
}
}
@@ -301,6 +304,12 @@ impl App {
match crate::storage::clear_disposable_caches(&meta_dir) {
Ok(()) => {
self.reset_discovery_states();
if let Some(state) = self.global_settings.as_mut() {
state.invalidate_java_cache();
}
if let Some(state) = self.instance_settings.as_mut() {
state.invalidate_java_cache();
}
error_buffer::push_message(
tracing::Level::INFO,
"Cleared launcher caches",
@@ -348,11 +357,9 @@ impl App {
);
if let Some(widgets::popups::global_settings::Action::Save(
config,
theme,
border,
)) = action
{
self.apply_global_settings(*config, theme, border);
self.apply_global_settings(*config);
}
}
}
@@ -375,8 +382,12 @@ impl App {
FocusedArea::Settings
}
Some(confirm_popup::ConfirmTarget::InstanceRuntime { .. }) => {
if let Some(state) = self.instance_settings.as_mut() {
state.cancel_runtime_change();
let remaining = self
.instance_settings
.as_mut()
.and_then(|state| state.cancel_runtime_change());
if let Some((updated, desktop)) = remaining {
self.apply_instance_settings(*updated, desktop);
}
FocusedArea::InstanceSettings
}
@@ -695,6 +706,16 @@ impl App {
}
widgets::settings::SettingsAction::SelectProfile(profile) => {
if let Some(instance) = self.instances_state.selected_instance().cloned() {
if self
.pending_instance_settings_updates
.contains(&instance.name)
{
error_buffer::push_message(
tracing::Level::WARN,
super::app::RUNTIME_UPDATE_PENDING_MESSAGE,
);
return Ok(());
}
let instance_dir = self.instance_manager.instances_dir.join(&instance.name);
match crate::instance::config_sync::switch_profile(
&instance.name,
@@ -784,8 +805,8 @@ impl App {
self.global_settings = None;
self.focused = self.pre_overlay_focused;
}
widgets::popups::global_settings::Action::Save(config, theme, border) => {
self.apply_global_settings(*config, theme, border);
widgets::popups::global_settings::Action::Save(config) => {
self.apply_global_settings(*config);
}
}
return Ok(());
@@ -995,8 +1016,15 @@ impl App {
{
if let Some(instance) = self.instances_state.selected_instance() {
let name = instance.name.clone();
confirm_popup::set_pending_instance_delete(&name);
self.focused = FocusedArea::ConfirmDelete;
if self.pending_instance_settings_updates.contains(&name) {
error_buffer::push_message(
tracing::Level::WARN,
super::app::RUNTIME_UPDATE_PENDING_MESSAGE,
);
} else {
confirm_popup::set_pending_instance_delete(&name);
self.focused = FocusedArea::ConfirmDelete;
}
}
}
// shift+enter = open .minecraft folder in file manager
@@ -1050,7 +1078,14 @@ impl App {
&& !self.instances_state.search.active =>
{
if let Some(inst) = self.instances_state.selected_instance() {
self.instances_state.renaming = Some(inst.name.clone());
if self.pending_instance_settings_updates.contains(&inst.name) {
error_buffer::push_message(
tracing::Level::WARN,
super::app::RUNTIME_UPDATE_PENDING_MESSAGE,
);
} else {
self.instances_state.renaming = Some(inst.name.clone());
}
}
}
// esc = kill running instance. brutal but effective
@@ -1090,6 +1125,20 @@ impl App {
}
fn spawn_modpack_update(&mut self) {
if self
.instances_state
.selected_instance()
.is_some_and(|instance| {
self.pending_instance_settings_updates
.contains(&instance.name)
})
{
error_buffer::push_message(
tracing::Level::WARN,
super::app::RUNTIME_UPDATE_PENDING_MESSAGE,
);
return;
}
let Some(target) = self.instances_state.selected_modpack_update() else {
return;
};
@@ -1100,6 +1149,16 @@ impl App {
let Some(instance) = self.instances_state.selected_instance() else {
return;
};
if self
.pending_instance_settings_updates
.contains(&instance.name)
{
error_buffer::push_message(
tracing::Level::WARN,
super::app::RUNTIME_UPDATE_PENDING_MESSAGE,
);
return;
}
let Some(source) = instance.modpack_source.clone() else {
return;
};
@@ -2163,19 +2222,10 @@ impl App {
self.focused = FocusedArea::InstanceSettings;
}
fn apply_global_settings(
&mut self,
config: crate::config::Config,
theme: String,
border: crate::config::theme::BorderStyle,
) {
fn apply_global_settings(&mut self, config: crate::config::Config) {
let result = crate::config::SETTINGS.save_launcher_settings(config);
match result {
Ok(outcome) => {
if let Err(error) = crate::config::theme::apply_theme(theme, border) {
error_buffer::push_message(tracing::Level::ERROR, error.to_string());
return;
}
if outcome.provider_changed {
self.reset_discovery_states();
}
@@ -2195,13 +2245,18 @@ impl App {
}
crate::feedback::request_redraw();
}
Err(error) => error_buffer::push_message(tracing::Level::ERROR, error.to_string()),
Err(error) => {
if let Some(state) = self.global_settings.as_mut() {
state.mark_save_failed();
}
error_buffer::push_message(tracing::Level::ERROR, error.to_string());
}
}
}
fn apply_instance_settings(
pub(super) fn apply_instance_settings(
&mut self,
updated: crate::instance::models::InstanceConfig,
mut updated: crate::instance::models::InstanceConfig,
desktop: bool,
) {
let Some(previous) = self.instances_state.selected_instance().cloned() else {
@@ -2219,7 +2274,10 @@ impl App {
pushed_at: std::time::Instant::now(),
});
if let Some(state) = self.instance_settings.as_mut() {
state.cancel_runtime_change();
let remaining = state.cancel_runtime_change();
if let Some((updated, desktop)) = remaining {
self.apply_instance_settings(*updated, desktop);
}
}
return;
}
@@ -2232,13 +2290,20 @@ impl App {
return;
}
let current = match self.instance_manager.load_one(&previous.name) {
Ok(current) => current,
Err(error) => {
if let Some(state) = self.instance_settings.as_mut() {
state.mark_save_failed();
}
error_buffer::push_message(tracing::Level::ERROR, error.to_string());
return;
}
};
updated = super::event::merge_instance_settings(&previous, &updated, current);
match self.instance_manager.save(&updated) {
Ok(()) => {
let shortcut_result = if desktop {
crate::instance::desktop::create(&updated).map(|_| ())
} else {
crate::instance::desktop::remove(&updated.name)
};
let shortcut_result = crate::instance::desktop::set_enabled(&updated, desktop);
let saved_desktop = match shortcut_result {
Ok(()) => desktop,
Err(error) => {
@@ -2257,12 +2322,17 @@ impl App {
state.mark_saved(&updated, saved_desktop);
}
}
Err(error) => error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: error.to_string(),
pushed_at: std::time::Instant::now(),
}),
Err(error) => {
if let Some(state) = self.instance_settings.as_mut() {
state.mark_save_failed();
}
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: error.to_string(),
pushed_at: std::time::Instant::now(),
});
}
}
}
+63 -2
View File
@@ -26,6 +26,26 @@ fn edited_instance_config_reloads_into_the_ui() {
);
}
#[test]
fn runtime_update_merges_only_confirmed_fields_into_latest_config() {
let mut ui = UiHarness::new();
ui.add_instance("Merge Runtime");
let previous = ui.app.instances_state.selected_instance().unwrap().clone();
let mut updated = previous.clone();
updated.game_version = "1.21.2".to_owned();
updated.memory_max = Some("8G".to_owned());
let mut current = previous.clone();
current.config_sync_profile = Some("shared".to_owned());
current.preferred_account = Some("newer-account".to_owned());
let merged = merge_instance_settings(&previous, &updated, current);
assert_eq!(merged.game_version, "1.21.2");
assert_eq!(merged.memory_max.as_deref(), Some("8G"));
assert_eq!(merged.config_sync_profile.as_deref(), Some("shared"));
assert_eq!(merged.preferred_account.as_deref(), Some("newer-account"));
}
#[test]
fn completed_background_instance_is_drained_into_the_ui() {
let mut ui = UiHarness::new();
@@ -57,6 +77,42 @@ fn completed_background_instance_is_drained_into_the_ui() {
assert_eq!(ui.app.mods_state.loaded_for.as_deref(), Some("Pending"));
}
#[test]
fn unrelated_background_result_does_not_complete_runtime_update() {
let mut ui = UiHarness::new();
ui.add_instance("Pending Runtime");
ui.app
.pending_instance_settings_updates
.insert("Pending Runtime".to_owned());
let config = ui.app.instances_state.selected_instance().unwrap().clone();
PENDING_INSTANCES.lock().unwrap().push(config);
ui.app.drain_pending_instances();
assert!(
ui.app
.pending_instance_settings_updates
.contains("Pending Runtime")
);
}
#[test]
fn pending_runtime_update_blocks_instance_rename() {
let mut ui = UiHarness::new();
ui.add_instance("Pending Rename");
ui.app
.pending_instance_settings_updates
.insert("Pending Rename".to_owned());
ui.key(crossterm::event::KeyCode::Char('r'));
assert!(ui.app.instances_state.renaming.is_none());
assert_eq!(
crate::feedback::errors::peek_error().map(|error| error.message),
Some(RUNTIME_UPDATE_PENDING_MESSAGE.to_owned())
);
}
#[test]
fn runtime_settings_update_keeps_the_editor_open_and_handles_results() {
let mut ui = UiHarness::new();
@@ -82,8 +138,12 @@ fn runtime_settings_update_keeps_the_editor_open_and_handles_results() {
let mut updated = ui.app.instances_state.selected_instance().unwrap().clone();
updated.game_version = "1.21.2".to_owned();
PENDING_INSTANCES.lock().unwrap().push(updated);
ui.app.drain_pending_instances();
ui.app.instance_manager.save(&updated).unwrap();
COMPLETED_INSTANCE_SETTINGS_UPDATES
.lock()
.unwrap()
.push(updated);
ui.app.drain_completed_instance_settings_updates();
let state = ui.app.instance_settings.as_ref().unwrap();
assert_eq!(state.draft.game_version, "1.21.2");
@@ -188,6 +248,7 @@ fn structural_settings_update_repairs_runtime_before_persisting() {
serde_json::to_vec(&serde_json::json!({
"id": "1.21.2",
"mainClass": "net.minecraft.client.main.Main",
"arguments": { "game": [], "jvm": [] },
"assetIndex": {
"id": "1.21.2",
"url": format!("{}/assets.json", server.uri()),
+8
View File
@@ -30,6 +30,14 @@ impl UiHarness {
.lock()
.unwrap_or_else(|error| error.into_inner())
.clear();
crate::tui::app::COMPLETED_INSTANCE_SETTINGS_UPDATES
.lock()
.unwrap_or_else(|error| error.into_inner())
.clear();
crate::tui::app::PENDING_INSTANCES
.lock()
.unwrap_or_else(|error| error.into_inner())
.clear();
widgets::popups::new_instance::reset_for_test();
widgets::popups::import_modpack::reset_for_test();
crate::feedback::errors::ERROR_EVENTS
+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}")