feat: add instance launch settings

This commit is contained in:
objz committed 2026-09-04 20:06:22 +02:00
1 parent 59407ee01d
commit 8de0cbaa09
25 files changed
+2463 -482

No files matched your search

+30 -16
View File
@@ -48,23 +48,40 @@ pub enum ConfirmTarget {
InstanceRuntime {
name: String,
},
JvmArguments {
name: String,
},
JavaAuto {
AutomaticSelection {
setting: AutomaticSetting,
instance: Option<String>,
from: String,
to: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutomaticSetting {
Java,
Account,
}
impl AutomaticSetting {
fn title(self) -> &'static str {
match self {
Self::Java => " Enable automatic Java ",
Self::Account => " Enable automatic account ",
}
}
fn description(self) -> &'static str {
match self {
Self::Java => "Use the automatically selected Java runtime",
Self::Account => "Use the currently active account",
}
}
}
impl ConfirmTarget {
fn title(&self) -> String {
match self {
Self::OrphanDependencies { .. } => " Remove unused dependencies ".to_owned(),
Self::InstanceRuntime { .. } => " Change runtime ".to_owned(),
Self::JvmArguments { .. } => " Clear JVM arguments ".to_owned(),
Self::JavaAuto { .. } => " Enable automatic Java ".to_owned(),
Self::AutomaticSelection { setting, .. } => setting.title().to_owned(),
_ => format!(" Delete '{}' ", self.name()),
}
}
@@ -104,10 +121,7 @@ impl ConfirmTarget {
.collect::<Vec<_>>()
.join("\n"),
ConfirmTarget::InstanceRuntime { .. } => "Apply this runtime change".to_owned(),
ConfirmTarget::JvmArguments { .. } => "Remove all JVM arguments".to_owned(),
ConfirmTarget::JavaAuto { from, to, .. } => {
format!("Java runtime will change:\n{from} → {to}")
}
ConfirmTarget::AutomaticSelection { setting, .. } => setting.description().to_owned(),
}
}
@@ -119,8 +133,9 @@ impl ConfirmTarget {
ConfirmTarget::Content { name, .. } => name,
ConfirmTarget::OrphanDependencies { .. } => "unused dependencies",
ConfirmTarget::InstanceRuntime { name, .. } => name,
ConfirmTarget::JvmArguments { name, .. } => name,
ConfirmTarget::JavaAuto { instance, .. } => instance.as_deref().unwrap_or("launcher"),
ConfirmTarget::AutomaticSelection { instance, .. } => {
instance.as_deref().unwrap_or("launcher")
}
}
}
@@ -129,8 +144,7 @@ impl ConfirmTarget {
Self::Content { dependents, .. } if !dependents.is_empty() => " delete anyway",
Self::OrphanDependencies { .. } => " remove all",
Self::InstanceRuntime { .. } => " change",
Self::JvmArguments { .. } => " clear",
Self::JavaAuto { .. } => " enable",
Self::AutomaticSelection { .. } => " enable",
_ => " confirm",
}
}
+33 -54
View File
@@ -11,7 +11,7 @@ use ratatui::{
text::{Line, Span},
widgets::{Block, Borders, Clear, ListItem, Paragraph},
};
use ratatui_textarea::{CursorMove, TextArea};
use ratatui_textarea::TextArea;
use crate::{
config::{
@@ -20,8 +20,9 @@ use crate::{
},
instance::models::normalize_memory_value,
tui::widgets::popups::settings_controls::{
JavaChoice, JavaPicker, adjust_memory, auto_label, handle_text_area_input, memory_kib,
render_memory_gauge,
JavaChoice, JavaPicker, SettingsPickerAction, adjust_memory, auto_label,
handle_text_area_input, memory_kib, render_memory_gauge, render_settings_picker,
settings_text_area,
},
};
@@ -43,7 +44,7 @@ pub enum Action {
None,
Save(Box<Config>, String, BorderStyle),
Error(String),
ConfirmJavaAuto { from: String, to: String },
ConfirmJavaAuto,
OpenRaw(std::path::PathBuf),
Close,
}
@@ -56,8 +57,14 @@ impl State {
.iter()
.position(|candidate| candidate == &theme.theme)
.unwrap_or(0);
let config = crate::config::SETTINGS.read().clone();
let java_cache = crate::storage::MetadataPaths::new(config.paths.resolve_meta_dir())
.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());
Self {
config: crate::config::SETTINGS.read().clone(),
config,
theme,
selected: 0,
editing: None,
@@ -67,7 +74,7 @@ impl State {
theme_picker: false,
theme_index,
java_picker_open: false,
java_picker: JavaPicker::new(),
java_picker,
}
}
@@ -85,15 +92,14 @@ impl State {
fn display_value(&self, field: usize) -> String {
match field {
1 => format!("{:?}", self.theme.border_style).to_lowercase(),
4 if self
.config
.paths
.java_path
.as_deref()
.is_none_or(str::is_empty) =>
{
self.java_picker.detected_path().to_owned()
}
4 => self.java_picker.display_label(
self.config
.paths
.java_path
.as_deref()
.filter(|path| !path.is_empty())
.unwrap_or_else(|| self.java_picker.detected_path()),
),
_ => self.value(field),
}
}
@@ -107,7 +113,7 @@ impl State {
self.error = None;
let invalid = |state: &mut Self, message: String| {
state.error = Some(message);
state.editing = Some(new_text_area(editor.lines().to_vec()));
state.editing = Some(settings_text_area(editor.lines().to_vec()));
};
match self.selected {
2 | 3 if normalize_memory_value(value).is_none() => invalid(
@@ -206,8 +212,8 @@ impl State {
self.error = None;
return Action::None;
};
if let Some((from, to)) = self.java_picker.automatic_change(current) {
return Action::ConfirmJavaAuto { from, to };
if self.java_picker.automatic_change(current) {
return Action::ConfirmJavaAuto;
}
self.enable_auto_java();
Action::None
@@ -231,16 +237,9 @@ impl State {
fn handle_java_picker_key(&mut self, key: &KeyEvent) {
self.java_picker.initialize();
let count = self.java_picker.labels().len();
match key.code {
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => self.java_picker_open = false,
KeyCode::Char('j') | KeyCode::Down if count > 0 => {
self.java_picker.selected = (self.java_picker.selected + 1).min(count - 1);
}
KeyCode::Char('k') | KeyCode::Up => {
self.java_picker.selected = self.java_picker.selected.saturating_sub(1);
}
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
match self.java_picker.selection_mut().handle_key(key) {
SettingsPickerAction::Back => self.java_picker_open = false,
SettingsPickerAction::Select => {
match self.java_picker.selected_choice() {
JavaChoice::Installation(path) => {
if self.config.paths.java_path.as_deref() != Some(&path) {
@@ -251,7 +250,7 @@ impl State {
}
self.java_picker_open = false;
}
_ => {}
SettingsPickerAction::None => {}
}
}
@@ -328,14 +327,14 @@ impl State {
0 => self.theme_picker = true,
1 => self.cycle_border(true),
2 | 3 => {
self.editing = Some(new_text_area(vec![self.value(self.selected)]));
self.editing = Some(settings_text_area(vec![self.value(self.selected)]));
}
4 => self.open_java_picker(),
field => self.editing = Some(new_text_area(vec![self.value(field)])),
field => self.editing = Some(settings_text_area(vec![self.value(field)])),
},
KeyCode::Char('a') if self.selected == 4 => return self.toggle_auto_java(),
KeyCode::Char('c') if self.selected == 4 => {
self.editing = Some(new_text_area(vec![self.value(4)]));
self.editing = Some(settings_text_area(vec![self.value(4)]));
}
KeyCode::Char('E') => {
let file = if self.selected <= 1 {
@@ -382,21 +381,6 @@ fn available_themes() -> Vec<String> {
themes
}
fn new_text_area(lines: Vec<String>) -> TextArea<'static> {
let theme = THEME.as_ref();
let mut editor = TextArea::new(if lines.is_empty() {
vec![String::new()]
} else {
lines
});
editor.set_style(Style::default().fg(theme.text()).bg(theme.surface()));
editor.set_cursor_line_style(Style::default());
editor.set_cursor_style(Style::default().fg(theme.background()).bg(theme.accent()));
editor.move_cursor(CursorMove::Bottom);
editor.move_cursor(CursorMove::End);
editor
}
pub fn popup_rect(area: Rect, state: &State) -> Rect {
let height = if state.theme_picker || state.java_picker_open {
(area.height * 2 / 3).max(10)
@@ -508,12 +492,7 @@ fn render_java_picker(frame: &mut Frame, area: Rect, state: &mut State) {
Err(error) => crate::feedback::errors::push_message(tracing::Level::ERROR, error),
}
}
super::select_list::render_styled(
state.java_picker.items(),
state.java_picker.selected,
list_area,
frame.buffer_mut(),
);
render_settings_picker(state.java_picker.selection(), list_area, frame.buffer_mut());
}
fn render_settings_list(frame: &mut Frame, area: Rect, state: &State) {
@@ -667,7 +646,7 @@ mod tests {
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Char('a'))),
Action::ConfirmJavaAuto { .. }
Action::ConfirmJavaAuto
));
assert_eq!(
state.config.paths.java_path.as_deref(),
File diff suppressed because it is too large. Load diff
+702 -133
View File
@@ -3,7 +3,11 @@
// Reusable interactive controls shared by instance and launcher settings.
use std::sync::{Arc, Mutex};
use std::{
collections::BTreeSet,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
@@ -13,7 +17,7 @@ use ratatui::{
text::{Line, Span},
widgets::{LineGauge, ListItem, Paragraph},
};
use ratatui_textarea::TextArea;
use ratatui_textarea::{CursorMove, TextArea};
use crate::{
config::theme::THEME,
@@ -25,13 +29,162 @@ const MEMORY_STEPS: [&str; 12] = [
"512M", "1G", "2G", "3G", "4G", "6G", "8G", "12G", "16G", "24G", "32G", "64G",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SettingsPickerBadge {
Auto,
Bundled,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SettingsPickerOption {
pub key: String,
pub title: String,
pub detail: Option<String>,
pub leading: Option<String>,
pub active: bool,
pub badge: Option<SettingsPickerBadge>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SettingsPickerAction {
None,
Back,
Select,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct SettingsPicker {
options: Vec<SettingsPickerOption>,
selected: usize,
}
impl SettingsPicker {
pub(crate) fn reset(&mut self) {
self.options.clear();
self.selected = 0;
}
pub(crate) fn sync(&mut self, options: Vec<SettingsPickerOption>, preferred: Option<&str>) {
let selected_key = self
.options
.get(self.selected)
.map(|option| option.key.clone())
.or_else(|| preferred.map(str::to_owned));
self.options = options;
self.selected = selected_key
.as_deref()
.and_then(|key| self.options.iter().position(|option| option.key == key))
.unwrap_or(0);
}
pub(crate) fn handle_key(&mut self, key: &KeyEvent) -> SettingsPickerAction {
match key.code {
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => SettingsPickerAction::Back,
KeyCode::Char('j') | KeyCode::Down if !self.options.is_empty() => {
self.selected = (self.selected + 1).min(self.options.len() - 1);
SettingsPickerAction::None
}
KeyCode::Char('k') | KeyCode::Up => {
self.selected = self.selected.saturating_sub(1);
SettingsPickerAction::None
}
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right if !self.options.is_empty() => {
SettingsPickerAction::Select
}
_ => SettingsPickerAction::None,
}
}
pub(crate) fn selected(&self) -> usize {
self.selected
}
pub(crate) fn selected_key(&self) -> Option<&str> {
self.options
.get(self.selected)
.map(|option| option.key.as_str())
}
pub(crate) fn labels(&self) -> Vec<String> {
self.options
.iter()
.map(|option| {
option.detail.as_ref().map_or_else(
|| option.title.clone(),
|detail| format!("{} {detail}", option.title),
)
})
.collect()
}
pub(crate) fn items(&self) -> Vec<ListItem<'static>> {
let theme = THEME.as_ref();
self.options
.iter()
.enumerate()
.map(|(index, option)| {
let selected = index == self.selected;
let title_style = if selected {
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else if option.active {
Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.text())
};
let mut spans = Vec::new();
if let Some(leading) = &option.leading {
spans.push(Span::styled(
leading.clone(),
Style::default().fg(theme.success()),
));
}
spans.push(Span::styled(option.title.clone(), title_style));
if let Some(detail) = &option.detail {
spans.push(Span::styled(
format!(" {detail}"),
Style::default()
.fg(if selected {
theme.accent()
} else {
theme.text_dim()
})
.add_modifier(if selected {
Modifier::BOLD
} else {
Modifier::empty()
}),
));
}
if let Some(badge) = option.badge {
spans.extend([
Span::raw(" "),
status_badge(
match badge {
SettingsPickerBadge::Auto => "Auto",
SettingsPickerBadge::Bundled => "Bundled",
},
theme.success(),
),
]);
}
ListItem::new(Line::from(spans))
})
.collect()
}
}
#[derive(Debug, Clone)]
pub(crate) struct JavaPicker {
load: Arc<Mutex<LoadState<Vec<JavaInstallation>>>>,
current: Option<String>,
detected: String,
pub selected: usize,
previous_choices: Vec<JavaChoice>,
picker: SettingsPicker,
cache_path: Option<PathBuf>,
refresh_started: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -39,6 +192,26 @@ pub(crate) enum JavaChoice {
Installation(String),
}
#[derive(Debug, Clone)]
pub(crate) struct GlfwPicker {
load: Arc<Mutex<LoadState<Vec<GlfwInstallation>>>>,
current: Option<String>,
bundled_version: Option<String>,
picker: SettingsPicker,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum GlfwChoice {
Bundled,
System(String),
}
#[derive(Debug, Clone)]
struct GlfwInstallation {
path: PathBuf,
version: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DisplayResolution {
pub width: u32,
@@ -53,30 +226,63 @@ impl JavaPicker {
}
pub(crate) fn with_auto_path(detected: String) -> Self {
Self::with_cache(detected, None)
}
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);
Self {
load: Arc::new(Mutex::new(LoadState::Idle)),
load: Arc::new(Mutex::new(
cached.map_or(LoadState::Idle, LoadState::Loaded),
)),
current: None,
detected,
selected: 0,
previous_choices: Vec::new(),
picker: SettingsPicker::default(),
cache_path,
refresh_started: false,
}
}
pub(crate) fn open(&mut self, current: Option<&str>) {
self.current = current.map(str::to_owned);
self.previous_choices.clear();
self.picker.reset();
if self.refresh_started {
return;
}
self.refresh_started = true;
let mut load = self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !matches!(*load, LoadState::Idle | LoadState::Error(_)) {
return;
if matches!(*load, LoadState::Idle | LoadState::Error(_)) {
*load = LoadState::Loading;
}
*load = LoadState::Loading;
drop(load);
let target = self.load.clone();
let cache_path = self.cache_path.clone();
let selected_paths = [Some(self.detected.clone()), self.current.clone()];
let discover = move || {
let installations = crate::instance::java::discover_installations();
let mut installations = crate::instance::java::discover_installations();
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))
{
installations.push(installation);
}
}
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) =
@@ -86,10 +292,7 @@ impl JavaPicker {
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn_blocking(discover);
} else {
*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = LoadState::Loaded(Vec::new());
self.refresh_started = false;
}
}
@@ -106,18 +309,29 @@ impl JavaPicker {
.map(|installation| installation.path.to_string_lossy().into_owned()),
);
}
if !paths.contains(&self.detected) {
if let Some(index) = paths
.iter()
.position(|path| same_executable(path, &self.detected))
{
paths[index].clone_from(&self.detected);
} else {
paths.insert(0, self.detected.clone());
}
if let Some(current) = &self.current
&& !paths.contains(current)
{
paths.push(current.clone());
if let Some(current) = &self.current {
if let Some(index) = paths.iter().position(|path| same_executable(path, current)) {
paths[index].clone_from(current);
} else {
paths.push(current.clone());
}
}
paths.into_iter().map(JavaChoice::Installation).collect()
}
pub(crate) fn labels(&self) -> Vec<String> {
self.picker.labels()
}
fn options(&self) -> Vec<SettingsPickerOption> {
let installations = match &*self
.load
.lock()
@@ -129,62 +343,24 @@ impl JavaPicker {
self.choices()
.into_iter()
.map(|choice| match choice {
JavaChoice::Installation(path) => installations
.as_ref()
.and_then(|items| {
JavaChoice::Installation(path) => {
let installation = installations.as_ref().and_then(|items| {
items
.iter()
.find(|item| item.path.to_string_lossy() == path)
})
.map_or_else(|| format!("Java {path}"), JavaInstallation::label),
})
.collect()
}
pub(crate) fn items(&self) -> Vec<ListItem<'static>> {
let theme = THEME.as_ref();
let installations = match &*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
{
LoadState::Loaded(installations) => installations.clone(),
_ => Vec::new(),
};
self.choices()
.into_iter()
.enumerate()
.map(|(index, choice)| match choice {
JavaChoice::Installation(path) => {
let installation = installations
.iter()
.find(|installation| installation.path.to_string_lossy() == path);
let version = installation
.find(|item| same_executable(&item.path.to_string_lossy(), &path))
});
let title = installation
.and_then(|installation| installation.version.as_deref())
.map_or_else(|| "Java".to_owned(), |version| format!("Java {version}"));
let selected = index == self.selected;
let mut spans = vec![
Span::styled(
version,
Style::default().fg(if selected {
theme.accent()
} else {
theme.text()
}),
),
Span::styled(
format!(" {path}"),
Style::default().fg(if selected {
theme.accent()
} else {
theme.text_dim()
}),
),
];
if self.current.is_none() && path == self.detected {
spans.extend([Span::raw(" "), auto_label()]);
.map_or_else(|| "Java".to_owned(), java_title);
SettingsPickerOption {
key: path.clone(),
title,
detail: Some(path.clone()),
leading: None,
active: false,
badge: (self.current.is_none() && path == self.detected)
.then_some(SettingsPickerBadge::Auto),
}
ListItem::new(Line::from(spans))
}
})
.collect()
@@ -211,65 +387,51 @@ impl JavaPicker {
}
pub(crate) fn initialize(&mut self) {
let choices = self.choices();
if choices == self.previous_choices {
return;
}
let selected = self
.previous_choices
.get(self.selected)
.cloned()
.or_else(|| {
Some(JavaChoice::Installation(
self.current
.clone()
.unwrap_or_else(|| self.detected.clone()),
))
})
.unwrap_or_else(|| JavaChoice::Installation(self.detected.clone()));
self.selected = choices
.iter()
.position(|choice| choice == &selected)
.unwrap_or(0);
self.previous_choices = choices;
let preferred = self
.current
.clone()
.unwrap_or_else(|| self.detected.clone());
self.picker.sync(self.options(), Some(&preferred));
}
pub(crate) fn selected_choice(&self) -> JavaChoice {
self.choices()
.get(self.selected)
.cloned()
.unwrap_or_else(|| JavaChoice::Installation(self.detected.clone()))
JavaChoice::Installation(
self.picker
.selected_key()
.unwrap_or(&self.detected)
.to_owned(),
)
}
pub(crate) fn selection(&self) -> &SettingsPicker {
&self.picker
}
pub(crate) fn selection_mut(&mut self) -> &mut SettingsPicker {
&mut self.picker
}
pub(crate) fn detected_path(&self) -> &str {
&self.detected
}
pub(crate) fn automatic_change(&self, current: &str) -> Option<(String, String)> {
if same_executable(current, &self.detected) {
return None;
}
let load = self
pub(crate) fn display_label(&self, path: &str) -> String {
let version = match &*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let installations = match &*load {
LoadState::Loaded(installations) => installations,
_ => return Some((current.to_owned(), self.detected.clone())),
};
let version_for = |path: &str| {
installations
.unwrap_or_else(std::sync::PoisonError::into_inner)
{
LoadState::Loaded(installations) => installations
.iter()
.find(|installation| same_executable(&installation.path.to_string_lossy(), path))
.and_then(|installation| installation.version.clone())
.and_then(|installation| installation.version.clone()),
_ => None,
};
let current_version = version_for(current);
let detected_version = version_for(&self.detected);
Some((
java_runtime_label(current, current_version.as_deref()),
java_runtime_label(&self.detected, detected_version.as_deref()),
))
java_runtime_label(path, version.as_deref())
}
pub(crate) fn automatic_change(&self, current: &str) -> bool {
!same_executable(current, &self.detected)
}
}
@@ -279,6 +441,299 @@ impl Default for JavaPicker {
}
}
impl GlfwPicker {
pub(crate) fn new() -> Self {
Self::with_bundled_version(None)
}
pub(crate) fn with_bundled_version(bundled_version: Option<String>) -> Self {
Self {
load: Arc::new(Mutex::new(LoadState::Idle)),
current: None,
bundled_version,
picker: SettingsPicker::default(),
}
}
pub(crate) fn open(&mut self, current: Option<&str>) {
self.current = current.map(str::to_owned);
self.picker.reset();
let mut load = self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !matches!(*load, LoadState::Idle | LoadState::Error(_)) {
return;
}
*load = LoadState::Loading;
drop(load);
let target = self.load.clone();
let discover = move || {
let installations = discover_glfw_installations();
*target
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
LoadState::Loaded(installations);
crate::feedback::request_redraw();
};
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn_blocking(discover);
} else {
*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = LoadState::Loaded(Vec::new());
}
}
pub(crate) fn set_bundled_version(&mut self, version: Option<String>) {
self.bundled_version = version;
}
pub(crate) fn choices(&self) -> Vec<GlfwChoice> {
let mut choices = vec![GlfwChoice::Bundled];
if let LoadState::Loaded(installations) = &*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
{
choices.extend(installations.iter().map(|installation| {
GlfwChoice::System(installation.path.to_string_lossy().into_owned())
}));
}
if let Some(current) = &self.current {
if let Some(choice) = choices.iter_mut().find(|choice| {
matches!(choice, GlfwChoice::System(path) if same_executable(path, current))
}) {
*choice = GlfwChoice::System(current.clone());
} else {
choices.push(GlfwChoice::System(current.clone()));
}
}
choices
}
pub(crate) fn initialize(&mut self) {
let preferred = self.current.as_deref().unwrap_or(BUNDLED_GLFW_KEY);
self.picker.sync(self.options(), Some(preferred));
}
pub(crate) fn selected_choice(&self) -> GlfwChoice {
match self.picker.selected_key() {
Some(BUNDLED_GLFW_KEY) | None => GlfwChoice::Bundled,
Some(path) => GlfwChoice::System(path.to_owned()),
}
}
pub(crate) fn labels(&self) -> Vec<String> {
self.picker.labels()
}
pub(crate) fn bundled_label(&self) -> String {
self.bundled_version.as_ref().map_or_else(
|| "Minecraft GLFW".to_owned(),
|version| format!("LWJGL GLFW {version}"),
)
}
pub(crate) fn display_label(&self, path: Option<&str>) -> String {
let Some(path) = path else {
return self.bundled_label();
};
let detected_version = match &*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
{
LoadState::Loaded(installations) => installations
.iter()
.find(|installation| installation.path.to_string_lossy() == path)
.and_then(|installation| installation.version.clone()),
_ => None,
};
detected_version
.or_else(|| glfw_version_from_path(Path::new(path)))
.map_or_else(
|| format!("System GLFW {path}"),
|version| format!("GLFW {version} {path}"),
)
}
fn options(&self) -> Vec<SettingsPickerOption> {
let installations = match &*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
{
LoadState::Loaded(installations) => installations.clone(),
_ => Vec::new(),
};
self.choices()
.into_iter()
.map(|choice| match choice {
GlfwChoice::Bundled => SettingsPickerOption {
key: BUNDLED_GLFW_KEY.to_owned(),
title: self.bundled_label(),
detail: None,
leading: None,
active: false,
badge: Some(SettingsPickerBadge::Bundled),
},
GlfwChoice::System(path) => {
let version = installations
.iter()
.find(|installation| {
same_executable(&installation.path.to_string_lossy(), &path)
})
.and_then(|installation| installation.version.as_deref());
SettingsPickerOption {
key: path.clone(),
title: version.map_or_else(
|| "System GLFW".to_owned(),
|version| format!("GLFW {version}"),
),
detail: Some(path),
leading: None,
active: false,
badge: None,
}
}
})
.collect()
}
pub(crate) fn selection(&self) -> &SettingsPicker {
&self.picker
}
pub(crate) fn selection_mut(&mut self) -> &mut SettingsPicker {
&mut self.picker
}
pub(crate) fn take_status(&mut self) -> Option<&'static str> {
match &*self
.load
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
{
LoadState::Loading => Some("Detecting installed GLFW libraries…"),
LoadState::Loaded(installations) if installations.is_empty() => {
Some("No system GLFW libraries found; bundled remains available.")
}
_ => None,
}
}
}
const BUNDLED_GLFW_KEY: &str = "\0bundled-glfw";
impl Default for GlfwPicker {
fn default() -> Self {
Self::new()
}
}
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 {
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
return false;
};
let name = name.to_ascii_lowercase();
name.starts_with("libglfw") && (name.contains(".so") || 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;
@@ -291,11 +746,22 @@ fn same_executable(left: &str, right: &str) -> bool {
fn java_runtime_label(path: &str, version: Option<&str>) -> String {
version.map_or_else(
|| path.to_owned(),
|version| format!("Java {version} {path}"),
|| format!("Java {path}"),
|version| format!("{} {path}", java_title(version)),
)
}
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)
} else {
first
};
format!("Java {major}")
}
pub(crate) fn memory_kib(value: &str) -> Option<u64> {
let normalized = crate::instance::models::normalize_memory_value(value)?;
let (number, suffix) = normalized.split_at(normalized.len().saturating_sub(1));
@@ -406,10 +872,37 @@ 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 mut editor = TextArea::new(if lines.is_empty() {
vec![String::new()]
} else {
lines
});
editor.set_style(Style::default().fg(theme.text()).bg(theme.surface()));
editor.set_cursor_line_style(Style::default());
editor.set_cursor_style(Style::default().fg(theme.background()).bg(theme.accent()));
editor.move_cursor(CursorMove::Bottom);
editor.move_cursor(CursorMove::End);
editor
}
pub(crate) fn auto_label() -> Span<'static> {
status_badge("Auto", THEME.as_ref().success())
}
pub(crate) fn bundled_label() -> Span<'static> {
status_badge("Bundled", THEME.as_ref().success())
}
pub(crate) fn render_settings_picker(
picker: &SettingsPicker,
area: Rect,
buffer: &mut ratatui::buffer::Buffer,
) {
super::select_list::render_styled(picker.items(), picker.selected(), area, buffer);
}
pub(crate) fn display_resolutions() -> Vec<DisplayResolution> {
let Ok(displays) = display_info::DisplayInfo::all() else {
return Vec::new();
@@ -463,25 +956,101 @@ mod tests {
picker.selected_choice(),
JavaChoice::Installation("/opt/jdk/bin/java".to_owned())
);
assert_eq!(
picker.display_label("/opt/jdk/bin/java"),
"Java 21 /opt/jdk/bin/java"
);
}
#[test]
fn java_title_is_minimal_and_uses_the_major_version() {
let picker = JavaPicker::with_auto_path("/opt/jdk-25/bin/java".to_owned());
assert_eq!(
picker.display_label("/opt/jdk-25/bin/java"),
"Java /opt/jdk-25/bin/java"
);
*picker.load.lock().unwrap() = LoadState::Loaded(vec![JavaInstallation {
path: "/opt/jdk-25/bin/java".into(),
version: Some("25.0.1".to_owned()),
}]);
assert_eq!(
picker.display_label("/opt/jdk-25/bin/java"),
"Java 25 /opt/jdk-25/bin/java"
);
assert_eq!(java_title("1.8.0_412"), "Java 8");
}
#[test]
fn automatic_java_compares_selected_executables() {
let picker = JavaPicker::with_auto_path("/auto/java".to_owned());
*picker.load.lock().unwrap() = LoadState::Loaded(vec![
JavaInstallation {
path: "/current/java".into(),
version: Some("21.0.8".to_owned()),
},
JavaInstallation {
path: "/auto/java".into(),
version: Some("21.0.8".to_owned()),
},
]);
assert!(!picker.automatic_change("/auto/java"));
assert!(picker.automatic_change("/current/java"));
assert!(picker.automatic_change("/other/java"));
}
assert!(picker.automatic_change("/auto/java").is_none());
assert!(picker.automatic_change("/current/java").is_some());
assert!(picker.automatic_change("/other/java").is_some());
#[test]
fn settings_picker_shares_navigation_and_preserves_selection() {
let option = |key: &str| SettingsPickerOption {
key: key.to_owned(),
title: key.to_owned(),
detail: None,
leading: None,
active: false,
badge: None,
};
let mut picker = SettingsPicker::default();
picker.sync(vec![option("one"), option("two")], Some("one"));
assert_eq!(
picker.handle_key(&KeyEvent::from(KeyCode::Char('j'))),
SettingsPickerAction::None
);
assert_eq!(picker.selected_key(), Some("two"));
picker.sync(
vec![option("zero"), option("one"), option("two")],
Some("one"),
);
assert_eq!(picker.selected_key(), Some("two"));
assert_eq!(
picker.handle_key(&KeyEvent::from(KeyCode::Enter)),
SettingsPickerAction::Select
);
}
#[test]
fn bundled_glfw_version_comes_from_minecraft_metadata() {
let temp = tempfile::tempdir().unwrap();
let versions = crate::storage::MetadataPaths::new(temp.path()).versions();
std::fs::create_dir_all(versions.join("1.21.1")).unwrap();
std::fs::write(
versions.join("1.21.1/meta.json"),
r#"{"libraries":[{"name":"org.lwjgl:lwjgl-glfw:3.3.3"}]}"#,
)
.unwrap();
assert_eq!(
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()));
picker.initialize();
assert_eq!(picker.labels()[0], "LWJGL GLFW 3.3.3");
assert_eq!(
picker.selection().options[0].badge,
Some(SettingsPickerBadge::Bundled)
);
}
#[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_eq!(
glfw_version_from_path(Path::new("/usr/lib/libglfw.so.3.4")).as_deref(),
Some("3.4")
);
}
#[test]