fix: reload editor saves and reject stale TUI actions

This commit is contained in:
objz committed 2026-10-01 23:25:43 +02:00
1 parent eb53c7164e
commit 9cd454cee2
33 files changed
+2297 -638

No files matched your search

+17 -5
View File
@@ -1364,11 +1364,8 @@ impl DiscoveryState {
pub(crate) fn set_filter_loader(&mut self, loader: ModLoader) {
if self.filter_loader != loader {
*self
.filter_game_versions
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
crate::tui::widgets::popups::LoadState::Idle;
self.filter_game_versions =
Arc::new(Mutex::new(crate::tui::widgets::popups::LoadState::Idle));
}
self.filter_loader = loader;
}
@@ -2645,6 +2642,21 @@ impl DiscoveryState {
self.pending_orphan_cleanup.take()
}
pub(in crate::tui) fn text_input_active(&self) -> bool {
if let Some(popup) = &self.version_popup {
return popup.selecting_world && !popup.confirming && popup.worlds.search.active;
}
if self.project_page_open() {
return false;
}
if self.sort_panel_open && !self.search.active {
return self.sort_panel_focused
&& self.filter_version_picker_open
&& self.filter_version_search.active;
}
self.search.active
}
fn should_load_more(&self) -> bool {
if self.page_loading
|| (self.preparing_list.is_some() && self.retry_page_at.is_none())
+1 -8
View File
@@ -578,7 +578,7 @@ impl ContentListState {
&& !self
.version_metadata
.contains_key(&(project.provider.clone(), project.version_id.clone()));
if !self.requested_provider_icons.insert(key) && !missing_version {
if !self.requested_provider_icons.insert(key) {
continue;
}
let pending = self.pending_provider_icons.clone();
@@ -875,8 +875,6 @@ impl ContentListState {
}
}
// drain streaming entries from the initial load. each entry arrives
// individually and is inserted in sorted position for a smooth fill-in
pub fn drain_pending(&mut self) -> bool {
let Some(rx) = &self.stream_rx else {
return false;
@@ -1808,8 +1806,6 @@ impl ContentListState {
.collect();
}
// enable/disable by renaming the file with/without .disabled extension.
// this is how most minecraft launchers handle it
pub fn toggle_selected(&mut self) {
let Some(index) = self.list_state.selected else {
return;
@@ -2694,9 +2690,6 @@ fn preserve_visual_metadata(entry: &mut ContentEntry, previous: &mut ContentEntr
}
}
// renders one row of a mod icon using half-block characters (U+2584).
// each cell packs two vertical pixels via fg/bg colors, giving
// double the vertical resolution out of the terminal
fn icon_spans(
icon_pixels: Option<&Vec<Vec<IconCell>>>,
row: usize,
+2 -3
View File
@@ -597,7 +597,6 @@ pub fn render(
return;
}
// lazy-load: only scan when switching to an instance that hasn't been loaded yet
match tab {
ContentTab::Mods
| ContentTab::ResourcePacks
@@ -643,8 +642,8 @@ pub fn render(
}
ContentTab::Worlds => {
if let Some(instance) = instance {
if let Some((world_name, world_path)) = open_world_datapacks {
let cache_key = format!("{}:{world_name}", instance.name);
if let Some((_, world_path)) = open_world_datapacks {
let cache_key = format!("{}:{world_path:?}", instance.name);
let content_dir = world_path.join("datapacks");
if world_datapacks_state.loaded_for.as_deref() != Some(cache_key.as_str()) {
world_datapacks_state.start_load(
+24 -25
View File
@@ -76,6 +76,7 @@ impl LogsState {
self.viewer_scroll = 0;
self.viewer_focused = false;
self.selected_path = None;
self.was_live = false;
self.last_rescan = std::time::Instant::now();
let dir = instances_dir.to_path_buf();
@@ -99,33 +100,38 @@ impl LogsState {
pub fn drain_pending(&mut self) {
let live_now = self.has_live();
self.was_live = live_now;
let live_changed = live_now != self.was_live;
let selected_live =
self.was_live && self.selected_path.is_none() && self.list_state.selected.is_some();
let taken = match self.pending.lock() {
Ok(mut slot) => slot.take(),
_ => None,
};
if let Some((instance_name, entries)) = taken
let updated = if let Some((instance_name, entries)) = taken
&& self.loaded_for.as_deref() == Some(&instance_name)
{
let prev_selected = self.list_state.selected;
self.entries = entries;
self.loading = false;
let display_count = self.display_count();
if display_count > 0 && prev_selected.is_none() {
self.list_state.selected = Some(0);
self.load_selected_content();
} else if let Some(sel) = prev_selected
&& sel >= display_count
&& display_count > 0
{
self.list_state.selected = Some(display_count - 1);
}
true
} else {
false
};
if updated || live_changed {
let previous = self.list_state.selected.unwrap_or(0);
let indices = self.display_indices();
self.list_state.selected = indices
.iter()
.position(|index| match index {
None => selected_live,
Some(index) => self.selected_path.as_ref() == Some(&self.entries[*index].path),
})
.or_else(|| (!indices.is_empty()).then(|| previous.min(indices.len() - 1)));
self.update_scrollbar();
self.load_selected_content();
}
self.was_live = live_now;
}
pub fn try_rescan(&mut self) {
@@ -448,7 +454,6 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused:
return;
}
let has_live = state.has_live();
let display_count = state.display_count();
if display_count == 0 {
@@ -468,7 +473,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused:
Layout::horizontal([Constraint::Length(30), Constraint::Min(0)]).areas(area);
render_list(frame, list_area, state, is_focused);
render_viewer(frame, viewer_area, state, is_focused, has_live);
render_viewer(frame, viewer_area, state);
}
fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: bool) {
@@ -558,15 +563,9 @@ fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused:
);
}
fn render_viewer(
frame: &mut Frame,
area: Rect,
state: &mut LogsState,
_is_focused: bool,
has_live: bool,
) {
fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) {
let theme = THEME.as_ref();
let is_live = has_live && state.list_state.selected == Some(0);
let is_live = state.is_live_selected();
let all_lines: Vec<ViewerLine> = if is_live {
let name = state.loaded_for.as_deref().unwrap_or("");
+9 -7
View File
@@ -335,6 +335,12 @@ fn normalize_html(source: &str) -> NormalizedDocument {
}
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 visitor: VisitorHandle = Arc::new(Mutex::new(ImageAlignmentVisitor {
centered: Vec::new(),
@@ -617,17 +623,13 @@ fn external_markdown_text(source: &str, width: u16) -> (Text<'static>, Vec<LinkT
line.style = line_style;
line.spans.retain(|span| {
let content = span.content.as_ref();
content != "*"
&& !(span.style.add_modifier.contains(Modifier::UNDERLINED)
&& content.starts_with("(http")
&& content.ends_with(')'))
!(span.style.add_modifier.contains(Modifier::UNDERLINED)
&& content.starts_with("(http")
&& content.ends_with(')'))
});
remove_link_destination(line);
for span in &mut line.spans {
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)
-2
View File
@@ -20,8 +20,6 @@ pub mod search;
pub mod settings;
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<'_> {
let theme = THEME.as_ref();
if !highlight || title.is_empty() {
+124 -8
View File
@@ -14,7 +14,10 @@ use ratatui_textarea::TextArea;
use crate::{
config::{
Config,
settings::{ContentProvider, DEFAULT_RESOLUTION, ImageProtocol, ShortcutHintScope},
settings::{
ContentProvider, DEFAULT_RESOLUTION, ImageProtocol, ShortcutHintScope,
format_tag_values, parse_tag_values,
},
theme::{BORDER_STYLE, BorderStyle, THEME, ThemeConfig},
},
instance::models::{memory_kib, normalize_memory_value, parse_resolution},
@@ -22,10 +25,10 @@ use crate::{
DisplayResolution, JavaChoice, JavaPicker, ResolutionChoice, ResolutionPickerAction,
SettingsPicker, SettingsPickerAction, SettingsPickerOption, adjust_memory, auto_label,
default_label, default_resolution, display_resolutions, environment_labels,
format_tag_values, handle_resolution_picker_key, handle_text_area_input,
is_default_resolution, parse_environment, parse_tag_values, render_memory_gauge,
render_settings_picker, resolution_choices, resolution_items, settings_text_area,
tagged_row_count, tagged_value_lines, toggle_window_mode, window_mode_title,
handle_resolution_picker_key, handle_text_area_input, is_default_resolution,
parse_environment, render_memory_gauge, render_settings_picker, resolution_choices,
resolution_items, settings_text_area, tagged_row_count, tagged_value_lines,
toggle_window_mode, window_mode_title,
},
tui::widgets::status_badge,
};
@@ -96,8 +99,13 @@ impl State {
let java_cache =
crate::storage::MetadataPaths::new(runtime_config.paths.resolve_meta_dir())
.java_installations();
let mut java_picker =
JavaPicker::with_cache(crate::instance::java::detect_java_path(), Some(java_cache));
let cwd = std::env::current_dir().unwrap_or_default();
let environment = crate::instance::java::merge_environment(
&config.defaults.environment,
&Default::default(),
);
let detected = crate::instance::java::resolve_java_path_in(None, &cwd, &environment);
let mut java_picker = JavaPicker::with_cache(detected, Some(java_cache), cwd, environment);
java_picker.set_current(config.paths.java_path.as_deref());
Self {
config,
@@ -238,6 +246,7 @@ impl State {
9 => match parse_environment(value) {
Ok(environment) => {
self.config.defaults.environment = environment;
self.refresh_java_context();
self.save_pending = true;
}
Err(error) => invalid(self, error),
@@ -563,7 +572,8 @@ impl State {
.iter()
.position(|mode| *mode == current);
let index = match (index, forward) {
(Some(2), true) | (Some(0), false) => 0,
(Some(2), true) => 0,
(Some(0), false) => 2,
(Some(index), true) => index + 1,
(Some(index), false) => index - 1,
(None, true) => 0,
@@ -579,6 +589,7 @@ impl State {
}
fn open_java_picker(&mut self) {
self.refresh_java_context();
self.java_picker
.open(self.config.paths.java_path.as_deref());
self.java_picker.initialize();
@@ -586,6 +597,7 @@ impl State {
}
fn toggle_auto_java(&mut self) -> Action {
self.refresh_java_context();
let Some(current) = self.config.paths.java_path.as_deref() else {
self.config.paths.java_path = Some(self.java_picker.detected_path().to_owned());
self.save_pending = true;
@@ -617,6 +629,17 @@ impl State {
pub fn invalidate_java_cache(&mut self) {
self.java_picker.invalidate_cache();
self.refresh_java_context();
}
fn refresh_java_context(&mut self) {
let cwd = std::env::current_dir().unwrap_or_default();
let environment = crate::instance::java::merge_environment(
&self.config.defaults.environment,
&Default::default(),
);
let detected = crate::instance::java::resolve_java_path_in(None, &cwd, &environment);
self.java_picker.set_context(detected, cwd, environment);
}
fn handle_java_picker_key(&mut self, key: &KeyEvent) {
@@ -687,6 +710,13 @@ impl State {
self.error = None;
}
pub(in crate::tui) fn text_input_active(&self) -> bool {
self.choice_picker.is_none()
&& !self.java_picker_open
&& !self.theme_picker
&& self.editing.is_some()
}
pub fn handle_key(&mut self, key: &KeyEvent) -> Action {
let action = self.handle_key_inner(key);
if !matches!(action, Action::None) {
@@ -1318,6 +1348,88 @@ mod tests {
use super::*;
use crate::instance::models::WindowMode;
#[test]
fn dispatch_repeats_launcher_text_but_not_setting_toggles() {
use crate::tui::{app::FocusedArea, tests::harness::UiHarness};
use crossterm::event::{KeyEventKind, KeyModifiers};
let mut ui = UiHarness::new();
let mut state = State::new();
state.selected = 6;
let mode = state.config.defaults.window_mode;
ui.app.global_settings = Some(state);
ui.app.focused = FocusedArea::GlobalSettings;
for code in [KeyCode::Right, KeyCode::Char('l'), KeyCode::Enter] {
assert!(!ui.key_event(KeyEvent::new_with_kind(
code,
KeyModifiers::NONE,
KeyEventKind::Repeat
)));
}
assert_eq!(
ui.app
.global_settings
.as_ref()
.unwrap()
.config
.defaults
.window_mode,
mode
);
ui.app.global_settings.as_mut().unwrap().editing =
Some(settings_text_area(vec![String::new()]));
ui.key(KeyCode::Char('l'));
assert!(ui.key_event(KeyEvent::new_with_kind(
KeyCode::Char('l'),
KeyModifiers::NONE,
KeyEventKind::Repeat
)));
assert!(!ui.key_event(KeyEvent::new_with_kind(
KeyCode::Char('l'),
KeyModifiers::NONE,
KeyEventKind::Release
)));
assert_eq!(
ui.app
.global_settings
.as_ref()
.unwrap()
.editing
.as_ref()
.unwrap()
.lines(),
&["ll"]
);
assert!(ui.key_event(KeyEvent::new_with_kind(
KeyCode::Left,
KeyModifiers::NONE,
KeyEventKind::Repeat
)));
assert!(ui.key_event(KeyEvent::new_with_kind(
KeyCode::Delete,
KeyModifiers::NONE,
KeyEventKind::Repeat
)));
assert_eq!(
ui.app
.global_settings
.as_ref()
.unwrap()
.editing
.as_ref()
.unwrap()
.lines(),
&["l"]
);
assert!(!ui.key_event(KeyEvent::new_with_kind(
KeyCode::Enter,
KeyModifiers::NONE,
KeyEventKind::Repeat
)));
assert!(ui.app.global_settings.as_ref().unwrap().editing.is_some());
}
#[test]
fn launcher_memory_uses_slider_and_java_uses_picker() {
let mut state = State::new();
@@ -1550,6 +1662,10 @@ mod tests {
state.selected = 2;
state.handle_key(&KeyEvent::from(KeyCode::Down));
assert_eq!(state.selected, 24);
state.cycle_shortcut_hints(false);
assert_eq!(shortcut_hint_mode(&state.config.ui), "Hidden");
state.cycle_shortcut_hints(true);
assert_eq!(shortcut_hint_mode(&state.config.ui), "All");
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Right)),
@@ -7,6 +7,7 @@ mod state;
#[cfg(test)]
pub use render::render;
pub use render::{popup_rect, render_with_picker};
pub(in crate::tui) use state::text_input_active;
pub use state::{
ImportResult, ImportStep, ImportWizardState, discovery_activity, drain, handle_discovery_click,
handle_key, has_version_popup, open, take_result,
@@ -120,6 +120,23 @@ pub fn has_version_popup() -> bool {
.is_ok_and(|state| state.version_popup.is_some())
}
pub(in crate::tui) fn text_input_active() -> bool {
let Ok(state) = IMPORT_STATE.lock() else {
return false;
};
match state.step {
ImportStep::Input => true,
ImportStep::Version => state.version_search.active,
ImportStep::Discover => {
drop(state);
DISCOVERY_STATE
.lock()
.is_ok_and(|discovery| discovery.text_input_active())
}
_ => false,
}
}
pub fn discovery_activity() -> Option<&'static str> {
let wizard = IMPORT_STATE.lock().ok()?;
let step = wizard.step.clone();
+153 -15
View File
@@ -16,8 +16,10 @@ use crate::{
auth::{Account, AccountType},
config::{
SETTINGS,
settings::{format_tag_values, parse_tag_values},
theme::{BORDER_STYLE, THEME},
},
instance::glfw::bundled_glfw_version,
instance::loader::GameVersion,
instance::models::{
InstanceConfig, LaunchCommand, ModLoader, memory_kib, normalize_memory_value,
@@ -30,12 +32,12 @@ use crate::{
DisplayResolution, GlfwChoice, GlfwPicker, JavaChoice, JavaPicker,
ResolutionChoice, ResolutionPickerAction, SettingsPicker, SettingsPickerAction,
SettingsPickerBadge, SettingsPickerOption, adjust_memory, auto_label,
bundled_glfw_version, bundled_label as bundled_badge, default_label,
default_resolution, display_resolutions, environment_labels, format_tag_values,
handle_resolution_picker_key, handle_text_area_input, is_default_resolution,
parse_environment, parse_tag_values, render_memory_gauge, render_settings_picker,
resolution_choices, resolution_items, settings_text_area, tagged_row_count,
tagged_value_lines, toggle_window_mode, window_mode_title,
bundled_label as bundled_badge, default_label, default_resolution,
display_resolutions, environment_labels, handle_resolution_picker_key,
handle_text_area_input, is_default_resolution, parse_environment,
render_memory_gauge, render_settings_picker, resolution_choices, resolution_items,
settings_text_area, tagged_row_count, tagged_value_lines, toggle_window_mode,
window_mode_title,
},
},
search::SearchState,
@@ -92,6 +94,7 @@ pub struct State {
account_picker: SettingsPicker,
accounts: Vec<Account>,
meta_dir: std::path::PathBuf,
minecraft_dir: std::path::PathBuf,
display_resolutions: Vec<DisplayResolution>,
runtime_update_pending: bool,
save_retry_pending: bool,
@@ -111,9 +114,16 @@ pub enum Action {
impl State {
pub fn new(instance: &InstanceConfig, meta_dir: &std::path::Path) -> Self {
let minecraft_dir = crate::config::SETTINGS
.read()
.paths
.resolve_instances_dir()
.join(&instance.name)
.join(crate::storage::MINECRAFT_DIR_NAME);
Self::with_accounts(
instance,
meta_dir,
&minecraft_dir,
crate::auth::AccountStore::load().accounts,
)
}
@@ -121,16 +131,24 @@ impl State {
pub fn with_accounts(
instance: &InstanceConfig,
meta_dir: &std::path::Path,
minecraft_dir: &std::path::Path,
accounts: Vec<Account>,
) -> Self {
let auto_java_path = SETTINGS
.read()
.paths
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::instance::java::detect_java_path);
let settings = SETTINGS.read();
let cwd = minecraft_dir.to_owned();
let environment = crate::instance::java::merge_environment(
&settings.defaults.environment,
&instance.environment,
);
let auto_java_path = crate::instance::java::resolve_java_path_in(
settings.paths.effective_java_path(),
&cwd,
&environment,
);
drop(settings);
let java_cache = crate::storage::MetadataPaths::new(meta_dir).java_installations();
let mut java_picker = JavaPicker::with_cache(auto_java_path, Some(java_cache));
let mut java_picker =
JavaPicker::with_cache(auto_java_path, Some(java_cache), cwd, environment);
java_picker.set_current(instance.java_path.as_deref());
let desktop = crate::instance::desktop::exists(&instance.name);
Self {
@@ -158,6 +176,7 @@ impl State {
account_picker: SettingsPicker::default(),
accounts,
meta_dir: meta_dir.to_path_buf(),
minecraft_dir: minecraft_dir.to_owned(),
display_resolutions: display_resolutions(),
runtime_update_pending: false,
save_retry_pending: false,
@@ -405,6 +424,7 @@ impl State {
.unwrap_or(0);
}
ChoicePicker::Java => {
self.refresh_java_context();
self.java_picker.open(self.draft.java_path.as_deref());
self.java_picker.initialize();
}
@@ -770,6 +790,7 @@ impl State {
}
fn toggle_auto_java(&mut self) -> Action {
self.refresh_java_context();
let Some(current) = self.draft.java_path.as_deref() else {
self.draft.java_path = Some(self.java_picker.detected_path().to_owned());
self.error = None;
@@ -937,7 +958,10 @@ impl State {
Err(error) => invalid(self, error),
},
7 => match parse_environment(value) {
Ok(environment) => self.draft.environment = environment,
Ok(environment) => {
self.draft.environment = environment;
self.refresh_java_context();
}
Err(error) => invalid(self, error),
},
9 if value.is_empty() => {
@@ -964,6 +988,16 @@ impl State {
}
}
pub(in crate::tui) fn text_input_active(&self) -> bool {
!self.runtime_update_pending
&& self.choice_picker.is_none()
&& if self.picker.is_some() {
self.picker_search.active
} else {
self.editing.is_some()
}
}
pub fn handle_key(&mut self, key: &KeyEvent) -> Action {
if self.runtime_update_pending {
return if key.code == KeyCode::Esc {
@@ -1106,6 +1140,23 @@ impl State {
pub fn invalidate_java_cache(&mut self) {
self.java_picker.invalidate_cache();
self.refresh_java_context();
}
fn refresh_java_context(&mut self) {
let settings = SETTINGS.read();
let environment = crate::instance::java::merge_environment(
&settings.defaults.environment,
&self.draft.environment,
);
let detected = crate::instance::java::resolve_java_path_in(
settings.paths.effective_java_path(),
&self.minecraft_dir,
&environment,
);
drop(settings);
self.java_picker
.set_context(detected, self.minecraft_dir.clone(), environment);
}
pub fn cancel_runtime_change(&mut self) -> Option<(Box<InstanceConfig>, bool)> {
@@ -1740,6 +1791,79 @@ mod tests {
use crate::instance::WindowMode;
use chrono::Utc;
#[test]
fn dispatch_repeats_picker_search_without_snapshot_toggle_or_selection() {
use crate::tui::{app::FocusedArea, tests::harness::UiHarness};
use crossterm::event::{KeyEventKind, KeyModifiers};
let mut ui = UiHarness::new();
ui.add_instance("Picker Search");
let config = ui.app.instances_state.selected_instance().unwrap();
let mut state = State::with_accounts(
config,
&ui.app.instance_manager.meta_dir,
&ui.instance_path(&config.name).join("minecraft"),
Vec::new(),
);
state.picker = Some(VersionPicker::Game);
state.game_versions = Arc::new(Mutex::new(LoadState::Loaded(vec![GameVersion {
id: "1.21.1".to_owned(),
stable: true,
}])));
state.picker_search.activate();
ui.app.instance_settings = Some(state);
ui.app.focused = FocusedArea::InstanceSettings;
assert!(ui.key_event(KeyEvent::new_with_kind(
KeyCode::Char('s'),
KeyModifiers::NONE,
KeyEventKind::Repeat
)));
let state = ui.app.instance_settings.as_ref().unwrap();
assert_eq!(state.picker_search.query, "s");
assert!(!state.show_snapshots);
assert!(!ui.key_event(KeyEvent::new_with_kind(
KeyCode::Enter,
KeyModifiers::NONE,
KeyEventKind::Repeat
)));
assert_eq!(
ui.app.instance_settings.as_ref().unwrap().picker,
Some(VersionPicker::Game)
);
assert!(ui.key_event(KeyEvent::new_with_kind(
KeyCode::Backspace,
KeyModifiers::CONTROL,
KeyEventKind::Repeat
)));
assert!(
ui.app
.instance_settings
.as_ref()
.unwrap()
.picker_search
.query
.is_empty()
);
ui.key(KeyCode::Enter);
assert!(
!ui.app
.instance_settings
.as_ref()
.unwrap()
.picker_search
.active
);
assert!(!ui.key_event(KeyEvent::new_with_kind(
KeyCode::Right,
KeyModifiers::NONE,
KeyEventKind::Repeat
)));
assert_eq!(
ui.app.instance_settings.as_ref().unwrap().picker,
Some(VersionPicker::Game)
);
}
fn instance() -> InstanceConfig {
InstanceConfig {
name: "test".to_owned(),
@@ -2231,6 +2355,15 @@ mod tests {
assert!(lines.len() > 1);
assert_eq!(tagged_row_count(&state.draft.jvm_args, 48), lines.len());
assert!(lines.iter().any(|line| line.to_string().contains("second")));
let values = vec![
"界界界界界".to_owned(),
"abcdefghijklmn".to_owned(),
"e\u{301}".to_owned(),
];
let lines = tagged_field_lines(&state, 6, "JVM args", &values, "", 48);
assert_eq!(lines.len(), 2);
assert_eq!(tagged_row_count(&values, 48), lines.len());
assert!(lines.iter().all(|line| line.width() <= 48));
}
#[test]
@@ -2296,7 +2429,12 @@ mod tests {
cached_mc_token: None,
cached_mc_token_expires_at: None,
}];
let mut state = State::with_accounts(&instance(), temp.path(), accounts);
let mut state = State::with_accounts(
&instance(),
temp.path(),
&temp.path().join("minecraft"),
accounts,
);
state.selected = 10;
state.begin_edit();
assert_eq!(state.choice_index, 0);
@@ -5,6 +5,7 @@ mod render;
mod state;
pub use render::{popup_rect, render};
pub(in crate::tui) use state::text_input_active;
pub use state::{WizardParams, WizardState, WizardStep, handle_key, take_result};
#[cfg(test)]
@@ -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(
state: &mut WizardState,
key_event: &KeyEvent,
+115 -239
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-only
use std::{
collections::{BTreeMap, BTreeSet},
collections::BTreeMap,
path::{Path, PathBuf},
sync::{
Arc, Mutex,
@@ -21,8 +21,12 @@ use ratatui::{
use ratatui_textarea::{CursorMove, TextArea};
use crate::{
config::{settings::DEFAULT_RESOLUTION, theme::THEME},
config::{
settings::{DEFAULT_RESOLUTION, parse_tag_values},
theme::THEME,
},
instance::{
glfw::{GlfwInstallation, discover_glfw_installations, glfw_version_from_path},
java::JavaInstallation,
models::{WindowMode, memory_kib},
},
@@ -204,6 +208,9 @@ pub(crate) struct JavaPicker {
cache_path: Option<PathBuf>,
refresh_started: bool,
generation: Arc<AtomicU64>,
cwd: PathBuf,
environment: BTreeMap<String, String>,
context_key: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -225,12 +232,6 @@ pub(crate) enum GlfwChoice {
System(String),
}
#[derive(Debug, Clone)]
struct GlfwInstallation {
path: PathBuf,
version: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DisplayResolution {
pub width: u32,
@@ -298,13 +299,24 @@ impl JavaPicker {
}
pub(crate) fn with_auto_path(detected: String) -> Self {
Self::with_cache(detected, None)
let cwd = std::env::current_dir().unwrap_or_default();
let environment = crate::instance::java::merge_environment(
&crate::config::SETTINGS.read().defaults.environment,
&BTreeMap::new(),
);
Self::with_cache(detected, None, cwd, environment)
}
pub(crate) fn with_cache(detected: String, cache_path: Option<PathBuf>) -> Self {
let cached = cache_path
.as_deref()
.and_then(crate::instance::java::load_installation_cache);
pub(crate) fn with_cache(
detected: String,
cache_path: Option<PathBuf>,
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 {
load: Arc::new(Mutex::new(
cached.map_or(LoadState::Idle, LoadState::Loaded),
@@ -315,6 +327,25 @@ impl JavaPicker {
cache_path,
refresh_started: false,
generation: Arc::new(AtomicU64::new(0)),
cwd,
environment,
context_key,
}
}
pub(crate) fn set_context(
&mut self,
detected: String,
cwd: PathBuf,
environment: BTreeMap<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 generation = self.generation.clone();
let selected_paths = [Some(self.detected.clone()), self.current.clone()];
let cwd = self.cwd.clone();
let environment = self.environment.clone();
let discover = move || {
let mut installations = crate::instance::java::discover_installations();
let mut installations =
crate::instance::java::discover_installations_in(&cwd, &environment);
for path in selected_paths.into_iter().flatten() {
if installations.iter().any(|installation| {
same_executable(&installation.path.to_string_lossy(), &path)
}) {
continue;
}
if let Some(installation) =
crate::instance::java::inspect_installation(Path::new(&path))
{
if let Some(installation) = crate::instance::java::inspect_installation_in(
Path::new(&path),
&cwd,
&environment,
) {
installations.push(installation);
}
}
@@ -363,8 +399,12 @@ impl JavaPicker {
return;
}
if let Some(cache_path) = cache_path
&& let Err(error) =
crate::instance::java::save_installation_cache(&cache_path, &installations)
&& let Err(error) = crate::instance::java::save_installation_cache_in(
&cache_path,
&installations,
&cwd,
&environment,
)
{
tracing::debug!("Could not cache Java installations: {error}");
}
@@ -737,121 +777,6 @@ impl Default for GlfwPicker {
}
}
pub(crate) fn bundled_glfw_version(meta_dir: &Path, game_version: &str) -> Option<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 {
if left == right {
return true;
@@ -995,76 +920,6 @@ 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 parse_tag_values(value)? {
@@ -1118,7 +973,7 @@ pub(crate) fn tagged_value_lines(
let mut spans = prefix;
let mut used = 0usize;
for value in values {
let badge_width = value.chars().count() + 2;
let badge_width = Span::raw(value).width() + 2;
let separator = usize::from(used > 0);
if used > 0 && used + separator + badge_width > available {
lines.push(Line::from(spans));
@@ -1147,22 +1002,7 @@ pub(crate) fn tagged_value_lines(
}
pub(crate) fn tagged_row_count(values: &[String], width: u16) -> usize {
if values.is_empty() {
return 1;
}
let available = width.saturating_sub(20) as usize;
let mut rows = 1;
let mut used = 0usize;
for value in values {
let badge_width = value.chars().count() + 2;
let separator = usize::from(used > 0);
if used > 0 && used + separator + badge_width > available {
rows += 1;
used = 0;
}
used += usize::from(used > 0) + badge_width;
}
rows
tagged_value_lines(Vec::new(), false, false, values, "", width).len()
}
pub(crate) fn auto_label() -> Span<'static> {
@@ -1303,6 +1143,7 @@ pub(crate) fn resolution_items(
#[cfg(test)]
mod tests {
use super::*;
use crate::config::settings::format_tag_values;
#[test]
fn memory_steps_move_and_clamp() {
@@ -1387,7 +1228,12 @@ mod tests {
let cache = temp.path().join("cache/java/installations.json");
std::fs::create_dir_all(cache.parent().unwrap()).unwrap();
std::fs::write(&cache, "[]").unwrap();
let mut picker = JavaPicker::with_cache("/auto/java".to_owned(), Some(cache.clone()));
let mut picker = JavaPicker::with_cache(
"/auto/java".to_owned(),
Some(cache.clone()),
temp.path().to_owned(),
BTreeMap::new(),
);
*picker.load.lock().unwrap() = LoadState::Loaded(vec![JavaInstallation {
path: "/cached/java".into(),
version: Some("21".to_owned()),
@@ -1401,6 +1247,48 @@ mod tests {
assert!(matches!(*picker.load.lock().unwrap(), LoadState::Idle));
}
#[test]
fn java_picker_cache_and_workers_are_bound_to_the_captured_context() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("java");
std::fs::write(&path, b"java").unwrap();
let cache = temp.path().join("installations.json");
let environment = BTreeMap::from([("JAVA_TEST_CONTEXT".to_owned(), "first".to_owned())]);
let installations = vec![JavaInstallation {
path: path.clone(),
version: Some("21".to_owned()),
}];
crate::instance::java::save_installation_cache_in(
&cache,
&installations,
temp.path(),
&environment,
)
.unwrap();
let detected = path.to_string_lossy().into_owned();
let mut picker = JavaPicker::with_cache(
detected.clone(),
Some(cache.clone()),
temp.path().to_owned(),
environment.clone(),
);
assert!(
matches!(&*picker.load.lock().unwrap(), LoadState::Loaded(found) if *found == installations)
);
picker.refresh_started = true;
let generation = picker.generation.load(Ordering::Relaxed);
picker.set_context(detected.clone(), temp.path().to_owned(), environment);
assert_eq!(picker.generation.load(Ordering::Relaxed), generation);
let changed = BTreeMap::from([("JAVA_TEST_CONTEXT".to_owned(), "second".to_owned())]);
picker.set_context(detected, temp.path().join("other"), changed.clone());
assert_eq!(picker.generation.load(Ordering::Relaxed), generation + 1);
assert!(!picker.refresh_started);
assert!(matches!(*picker.load.lock().unwrap(), LoadState::Idle));
assert!(!cache.exists());
assert_eq!(picker.cwd, temp.path().join("other"));
assert_eq!(picker.environment, changed);
}
#[test]
fn java_title_is_minimal_and_uses_the_major_version() {
let picker = JavaPicker::with_auto_path("/opt/jdk-25/bin/java".to_owned());
@@ -1483,7 +1371,7 @@ mod tests {
.unwrap();
assert_eq!(
bundled_glfw_version(temp.path(), "1.21.1").as_deref(),
crate::instance::glfw::bundled_glfw_version(temp.path(), "1.21.1").as_deref(),
Some("3.3.3")
);
let mut picker = GlfwPicker::with_bundled_version(Some("3.3.3".to_owned()));
@@ -1495,19 +1383,6 @@ mod tests {
);
}
#[test]
fn glfw_library_names_are_recognized() {
assert!(is_glfw_library_name("libglfw.so.3"));
assert!(is_glfw_library_name("libglfw.3.dylib"));
assert!(is_glfw_library_name("glfw3.dll"));
assert!(!is_glfw_library_name("libglfw.so.backup"));
assert!(!is_glfw_library_name("libGL.so"));
assert_eq!(
glfw_version_from_path(Path::new("/usr/lib/libglfw.so.3.4")).as_deref(),
Some("3.4")
);
}
#[test]
fn settings_text_input_deletes_the_previous_word() {
let mut input = TextArea::from(["one two"]);
@@ -1538,10 +1413,10 @@ mod tests {
}
#[test]
fn tag_values_drop_exact_duplicates_without_reordering() {
fn tag_values_preserve_repeated_options_and_their_operands() {
assert_eq!(
parse_tag_values("-Xmx2G '-Dlabel=hello world' -Xmx2G").unwrap(),
["-Xmx2G", "-Dlabel=hello world"]
parse_tag_values("--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED").unwrap(),
["--add-opens", "java.base/java.lang=ALL-UNNAMED", "--add-opens", "java.base/java.util=ALL-UNNAMED"]
);
}
@@ -1560,6 +1435,7 @@ mod tests {
);
assert!(parse_environment("=missing").is_err());
assert!(parse_environment("KEY=one KEY=two").is_err());
assert!(parse_environment("KEY=one KEY=one").is_err());
}
#[test]
+12 -3
View File
@@ -57,12 +57,21 @@ impl SearchState {
let query_lower = self.query.to_lowercase();
let text_lower = text.to_lowercase();
let mut original_ranges = Vec::with_capacity(text_lower.len());
for (start, character) in text.char_indices() {
let lowercase_bytes = character.to_lowercase().map(char::len_utf8).sum::<usize>();
original_ranges.extend(std::iter::repeat_n(
(start, start + character.len_utf8()),
lowercase_bytes,
));
}
let mut spans = Vec::new();
let mut last = 0;
for (start, _) in text_lower.match_indices(&query_lower) {
let end = start + query_lower.len();
if !text.is_char_boundary(start) || !text.is_char_boundary(end) {
for (lower_start, _) in text_lower.match_indices(&query_lower) {
let start = original_ranges[lower_start].0;
let end = original_ranges[lower_start + query_lower.len() - 1].1;
if start < last {
continue;
}
if start > last {
+69 -46
View File
@@ -44,14 +44,16 @@ pub struct SettingsState {
pub add_mode: AddMode,
pub pane: SettingsPane,
meta_dir: PathBuf,
instances_dir: PathBuf,
active_profile: Option<String>,
instance_name: Option<String>,
java_key: Option<String>,
java_label: String,
pending_java: std::sync::Arc<std::sync::Mutex<Option<String>>>,
}
impl SettingsState {
pub fn new(meta_dir: PathBuf) -> Self {
pub fn new(meta_dir: PathBuf, instances_dir: PathBuf) -> Self {
let profiles = crate::instance::config_sync::list_profiles(&meta_dir).unwrap_or_else(|e| {
tracing::warn!("Failed to load config sync profiles: {}", e);
Vec::new()
@@ -62,10 +64,12 @@ impl SettingsState {
add_mode: AddMode::None,
pane: SettingsPane::Profile,
meta_dir,
instances_dir,
active_profile: None,
instance_name: None,
java_key: None,
java_label: "unknown".to_string(),
pending_java: Default::default(),
};
state.select_active();
state
@@ -116,15 +120,53 @@ impl SettingsState {
self.select_active();
}
let java_key = instance.map(java_path_key);
let context = instance.map(|instance| {
let settings = SETTINGS.read();
let cwd = self
.instances_dir
.join(&instance.name)
.join(crate::storage::MINECRAFT_DIR_NAME);
let environment = crate::instance::java::merge_environment(
&settings.defaults.environment,
&instance.environment,
);
let java = crate::instance::java::resolve_java_path_in(
instance
.java_path
.as_deref()
.filter(|path| !path.is_empty())
.or(settings.paths.effective_java_path()),
&cwd,
&environment,
);
(java, cwd, environment)
});
let java_key = context
.as_ref()
.map(|(java, cwd, environment)| java_path_key(java, cwd, environment));
if self.java_key != java_key {
let java_source = instance.map(effective_java_path);
self.java_label = java_source
.as_deref()
.map(java_version_label)
.unwrap_or_else(|| "unknown".to_string());
self.pending_java = Default::default();
self.java_label = "unknown".to_owned();
if let Some((java, cwd, environment)) = context {
let pending = self.pending_java.clone();
std::thread::spawn(move || {
let label = java_version_label(&java, &cwd, &environment);
*pending
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(label);
crate::feedback::request_redraw();
});
}
self.java_key = java_key;
}
if let Some(label) = self
.pending_java
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take()
{
self.java_label = label;
}
}
}
@@ -137,38 +179,25 @@ fn add_active_profile(profiles: &mut Vec<String>, active_profile: Option<&str>)
}
}
fn java_path_key(instance: &InstanceConfig) -> String {
instance
.java_path
.as_deref()
.filter(|path| !path.is_empty())
.map(str::to_owned)
.or_else(|| {
SETTINGS
.read()
.paths
.effective_java_path()
.map(str::to_owned)
})
.unwrap_or_else(|| "<auto>".to_owned())
fn java_path_key(
java: &str,
cwd: &Path,
environment: &std::collections::BTreeMap<String, String>,
) -> String {
format!(
"{java}:{}",
crate::instance::java::probe_context_key(cwd, environment)
)
}
fn effective_java_path(instance: &InstanceConfig) -> String {
instance
.java_path
.clone()
.or_else(|| {
SETTINGS
.read()
.paths
.effective_java_path()
.map(str::to_owned)
})
.unwrap_or_else(crate::instance::java::detect_java_path)
}
fn java_version_label(java_path: &str) -> String {
let Some(version) = crate::instance::java::java_version(Path::new(java_path)) else {
fn java_version_label(
java_path: &str,
cwd: &Path,
environment: &std::collections::BTreeMap<String, String>,
) -> String {
let Some(version) =
crate::instance::java::java_version_in(Path::new(java_path), cwd, environment)
else {
return "unknown".to_string();
};
let major = crate::instance::java::java_major(Some(&version));
@@ -445,15 +474,9 @@ fn render_add_profile_popup(frame: &mut Frame, name: &str) {
}
fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
let area = frame.area();
let x = area.x + (area.width.saturating_sub(width)) / 2;
let y = area.y + (area.height.saturating_sub(height)) / 2;
Rect {
x,
y,
width: width.min(area.width),
height: height.min(area.height),
}
frame
.area()
.centered(Constraint::Length(width), Constraint::Length(height))
}
pub enum SettingsAction {