Merge pull request #24 from objz/feature/config-sync

feat(config-sync): add shared config profiles
This commit is contained in:
objz authored and GitHub committed 2026-07-10 16:30:00 +02:00
commit 4ddb8f49bb
15 files changed
+1430 -116

No files matched your search

+76
View File
@@ -11,6 +11,7 @@ use crate::instance::{InstanceManager, ModLoader};
use crate::running::RunState;
type CliResult = Result<(), Box<dyn std::error::Error>>;
const LOCAL_CONFIG_PROFILE: &str = "instance default";
pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
match matches.subcommand() {
@@ -20,6 +21,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
Some(("rename", sub_matches)) => rename_instance(sub_matches),
Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
Some(("config", sub_matches)) => config_instance(sub_matches),
Some(("profile", sub_matches)) => profile_instance(sub_matches),
Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
_ => Ok(()),
}
@@ -233,12 +235,86 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
.map(|(width, height)| format!("{}x{}", width, height))
.unwrap_or_else(|| "-".to_string()),
],
vec![
"config-sync-profile".to_string(),
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
],
];
print_table(&["Field", "Value"], &rows);
Ok(())
}
fn profile_instance(matches: &ArgMatches) -> CliResult {
let name = required_arg(matches, "name")?;
let manager = manager();
let mut config = manager.load_one(name)?;
let profiles = crate::instance::config_sync::list_profiles(&manager.meta_dir)?;
if config
.config_sync_profile
.as_ref()
.is_some_and(|profile| !profiles.iter().any(|candidate| candidate == profile))
{
config.config_sync_profile = None;
manager.save(&config)?;
}
let Some(profile) = matches.get_one::<String>("profile") else {
let rows = vec![
vec![
"current".to_string(),
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
],
vec![
"available".to_string(),
if profiles.is_empty() {
LOCAL_CONFIG_PROFILE.to_string()
} else {
format!("{}, {}", LOCAL_CONFIG_PROFILE, profiles.join(", "))
},
],
];
print_table(&["Field", "Value"], &rows);
return Ok(());
};
let target = if is_local_profile_alias(profile) {
None
} else {
Some(profile.as_str())
};
let instance_dir = manager.instances_dir.join(&config.name);
let selected = crate::instance::config_sync::switch_profile(
&config.name,
config.config_sync_profile.as_deref(),
target,
&manager.meta_dir,
&instance_dir,
)?;
config.config_sync_profile = selected;
manager.save(&config)?;
println!(
"Updated '{}' config profile to {}.",
name,
display_config_profile(config.config_sync_profile.as_deref())
);
Ok(())
}
fn display_config_profile(profile: Option<&str>) -> &str {
profile.unwrap_or(LOCAL_CONFIG_PROFILE)
}
fn is_local_profile_alias(profile: &str) -> bool {
let profile = profile.trim();
profile.eq_ignore_ascii_case("none")
|| profile.eq_ignore_ascii_case("default")
|| profile.eq_ignore_ascii_case("local")
|| profile.eq_ignore_ascii_case("instance-default")
|| profile.eq_ignore_ascii_case("instance default")
}
// maps --set key=value pairs to config fields. empty value = clear the field.
fn apply_config_update(
config: &mut crate::instance::InstanceConfig,
+7
View File
@@ -104,6 +104,13 @@ fn build_command() -> Command {
.arg(Arg::new("name").required(true).action(ArgAction::Set))
.arg(Arg::new("set").long("set").action(ArgAction::Set)),
)
.subcommand(
Command::new("profile")
.about("Show or set an instance config-sync profile")
.arg_required_else_help(true)
.arg(Arg::new("name").required(true).action(ArgAction::Set))
.arg(Arg::new("profile").action(ArgAction::Set)),
)
.subcommand(
Command::new("desktop")
.about("Toggle desktop shortcut for an instance")
+677
View File
@@ -0,0 +1,677 @@
use std::path::{Path, PathBuf};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigSyncError {
#[error("Invalid config sync profile: {0}")]
InvalidProfile(String),
#[error("Config sync profile '{profile}' is already in use")]
AlreadyLocked { profile: String },
#[error("Cannot switch config profiles while '{instance}' is running")]
InstanceRunning { instance: String },
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
#[derive(Debug)]
pub struct ConfigSyncLock {
path: PathBuf,
}
impl Drop for ConfigSyncLock {
fn drop(&mut self) {
if let Err(e) = std::fs::remove_file(&self.path)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("Failed to release config sync lock: {}", e);
}
}
}
pub fn prepare(
profile: Option<&str>,
meta_dir: &Path,
minecraft_dir: &Path,
) -> Result<Option<ConfigSyncLock>, ConfigSyncError> {
let Some(profile) = profile.and_then(normalize_profile) else {
return Ok(None);
};
validate_profile(profile)?;
let profile_dir = profile_dir(meta_dir, profile);
if !profile_dir.exists() {
return Ok(None);
}
let lock = acquire_lock(&profile_dir, profile)?;
if !profile_payload_exists(&profile_dir)? {
sync_to_profile(minecraft_dir, &profile_dir)?;
} else {
sync_from_profile(&profile_dir, minecraft_dir)?;
}
Ok(Some(lock))
}
pub fn finish(
profile: Option<&str>,
meta_dir: &Path,
minecraft_dir: &Path,
) -> Result<(), ConfigSyncError> {
let Some(profile) = profile.and_then(normalize_profile) else {
return Ok(());
};
validate_profile(profile)?;
sync_to_profile(minecraft_dir, &profile_dir(meta_dir, profile))
}
pub fn list_profiles(meta_dir: &Path) -> Result<Vec<String>, ConfigSyncError> {
let root = profiles_dir(meta_dir);
let mut profiles = Vec::new();
if !root.exists() {
return Ok(profiles);
}
for entry in std::fs::read_dir(root)? {
let entry = entry?;
if entry.file_type()?.is_dir() {
let name = entry.file_name().to_string_lossy().to_string();
if validate_profile(&name).is_ok() {
profiles.push(name);
}
}
}
profiles.sort_unstable();
Ok(profiles)
}
pub fn create_profile(meta_dir: &Path, profile: &str) -> Result<String, ConfigSyncError> {
let Some(profile) = normalize_profile(profile) else {
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
};
validate_profile(profile)?;
std::fs::create_dir_all(profile_dir(meta_dir, profile))?;
Ok(profile.to_string())
}
pub fn delete_profile(meta_dir: &Path, profile: &str) -> Result<(), ConfigSyncError> {
validate_profile(profile)?;
let dir = profile_dir(meta_dir, profile);
if dir.exists() {
remove_path(&dir)?;
}
Ok(())
}
pub fn switch_profile(
instance_name: &str,
current_profile: Option<&str>,
target_profile: Option<&str>,
meta_dir: &Path,
instance_dir: &Path,
) -> Result<Option<String>, ConfigSyncError> {
if crate::running::get(instance_name).is_some() {
return Err(ConfigSyncError::InstanceRunning {
instance: instance_name.to_string(),
});
}
let current_profile = current_profile.and_then(normalize_profile);
let target_profile = target_profile.and_then(normalize_profile);
if let Some(profile) = current_profile {
validate_profile(profile)?;
}
if let Some(profile) = target_profile {
validate_profile(profile)?;
}
if current_profile == target_profile {
return Ok(current_profile.map(str::to_string));
}
if let Some(profile) = current_profile {
let profile_dir = profile_dir(meta_dir, profile);
if profile_dir.exists() {
let _lock = acquire_lock(&profile_dir, profile)?;
finish(Some(profile), meta_dir, &minecraft_dir(instance_dir))?;
}
}
match (current_profile, target_profile) {
(None, Some(_)) => {
sync_to_profile(
&minecraft_dir(instance_dir),
&local_backup_dir(instance_dir),
)?;
}
(Some(_), None) => {
let backup = local_backup_dir(instance_dir);
if backup.exists() {
sync_from_profile(&backup, &minecraft_dir(instance_dir))?;
}
return Ok(None);
}
_ => {}
}
let Some(profile) = target_profile else {
return Ok(None);
};
let profile_dir = profile_dir(meta_dir, profile);
let _lock = acquire_lock(&profile_dir, profile)?;
if !profile_payload_exists(&profile_dir)? {
sync_to_profile(&minecraft_dir(instance_dir), &profile_dir)?;
}
sync_from_profile(&profile_dir, &minecraft_dir(instance_dir))?;
Ok(Some(profile.to_string()))
}
fn normalize_profile(profile: &str) -> Option<&str> {
let trimmed = profile.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed)
}
}
pub fn validate_profile(profile: &str) -> Result<(), ConfigSyncError> {
if profile.is_empty()
|| profile.len() > 64
|| profile.starts_with('.')
|| profile.contains('/')
|| profile.contains('\\')
|| profile.eq_ignore_ascii_case("default")
|| profile.eq_ignore_ascii_case("none")
|| profile.eq_ignore_ascii_case("local")
|| profile.eq_ignore_ascii_case("instance default")
|| profile.eq_ignore_ascii_case("local default")
|| profile
.chars()
.any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*'))
{
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
}
Ok(())
}
fn profile_dir(meta_dir: &Path, profile: &str) -> PathBuf {
profiles_dir(meta_dir).join(profile)
}
fn profiles_dir(meta_dir: &Path) -> PathBuf {
meta_dir.join("config-sync").join("profiles")
}
fn minecraft_dir(instance_dir: &Path) -> PathBuf {
instance_dir.join(".minecraft")
}
fn local_backup_dir(instance_dir: &Path) -> PathBuf {
instance_dir
.join(".rmcl")
.join("config-sync")
.join("local-config")
}
fn acquire_lock(profile_dir: &Path, profile: &str) -> Result<ConfigSyncLock, ConfigSyncError> {
std::fs::create_dir_all(profile_dir)?;
let path = profile_dir.join(".lock");
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(_) => Ok(ConfigSyncLock { path }),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
Err(ConfigSyncError::AlreadyLocked {
profile: profile.to_string(),
})
}
Err(e) => Err(e.into()),
}
}
fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
if dst.exists() {
remove_path(dst)?;
}
std::fs::create_dir_all(dst)?;
if !src.exists() {
return Ok(());
}
copy_dir_contents(src, dst)
}
fn sync_to_profile(minecraft_dir: &Path, profile_dir: &Path) -> Result<(), ConfigSyncError> {
mirror_dir(&minecraft_dir.join("config"), &profile_dir.join("config"))?;
mirror_options(minecraft_dir, profile_dir)
}
fn sync_from_profile(profile_dir: &Path, minecraft_dir: &Path) -> Result<(), ConfigSyncError> {
mirror_dir(&profile_dir.join("config"), &minecraft_dir.join("config"))?;
mirror_options(profile_dir, minecraft_dir)
}
fn profile_payload_exists(profile_dir: &Path) -> Result<bool, ConfigSyncError> {
if profile_dir.join("config").exists() {
return Ok(true);
}
if !profile_dir.exists() {
return Ok(false);
}
for entry in std::fs::read_dir(profile_dir)? {
let entry = entry?;
if entry.file_type()?.is_file() && is_options_file(&entry.file_name().to_string_lossy()) {
return Ok(true);
}
}
Ok(false)
}
fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
remove_options(dst)?;
std::fs::create_dir_all(dst)?;
if !src.exists() {
return Ok(());
}
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let name = entry.file_name();
if entry.file_type()?.is_file() && is_options_file(&name.to_string_lossy()) {
std::fs::copy(entry.path(), dst.join(name))?;
}
}
Ok(())
}
fn remove_options(dir: &Path) -> Result<(), ConfigSyncError> {
if !dir.exists() {
return Ok(());
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
if is_options_file(&entry.file_name().to_string_lossy()) {
remove_path(&entry.path())?;
}
}
Ok(())
}
fn is_options_file(name: &str) -> bool {
name == "options.txt" || name.starts_with("options") && name.ends_with(".txt")
}
fn remove_path(path: &Path) -> Result<(), ConfigSyncError> {
let meta = std::fs::symlink_metadata(path)?;
if meta.is_dir() {
std::fs::remove_dir_all(path)?;
} else {
std::fs::remove_file(path)?;
}
Ok(())
}
fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let source = entry.path();
let target = dst.join(entry.file_name());
let file_type = entry.file_type()?;
if file_type.is_dir() {
std::fs::create_dir_all(&target)?;
copy_dir_contents(&source, &target)?;
} else if file_type.is_file() {
std::fs::copy(&source, &target)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_prepare_seeds_shared_config() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config/nested")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("optionsshaders.txt"), "shader-options").unwrap();
std::fs::write(minecraft.join("config/options.txt"), "local-config").unwrap();
std::fs::write(minecraft.join("config/nested/mod.toml"), "nested").unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/optionsshaders.txt"))
.unwrap(),
"shader-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/options.txt"))
.unwrap(),
"local-config"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/nested/mod.toml"))
.unwrap(),
"nested"
);
}
#[test]
fn prepare_mirrors_shared_config_into_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/options.txt"),
"shared-options",
)
.unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/config/shared.toml"),
"shared",
)
.unwrap();
std::fs::write(minecraft.join("options.txt"), "stale-options").unwrap();
std::fs::write(minecraft.join("config/local.toml"), "stale").unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"shared-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/shared.toml")).unwrap(),
"shared"
);
assert!(!minecraft.join("config/local.toml").exists());
}
#[test]
fn finish_mirrors_instance_config_back_to_shared() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/config/old.toml"),
"old",
)
.unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "new-options").unwrap();
std::fs::write(minecraft.join("config/new.toml"), "new").unwrap();
finish(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"new-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/new.toml"))
.unwrap(),
"new"
);
assert!(
!meta
.join("config-sync/profiles/main/config/old.toml")
.exists()
);
}
#[test]
fn lock_blocks_second_prepare() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
let err = prepare(Some("main"), &meta, &minecraft).unwrap_err();
assert!(matches!(err, ConfigSyncError::AlreadyLocked { .. }));
}
#[test]
fn profile_rejects_path_traversal() {
let tmp = tempfile::tempdir().unwrap();
let err = prepare(Some("../bad"), tmp.path(), tmp.path()).unwrap_err();
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
}
#[test]
fn profile_rejects_builtin_names() {
for profile in [
"none",
"default",
"local",
"instance default",
"local default",
] {
let err = validate_profile(profile).unwrap_err();
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
}
}
#[test]
fn prepare_ignores_deleted_profile() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap();
assert!(lock.is_none());
assert!(!meta.join("config-sync/profiles/deleted").exists());
}
#[test]
fn create_profile_trims_and_lists_profiles() {
let tmp = tempfile::tempdir().unwrap();
let profile = create_profile(tmp.path(), " main ").unwrap();
let profiles = list_profiles(tmp.path()).unwrap();
assert_eq!(profile, "main");
assert_eq!(profiles, vec!["main"]);
}
#[test]
fn delete_profile_removes_profile_dir() {
let tmp = tempfile::tempdir().unwrap();
create_profile(tmp.path(), "main").unwrap();
delete_profile(tmp.path(), "main").unwrap();
assert!(list_profiles(tmp.path()).unwrap().is_empty());
}
#[test]
fn switch_to_profile_backs_up_local_config_and_restores_none() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("config/local.txt"), "local").unwrap();
let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("main"));
assert_eq!(
std::fs::read_to_string(instance.join(".rmcl/config-sync/local-config/options.txt"))
.unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(
instance.join(".rmcl/config-sync/local-config/config/local.txt")
)
.unwrap(),
"local"
);
std::fs::write(minecraft.join("options.txt"), "shared-options").unwrap();
std::fs::write(minecraft.join("config/shared.txt"), "shared").unwrap();
let selected = switch_profile("inst", Some("main"), None, &meta, &instance).unwrap();
assert_eq!(selected, None);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"shared-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/shared.txt"))
.unwrap(),
"shared"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!minecraft.join("config/shared.txt").exists());
}
#[test]
fn switch_from_deleted_profile_restores_local_without_recreating_profile() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::create_dir_all(instance.join(".rmcl/config-sync/local-config/config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap();
std::fs::write(
instance.join(".rmcl/config-sync/local-config/options.txt"),
"local-options",
)
.unwrap();
std::fs::write(
instance.join(".rmcl/config-sync/local-config/config/local.txt"),
"local",
)
.unwrap();
let selected = switch_profile("inst", Some("deleted"), None, &meta, &instance).unwrap();
assert_eq!(selected, None);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!meta.join("config-sync/profiles/deleted").exists());
}
#[test]
fn switch_between_profiles_saves_old_and_loads_new() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap();
std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap();
create_profile(&meta, "a").unwrap();
std::fs::create_dir_all(meta.join("config-sync/profiles/b/config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/b/options.txt"),
"profile-b-options",
)
.unwrap();
std::fs::write(
meta.join("config-sync/profiles/b/config/b.txt"),
"profile-b",
)
.unwrap();
let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("b"));
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/a/options.txt")).unwrap(),
"changed-a-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/a/config/a.txt")).unwrap(),
"changed-a"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"profile-b-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/b.txt")).unwrap(),
"profile-b"
);
assert!(!minecraft.join("config/a.txt").exists());
}
#[test]
fn second_instance_uses_profile_options_saved_by_first_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let first = tmp.path().join("first/.minecraft");
let second_instance = tmp.path().join("second");
let second = second_instance.join(".minecraft");
std::fs::create_dir_all(first.join("config")).unwrap();
std::fs::create_dir_all(second.join("config")).unwrap();
std::fs::write(first.join("options.txt"), "first-default").unwrap();
std::fs::write(second.join("options.txt"), "second-local").unwrap();
create_profile(&meta, "main").unwrap();
let _lock = prepare(Some("main"), &meta, &first).unwrap();
std::fs::write(first.join("options.txt"), "changed-in-main").unwrap();
finish(Some("main"), &meta, &first).unwrap();
drop(_lock);
switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap();
assert_eq!(
std::fs::read_to_string(second.join("options.txt")).unwrap(),
"changed-in-main"
);
assert_eq!(
std::fs::read_to_string(
second_instance.join(".rmcl/config-sync/local-config/options.txt")
)
.unwrap(),
"second-local"
);
}
}
+23
View File
@@ -46,6 +46,8 @@ pub enum LaunchError {
},
#[error("{0}")]
Auth(String),
#[error("Config sync error: {0}")]
ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError),
}
fn build_game_args(
@@ -621,6 +623,13 @@ pub async fn launch(
invocation.game_args.len(),
invocation.main_class
);
let config_sync_profile = config.config_sync_profile.clone();
let config_sync_lock = crate::instance::config_sync::prepare(
config_sync_profile.as_deref(),
meta_dir,
&invocation.working_dir,
)?;
let config_sync_active = config_sync_lock.is_some();
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
crate::running::register_kill(&name, kill_tx);
@@ -682,6 +691,7 @@ pub async fn launch(
let name_for_task = name.clone();
let instances_dir_owned = instances_dir.to_path_buf();
let meta_dir_owned = meta_dir.to_path_buf();
let minecraft_dir_owned = invocation.working_dir.clone();
// spawn a background task to babysit the child process: capture stdout/stderr
// into both the TUI log viewer and a timestamped log file on disk
@@ -783,6 +793,17 @@ pub async fn launch(
let _ = parser_task.await;
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
if config_sync_active
&& let Err(e) = crate::instance::config_sync::finish(
config_sync_profile.as_deref(),
&meta_dir_owned,
&minecraft_dir_owned,
)
{
tracing::warn!("Failed to sync config for '{}': {}", name_for_task, e);
}
drop(config_sync_lock);
if code == Some(0) || killed_by_user {
crate::running::remove(&name_for_task);
tracing::debug!(
@@ -1015,6 +1036,7 @@ mod tests {
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
};
let result =
@@ -1062,6 +1084,7 @@ mod tests {
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
};
let result = migrate_legacy_loader_profile_if_needed(
+2
View File
@@ -269,6 +269,7 @@ impl InstanceManager {
memory_min: None,
jvm_args: vec![],
resolution: None,
config_sync_profile: None,
};
self.save(&config)?;
@@ -518,6 +519,7 @@ mod tests {
memory_min: None,
jvm_args: vec![],
resolution: None,
config_sync_profile: None,
}
}
+2
View File
@@ -1,5 +1,7 @@
// instance management: creation, launching, importing modpacks, and all the
// bookkeeping that comes with pretending to be a real launcher
pub mod config_sync;
pub mod content;
pub mod desktop;
pub mod import;
+3
View File
@@ -47,6 +47,8 @@ pub struct InstanceConfig {
pub jvm_args: Vec<String>,
#[serde(default)]
pub resolution: Option<(u32, u32)>,
#[serde(default)]
pub config_sync_profile: Option<String>,
}
pub fn normalize_memory_value(raw: &str) -> Option<String> {
@@ -137,6 +139,7 @@ mod tests {
memory_min: Some("512M".to_string()),
jvm_args: vec![],
resolution: Some((1920, 1080)),
config_sync_profile: None,
};
let json = serde_json::to_string_pretty(&config).expect("serialize");
let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize");
+2
View File
@@ -29,6 +29,7 @@ pub struct App {
pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState,
pub(super) logs_state: widgets::logs_viewer::LogsState,
pub(super) account_state: widgets::account::AccountState,
pub(super) settings_state: widgets::settings::SettingsState,
pub(super) picker: ratatui_image::picker::Picker,
pub(super) instance_manager: InstanceManager,
pub(super) log_overlay_scroll: usize,
@@ -87,6 +88,7 @@ impl App {
worlds_state: widgets::content::list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(),
account_state: widgets::account::AccountState::default(),
settings_state: widgets::settings::SettingsState::new(manager.meta_dir.clone()),
screenshots_state: {
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
s.font_size = picker.font_size();
+115 -9
View File
@@ -70,18 +70,49 @@ impl App {
if self.focused == FocusedArea::ConfirmDelete {
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let name = confirm_popup::pending_delete_name();
if !name.is_empty()
&& let Ok(_) = self.instance_manager.delete(&name) {
self.instances_state.remove_instance(&name);
if let Some(target) = confirm_popup::pending_target() {
match target {
confirm_popup::ConfirmTarget::Instance { name } => {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.instances_state.remove_instance(&name);
}
Err(e) => {
tracing::error!(
"Failed to delete instance '{}': {}",
name,
e
);
}
}
self.focused = FocusedArea::Instances;
}
confirm_popup::ConfirmTarget::ConfigProfile { profile } => {
if let Err(e) = self.delete_config_profile(&profile) {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: e.to_string(),
pushed_at: std::time::Instant::now(),
});
}
self.focused = FocusedArea::Settings;
}
}
}
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
return Ok(());
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
if matches!(
confirm_popup::pending_target(),
Some(confirm_popup::ConfirmTarget::ConfigProfile { .. })
) {
self.focused = FocusedArea::Settings;
} else {
self.focused = FocusedArea::Instances;
}
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
return Ok(());
}
_ => {
@@ -132,6 +163,7 @@ impl App {
if self.focused == FocusedArea::Settings {
match widgets::settings::handle_key(
&key_event,
&mut self.settings_state,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
) {
@@ -167,6 +199,53 @@ impl App {
}
return Ok(());
}
widgets::settings::SettingsAction::SelectProfile(profile) => {
if let Some(inst) = self.instances_state.selected_instance().cloned() {
let instance_dir = self.instance_manager.instances_dir.join(&inst.name);
match crate::instance::config_sync::switch_profile(
&inst.name,
inst.config_sync_profile.as_deref(),
profile.as_deref(),
&self.instance_manager.meta_dir,
&instance_dir,
) {
Ok(selected) => {
let mut updated = inst.clone();
updated.config_sync_profile = selected;
if let Err(e) = self.instance_manager.save(&updated) {
tracing::error!("Failed to save config profile: {}", e);
} else {
self.instances_state.replace_instance(&inst.name, updated);
}
}
Err(e) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: e.to_string(),
pushed_at: std::time::Instant::now(),
});
}
}
}
return Ok(());
}
widgets::settings::SettingsAction::ConfirmDeleteProfile(profile) => {
confirm_popup::set_pending(confirm_popup::ConfirmTarget::ConfigProfile {
profile,
});
self.focused = FocusedArea::ConfirmDelete;
return Ok(());
}
widgets::settings::SettingsAction::Error(message) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message,
pushed_at: std::time::Instant::now(),
});
return Ok(());
}
widgets::settings::SettingsAction::None => {}
}
}
@@ -192,9 +271,9 @@ impl App {
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_owned();
}
{
inst.name = new_name.trim().to_owned();
}
}
}
KeyCode::Esc => {
@@ -333,4 +412,31 @@ impl App {
Ok(())
}
fn delete_config_profile(&mut self, profile: &str) -> color_eyre::Result<()> {
let instances = self.instance_manager.load_all();
for instance in instances
.into_iter()
.filter(|instance| instance.config_sync_profile.as_deref() == Some(profile))
{
let instance_dir = self.instance_manager.instances_dir.join(&instance.name);
let mut updated = instance.clone();
updated.config_sync_profile = crate::instance::config_sync::switch_profile(
&instance.name,
instance.config_sync_profile.as_deref(),
None,
&self.instance_manager.meta_dir,
&instance_dir,
)?;
self.instance_manager.save(&updated)?;
self.instances_state
.replace_instance(&instance.name, updated);
}
crate::instance::config_sync::delete_profile(&self.instance_manager.meta_dir, profile)?;
self.settings_state
.profiles
.retain(|candidate| candidate != profile);
Ok(())
}
}
+8 -8
View File
@@ -70,8 +70,8 @@ impl App {
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(30),
Constraint::Percentage(40),
Constraint::Percentage(24),
Constraint::Percentage(46),
Constraint::Percentage(30),
])
.split(main_chunks[2]);
@@ -86,6 +86,7 @@ impl App {
frame,
bottom_chunks[1],
self.focused,
&mut self.settings_state,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
);
@@ -123,12 +124,11 @@ impl App {
import_modpack::render(frame, area, self.focused);
}
if self.focused == FocusedArea::ConfirmDelete {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
let area = confirm_popup_area(frame.area(), &name);
frame.render_widget(ConfirmPopup::new(&name), area);
}
if self.focused == FocusedArea::ConfirmDelete
&& let Some(target) = confirm_popup::pending_target()
{
let area = confirm_popup_area(frame.area(), &target);
frame.render_widget(ConfirmPopup::for_target(&target), area);
}
}
+10 -30
View File
@@ -310,9 +310,11 @@ fn render_account_list(
let (username, acc_type, is_active) = &accounts[context.index];
let show_selected = is_focused && context.is_selected;
let stripe_bg = theme.background();
let bg = stripe_bg;
let bg = if show_selected {
theme.stripe()
} else {
theme.background()
};
let active_marker = if *is_active { "\u{25b8} " } else { " " };
@@ -494,8 +496,7 @@ fn render_offline_blocked_popup(frame: &mut Frame) {
}
fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
use super::popups::confirm::ConfirmPopup;
let username = state
.store
.accounts
@@ -503,34 +504,13 @@ fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
.map(|a| a.username.as_str())
.unwrap_or("?");
let border_color = theme.text_dim();
let title = Line::from(Span::styled(
format!(" Delete '{}' ", username),
Style::default()
.fg(border_color)
.add_modifier(Modifier::BOLD),
));
let body = "This will permanently remove this account";
let popup_w = (username.len() + 14).max(body.len() + 2).min(48) as u16 + 2;
let area = popup_area(frame, popup_w, 3);
let bg_color = theme.surface();
let text_color = theme.text();
PopupFrame {
title,
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " confirm")])),
search_line: None,
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove this account")
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
}
.render(area, frame.buffer_mut());
frame.render_widget(
ConfirmPopup::new(format!(" Delete '{}' ", username), body),
area,
);
}
fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
+1
View File
@@ -387,6 +387,7 @@ mod tests {
memory_min: None,
jvm_args: vec![],
resolution: None,
config_sync_profile: None,
}
}
+57 -17
View File
@@ -19,13 +19,44 @@ static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> =
#[derive(Debug, Default)]
struct ConfirmState {
instance_name: String,
target: Option<ConfirmTarget>,
}
pub fn set_pending_delete(name: impl Into<String>) {
#[derive(Debug, Clone)]
pub enum ConfirmTarget {
Instance { name: String },
ConfigProfile { profile: String },
}
impl ConfirmTarget {
fn title(&self) -> String {
match self {
ConfirmTarget::Instance { name } => format!(" Delete '{}' ", name),
ConfirmTarget::ConfigProfile { profile } => format!(" Delete '{}' ", profile),
}
}
fn body(&self) -> &'static str {
match self {
ConfirmTarget::Instance { .. } => "This will permanently remove the instance",
ConfirmTarget::ConfigProfile { .. } => {
"This will permanently remove this config profile"
}
}
}
fn name(&self) -> &str {
match self {
ConfirmTarget::Instance { name } => name,
ConfirmTarget::ConfigProfile { profile } => profile,
}
}
}
pub fn set_pending(target: ConfirmTarget) {
match CONFIRM_STATE.lock() {
Ok(mut s) => {
s.instance_name = name.into();
s.target = Some(target);
}
Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e);
@@ -33,17 +64,21 @@ pub fn set_pending_delete(name: impl Into<String>) {
}
}
pub fn pending_delete_name() -> String {
pub fn set_pending_delete(name: impl Into<String>) {
set_pending(ConfirmTarget::Instance { name: name.into() });
}
pub fn pending_target() -> Option<ConfirmTarget> {
match CONFIRM_STATE.lock() {
Ok(s) => s.instance_name.clone(),
Err(_) => String::new(),
Ok(s) => s.target.clone(),
Err(_) => None,
}
}
pub fn clear_pending() {
match CONFIRM_STATE.lock() {
Ok(mut s) => {
s.instance_name.clear();
s.target = None;
}
Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e);
@@ -52,15 +87,21 @@ pub fn clear_pending() {
}
pub struct ConfirmPopup {
instance_name: String,
title: String,
body: &'static str,
}
impl ConfirmPopup {
pub fn new(instance_name: impl Into<String>) -> Self {
pub fn new(title: impl Into<String>, body: &'static str) -> Self {
Self {
instance_name: instance_name.into(),
title: title.into(),
body,
}
}
pub fn for_target(target: &ConfirmTarget) -> Self {
Self::new(target.title(), target.body())
}
}
impl Widget for ConfirmPopup {
@@ -69,7 +110,7 @@ impl Widget for ConfirmPopup {
let theme = THEME.as_ref();
let title = Line::from(vec![Span::styled(
format!(" Delete '{}' ", self.instance_name),
self.title,
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
@@ -86,7 +127,7 @@ impl Widget for ConfirmPopup {
keybinds: Some(kb),
search_line: None,
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove the instance")
Paragraph::new(self.body)
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
@@ -96,15 +137,14 @@ impl Widget for ConfirmPopup {
}
}
pub fn confirm_popup_area(frame_area: Rect, name: &str) -> Rect {
pub fn confirm_popup_area(frame_area: Rect, target: &ConfirmTarget) -> Rect {
use super::word_wrap_size;
use ratatui::layout::Constraint;
const MAX_W: usize = 48;
const BODY: &str = "This will permanently remove the instance";
let title_w = name.len() + 12;
let (body_w, _) = word_wrap_size(BODY, MAX_W);
let title_w = target.name().len() + 12;
let (body_w, _) = word_wrap_size(target.body(), MAX_W);
let inner_w = title_w.max(body_w).min(MAX_W);
let (_, lines) = word_wrap_size(BODY, inner_w);
let (_, lines) = word_wrap_size(target.body(), inner_w);
let popup_w = ((inner_w + 2) as u16).min(frame_area.width.saturating_sub(4));
let popup_h = ((lines + 2) as u16).min(frame_area.height.saturating_sub(4));
frame_area.centered(Constraint::Length(popup_w), Constraint::Length(popup_h))
+446 -52
View File
@@ -1,13 +1,20 @@
// settings panel: shows instance config (memory, java, jvm args, resolution)
// and provides keybinds to open config files in $EDITOR
// settings panel: manages config profiles and shows compact instance info.
// also provides keybinds to open config files in $EDITOR.
use std::{
path::{Path, PathBuf},
process::Command,
};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
Frame,
layout::Rect,
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
widgets::{Block, Borders, Paragraph, Widget},
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::{
SETTINGS,
@@ -18,13 +25,155 @@ use crate::tui::app::FocusedArea;
use super::styled_title;
const LOCAL_PROFILE_LABEL: &str = "instance default";
#[derive(Default)]
pub enum AddMode {
#[default]
None,
ProfileName(String),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SettingsPane {
#[default]
Profile,
Info,
}
pub struct SettingsState {
pub list_state: TuiListState,
pub profiles: Vec<String>,
pub add_mode: AddMode,
pub pane: SettingsPane,
meta_dir: PathBuf,
active_profile: Option<String>,
instance_name: Option<String>,
java_source: Option<String>,
java_label: String,
}
impl SettingsState {
pub fn new(meta_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()
});
let mut state = Self {
list_state: TuiListState::default(),
profiles,
add_mode: AddMode::None,
pane: SettingsPane::Profile,
meta_dir,
active_profile: None,
instance_name: None,
java_source: None,
java_label: "unknown".to_string(),
};
state.select_active();
state
}
fn reload_profiles(&mut self) {
match crate::instance::config_sync::list_profiles(&self.meta_dir) {
Ok(mut profiles) => {
add_active_profile(&mut profiles, self.active_profile.as_deref());
self.profiles = profiles;
}
Err(e) => tracing::warn!("Failed to reload config sync profiles: {}", e),
}
}
fn select_active(&mut self) {
self.list_state.selected = Some(
self.active_profile
.as_deref()
.and_then(|active| self.profiles.iter().position(|profile| profile == active))
.map(|idx| idx + 1)
.unwrap_or(0),
);
}
fn count(&self) -> usize {
self.profiles.len() + 1
}
fn update_for_instance(&mut self, instance: Option<&InstanceConfig>) {
let instance_name = instance.map(|inst| inst.name.clone());
let active_profile = instance.and_then(|inst| inst.config_sync_profile.clone());
let active_profile = active_profile
.filter(|profile| self.profiles.iter().any(|candidate| candidate == profile));
if self.instance_name != instance_name || self.active_profile != active_profile {
self.instance_name = instance_name;
self.active_profile = active_profile;
add_active_profile(&mut self.profiles, self.active_profile.as_deref());
self.select_active();
}
let java_source = instance.map(effective_java_path);
if self.java_source != java_source {
self.java_label = java_source
.as_deref()
.map(java_version_label)
.unwrap_or_else(|| "unknown".to_string());
self.java_source = java_source;
}
}
}
fn add_active_profile(profiles: &mut Vec<String>, active_profile: Option<&str>) {
if let Some(active) = active_profile
&& !profiles.iter().any(|profile| profile == active)
{
profiles.push(active.to_string());
profiles.sort_unstable();
}
}
fn effective_java_path(instance: &InstanceConfig) -> String {
instance
.java_path
.clone()
.or_else(|| SETTINGS.paths.effective_java_path().map(str::to_string))
.unwrap_or_else(crate::net::detect_java_path)
}
fn java_version_label(java_path: &str) -> String {
let output = Command::new(java_path).arg("-version").output();
let Ok(output) = output 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() {
"unknown".to_string()
} else {
format!("jdk{major}")
}
}
pub fn render(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &mut SettingsState,
instance: Option<&InstanceConfig>,
_instances_dir: &std::path::Path,
_instances_dir: &Path,
) {
state.update_for_instance(instance);
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings {
theme.accent()
@@ -39,14 +188,22 @@ pub fn render(
.border_style(Style::default().fg(color));
if focused == FocusedArea::Settings {
let lines = super::popups::keybind_lines_wrapped(
&[
("e", " edit instance"),
("g", " edit global"),
("d", " desktop"),
let keybinds: &[(&str, &str)] = match state.pane {
SettingsPane::Profile => &[
("⏎", " select"),
("a", " add"),
("d", " del"),
("j/k", " move"),
("h/l", " tab"),
],
area.width.saturating_sub(2),
);
SettingsPane::Info => &[
("e", " inst"),
("g", " global"),
("d", " desk"),
("h/l", " tab"),
],
};
let lines = super::popups::keybind_lines_wrapped(keybinds, area.width.saturating_sub(2));
for line in lines {
block = block.title_bottom(line);
}
@@ -55,19 +212,62 @@ pub fn render(
let inner = block.inner(area);
frame.render_widget(block, area);
let Some(inst) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())),
inner,
);
return;
};
if inner.width >= 42 {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(50),
Constraint::Length(3),
Constraint::Percentage(50),
])
.split(inner);
render_profile_list(frame, chunks[0], focused, state);
render_separator(frame, chunks[1], focused, state.pane);
render_instance_info(frame, chunks[2], focused, state, instance);
} else {
render_profile_list(frame, inner, focused, state);
}
if let AddMode::ProfileName(name) = &state.add_mode {
render_add_profile_popup(frame, name);
}
}
fn render_separator(frame: &mut Frame, area: Rect, focused: FocusedArea, pane: SettingsPane) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings && pane == SettingsPane::Info {
theme.accent()
} else {
theme.border()
};
let line = if area.width >= 3 {
" │ \n".repeat(area.height as usize)
} else {
"│\n".repeat(area.height as usize)
};
frame.render_widget(Paragraph::new(line).style(Style::default().fg(color)), area);
}
fn render_instance_info(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &SettingsState,
instance: Option<&InstanceConfig>,
) {
let theme = THEME.as_ref();
let label_style = Style::default().fg(theme.text_dim());
let value_style = Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD);
let dim_style = Style::default().fg(theme.text_dim());
let Some(inst) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())),
area,
);
return;
};
let memory_min = inst
.memory_min
@@ -77,58 +277,252 @@ pub fn render(
.memory_max
.as_deref()
.unwrap_or(&SETTINGS.defaults.memory_max);
let java_path = inst
.java_path
.as_deref()
.or_else(|| SETTINGS.paths.effective_java_path())
.unwrap_or("system");
let jvm_args = if inst.jvm_args.is_empty() {
"none".to_string()
let active_style = if focused == FocusedArea::Settings && state.pane == SettingsPane::Info {
value_style.fg(theme.accent())
} else {
inst.jvm_args.join(" ")
value_style
};
let desktop = if crate::instance::desktop::exists(&inst.name) {
"yes"
} else {
"no"
};
let resolution = inst
.resolution
.map(|(w, h)| format!("{}x{}", w, h))
.unwrap_or_else(|| "default".to_string());
let lines = vec![
Line::from(vec![
Span::styled("Memory ", label_style),
Span::styled(format!("{memory_min} - {memory_max}"), value_style),
Span::styled("Memory ", label_style),
Span::styled(format!("{memory_min} - {memory_max}"), active_style),
]),
Line::from(vec![
Span::styled("Java ", label_style),
Span::styled(java_path, value_style),
Span::styled("Java ", label_style),
Span::styled(state.java_label.as_str(), active_style),
]),
Line::from(vec![
Span::styled("JVM ", label_style),
Span::styled(jvm_args, dim_style),
]),
Line::from(vec![
Span::styled("Display ", label_style),
Span::styled(resolution, value_style),
Span::styled("Desktop ", label_style),
Span::styled(desktop, active_style),
]),
];
frame.render_widget(Paragraph::new(lines), inner);
frame.render_widget(Paragraph::new(lines), area);
}
fn render_profile_list(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &mut SettingsState,
) {
let is_focused = focused == FocusedArea::Settings;
let pane = state.pane;
let active_profile = state.active_profile.clone();
let profiles = state.profiles.clone();
let count = profiles.len() + 1;
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let name = if context.index == 0 {
LOCAL_PROFILE_LABEL.to_string()
} else {
profiles[context.index - 1].clone()
};
let is_active = if context.index == 0 {
active_profile.is_none()
} else {
active_profile.as_deref() == Some(name.as_str())
};
let show_selected = is_focused && pane == SettingsPane::Profile && context.is_selected;
let marker = if is_active { "\u{25b8} " } else { " " };
let background = if show_selected {
theme.stripe()
} else {
theme.background()
};
let style = if show_selected {
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else if is_active {
Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.text())
};
let line = Line::from(vec![
Span::styled(marker, Style::default().fg(theme.success())),
Span::styled(name, style),
]);
(
ratatui::text::Text::from(line).style(Style::default().bg(background)),
1,
)
});
frame.render_stateful_widget(ListView::new(builder, count), area, &mut state.list_state);
}
fn render_add_profile_popup(frame: &mut Frame, name: &str) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let area = popup_area(frame, 42, 5);
let name = name.to_string();
let border_color = theme.text_dim();
let bg_color = theme.surface();
let dim_color = theme.text_dim();
let text_color = theme.text();
PopupFrame {
title: Line::from(Span::styled(
" Config Profile ",
Style::default()
.fg(border_color)
.add_modifier(Modifier::BOLD),
))
.centered(),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " create"), ("Esc", " cancel")])),
search_line: None,
content: Box::new(move |inner, buf| {
let line = if name.is_empty() {
Line::from(vec![
Span::styled("Profile name...", Style::default().fg(dim_color)),
Span::styled(
"\u{2588}",
Style::default()
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(name.as_str(), Style::default().fg(text_color)),
Span::styled(
"\u{2588}",
Style::default()
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(line).render(inner, buf);
}),
}
.render(area, frame.buffer_mut());
}
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),
}
}
pub enum SettingsAction {
None,
EditInstance(std::path::PathBuf),
EditGlobal(std::path::PathBuf),
EditInstance(PathBuf),
EditGlobal(PathBuf),
ToggleDesktop,
SelectProfile(Option<String>),
ConfirmDeleteProfile(String),
Error(String),
}
pub fn handle_key(
key_event: &crossterm::event::KeyEvent,
key_event: &KeyEvent,
state: &mut SettingsState,
instance: Option<&InstanceConfig>,
instances_dir: &std::path::Path,
instances_dir: &Path,
) -> SettingsAction {
if let AddMode::ProfileName(name) = &state.add_mode {
match key_event.code {
KeyCode::Enter => {
let name = name.trim().to_string();
state.add_mode = AddMode::None;
if name.is_empty() {
return SettingsAction::None;
}
return match crate::instance::config_sync::create_profile(&state.meta_dir, &name) {
Ok(profile) => {
state.reload_profiles();
state.active_profile = Some(profile);
state.select_active();
SettingsAction::SelectProfile(state.active_profile.clone())
}
Err(e) => SettingsAction::Error(e.to_string()),
};
}
KeyCode::Esc => {
state.add_mode = AddMode::None;
return SettingsAction::None;
}
KeyCode::Backspace => {
let mut new_name = name.clone();
new_name.pop();
state.add_mode = AddMode::ProfileName(new_name);
return SettingsAction::None;
}
KeyCode::Char(c) => {
let mut new_name = name.clone();
new_name.push(c);
state.add_mode = AddMode::ProfileName(new_name);
return SettingsAction::None;
}
_ => return SettingsAction::None,
}
}
match key_event.code {
crossterm::event::KeyCode::Char('e') => {
KeyCode::Char('h') | KeyCode::Left => {
state.pane = SettingsPane::Profile;
SettingsAction::None
}
KeyCode::Char('l') | KeyCode::Right => {
state.pane = SettingsPane::Info;
SettingsAction::None
}
KeyCode::Enter if state.pane == SettingsPane::Profile => {
let selected = state.list_state.selected.unwrap_or(0);
let profile = if selected == 0 {
None
} else {
state.profiles.get(selected - 1).cloned()
};
SettingsAction::SelectProfile(profile)
}
KeyCode::Char('a') if state.pane == SettingsPane::Profile => {
state.add_mode = AddMode::ProfileName(String::new());
SettingsAction::None
}
KeyCode::Char('d') if state.pane == SettingsPane::Profile => {
let selected = state.list_state.selected.unwrap_or(0);
if selected == 0 {
SettingsAction::None
} else if let Some(profile) = state.profiles.get(selected - 1) {
SettingsAction::ConfirmDeleteProfile(profile.clone())
} else {
SettingsAction::None
}
}
KeyCode::Char('j') | KeyCode::Down if state.pane == SettingsPane::Profile => {
let count = state.count();
if count > 0 {
let cur = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some((cur + 1).min(count - 1));
}
SettingsAction::None
}
KeyCode::Char('k') | KeyCode::Up if state.pane == SettingsPane::Profile => {
let cur = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some(cur.saturating_sub(1));
SettingsAction::None
}
KeyCode::Char('e') if state.pane == SettingsPane::Info => {
if let Some(inst) = instance {
let path = instances_dir.join(&inst.name).join("instance.json");
SettingsAction::EditInstance(path)
@@ -136,11 +530,11 @@ pub fn handle_key(
SettingsAction::None
}
}
crossterm::event::KeyCode::Char('g') => {
KeyCode::Char('g') if state.pane == SettingsPane::Info => {
let path = crate::config::get_config_path().join("config.toml");
SettingsAction::EditGlobal(path)
}
crossterm::event::KeyCode::Char('d') => SettingsAction::ToggleDesktop,
KeyCode::Char('d') if state.pane == SettingsPane::Info => SettingsAction::ToggleDesktop,
_ => SettingsAction::None,
}
}
+1
View File
@@ -52,6 +52,7 @@ fn make_config_with(
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
}
}