17 Commits
Author SHA1 Message Date
objz 6dda8dc410 chore: updated readme and updated to 0.3.3 release 2026-07-11 17:49:35 +02:00
objz b4d03e7212 perf(content): use stable keys for icon caches 2026-07-11 17:16:30 +02:00
objz c792e1cc11 perf(tui): avoid redundant idle rendering 2026-07-11 17:13:02 +02:00
objz d10be1676e Merge pull request #25 from objz/feature/image-render-options
Feature/image render options
2026-07-11 16:04:25 +02:00
objz b94957a952 fix: formatting 2026-07-11 15:46:15 +02:00
objz 6f5722aa02 feat(tui): render streamed content icons 2026-07-11 15:41:51 +02:00
objz 4bf43a438b feat(content): add quadrant icon rasterization 2026-07-11 15:41:36 +02:00
objz b372571648 feat(config): add terminal image mode setting 2026-07-11 15:41:21 +02:00
objz b5d98e5e8a fix: polling noice on log and cache for scanning java version 2026-07-10 17:06:59 +02:00
objz 7e5ff7f75f fix(ci): choco validation file was remove and fixed icon paths 2026-07-10 16:56:11 +02:00
objz 099d96bcca Merge pull request #23 from objz/feature/delete-mods
feat(tui): add delete actions for instance content
2026-07-10 16:46:34 +02:00
objz 4ba9c65f73 fix(tui): route account deletes through shared confirmation 2026-07-10 16:39:43 +02:00
objz be01370ab2 feature(tui): added delete button to every content type 2026-07-10 16:35:55 +02:00
objz 4ddb8f49bb Merge pull request #24 from objz/feature/config-sync
feat(config-sync): add shared config profiles
2026-07-10 16:30:00 +02:00
objz 4576da4551 fix(config-sync): satisfy clippy warnings 2026-07-10 16:20:03 +02:00
objz 269814945d feat(tui): manage config profiles from settings 2026-07-10 16:12:48 +02:00
objz 69549b7152 feat(config-sync): add per-instance config profiles 2026-07-10 16:09:47 +02:00
39 changed files with 2385 additions and 325 deletions

No files matched your search

-1
View File
@@ -46,7 +46,6 @@ jobs:
checksum="$(awk '{print $1}' "$package_dir/$checksum_file")" checksum="$(awk '{print $1}' "$package_dir/$checksum_file")"
sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/chocolateyInstall.ps1" sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/chocolateyInstall.ps1"
sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/VERIFICATION.txt"
echo "version=$version" >> "$GITHUB_OUTPUT" echo "version=$version" >> "$GITHUB_OUTPUT"
echo "package_dir=$package_dir" >> "$GITHUB_OUTPUT" echo "package_dir=$package_dir" >> "$GITHUB_OUTPUT"
Generated
+1 -1
View File
@@ -3195,7 +3195,7 @@ dependencies = [
[[package]] [[package]]
name = "rmcl" name = "rmcl"
version = "0.3.2" version = "0.3.3"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"chrono", "chrono",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "rmcl" name = "rmcl"
version = "0.3.2" version = "0.3.3"
authors = ["objz"] authors = ["objz"]
edition = "2024" edition = "2024"
description = "A fully featured Minecraft TUI launcher" description = "A fully featured Minecraft TUI launcher"
+46 -36
View File
@@ -20,24 +20,27 @@
## about ## about
we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use (performance wise; no hatespeech here). so here's rmcl, a fully featured Minecraft launcher that lives in your terminal. written in Rust because if you're replacing something bloated you might as well go all the way. we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use (performance wise; no hatespeech here). so here's rmcl, a fully featured Minecraft launcher that lives in your terminal. written in Rust.
it does everything you'd expect from a launcher. multiple instances, mod loaders, modpack imports, Microsoft auth, content management, launching. all from a TUI or from the command line. the TUI is the main thing though, the CLI is there for scripting and automation. it does everything you'd expect from a launcher.
![shocase](assets/showcase.gif) ![showcase](assets/showcase.gif)
## features ## features
| Mod Loader | Supported |
|------------|-----------|
| Vanilla | ✅ |
| Fabric | ✅ |
| Forge | ✅ |
| NeoForge | ✅ |
| Quilt | ✅ |
| LiteLoader | ❌ |
| Rift | ❌ |
| | |
|---|---| ### modpacks and accounts
| **instances** | create and manage multiple instances, each with their own version, loader, mods, and settings |
| **mod loaders** | vanilla, Fabric, Quilt, Forge, NeoForge. more might show up later | `Modrinth`, `MultiMC`, and `GTNH` modpacks format is supported. Import it from a file, URL, or just the slug. Able to use multiple Microsoft accounts and offline accounts aswell.
| **content** | browse and toggle mods, shaders, resource packs. view worlds, screenshots, and logs |
| **modpack import** | import from Modrinth or MultiMC or GTNH via file, URL, or slug |
| **accounts** | multiple Microsoft accounts and offline players, switch between them |
| **launching** | launch directly from the TUI or generate a desktop shortcut for any instance |
| **CLI** | every feature the TUI has is also available as a subcommand |
| **theming** | 10 built-in themes, custom themes, color overrides |
--- ---
@@ -49,10 +52,14 @@ Authentication is performed through Microsoft’s official services.
## installation ## installation
[![GitHub release](https://img.shields.io/github/v/release/objz/rmcl?style=for-the-badge&logo=github)](https://github.com/objz/rmcl/releases)
### macOS / Linux ### macOS / Linux
prebuilt archives are attached to each GitHub release. prebuilt archives are attached to each GitHub release.
[![Homebrew tap](https://img.shields.io/badge/homebrew-objz%2Ftap-FBB040?style=for-the-badge&logo=homebrew)](https://github.com/objz/homebrew-tap)
```sh ```sh
# Homebrew # Homebrew
brew install objz/tap/rmcl brew install objz/tap/rmcl
@@ -63,6 +70,9 @@ brew install objz/tap/rmcl
release builds include a `.zip` archive and an `.msi`. WinGet and Chocolatey release builds include a `.zip` archive and an `.msi`. WinGet and Chocolatey
packages are submitted from release CI and become available after review. packages are submitted from release CI and become available after review.
[![WinGet](https://img.shields.io/badge/winget-Objz.Rmcl-0078D4?style=for-the-badge&logo=windows11)](https://winstall.app/apps/Objz.Rmcl)
[![Chocolatey](https://img.shields.io/chocolatey/v/rmcl?style=for-the-badge&logo=chocolatey)](https://community.chocolatey.org/packages/rmcl)
```powershell ```powershell
# WinGet # WinGet
winget install Objz.Rmcl winget install Objz.Rmcl
@@ -73,6 +83,10 @@ choco install rmcl
### Arch Linux ### Arch Linux
[![AUR rmcl](https://img.shields.io/aur/version/rmcl?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl)
[![AUR rmcl-bin](https://img.shields.io/aur/version/rmcl-bin?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-bin)
[![AUR rmcl-git](https://img.shields.io/aur/version/rmcl-git?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-git)
```sh ```sh
# from source (release tarball) # from source (release tarball)
paru -S rmcl paru -S rmcl
@@ -86,29 +100,11 @@ paru -S rmcl-git
### Cargo ### Cargo
[![crates.io](https://img.shields.io/crates/v/rmcl?style=for-the-badge&logo=rust)](https://crates.io/crates/rmcl)
```sh ```sh
cargo install rmcl cargo install rmcl
``` ```
### package status
release:
[![GitHub release](https://img.shields.io/github/v/release/objz/rmcl?style=for-the-badge&logo=github)](https://github.com/objz/rmcl/releases)
[![crates.io](https://img.shields.io/crates/v/rmcl?style=for-the-badge&logo=rust)](https://crates.io/crates/rmcl)
package managers:
[![Homebrew tap](https://img.shields.io/badge/homebrew-objz%2Ftap-FBB040?style=for-the-badge&logo=homebrew)](https://github.com/objz/homebrew-tap)
[![WinGet](https://img.shields.io/badge/winget-Objz.Rmcl-0078D4?style=for-the-badge&logo=windows11)](https://winstall.app/apps/Objz.Rmcl)
[![Chocolatey](https://img.shields.io/chocolatey/v/rmcl?style=for-the-badge&logo=chocolatey)](https://community.chocolatey.org/packages/rmcl)
aur:
[![AUR rmcl](https://img.shields.io/aur/version/rmcl?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl)
[![AUR rmcl-bin](https://img.shields.io/aur/version/rmcl-bin?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-bin)
[![AUR rmcl-git](https://img.shields.io/aur/version/rmcl-git?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-git)
### from source ### from source
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`). requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
@@ -133,7 +129,7 @@ settings, accounts, instances, and cached game metadata.
| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%LOCALAPPDATA%\rmcl\instances\` | | instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%LOCALAPPDATA%\rmcl\instances\` |
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%LOCALAPPDATA%\rmcl\meta\` | | metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%LOCALAPPDATA%\rmcl\meta\` |
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. standard layout, nothing weird. each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files.
### logs ### logs
@@ -146,9 +142,23 @@ launcher logs are per-session and contain rmcl's own output. instance launch log
--- ---
## configuration ## performance
everything is configured through TOML files. `config.toml` for paths, default memory allocation, and UI behavior. `theme.toml` for theme selection and border style. you can also override individual colors without making a full custom theme. the following measurements were taken from a release build on a Linux development system. they are intended as a practical reference, since terminal, window size, content count, and hardware all affect the result.
### idle instance list
over a `60` second sample, the instance list used `497.81 ms` of CPU time. that is about `0.83%` of one CPU core. resident memory was `15.1 MiB`.
### idle mods list
with a populated mods list and its icons loaded, a `60` second sample used `664.77 ms` of CPU time. that is about `1.11%` of one CPU core. resident memory was `67.2 MiB`, with a peak of `69.9 MiB`.
### scrolling mods list
continuously scrolling through the populated mods list used `1000.02 ms` of CPU time over 30 seconds. that is about `3.33%` of one CPU core.
In comparison, the Modrinth AppImage used approximately `14-30%` of a CPU core and about `327 Mib` of memory while browsing the mod list.
--- ---
@@ -164,7 +174,7 @@ you can create your own by dropping a TOML file in `~/.config/rmcl/theme/` and r
## contributing ## contributing
contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md) for code style and project structure. contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md)
--- ---
+2
View File
@@ -14,6 +14,8 @@ memory_min = "512M"
memory_max = "2G" memory_max = "2G"
[ui] [ui]
# image protocol for content icons and screenshots: halfblocks, quadrants, kitty, or iterm2
image_protocol = "kitty"
# error popup timing (in ms) # error popup timing (in ms)
error_auto_dismiss_ms = 5000 error_auto_dismiss_ms = 5000
error_slide_start_ms = 3500 error_slide_start_ms = 3500
+2 -1
View File
@@ -5,7 +5,7 @@
<version>0.0.0</version> <version>0.0.0</version>
<packageSourceUrl>https://github.com/objz/rmcl</packageSourceUrl> <packageSourceUrl>https://github.com/objz/rmcl</packageSourceUrl>
<owners>objz</owners> <owners>objz</owners>
<title>rmcl</title> <title>rmcl Minecraft Launcher</title>
<authors>objz</authors> <authors>objz</authors>
<projectUrl>https://github.com/objz/rmcl</projectUrl> <projectUrl>https://github.com/objz/rmcl</projectUrl>
<licenseUrl>https://github.com/objz/rmcl/blob/master/LICENSE</licenseUrl> <licenseUrl>https://github.com/objz/rmcl/blob/master/LICENSE</licenseUrl>
@@ -13,6 +13,7 @@
<projectSourceUrl>https://github.com/objz/rmcl</projectSourceUrl> <projectSourceUrl>https://github.com/objz/rmcl</projectSourceUrl>
<docsUrl>https://github.com/objz/rmcl#readme</docsUrl> <docsUrl>https://github.com/objz/rmcl#readme</docsUrl>
<bugTrackerUrl>https://github.com/objz/rmcl/issues</bugTrackerUrl> <bugTrackerUrl>https://github.com/objz/rmcl/issues</bugTrackerUrl>
<releaseNotes>https://github.com/objz/rmcl/releases</releaseNotes>
<tags>minecraft launcher cli tui rust</tags> <tags>minecraft launcher cli tui rust</tags>
<summary>Minecraft launcher TUI</summary> <summary>Minecraft launcher TUI</summary>
<description>A fully featured Minecraft launcher TUI with Microsoft account authentication, instance management, mod loaders, imports, content management, and launch support.</description> <description>A fully featured Minecraft launcher TUI with Microsoft account authentication, instance management, mod loaders, imports, content management, and launch support.</description>
-12
View File
@@ -1,12 +0,0 @@
VERIFICATION
This package downloads the official MSI from the GitHub release:
https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi
The SHA256 checksum is generated by cargo-dist and published next to the release asset:
https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi.sha256
Expected SHA256:
__CHECKSUM64__
+2
View File
@@ -61,6 +61,7 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
user_code: details.user_code().secret().to_owned(), user_code: details.user_code().secret().to_owned(),
verification_uri: details.verification_uri().to_string(), verification_uri: details.verification_uri().to_string(),
}); });
crate::tui::request_redraw();
} }
let token = oauth_client let token = oauth_client
@@ -85,6 +86,7 @@ pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
let outcome = run_full_auth_flow().await; let outcome = run_full_auth_flow().await;
if let Ok(mut slot) = result_clone.lock() { if let Ok(mut slot) = result_clone.lock() {
*slot = Some(outcome); *slot = Some(outcome);
crate::tui::request_redraw();
} }
}); });
+76
View File
@@ -11,6 +11,7 @@ use crate::instance::{InstanceManager, ModLoader};
use crate::running::RunState; use crate::running::RunState;
type CliResult = Result<(), Box<dyn std::error::Error>>; type CliResult = Result<(), Box<dyn std::error::Error>>;
const LOCAL_CONFIG_PROFILE: &str = "instance default";
pub async fn handle_instance(matches: &ArgMatches) -> CliResult { pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
match matches.subcommand() { match matches.subcommand() {
@@ -20,6 +21,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
Some(("rename", sub_matches)) => rename_instance(sub_matches), Some(("rename", sub_matches)) => rename_instance(sub_matches),
Some(("launch", sub_matches)) => launch_instance(sub_matches).await, Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
Some(("config", sub_matches)) => config_instance(sub_matches), Some(("config", sub_matches)) => config_instance(sub_matches),
Some(("profile", sub_matches)) => profile_instance(sub_matches),
Some(("desktop", sub_matches)) => desktop_instance(sub_matches), Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
_ => Ok(()), _ => Ok(()),
} }
@@ -233,12 +235,86 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
.map(|(width, height)| format!("{}x{}", width, height)) .map(|(width, height)| format!("{}x{}", width, height))
.unwrap_or_else(|| "-".to_string()), .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); print_table(&["Field", "Value"], &rows);
Ok(()) 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. // maps --set key=value pairs to config fields. empty value = clear the field.
fn apply_config_update( fn apply_config_update(
config: &mut crate::instance::InstanceConfig, 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("name").required(true).action(ArgAction::Set))
.arg(Arg::new("set").long("set").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( .subcommand(
Command::new("desktop") Command::new("desktop")
.about("Toggle desktop shortcut for an instance") .about("Toggle desktop shortcut for an instance")
+8 -7
View File
@@ -23,13 +23,14 @@ fn ensure_config_exists() -> PathBuf {
let config_path = get_config_path().join("config.toml"); let config_path = get_config_path().join("config.toml");
if !config_path.exists() { if !config_path.exists() {
if let Some(parent) = config_path.parent() if let Some(parent) = config_path.parent()
&& let Err(e) = fs::create_dir_all(parent) { && let Err(e) = fs::create_dir_all(parent)
tracing::warn!( {
"Failed to create config directory {}: {}", tracing::warn!(
parent.display(), "Failed to create config directory {}: {}",
e parent.display(),
); e
} );
}
match fs::write(&config_path, include_str!("../../assets/config.toml")) { match fs::write(&config_path, include_str!("../../assets/config.toml")) {
Ok(()) => tracing::debug!("Wrote default config to {}", config_path.display()), Ok(()) => tracing::debug!("Wrote default config to {}", config_path.display()),
Err(e) => tracing::warn!( Err(e) => tracing::warn!(
+13
View File
@@ -5,6 +5,16 @@ use std::path::PathBuf;
use serde::Deserialize; use serde::Deserialize;
#[derive(Debug, Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ImageProtocol {
Halfblocks,
Quadrants,
#[default]
Kitty,
Iterm2,
}
#[derive(Debug, Deserialize, Default)] #[derive(Debug, Deserialize, Default)]
pub struct General {} pub struct General {}
@@ -102,6 +112,8 @@ impl Default for Defaults {
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s, // timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow. // fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
pub struct Ui { pub struct Ui {
#[serde(default)]
pub image_protocol: ImageProtocol,
#[serde(default = "default_error_auto_dismiss_ms")] #[serde(default = "default_error_auto_dismiss_ms")]
pub error_auto_dismiss_ms: u64, pub error_auto_dismiss_ms: u64,
#[serde(default = "default_error_slide_start_ms")] #[serde(default = "default_error_slide_start_ms")]
@@ -128,6 +140,7 @@ fn default_max_error_events() -> usize {
impl Default for Ui { impl Default for Ui {
fn default() -> Self { fn default() -> Self {
Self { Self {
image_protocol: ImageProtocol::default(),
error_auto_dismiss_ms: default_error_auto_dismiss_ms(), error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
error_slide_start_ms: default_error_slide_start_ms(), error_slide_start_ms: default_error_slide_start_ms(),
error_fly_out_ms: default_error_fly_out_ms(), error_fly_out_ms: default_error_fly_out_ms(),
+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"
);
}
}
+128 -1
View File
@@ -13,6 +13,7 @@ use serde::Deserialize;
// where each character cell shows two vertical pixels (fg = top, bg = bottom) // where each character cell shows two vertical pixels (fg = top, bg = bottom)
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct IconCell { pub struct IconCell {
pub symbol: char,
pub bg_r: u8, pub bg_r: u8,
pub bg_g: u8, pub bg_g: u8,
pub bg_b: u8, pub bg_b: u8,
@@ -375,6 +376,14 @@ pub(crate) fn make_icon_pixels(
height: u16, height: u16,
) -> Option<Vec<Vec<IconCell>>> { ) -> Option<Vec<Vec<IconCell>>> {
let img = image::load_from_memory(bytes).ok()?; let img = image::load_from_memory(bytes).ok()?;
Some(make_icon_pixels_from_image(&img, width, height))
}
pub(crate) fn make_icon_pixels_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img.resize_exact( let resized = img.resize_exact(
u32::from(width), u32::from(width),
u32::from(height) * 2, u32::from(height) * 2,
@@ -391,6 +400,7 @@ pub(crate) fn make_icon_pixels(
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0; let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0; let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
cols.push(IconCell { cols.push(IconCell {
symbol: '\u{2584}',
bg_r: br, bg_r: br,
bg_g: bg, bg_g: bg,
bg_b: bb, bg_b: bb,
@@ -402,12 +412,110 @@ pub(crate) fn make_icon_pixels(
rows.push(cols); rows.push(cols);
} }
Some(rows) rows
}
pub(crate) fn make_icon_quadrants_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img
.resize_exact(
u32::from(width) * 2,
u32::from(height) * 2,
image::imageops::FilterType::Lanczos3,
)
.to_rgb8();
(0..height)
.map(|row| {
(0..width)
.map(|col| {
let x = u32::from(col) * 2;
let y = u32::from(row) * 2;
let pixels = [
resized.get_pixel(x, y).0,
resized.get_pixel(x + 1, y).0,
resized.get_pixel(x, y + 1).0,
resized.get_pixel(x + 1, y + 1).0,
];
quadrant_cell(pixels)
})
.collect()
})
.collect()
}
fn quadrant_cell(pixels: [[u8; 3]; 4]) -> IconCell {
let mut pair = (0, 0);
let mut max_distance = 0;
for left in 0..pixels.len() {
for right in (left + 1)..pixels.len() {
let distance = color_distance(pixels[left], pixels[right]);
if distance > max_distance {
max_distance = distance;
pair = (left, right);
}
}
}
let bg = pixels[pair.0];
let fg = pixels[pair.1];
let mask = pixels
.iter()
.enumerate()
.fold(0_u8, |mask, (index, pixel)| {
if color_distance(*pixel, fg) <= color_distance(*pixel, bg) {
mask | (1 << index)
} else {
mask
}
});
let symbol = match mask {
0 => ' ',
1 => '\u{2598}',
2 => '\u{259d}',
3 => '\u{2580}',
4 => '\u{2596}',
5 => '\u{258c}',
6 => '\u{259e}',
7 => '\u{259b}',
8 => '\u{2597}',
9 => '\u{259a}',
10 => '\u{2590}',
11 => '\u{259c}',
12 => '\u{2584}',
13 => '\u{2599}',
14 => '\u{259f}',
_ => '\u{2588}',
};
IconCell {
symbol,
bg_r: bg[0],
bg_g: bg[1],
bg_b: bg[2],
fg_r: fg[0],
fg_g: fg[1],
fg_b: fg[2],
}
}
fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
left.into_iter()
.zip(right)
.map(|(left, right)| {
let delta = i32::from(left) - i32::from(right);
(delta * delta) as u32
})
.sum()
} }
// 6x3 fallback icon showing a "?" pattern for mods without icons. // 6x3 fallback icon showing a "?" pattern for mods without icons.
pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> { pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
let b = IconCell { let b = IconCell {
symbol: '\u{2584}',
bg_r: 50, bg_r: 50,
bg_g: 50, bg_g: 50,
bg_b: 50, bg_b: 50,
@@ -416,6 +524,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
fg_b: 50, fg_b: 50,
}; };
let tb = IconCell { let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50, bg_r: 50,
bg_g: 50, bg_g: 50,
bg_b: 50, bg_b: 50,
@@ -424,6 +533,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
fg_b: 130, fg_b: 130,
}; };
let bt = IconCell { let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130, bg_r: 130,
bg_g: 130, bg_g: 130,
bg_b: 130, bg_b: 130,
@@ -441,6 +551,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
// 12x6 fallback icon showing a "?" pattern for worlds without icons. // 12x6 fallback icon showing a "?" pattern for worlds without icons.
pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> { pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
let b = IconCell { let b = IconCell {
symbol: '\u{2584}',
bg_r: 50, bg_r: 50,
bg_g: 50, bg_g: 50,
bg_b: 50, bg_b: 50,
@@ -449,6 +560,7 @@ pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
fg_b: 50, fg_b: 50,
}; };
let tb = IconCell { let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50, bg_r: 50,
bg_g: 50, bg_g: 50,
bg_b: 50, bg_b: 50,
@@ -457,6 +569,7 @@ pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
fg_b: 130, fg_b: 130,
}; };
let bt = IconCell { let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130, bg_r: 130,
bg_g: 130, bg_g: 130,
bg_b: 130, bg_b: 130,
@@ -497,6 +610,20 @@ pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn quadrant_raster_has_requested_dimensions() {
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(
2,
2,
image::Rgb([12, 34, 56]),
));
let rows = make_icon_quadrants_from_image(&image, 7, 3);
assert_eq!(rows.len(), 3);
assert!(rows.iter().all(|row| row.len() == 7));
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
}
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf { fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("mods"); let dir = tmp.join(instance).join(".minecraft").join("mods");
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
+16 -14
View File
@@ -145,13 +145,14 @@ async fn download_mod_files(
let completed = completed.clone(); let completed = completed.clone();
tasks.spawn(async move { tasks.spawn(async move {
if let Some(parent) = dest.parent() if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await { && let Err(e) = tokio::fs::create_dir_all(parent).await
tracing::warn!( {
"Failed to create mod download directory {}: {}", tracing::warn!(
parent.display(), "Failed to create mod download directory {}: {}",
e parent.display(),
); e
} );
}
progress::set_sub_action(filename); progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display()); tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?; crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
@@ -183,13 +184,14 @@ async fn download_mod_files(
let completed = completed.clone(); let completed = completed.clone();
tasks.spawn(async move { tasks.spawn(async move {
if let Some(parent) = dest.parent() if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await { && let Err(e) = tokio::fs::create_dir_all(parent).await
tracing::warn!( {
"Failed to create mod download directory {}: {}", tracing::warn!(
parent.display(), "Failed to create mod download directory {}: {}",
e parent.display(),
); e
} );
}
progress::set_sub_action(filename); progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display()); tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?; crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
+30 -7
View File
@@ -28,17 +28,13 @@ pub enum LaunchError {
Json(#[from] serde_json::Error), Json(#[from] serde_json::Error),
#[error("{0} launch is not yet supported")] #[error("{0} launch is not yet supported")]
NotSupported(String), NotSupported(String),
#[error( #[error("This instance requires Java {required}, but rmcl is using Java {detected}: {java}")]
"This instance requires Java {required}, but rmcl is using Java {detected}: {java}"
)]
JavaTooOld { JavaTooOld {
java: String, java: String,
required: u32, required: u32,
detected: u32, detected: u32,
}, },
#[error( #[error("This instance requires Java {required}, but rmcl could not check {java}: {reason}")]
"This instance requires Java {required}, but rmcl could not check {java}: {reason}"
)]
JavaCheckFailed { JavaCheckFailed {
java: String, java: String,
required: u32, required: u32,
@@ -46,6 +42,8 @@ pub enum LaunchError {
}, },
#[error("{0}")] #[error("{0}")]
Auth(String), Auth(String),
#[error("Config sync error: {0}")]
ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError),
} }
fn build_game_args( fn build_game_args(
@@ -412,7 +410,11 @@ pub async fn build_launch_invocation(
// so we check there first. // so we check there first.
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge); let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
let local_lib_dir = minecraft_dir.join("libraries"); let local_lib_dir = minecraft_dir.join("libraries");
let library_directory = if has_local_libs { &local_lib_dir } else { &lib_dir }; let library_directory = if has_local_libs {
&local_lib_dir
} else {
&lib_dir
};
let mut classpath: Vec<PathBuf> = Vec::new(); let mut classpath: Vec<PathBuf> = Vec::new();
for lib in &merged_profile.libraries { for lib in &merged_profile.libraries {
@@ -621,6 +623,13 @@ pub async fn launch(
invocation.game_args.len(), invocation.game_args.len(),
invocation.main_class 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::<()>(); let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
crate::running::register_kill(&name, kill_tx); crate::running::register_kill(&name, kill_tx);
@@ -682,6 +691,7 @@ pub async fn launch(
let name_for_task = name.clone(); let name_for_task = name.clone();
let instances_dir_owned = instances_dir.to_path_buf(); let instances_dir_owned = instances_dir.to_path_buf();
let meta_dir_owned = meta_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 // 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 // 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; let _ = parser_task.await;
tracing::info!("[{}] Exited with code {:?}", name_for_task, code); 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 { if code == Some(0) || killed_by_user {
crate::running::remove(&name_for_task); crate::running::remove(&name_for_task);
tracing::debug!( tracing::debug!(
@@ -1015,6 +1036,7 @@ mod tests {
memory_min: None, memory_min: None,
jvm_args: Vec::new(), jvm_args: Vec::new(),
resolution: None, resolution: None,
config_sync_profile: None,
}; };
let result = let result =
@@ -1062,6 +1084,7 @@ mod tests {
memory_min: None, memory_min: None,
jvm_args: Vec::new(), jvm_args: Vec::new(),
resolution: None, resolution: None,
config_sync_profile: None,
}; };
let result = migrate_legacy_loader_profile_if_needed( let result = migrate_legacy_loader_profile_if_needed(
+5 -1
View File
@@ -254,7 +254,9 @@ impl InstanceManager {
.await .await
.map_err(|e| match e { .map_err(|e| match e {
InstallError::Download(net_error) => InstanceError::Download(net_error), InstallError::Download(net_error) => InstanceError::Download(net_error),
InstallError::Installer(installer_error) => InstanceError::InstallerError(installer_error), InstallError::Installer(installer_error) => {
InstanceError::InstallerError(installer_error)
}
})?; })?;
let config = InstanceConfig { let config = InstanceConfig {
@@ -269,6 +271,7 @@ impl InstanceManager {
memory_min: None, memory_min: None,
jvm_args: vec![], jvm_args: vec![],
resolution: None, resolution: None,
config_sync_profile: None,
}; };
self.save(&config)?; self.save(&config)?;
@@ -518,6 +521,7 @@ mod tests {
memory_min: None, memory_min: None,
jvm_args: vec![], jvm_args: vec![],
resolution: None, resolution: None,
config_sync_profile: None,
} }
} }
+2
View File
@@ -1,5 +1,7 @@
// instance management: creation, launching, importing modpacks, and all the // instance management: creation, launching, importing modpacks, and all the
// bookkeeping that comes with pretending to be a real launcher // bookkeeping that comes with pretending to be a real launcher
pub mod config_sync;
pub mod content; pub mod content;
pub mod desktop; pub mod desktop;
pub mod import; pub mod import;
+3
View File
@@ -47,6 +47,8 @@ pub struct InstanceConfig {
pub jvm_args: Vec<String>, pub jvm_args: Vec<String>,
#[serde(default)] #[serde(default)]
pub resolution: Option<(u32, u32)>, pub resolution: Option<(u32, u32)>,
#[serde(default)]
pub config_sync_profile: Option<String>,
} }
pub fn normalize_memory_value(raw: &str) -> Option<String> { pub fn normalize_memory_value(raw: &str) -> Option<String> {
@@ -137,6 +139,7 @@ mod tests {
memory_min: Some("512M".to_string()), memory_min: Some("512M".to_string()),
jvm_args: vec![], jvm_args: vec![],
resolution: Some((1920, 1080)), resolution: Some((1920, 1080)),
config_sync_profile: None,
}; };
let json = serde_json::to_string_pretty(&config).expect("serialize"); let json = serde_json::to_string_pretty(&config).expect("serialize");
let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize"); let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize");
+43 -18
View File
@@ -227,38 +227,58 @@ pub(crate) async fn install_forge_from_profile(
let file = std::fs::File::open(installer_path) let file = std::fs::File::open(installer_path)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
let mut archive = zip::ZipArchive::new(file) let mut archive = zip::ZipArchive::new(file).map_err(|e| {
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to open installer as ZIP: {e}"))))?; InstallError::Installer(InstallerError::Profile(format!(
"Failed to open installer as ZIP: {e}"
)))
})?;
let profile_data: serde_json::Value = { let profile_data: serde_json::Value = {
let entry = archive.by_name("install_profile.json").map_err(|e| { let entry = archive.by_name("install_profile.json").map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!("install_profile.json not found in installer: {e}"))) InstallError::Installer(InstallerError::Profile(format!(
"install_profile.json not found in installer: {e}"
)))
})?; })?;
serde_json::from_reader(entry) serde_json::from_reader(entry).map_err(|e| {
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to parse install_profile.json: {e}"))))? InstallError::Installer(InstallerError::Profile(format!(
"Failed to parse install_profile.json: {e}"
)))
})?
}; };
let version_info = profile_data let version_info = profile_data.get("versionInfo").ok_or_else(|| {
.get("versionInfo") InstallError::Installer(InstallerError::Profile(
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("install_profile.json missing versionInfo".into())))?; "install_profile.json missing versionInfo".into(),
let install_info = profile_data ))
.get("install") })?;
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("install_profile.json missing install section".into())))?; let install_info = profile_data.get("install").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing install section".into(),
))
})?;
let libraries = version_info let libraries = version_info
.get("libraries") .get("libraries")
.and_then(|v| v.as_array()) .and_then(|v| v.as_array())
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing versionInfo.libraries".into())))?; .ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"missing versionInfo.libraries".into(),
))
})?;
let file_path = install_info let file_path = install_info
.get("filePath") .get("filePath")
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing install.filePath".into())))?; .ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.filePath".into()))
})?;
let install_path_coord = install_info let install_path_coord = install_info
.get("path") .get("path")
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing install.path".into())))?; .ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.path".into()))
})?;
// extract the universal jar to the correct maven location // extract the universal jar to the correct maven location
let universal_maven_path = let universal_maven_path =
@@ -300,12 +320,14 @@ pub(crate) async fn install_forge_from_profile(
// in mojang's modern version metadata, so we fetch those too. // in mojang's modern version metadata, so we fetch those too.
let libraries_dir = meta_dir.join("libraries"); let libraries_dir = meta_dir.join("libraries");
for lib in libraries { for lib in libraries {
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default(); let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
let maven_path = match crate::net::maven_coord_to_path(name) { let maven_path = match crate::net::maven_coord_to_path(name) {
Some(p) => p, Some(p) => p,
None => { None => {
return Err(InstallError::Installer(InstallerError::Profile(format!("Invalid Maven coordinate: {name}")))); return Err(InstallError::Installer(InstallerError::Profile(format!(
"Invalid Maven coordinate: {name}"
))));
} }
}; };
@@ -341,8 +363,11 @@ pub(crate) async fn install_forge_from_profile(
// and whitespace may differ from the original installer JSON because // and whitespace may differ from the original installer JSON because
// the source is a serde_json::Value (which doesn't preserve order), // the source is a serde_json::Value (which doesn't preserve order),
// but no field is silently dropped. // but no field is silently dropped.
let serialized = serde_json::to_vec(version_info) let serialized = serde_json::to_vec(version_info).map_err(|e| {
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to serialize Forge profile: {e}"))))?; InstallError::Installer(InstallerError::Profile(format!(
"Failed to serialize Forge profile: {e}"
)))
})?;
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized) crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?; .map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
Ok(()) Ok(())
+2 -2
View File
@@ -238,7 +238,7 @@ pub fn detect_java_path() -> String {
let java_name = if cfg!(windows) { "java.exe" } else { "java" }; let java_name = if cfg!(windows) { "java.exe" } else { "java" };
let bin = std::path::Path::new(&java_home).join("bin").join(java_name); let bin = std::path::Path::new(&java_home).join("bin").join(java_name);
if bin.exists() { if bin.exists() {
tracing::debug!("Detected Java from JAVA_HOME: {}", bin.display()); tracing::trace!("Detected Java from JAVA_HOME: {}", bin.display());
return bin.to_string_lossy().to_string(); return bin.to_string_lossy().to_string();
} }
tracing::warn!( tracing::warn!(
@@ -249,7 +249,7 @@ pub fn detect_java_path() -> String {
} }
match which::which("java") { match which::which("java") {
Ok(path) => { Ok(path) => {
tracing::debug!("Detected Java from PATH: {}", path.display()); tracing::trace!("Detected Java from PATH: {}", path.display());
path.to_string_lossy().to_string() path.to_string_lossy().to_string()
} }
Err(e) => { Err(e) => {
+3
View File
@@ -33,12 +33,14 @@ pub static KILL_SENDERS: LazyLock<KillSenders> =
pub fn set_state(name: &str, state: RunState) { pub fn set_state(name: &str, state: RunState) {
if let Ok(mut map) = RUNNING.lock() { if let Ok(mut map) = RUNNING.lock() {
map.insert(name.to_string(), state); map.insert(name.to_string(), state);
crate::tui::request_redraw();
} }
} }
pub fn remove(name: &str) { pub fn remove(name: &str) {
if let Ok(mut map) = RUNNING.lock() { if let Ok(mut map) = RUNNING.lock() {
map.remove(name); map.remove(name);
crate::tui::request_redraw();
} }
} }
@@ -59,6 +61,7 @@ pub fn all() -> Vec<(String, RunState)> {
pub fn push_last_played(name: &str, time: DateTime<Utc>) { pub fn push_last_played(name: &str, time: DateTime<Utc>) {
if let Ok(mut q) = PENDING_LAST_PLAYED.lock() { if let Ok(mut q) = PENDING_LAST_PLAYED.lock() {
q.push((name.to_string(), time)); q.push((name.to_string(), time));
crate::tui::request_redraw();
} }
} }
+2
View File
@@ -29,6 +29,7 @@ pub struct App {
pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState, pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState,
pub(super) logs_state: widgets::logs_viewer::LogsState, pub(super) logs_state: widgets::logs_viewer::LogsState,
pub(super) account_state: widgets::account::AccountState, pub(super) account_state: widgets::account::AccountState,
pub(super) settings_state: widgets::settings::SettingsState,
pub(super) picker: ratatui_image::picker::Picker, pub(super) picker: ratatui_image::picker::Picker,
pub(super) instance_manager: InstanceManager, pub(super) instance_manager: InstanceManager,
pub(super) log_overlay_scroll: usize, pub(super) log_overlay_scroll: usize,
@@ -87,6 +88,7 @@ impl App {
worlds_state: widgets::content::list::ContentListState::default(), worlds_state: widgets::content::list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(), logs_state: widgets::logs_viewer::LogsState::default(),
account_state: widgets::account::AccountState::default(), account_state: widgets::account::AccountState::default(),
settings_state: widgets::settings::SettingsState::new(manager.meta_dir.clone()),
screenshots_state: { screenshots_state: {
let mut s = widgets::screenshots_grid::ScreenshotsState::default(); let mut s = widgets::screenshots_grid::ScreenshotsState::default();
s.font_size = picker.font_size(); s.font_size = picker.font_size();
+8 -1
View File
@@ -38,6 +38,7 @@ pub fn push_error(event: ErrorEvent) {
while events.len() > MAX_ERROR_EVENTS { while events.len() > MAX_ERROR_EVENTS {
events.pop_front(); events.pop_front();
} }
crate::tui::request_redraw();
} }
Err(e) => { Err(e) => {
tracing::error!("Error buffer lock poisoned: {}", e); tracing::error!("Error buffer lock poisoned: {}", e);
@@ -56,7 +57,13 @@ pub fn has_errors() -> bool {
#[must_use] #[must_use]
pub fn pop_error() -> Option<ErrorEvent> { pub fn pop_error() -> Option<ErrorEvent> {
match ERROR_EVENTS.lock() { match ERROR_EVENTS.lock() {
Ok(mut events) => events.pop_front(), Ok(mut events) => {
let event = events.pop_front();
if event.is_some() {
crate::tui::request_redraw();
}
event
}
Err(_) => None, Err(_) => None,
} }
} }
+43 -15
View File
@@ -11,9 +11,13 @@ use crate::tui::error_buffer;
use crate::tui::progress; use crate::tui::progress;
impl App { impl App {
/// main loop: drain async results, render, handle input, repeat at ~60fps /// main loop: poll async results and input at ~60Hz, drawing only when state changes
pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> { pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
let mut last_draw = std::time::Instant::now()
.checked_sub(Duration::from_secs(1))
.unwrap_or_else(std::time::Instant::now);
while !self.exit { while !self.exit {
let redraw_requested = super::take_redraw_request();
// check if any popup wizard finished and wants to create/import // check if any popup wizard finished and wants to create/import
if let Some(params) = new_instance::take_result() { if let Some(params) = new_instance::take_result() {
self.spawn_create(params); self.spawn_create(params);
@@ -32,12 +36,20 @@ impl App {
self.drain_pending_last_played(); self.drain_pending_last_played();
self.mods_state.drain_pending(); self.mods_state.drain_pending();
self.mods_state.drain_watcher(); self.mods_state.drain_watcher();
self.mods_state.request_image_loads(&self.picker);
self.mods_state.drain_image_loads(&self.picker);
self.resource_packs_state.drain_pending(); self.resource_packs_state.drain_pending();
self.resource_packs_state.drain_watcher(); self.resource_packs_state.drain_watcher();
self.resource_packs_state.request_image_loads(&self.picker);
self.resource_packs_state.drain_image_loads(&self.picker);
self.shaders_state.drain_pending(); self.shaders_state.drain_pending();
self.shaders_state.drain_watcher(); self.shaders_state.drain_watcher();
self.shaders_state.request_image_loads(&self.picker);
self.shaders_state.drain_image_loads(&self.picker);
self.worlds_state.drain_pending(); self.worlds_state.drain_pending();
self.worlds_state.drain_watcher(); self.worlds_state.drain_watcher();
self.worlds_state.request_image_loads(&self.picker);
self.worlds_state.drain_image_loads(&self.picker);
self.logs_state.drain_pending(); self.logs_state.drain_pending();
self.logs_state.try_rescan(); self.logs_state.try_rescan();
self.account_state.drain_auth_result(); self.account_state.drain_auth_result();
@@ -45,14 +57,26 @@ impl App {
self.screenshots_state.drain_pending_entries(); self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads(); self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols(); self.create_screenshot_protocols();
// only advance the spinner every 8 ticks to keep it readable let progress_active = progress::is_active();
self.throbber_tick = self.throbber_tick.wrapping_add(1); if progress_active {
if self.throbber_tick.is_multiple_of(8) { // only advance the spinner every 8 ticks to keep it readable
self.throbber_state.calc_next(); self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
}
} }
terminal.draw(|frame| self.render_frame(frame))?; let input_changed = self.handle_events().wrap_err("handle events failed")?;
self.handle_events().wrap_err("handle events failed")?; let continuously_animated = progress_active || error_buffer::has_errors();
let safety_refresh = last_draw.elapsed() >= Duration::from_secs(1);
if input_changed
|| continuously_animated
|| safety_refresh
|| redraw_requested
{
terminal.draw(|frame| self.render_frame(frame))?;
last_draw = std::time::Instant::now();
}
if let Some(path) = self.pending_editor.take() if let Some(path) = self.pending_editor.take()
&& Self::run_editor(terminal, &path) && Self::run_editor(terminal, &path)
@@ -65,22 +89,24 @@ impl App {
// polls for input with a 16ms timeout (~60fps). only key presses are handled, // polls for input with a 16ms timeout (~60fps). only key presses are handled,
// releases and repeats are ignored thanks to the enhanced keyboard protocol // releases and repeats are ignored thanks to the enhanced keyboard protocol
fn handle_events(&mut self) -> color_eyre::Result<()> { fn handle_events(&mut self) -> color_eyre::Result<bool> {
match crossterm::event::poll(Duration::from_millis(16)) { match crossterm::event::poll(Duration::from_millis(16)) {
Ok(true) => match event::read() { Ok(true) => match event::read() {
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => self Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => {
.handle_key_event(key_event) self.handle_key_event(key_event)
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}")), .wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}"))?;
Ok(_) => Ok(()), Ok(true)
}
Ok(_) => Ok(true),
Err(e) => { Err(e) => {
tracing::error!("Event read error: {}", e); tracing::error!("Event read error: {}", e);
Ok(()) Ok(false)
} }
}, },
Ok(false) => Ok(()), Ok(false) => Ok(false),
Err(e) => { Err(e) => {
tracing::error!("Event poll error: {}", e); tracing::error!("Event poll error: {}", e);
Ok(()) Ok(false)
} }
} }
} }
@@ -107,6 +133,7 @@ impl App {
Ok(config) => { Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() { if let Ok(mut pending) = pending_instances.lock() {
pending.push(config); pending.push(config);
crate::tui::request_redraw();
} }
} }
Err(e) => { Err(e) => {
@@ -133,6 +160,7 @@ impl App {
Ok(config) => { Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() { if let Ok(mut pending) = pending_instances.lock() {
pending.push(config); pending.push(config);
crate::tui::request_redraw();
} }
} }
Err(e) => { Err(e) => {
+203 -15
View File
@@ -70,18 +70,69 @@ impl App {
if self.focused == FocusedArea::ConfirmDelete { if self.focused == FocusedArea::ConfirmDelete {
match key_event.code { match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => { KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let name = confirm_popup::pending_delete_name(); let focus_after = match confirm_popup::pending_target() {
if !name.is_empty() Some(confirm_popup::ConfirmTarget::Instance { name }) => {
&& let Ok(_) = self.instance_manager.delete(&name) { match self.instance_manager.delete(&name) {
self.instances_state.remove_instance(&name); Ok(_) => {
self.instances_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
}
}
FocusedArea::Instances
} }
Some(confirm_popup::ConfirmTarget::Account { index, .. }) => {
let count = self.account_state.store.accounts.len();
self.account_state.store.remove(index);
if count > 1 {
self.account_state.list_state.selected = Some(index.min(
self.account_state.store.accounts.len().saturating_sub(1),
));
} else {
self.account_state.list_state.selected = None;
}
FocusedArea::Account
}
Some(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(),
});
}
FocusedArea::Settings
}
Some(confirm_popup::ConfirmTarget::Content { name, path }) => {
match delete_content_path(&path) {
Ok(()) => {
self.remove_content_path_from_states(&path);
}
Err(e) => {
tracing::error!("Failed to delete content '{}': {}", name, e);
}
}
FocusedArea::Content
}
None => FocusedArea::Instances,
};
confirm_popup::clear_pending(); confirm_popup::clear_pending();
self.focused = FocusedArea::Instances; self.focused = focus_after;
return Ok(()); return Ok(());
} }
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => { KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
let focus_after = match confirm_popup::pending_target() {
Some(confirm_popup::ConfirmTarget::Content { .. }) => FocusedArea::Content,
Some(confirm_popup::ConfirmTarget::Account { .. }) => FocusedArea::Account,
Some(confirm_popup::ConfirmTarget::ConfigProfile { .. }) => {
FocusedArea::Settings
}
_ => FocusedArea::Instances,
};
confirm_popup::clear_pending(); confirm_popup::clear_pending();
self.focused = FocusedArea::Instances; self.focused = focus_after;
return Ok(()); return Ok(());
} }
_ => { _ => {
@@ -91,17 +142,41 @@ impl App {
} }
// content area delegates to whichever tab is active. // content area delegates to whichever tab is active.
// worlds get handle_key_no_toggle because you can't "disable" a world like you can a mod // worlds use the same list navigation without the toggle
if self.focused == FocusedArea::Content { if self.focused == FocusedArea::Content {
if self.content_tab == widgets::content::ContentTab::Logs { if self.content_tab == widgets::content::ContentTab::Logs {
if key_event.code == KeyCode::Char('d')
&& !self.logs_state.search.active
&& !self.logs_state.viewer_search.active
{
if let Some(pending) = self.logs_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::logs_viewer::handle_key(&key_event, &mut self.logs_state) { if widgets::logs_viewer::handle_key(&key_event, &mut self.logs_state) {
return Ok(()); return Ok(());
} }
} else if self.content_tab == widgets::content::ContentTab::Screenshots { } else if self.content_tab == widgets::content::ContentTab::Screenshots {
if key_event.code == KeyCode::Char('d') && !self.screenshots_state.search.active {
if let Some(pending) = self.screenshots_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::screenshots_grid::handle_key(&key_event, &mut self.screenshots_state) { if widgets::screenshots_grid::handle_key(&key_event, &mut self.screenshots_state) {
return Ok(()); return Ok(());
} }
} else if self.content_tab == widgets::content::ContentTab::Worlds { } else if self.content_tab == widgets::content::ContentTab::Worlds {
if key_event.code == KeyCode::Char('d') && !self.worlds_state.search.active {
if let Some(pending) = self.worlds_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state) if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state)
{ {
return Ok(()); return Ok(());
@@ -115,14 +190,34 @@ impl App {
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state), widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
_ => None, _ => None,
}; };
if let Some(state) = state if let Some(state) = state {
&& widgets::content::list::handle_key(&key_event, state) if key_event.code == KeyCode::Char('d') && !state.search.active {
{ if let Some(pending) = state.pending_delete() {
return Ok(()); confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::content::list::handle_key(&key_event, state) {
return Ok(());
}
} }
} }
} }
if self.focused == FocusedArea::Account
&& let KeyCode::Char('d') = key_event.code
&& let Some(index) = self.account_state.list_state.selected
&& let Some(account) = self.account_state.store.accounts.get(index)
{
confirm_popup::set_pending(confirm_popup::ConfirmTarget::Account {
username: account.username.clone(),
index,
});
self.focused = FocusedArea::ConfirmDelete;
return Ok(());
}
if self.focused == FocusedArea::Account if self.focused == FocusedArea::Account
&& widgets::account::handle_key(&key_event, &mut self.account_state) && widgets::account::handle_key(&key_event, &mut self.account_state)
{ {
@@ -132,6 +227,7 @@ impl App {
if self.focused == FocusedArea::Settings { if self.focused == FocusedArea::Settings {
match widgets::settings::handle_key( match widgets::settings::handle_key(
&key_event, &key_event,
&mut self.settings_state,
self.instances_state.selected_instance(), self.instances_state.selected_instance(),
&self.instance_manager.instances_dir, &self.instance_manager.instances_dir,
) { ) {
@@ -167,6 +263,53 @@ impl App {
} }
return Ok(()); 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 => {} widgets::settings::SettingsAction::None => {}
} }
} }
@@ -192,9 +335,9 @@ impl App {
.instances .instances
.iter_mut() .iter_mut()
.find(|i| i.name == old_name) .find(|i| i.name == old_name)
{ {
inst.name = new_name.trim().to_owned(); inst.name = new_name.trim().to_owned();
} }
} }
} }
KeyCode::Esc => { KeyCode::Esc => {
@@ -247,7 +390,7 @@ impl App {
{ {
if let Some(instance) = self.instances_state.selected_instance() { if let Some(instance) = self.instances_state.selected_instance() {
let name = instance.name.clone(); let name = instance.name.clone();
confirm_popup::set_pending_delete(&name); confirm_popup::set_pending_instance_delete(&name);
self.focused = FocusedArea::ConfirmDelete; self.focused = FocusedArea::ConfirmDelete;
} }
} }
@@ -333,4 +476,49 @@ impl App {
Ok(()) 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(())
}
fn remove_content_path_from_states(&mut self, path: &std::path::Path) {
self.mods_state.remove_path(path);
self.resource_packs_state.remove_path(path);
self.shaders_state.remove_path(path);
self.worlds_state.remove_path(path);
self.screenshots_state.remove_path(path);
self.logs_state.remove_path(path);
}
}
fn delete_content_path(path: &std::path::Path) -> std::io::Result<()> {
match std::fs::metadata(path) {
Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(path),
Ok(_) => std::fs::remove_file(path),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
} }
+29 -8
View File
@@ -91,10 +91,14 @@ pub fn init() -> WorkerGuard {
) )
.with( .with(
tui_logger::TuiTracingSubscriberLayer.with_filter(filter_fn(|metadata| { tui_logger::TuiTracingSubscriberLayer.with_filter(filter_fn(|metadata| {
should_record_app_log(metadata.target()) should_record_app_log(metadata.target(), *metadata.level())
})), })),
) )
.with(StatusLayer::new(error_buffer::ERROR_EVENTS.clone())) .with(
StatusLayer::new(error_buffer::ERROR_EVENTS.clone()).with_filter(filter_fn(
|metadata| should_record_app_log(metadata.target(), *metadata.level()),
)),
)
.init(); .init();
guard guard
@@ -127,11 +131,11 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
Level::TRACE => "TRACE", Level::TRACE => "TRACE",
}; };
let now = chrono::Local::now().format("%H:%M:%S"); let now = chrono::Local::now().format("%H:%M:%S");
if should_record_app_log(target) { if should_record_app_log(target, level) {
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message)); push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
} }
if level <= Level::WARN && should_record_app_log(target) { if level <= Level::WARN && should_record_app_log(target, level) {
error_buffer::push_error(ErrorEvent { error_buffer::push_error(ErrorEvent {
id: 0, id: 0,
level, level,
@@ -142,8 +146,12 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
} }
} }
fn should_record_app_log(target: &str) -> bool { fn should_record_app_log(target: &str, level: Level) -> bool {
target != MINECRAFT_LOG_TARGET if target == MINECRAFT_LOG_TARGET {
return false;
}
target == "rmcl" || target.starts_with("rmcl::") || level <= Level::WARN
} }
#[derive(Default)] #[derive(Default)]
@@ -178,11 +186,24 @@ mod tests {
#[test] #[test]
fn minecraft_events_are_not_general_app_logs() { fn minecraft_events_are_not_general_app_logs() {
assert!(!should_record_app_log(MINECRAFT_LOG_TARGET)); assert!(!should_record_app_log(MINECRAFT_LOG_TARGET, Level::ERROR));
} }
#[test] #[test]
fn rmcl_events_are_general_app_logs() { fn rmcl_events_are_general_app_logs() {
assert!(should_record_app_log("rmcl::instance::manager")); assert!(should_record_app_log(
"rmcl::instance::manager",
Level::TRACE
));
}
#[test]
fn dependency_debug_events_are_not_general_app_logs() {
assert!(!should_record_app_log("log", Level::DEBUG));
}
#[test]
fn dependency_warnings_are_general_app_logs() {
assert!(should_record_app_log("notify", Level::WARN));
} }
} }
+32 -1
View File
@@ -9,6 +9,18 @@ pub mod progress;
mod render; mod render;
pub mod widgets; pub mod widgets;
use std::sync::atomic::{AtomicBool, Ordering};
static REDRAW_REQUESTED: AtomicBool = AtomicBool::new(true);
pub fn request_redraw() {
REDRAW_REQUESTED.store(true, Ordering::Release);
}
pub(super) fn take_redraw_request() -> bool {
REDRAW_REQUESTED.swap(false, Ordering::AcqRel)
}
pub type Tui = ratatui::DefaultTerminal; pub type Tui = ratatui::DefaultTerminal;
pub async fn show() -> color_eyre::Result<()> { pub async fn show() -> color_eyre::Result<()> {
@@ -37,8 +49,27 @@ pub async fn show() -> color_eyre::Result<()> {
// figure out the terminal's font cell size for rendering images. // figure out the terminal's font cell size for rendering images.
// falls back to halfblock characters if the terminal doesn't respond // falls back to halfblock characters if the terminal doesn't respond
let picker = ratatui_image::picker::Picker::from_query_stdio() let mut picker = ratatui_image::picker::Picker::from_query_stdio()
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks()); .unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
let detected_protocol = picker.protocol_type();
let requested_protocol = match crate::config::SETTINGS.ui.image_protocol {
crate::config::settings::ImageProtocol::Halfblocks
| crate::config::settings::ImageProtocol::Quadrants => {
ratatui_image::picker::ProtocolType::Halfblocks
}
crate::config::settings::ImageProtocol::Kitty
if detected_protocol == ratatui_image::picker::ProtocolType::Kitty =>
{
ratatui_image::picker::ProtocolType::Kitty
}
crate::config::settings::ImageProtocol::Iterm2
if detected_protocol == ratatui_image::picker::ProtocolType::Iterm2 =>
{
ratatui_image::picker::ProtocolType::Iterm2
}
_ => ratatui_image::picker::ProtocolType::Halfblocks,
};
picker.set_protocol_type(requested_protocol);
let result = app::App::new(picker).run(&mut terminal).await; let result = app::App::new(picker).run(&mut terminal).await;
+10
View File
@@ -19,6 +19,7 @@ pub fn set_action(text: impl Into<String>) {
match PROGRESS.lock() { match PROGRESS.lock() {
Ok(mut state) => { Ok(mut state) => {
state.current_action = Some(text.clone()); state.current_action = Some(text.clone());
crate::tui::request_redraw();
} }
Err(e) => { Err(e) => {
tracing::error!("Progress lock poisoned: {}", e); tracing::error!("Progress lock poisoned: {}", e);
@@ -31,6 +32,7 @@ pub fn set_progress(current: u64, total: u64) {
match PROGRESS.lock() { match PROGRESS.lock() {
Ok(mut state) => { Ok(mut state) => {
state.progress = Some((current, total)); state.progress = Some((current, total));
crate::tui::request_redraw();
} }
Err(e) => { Err(e) => {
tracing::error!("Progress lock poisoned: {}", e); tracing::error!("Progress lock poisoned: {}", e);
@@ -43,6 +45,7 @@ pub fn set_sub_action(text: impl Into<String>) {
match PROGRESS.lock() { match PROGRESS.lock() {
Ok(mut state) => { Ok(mut state) => {
state.sub_action = Some(text.clone()); state.sub_action = Some(text.clone());
crate::tui::request_redraw();
} }
Err(e) => { Err(e) => {
tracing::error!("Progress lock poisoned: {}", e); tracing::error!("Progress lock poisoned: {}", e);
@@ -57,9 +60,16 @@ pub fn clear() {
state.current_action = None; state.current_action = None;
state.progress = None; state.progress = None;
state.sub_action = None; state.sub_action = None;
crate::tui::request_redraw();
} }
Err(e) => { Err(e) => {
tracing::error!("Progress lock poisoned: {}", e); tracing::error!("Progress lock poisoned: {}", e);
} }
} }
} }
pub fn is_active() -> bool {
PROGRESS
.lock()
.is_ok_and(|state| state.current_action.is_some())
}
+9 -8
View File
@@ -65,13 +65,14 @@ impl App {
&mut self.screenshots_state, &mut self.screenshots_state,
&mut self.logs_state, &mut self.logs_state,
&self.instance_manager.instances_dir, &self.instance_manager.instances_dir,
&self.picker,
); );
let bottom_chunks = Layout::default() let bottom_chunks = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
.constraints([ .constraints([
Constraint::Percentage(30), Constraint::Percentage(24),
Constraint::Percentage(40), Constraint::Percentage(46),
Constraint::Percentage(30), Constraint::Percentage(30),
]) ])
.split(main_chunks[2]); .split(main_chunks[2]);
@@ -86,6 +87,7 @@ impl App {
frame, frame,
bottom_chunks[1], bottom_chunks[1],
self.focused, self.focused,
&mut self.settings_state,
self.instances_state.selected_instance(), self.instances_state.selected_instance(),
&self.instance_manager.instances_dir, &self.instance_manager.instances_dir,
); );
@@ -123,12 +125,11 @@ impl App {
import_modpack::render(frame, area, self.focused); import_modpack::render(frame, area, self.focused);
} }
if self.focused == FocusedArea::ConfirmDelete { if self.focused == FocusedArea::ConfirmDelete
let name = confirm_popup::pending_delete_name(); && let Some(target) = confirm_popup::pending_target()
if !name.is_empty() { {
let area = confirm_popup_area(frame.area(), &name); let area = confirm_popup_area(frame.area(), &target);
frame.render_widget(ConfirmPopup::new(&name), area); frame.render_widget(ConfirmPopup::for_target(&target), area);
}
} }
} }
+5 -73
View File
@@ -27,7 +27,6 @@ pub enum AddMode {
ChooseType, ChooseType,
OfflineNameInput(String), OfflineNameInput(String),
OfflineBlocked, OfflineBlocked,
ConfirmDelete(usize),
DeviceCodeWaiting { DeviceCodeWaiting {
info: DeviceCodeInfo, info: DeviceCodeInfo,
pending: Arc<Mutex<Option<AuthResult>>>, pending: Arc<Mutex<Option<AuthResult>>>,
@@ -163,28 +162,6 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
} }
_ => true, _ => true,
}, },
AddMode::ConfirmDelete(idx) => {
let idx = *idx;
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let count = state.store.accounts.len();
state.store.remove(idx);
if count > 1 {
state.list_state.selected =
Some(idx.min(state.store.accounts.len().saturating_sub(1)));
} else {
state.list_state.selected = None;
}
state.add_mode = AddMode::None;
true
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
state.add_mode = AddMode::None;
true
}
_ => true,
}
}
AddMode::None => { AddMode::None => {
let count = state.store.accounts.len(); let count = state.store.accounts.len();
match key_event.code { match key_event.code {
@@ -192,12 +169,6 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
state.add_mode = AddMode::ChooseType; state.add_mode = AddMode::ChooseType;
true true
} }
KeyCode::Char('d') => {
if let Some(idx) = state.list_state.selected {
state.add_mode = AddMode::ConfirmDelete(idx);
}
true
}
KeyCode::Enter => { KeyCode::Enter => {
if let Some(idx) = state.list_state.selected { if let Some(idx) = state.list_state.selected {
state.store.set_active(idx); state.store.set_active(idx);
@@ -276,7 +247,6 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
AddMode::ChooseType => render_choose_popup(frame), AddMode::ChooseType => render_choose_popup(frame),
AddMode::OfflineNameInput(name) => render_offline_popup(frame, name), AddMode::OfflineNameInput(name) => render_offline_popup(frame, name),
AddMode::OfflineBlocked => render_offline_blocked_popup(frame), AddMode::OfflineBlocked => render_offline_blocked_popup(frame),
AddMode::ConfirmDelete(idx) => render_confirm_delete(frame, state, *idx),
AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info), AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info),
AddMode::None => {} AddMode::None => {}
} }
@@ -310,9 +280,11 @@ fn render_account_list(
let (username, acc_type, is_active) = &accounts[context.index]; let (username, acc_type, is_active) = &accounts[context.index];
let show_selected = is_focused && context.is_selected; let show_selected = is_focused && context.is_selected;
let stripe_bg = theme.background(); let bg = if show_selected {
theme.stripe()
let bg = stripe_bg; } else {
theme.background()
};
let active_marker = if *is_active { "\u{25b8} " } else { " " }; let active_marker = if *is_active { "\u{25b8} " } else { " " };
@@ -493,46 +465,6 @@ fn render_offline_blocked_popup(frame: &mut Frame) {
.render(area, frame.buffer_mut()); .render(area, frame.buffer_mut());
} }
fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let username = state
.store
.accounts
.get(idx)
.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());
}
fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) { fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
use super::popups::{base::PopupFrame, keybind_line}; use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref(); let theme = THEME.as_ref();
+353 -27
View File
@@ -4,7 +4,7 @@
// also handles minecraft's formatting codes for colored mod names/descriptions // also handles minecraft's formatting codes for colored mod names/descriptions
// because apparently mojang thought terminal UIs would need that. thanks guys // because apparently mojang thought terminal UIs would need that. thanks guys
use std::collections::HashMap; use std::collections::{HashMap, HashSet};
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex, mpsc}; use std::sync::{Arc, Mutex, mpsc};
@@ -16,12 +16,12 @@ use ratatui::{
text::{Line, Span, Text}, text::{Line, Span, Text},
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState}, widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
}; };
use ratatui_image::{CropOptions, Resize, StatefulImage, protocol::StatefulProtocol};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::THEME; use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell}; use crate::instance::content::mods::{ContentEntry, IconCell};
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry; type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
struct CachedList { struct CachedList {
@@ -29,6 +29,18 @@ struct CachedList {
selected: Option<usize>, selected: Option<usize>,
} }
struct PendingContentImage {
file_stem: String,
path: std::path::PathBuf,
icon_lines: Vec<Vec<IconCell>>,
image: Option<image::DynamicImage>,
}
struct DisplayMetadata {
description: String,
has_description: bool,
}
// result from the notify-triggered background diff // result from the notify-triggered background diff
struct WatcherDiff { struct WatcherDiff {
toggled: Vec<(String, bool, std::path::PathBuf)>, toggled: Vec<(String, bool, std::path::PathBuf)>,
@@ -42,6 +54,11 @@ pub struct ContentListState {
pub scrollbar_state: ScrollbarState, pub scrollbar_state: ScrollbarState,
pub loaded_for: Option<String>, pub loaded_for: Option<String>,
pub loading: bool, pub loading: bool,
image_protocols: HashMap<String, StatefulProtocol>,
requested_images: HashSet<String>,
pending_images: Arc<Mutex<Vec<PendingContentImage>>>,
images_dirty: bool,
display_metadata: HashMap<String, DisplayMetadata>,
pub search: crate::tui::widgets::search::SearchState, pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>, cache: HashMap<String, CachedList>,
// streaming: individual entries arrive here during initial load // streaming: individual entries arrive here during initial load
@@ -56,6 +73,12 @@ pub struct ContentListState {
content_ext: Option<&'static str>, content_ext: Option<&'static str>,
} }
#[derive(Clone, Debug)]
pub struct PendingContentDelete {
pub name: String,
pub path: std::path::PathBuf,
}
impl Default for ContentListState { impl Default for ContentListState {
fn default() -> Self { fn default() -> Self {
Self { Self {
@@ -64,6 +87,11 @@ impl Default for ContentListState {
scrollbar_state: ScrollbarState::default(), scrollbar_state: ScrollbarState::default(),
loaded_for: None, loaded_for: None,
loading: false, loading: false,
image_protocols: HashMap::new(),
requested_images: HashSet::new(),
pending_images: Arc::new(Mutex::new(Vec::new())),
images_dirty: true,
display_metadata: HashMap::new(),
search: crate::tui::widgets::search::SearchState::default(), search: crate::tui::widgets::search::SearchState::default(),
cache: HashMap::new(), cache: HashMap::new(),
stream_rx: None, stream_rx: None,
@@ -77,6 +105,108 @@ impl Default for ContentListState {
} }
impl ContentListState { impl ContentListState {
pub fn request_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
if !self.images_dirty {
return;
}
self.images_dirty = false;
let use_image_protocol =
picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
let use_quadrants = crate::config::SETTINGS.ui.image_protocol
== crate::config::settings::ImageProtocol::Quadrants;
if !use_image_protocol {
self.image_protocols.clear();
}
let valid_stems: HashSet<&str> = self
.entries
.iter()
.map(|entry| entry.file_stem.as_str())
.collect();
self.image_protocols
.retain(|stem, _| valid_stems.contains(stem.as_str()));
self.requested_images
.retain(|stem| valid_stems.contains(stem.as_str()));
let font_size = picker.font_size();
for entry in &self.entries {
if entry.icon_bytes.is_none()
|| !self.requested_images.insert(entry.file_stem.clone())
{
continue;
}
let file_stem = entry.file_stem.clone();
let path = entry.path.clone();
let bytes = entry.icon_bytes.clone().unwrap_or_default();
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u32;
let columns = square_icon_columns(rows as u16, font_size);
let pending = self.pending_images.clone();
tokio::spawn(async move {
let result = tokio::task::spawn_blocking(move || {
let image = image::load_from_memory(&bytes).ok()?;
let icon_lines = if use_quadrants {
crate::instance::content::mods::make_icon_quadrants_from_image(
&image,
columns,
rows as u16,
)
} else {
crate::instance::content::mods::make_icon_pixels_from_image(
&image,
columns,
rows as u16,
)
};
let side = rows * u32::from(font_size.1.max(1));
let image = use_image_protocol.then(|| {
image.resize_exact(side, side, image::imageops::FilterType::Lanczos3)
});
Some(PendingContentImage {
file_stem,
path,
icon_lines,
image,
})
})
.await
.ok()
.flatten();
if let Some(result) = result
&& let Ok(mut pending) = pending.lock()
{
pending.push(result);
crate::tui::request_redraw();
}
});
}
}
pub fn drain_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
let images = match self.pending_images.lock() {
Ok(mut pending) => std::mem::take(&mut *pending),
Err(_) => return,
};
for result in images {
if let Some(entry) = self
.entries
.iter_mut()
.find(|entry| {
entry.file_stem == result.file_stem && entry.path == result.path
})
{
entry.icon_lines = Some(result.icon_lines);
if let Some(image) = result.image {
self.image_protocols
.insert(result.file_stem, picker.new_resize_protocol(image));
}
}
}
}
// drain streaming entries from the initial load. each entry arrives // drain streaming entries from the initial load. each entry arrives
// individually and is inserted in sorted position for a smooth fill-in // individually and is inserted in sorted position for a smooth fill-in
pub fn drain_pending(&mut self) { pub fn drain_pending(&mut self) {
@@ -91,7 +221,10 @@ impl ContentListState {
match rx.try_recv() { match rx.try_recv() {
Ok(entry) => { Ok(entry) => {
received = true; received = true;
self.images_dirty = true;
received_count += 1; received_count += 1;
self.display_metadata
.insert(entry.file_stem.clone(), display_metadata(&entry));
let pos = self let pos = self
.entries .entries
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase())) .binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
@@ -145,6 +278,7 @@ impl ContentListState {
let Some(diff) = diff else { let Some(diff) = diff else {
return; return;
}; };
self.images_dirty = true;
// apply toggles (enabled/path changes) // apply toggles (enabled/path changes)
tracing::debug!( tracing::debug!(
@@ -165,10 +299,15 @@ impl ContentListState {
if !diff.removed.is_empty() { if !diff.removed.is_empty() {
self.entries self.entries
.retain(|e| !diff.removed.contains(&e.file_stem)); .retain(|e| !diff.removed.contains(&e.file_stem));
for stem in &diff.removed {
self.display_metadata.remove(stem);
}
} }
// insert new entries in sorted position // insert new entries in sorted position
for entry in diff.added { for entry in diff.added {
self.display_metadata
.insert(entry.file_stem.clone(), display_metadata(&entry));
let pos = self let pos = self
.entries .entries
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase())) .binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
@@ -288,6 +427,7 @@ impl ContentListState {
&& let Ok(mut slot) = diff_slot.lock() && let Ok(mut slot) = diff_slot.lock()
{ {
*slot = Some(diff); *slot = Some(diff);
crate::tui::request_redraw();
} }
if !dirty.load(Ordering::Relaxed) { if !dirty.load(Ordering::Relaxed) {
@@ -322,6 +462,16 @@ impl ContentListState {
.map(|(i, _)| i) .map(|(i, _)| i)
.collect() .collect()
} }
pub fn pending_delete(&self) -> Option<PendingContentDelete> {
let filtered = self.filtered_indices();
let real_idx = self.list_state.selected.and_then(|i| filtered.get(i))?;
let entry = self.entries.get(*real_idx)?;
Some(PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
} }
impl ContentListState { impl ContentListState {
@@ -337,6 +487,9 @@ impl ContentListState {
) { ) {
self.scan_one_fn = Some(scan_one_fn); self.scan_one_fn = Some(scan_one_fn);
self.content_ext = Some(ext); self.content_ext = Some(ext);
self.images_dirty = true;
self.image_protocols.clear();
self.requested_images.clear();
// save current entries to cache // save current entries to cache
if let Some(prev) = self.loaded_for.take() if let Some(prev) = self.loaded_for.take()
@@ -359,6 +512,7 @@ impl ContentListState {
// try cache first // try cache first
if let Some(cached) = self.cache.remove(instance_name) { if let Some(cached) = self.cache.remove(instance_name) {
self.entries = cached.entries; self.entries = cached.entries;
self.rebuild_display_metadata();
self.list_state.selected = cached.selected; self.list_state.selected = cached.selected;
self.loading = false; self.loading = false;
self.stream_rx = None; self.stream_rx = None;
@@ -374,6 +528,7 @@ impl ContentListState {
// no cache, stream entries one by one as each file is scanned // no cache, stream entries one by one as each file is scanned
self.entries.clear(); self.entries.clear();
self.display_metadata.clear();
self.list_state = TuiListState::default(); self.list_state = TuiListState::default();
self.loading = true; self.loading = true;
self.loaded_for = Some(instance_name.to_string()); self.loaded_for = Some(instance_name.to_string());
@@ -429,6 +584,7 @@ impl ContentListState {
if tx.send(entry).is_err() { if tx.send(entry).is_err() {
break; // receiver dropped (instance switched) break; // receiver dropped (instance switched)
} }
crate::tui::request_redraw();
} }
}) })
.await; .await;
@@ -442,6 +598,14 @@ impl ContentListState {
self.scrollbar_state = ScrollbarState::new(max).position(pos); self.scrollbar_state = ScrollbarState::new(max).position(pos);
} }
fn rebuild_display_metadata(&mut self) {
self.display_metadata = self
.entries
.iter()
.map(|entry| (entry.file_stem.clone(), display_metadata(entry)))
.collect();
}
// enable/disable by renaming the file with/without .disabled extension. // enable/disable by renaming the file with/without .disabled extension.
// this is how most minecraft launchers handle it // this is how most minecraft launchers handle it
pub fn toggle_selected(&mut self) { pub fn toggle_selected(&mut self) {
@@ -487,6 +651,30 @@ impl ContentListState {
} }
} }
} }
pub fn remove_path(&mut self, path: &Path) {
let file_stem = self
.entries
.iter()
.find(|entry| entry.path == path)
.map(|entry| entry.file_stem.clone());
self.entries.retain(|entry| entry.path != path);
if let Some(file_stem) = file_stem {
self.image_protocols.remove(&file_stem);
self.requested_images.remove(&file_stem);
self.display_metadata.remove(&file_stem);
}
self.images_dirty = true;
if let Some(sel) = self.list_state.selected {
let visible_count = self.filtered_indices().len();
if visible_count == 0 {
self.list_state.selected = None;
} else {
self.list_state.selected = Some(sel.min(visible_count.saturating_sub(1)));
}
}
self.update_scrollbar();
}
} }
fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool { fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
@@ -531,6 +719,7 @@ pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState)
} }
let filtered = state.filtered_indices(); let filtered = state.filtered_indices();
let count = filtered.len(); let count = filtered.len();
match key_event.code { match key_event.code {
KeyCode::Char('j') | KeyCode::Down => { KeyCode::Char('j') | KeyCode::Down => {
if count == 0 { if count == 0 {
@@ -566,6 +755,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
} }
let filtered = state.filtered_indices(); let filtered = state.filtered_indices();
let count = filtered.len(); let count = filtered.len();
match key_event.code { match key_event.code {
KeyCode::Char('j') | KeyCode::Down => { KeyCode::Char('j') | KeyCode::Down => {
if count == 0 { if count == 0 {
@@ -611,6 +801,7 @@ pub fn render(
is_focused: bool, is_focused: bool,
loading_text: &str, loading_text: &str,
empty_text: &str, empty_text: &str,
picker: &ratatui_image::picker::Picker,
) { ) {
let theme = THEME.as_ref(); let theme = THEME.as_ref();
if state.loading { if state.loading {
@@ -641,24 +832,23 @@ pub fn render(
state.list_state.selected = Some(count.saturating_sub(1)); state.list_state.selected = Some(count.saturating_sub(1));
} }
let snapshot: Vec<SnapshotRow> = filtered let use_image_protocol =
.iter() picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
.map(|&i| { let entries = &state.entries;
let entry = &state.entries[i]; let display_metadata = &state.display_metadata;
( let filtered_rows = &filtered;
entry.name.clone(),
entry.description.clone(),
entry.enabled,
entry.icon_lines.clone(),
)
})
.collect();
let builder = ListBuilder::new(move |context| { let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref(); let theme = THEME.as_ref();
let (name, description, enabled, icon_pixels) = &snapshot[context.index]; let entry = &entries[filtered_rows[context.index]];
let name = &entry.name;
let metadata = display_metadata.get(&entry.file_stem);
let enabled = entry.enabled;
let icon_pixels = &entry.icon_lines;
let has_image = entry.icon_bytes.is_some();
let protocol_columns = protocol_icon_columns(entry, picker) as usize;
let show_selected = is_focused && context.is_selected; let show_selected = is_focused && context.is_selected;
let use_mc_colors = *enabled; let use_mc_colors = enabled;
let stripe_bg = if context.index % 2 == 0 { let stripe_bg = if context.index % 2 == 0 {
theme.background() theme.background()
@@ -666,7 +856,7 @@ pub fn render(
theme.stripe() theme.stripe()
}; };
let (name_style, description_style, background) = match (*enabled, show_selected) { let (name_style, description_style, background) = match (enabled, show_selected) {
(true, true) => ( (true, true) => (
Style::default() Style::default()
.fg(theme.accent()) .fg(theme.accent())
@@ -698,9 +888,8 @@ pub fn render(
}; };
let has_icon = icon_pixels.is_some(); let has_icon = icon_pixels.is_some();
let full_desc = strip_mc_codes(description); let stripped_desc = metadata.map_or("", |metadata| metadata.description.as_str());
let stripped_desc = full_desc.lines().next().unwrap_or("").trim().to_string(); let has_description = metadata.is_some_and(|metadata| metadata.has_description);
let has_description = !stripped_desc.is_empty();
let compact = !has_icon && !has_description; let compact = !has_icon && !has_description;
let selector = if show_selected { let selector = if show_selected {
@@ -732,7 +921,12 @@ pub fn render(
}; };
let mut line_0 = vec![selector.clone()]; let mut line_0 = vec![selector.clone()];
line_0.extend(icon_spans(icon_pixels.as_ref(), 0)); line_0.extend(icon_spans(
icon_pixels.as_ref(),
0,
use_image_protocol && has_image,
protocol_columns,
));
line_0.push(Span::raw(" ")); line_0.push(Span::raw(" "));
if use_mc_colors { if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style)); line_0.extend(parse_mc_text(name, name_style));
@@ -744,16 +938,26 @@ pub fn render(
if has_description { if has_description {
let mut row = vec![pad.clone()]; let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), 1)); row.extend(icon_spans(
icon_pixels.as_ref(),
1,
use_image_protocol && has_image,
protocol_columns,
));
row.push(Span::raw(" ")); row.push(Span::raw(" "));
row.push(Span::styled(stripped_desc.clone(), description_style)); row.push(Span::styled(stripped_desc.to_string(), description_style));
lines.push(Line::from(row)); lines.push(Line::from(row));
} }
let desc_rows = if has_description { 1 } else { 0 }; let desc_rows = if has_description { 1 } else { 0 };
for r in (1 + desc_rows)..icon_row_count { for r in (1 + desc_rows)..icon_row_count {
let mut row = vec![pad.clone()]; let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), r)); row.extend(icon_spans(
icon_pixels.as_ref(),
r,
use_image_protocol && has_image,
protocol_columns,
));
lines.push(Line::from(row)); lines.push(Line::from(row));
} }
@@ -778,7 +982,7 @@ pub fn render(
}; };
lines.push(Line::from(vec![ lines.push(Line::from(vec![
pad, pad,
Span::styled(stripped_desc.clone(), description_style), Span::styled(stripped_desc.to_string(), description_style),
])); ]));
} }
@@ -791,6 +995,10 @@ pub fn render(
let list = ListView::new(builder, count); let list = ListView::new(builder, count);
frame.render_stateful_widget(list, area, &mut state.list_state); frame.render_stateful_widget(list, area, &mut state.list_state);
if picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks {
render_image_icons(frame, area, state, &filtered, picker);
}
let scrollbar_area = Rect { let scrollbar_area = Rect {
x: area.x + area.width.saturating_sub(0), x: area.x + area.width.saturating_sub(0),
y: area.y + 1, y: area.y + 1,
@@ -814,6 +1022,76 @@ pub fn render(
); );
} }
fn render_image_icons(
frame: &mut Frame,
area: Rect,
state: &mut ContentListState,
filtered: &[usize],
picker: &ratatui_image::picker::Picker,
) {
let truncation = state.list_state.scroll_truncation();
let mut y = area.y;
let first = state.list_state.scroll_offset_index();
for (visible_index, &entry_index) in filtered.iter().enumerate().skip(first) {
let Some(entry) = state.entries.get(entry_index) else {
continue;
};
let icon_rows = entry.icon_lines.as_ref().map_or(0, Vec::len);
let has_description = state
.display_metadata
.get(&entry.file_stem)
.is_some_and(|metadata| metadata.has_description);
let height = icon_rows.max(if has_description { 2 } else { 1 }) as u16;
if y >= area.y + area.height {
break;
}
let top_crop = if visible_index == first {
truncation.min(icon_rows as u16)
} else {
0
};
let visible_icon_rows = (icon_rows as u16)
.saturating_sub(top_crop)
.min(area.y + area.height - y);
if visible_icon_rows > 0
&& entry.icon_bytes.is_some()
&& let Some(protocol) = state.image_protocols.get_mut(&entry.file_stem)
{
let icon_area = Rect {
x: area.x + 1,
y,
width: protocol_icon_columns(entry, picker).min(area.width.saturating_sub(1)),
height: visible_icon_rows,
};
if icon_area.height > 0 && icon_area.width > 0 {
let clipped = top_crop > 0 || visible_icon_rows < icon_rows as u16;
let resize = if clipped {
Resize::Crop(Some(CropOptions {
clip_top: top_crop > 0,
clip_left: false,
}))
} else {
Resize::Scale(None)
};
let widget: StatefulImage<StatefulProtocol> =
StatefulImage::default().resize(resize);
frame.render_stateful_widget(widget, icon_area, protocol);
}
}
let visible_height = if visible_index == first {
height.saturating_sub(truncation)
} else {
height
};
y = y.saturating_add(visible_height);
if visible_index + 1 >= filtered.len() {
break;
}
}
}
// minecraft's 16-color palette, keyed by the formatting code character. // minecraft's 16-color palette, keyed by the formatting code character.
// these exact RGB values come from the minecraft wiki // these exact RGB values come from the minecraft wiki
fn mc_color(code: char) -> Option<Color> { fn mc_color(code: char) -> Option<Color> {
@@ -903,16 +1181,33 @@ fn strip_mc_codes(text: &str) -> String {
result result
} }
fn display_metadata(entry: &ContentEntry) -> DisplayMetadata {
let description = strip_mc_codes(&entry.description);
let description = description.lines().next().unwrap_or("").trim().to_string();
DisplayMetadata {
has_description: !description.is_empty(),
description,
}
}
// renders one row of a mod icon using half-block characters (U+2584). // renders one row of a mod icon using half-block characters (U+2584).
// each cell packs two vertical pixels via fg/bg colors, giving // each cell packs two vertical pixels via fg/bg colors, giving
// double the vertical resolution out of the terminal // double the vertical resolution out of the terminal
fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<'static>> { fn icon_spans(
icon_pixels: Option<&Vec<Vec<IconCell>>>,
row: usize,
use_image_protocol: bool,
protocol_columns: usize,
) -> Vec<Span<'static>> {
if use_image_protocol {
return vec![Span::raw(" ".repeat(protocol_columns))];
}
match icon_pixels.and_then(|rows| rows.get(row)) { match icon_pixels.and_then(|rows| rows.get(row)) {
Some(cols) => cols Some(cols) => cols
.iter() .iter()
.map(|cell| { .map(|cell| {
Span::styled( Span::styled(
"\u{2584}", cell.symbol.to_string(),
Style::default() Style::default()
.fg(Color::Rgb(cell.fg_r, cell.fg_g, cell.fg_b)) .fg(Color::Rgb(cell.fg_r, cell.fg_g, cell.fg_b))
.bg(Color::Rgb(cell.bg_r, cell.bg_g, cell.bg_b)), .bg(Color::Rgb(cell.bg_r, cell.bg_g, cell.bg_b)),
@@ -929,6 +1224,20 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
} }
} }
fn protocol_icon_columns(
entry: &crate::instance::content::mods::ContentEntry,
picker: &ratatui_image::picker::Picker,
) -> u16 {
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u16;
square_icon_columns(rows, picker.font_size())
}
fn square_icon_columns(rows: u16, font_size: (u16, u16)) -> u16 {
let width = u32::from(font_size.0.max(1));
let height = u32::from(font_size.1.max(1));
((u32::from(rows) * height + width / 2) / width).max(1) as u16
}
// reads a content directory and builds a stem -> (path, enabled) map. // reads a content directory and builds a stem -> (path, enabled) map.
// used both by watch_dir to initialize known state and by the watcher // used both by watch_dir to initialize known state and by the watcher
// thread to detect changes. when ext is empty (worlds), only directories // thread to detect changes. when ext is empty (worlds), only directories
@@ -966,3 +1275,20 @@ fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::pat
map map
} }
#[cfg(test)]
mod tests {
use super::square_icon_columns;
#[test]
fn square_columns_follow_terminal_cell_ratio() {
assert_eq!(square_icon_columns(3, (8, 16)), 6);
assert_eq!(square_icon_columns(3, (8, 18)), 7);
assert_eq!(square_icon_columns(6, (8, 18)), 14);
}
#[test]
fn square_columns_handle_missing_cell_size() {
assert_eq!(square_icon_columns(3, (0, 0)), 3);
}
}
+10
View File
@@ -80,6 +80,7 @@ pub fn render(
screenshots_state: &mut crate::tui::widgets::screenshots_grid::ScreenshotsState, screenshots_state: &mut crate::tui::widgets::screenshots_grid::ScreenshotsState,
logs_state: &mut crate::tui::widgets::logs_viewer::LogsState, logs_state: &mut crate::tui::widgets::logs_viewer::LogsState,
instances_dir: &std::path::Path, instances_dir: &std::path::Path,
picker: &ratatui_image::picker::Picker,
) { ) {
let theme = THEME.as_ref(); let theme = THEME.as_ref();
let is_focused = focused == FocusedArea::Content; let is_focused = focused == FocusedArea::Content;
@@ -148,12 +149,14 @@ pub fn render(
ContentTab::Mods | ContentTab::ResourcePacks | ContentTab::Shaders => &[ ContentTab::Mods | ContentTab::ResourcePacks | ContentTab::Shaders => &[
("j/k", " navigate"), ("j/k", " navigate"),
("⏎", " toggle"), ("⏎", " toggle"),
("d", " delete"),
("Shift+⏎", " open dir"), ("Shift+⏎", " open dir"),
("h/l", " tabs"), ("h/l", " tabs"),
("/", " search"), ("/", " search"),
], ],
ContentTab::Worlds => &[ ContentTab::Worlds => &[
("j/k", " navigate"), ("j/k", " navigate"),
("d", " delete"),
("Shift+⏎", " open dir"), ("Shift+⏎", " open dir"),
("h/l", " tabs"), ("h/l", " tabs"),
("/", " search"), ("/", " search"),
@@ -161,6 +164,7 @@ pub fn render(
ContentTab::Screenshots => &[ ContentTab::Screenshots => &[
("Shift+HJKL", " grid"), ("Shift+HJKL", " grid"),
("⏎", " open"), ("⏎", " open"),
("d", " delete"),
("Shift+⏎", " open dir"), ("Shift+⏎", " open dir"),
("h/l", " tabs"), ("h/l", " tabs"),
("/", " search"), ("/", " search"),
@@ -170,6 +174,7 @@ pub fn render(
&[ &[
("j/k", " scroll"), ("j/k", " scroll"),
("g/G", " top/bottom"), ("g/G", " top/bottom"),
("d", " delete"),
("Esc", " back"), ("Esc", " back"),
("/", " search"), ("/", " search"),
] ]
@@ -177,6 +182,7 @@ pub fn render(
&[ &[
("j/k", " navigate"), ("j/k", " navigate"),
("⏎", " view"), ("⏎", " view"),
("d", " delete"),
("h/l", " tabs"), ("h/l", " tabs"),
("/", " search"), ("/", " search"),
] ]
@@ -234,6 +240,7 @@ pub fn render(
is_focused, is_focused,
"Loading mods...", "Loading mods...",
"No mods installed.", "No mods installed.",
picker,
); );
} else { } else {
frame.render_widget( frame.render_widget(
@@ -265,6 +272,7 @@ pub fn render(
is_focused, is_focused,
"Loading resource packs...", "Loading resource packs...",
"No resource packs installed.", "No resource packs installed.",
picker,
); );
} else { } else {
frame.render_widget( frame.render_widget(
@@ -296,6 +304,7 @@ pub fn render(
is_focused, is_focused,
"Loading shaders...", "Loading shaders...",
"No shaders installed.", "No shaders installed.",
picker,
); );
} else { } else {
frame.render_widget( frame.render_widget(
@@ -365,6 +374,7 @@ pub fn render(
is_focused, is_focused,
"Loading worlds...", "Loading worlds...",
"No worlds saved.", "No worlds saved.",
picker,
); );
} else { } else {
frame.render_widget( frame.render_widget(
+1
View File
@@ -387,6 +387,7 @@ mod tests {
memory_min: None, memory_min: None,
jvm_args: vec![], jvm_args: vec![],
resolution: None, resolution: None,
config_sync_profile: None,
} }
} }
+44 -5
View File
@@ -37,7 +37,7 @@ pub struct LogsState {
pub viewer_search: super::search::SearchState, pub viewer_search: super::search::SearchState,
selected_path: Option<std::path::PathBuf>, selected_path: Option<std::path::PathBuf>,
pending: PendingLogs, pending: PendingLogs,
rescan_counter: u8, last_rescan: std::time::Instant,
instances_dir_cache: Option<std::path::PathBuf>, instances_dir_cache: Option<std::path::PathBuf>,
was_live: bool, was_live: bool,
} }
@@ -59,7 +59,7 @@ impl Default for LogsState {
viewer_search: super::search::SearchState::default(), viewer_search: super::search::SearchState::default(),
selected_path: None, selected_path: None,
pending: Arc::new(Mutex::new(None)), pending: Arc::new(Mutex::new(None)),
rescan_counter: 0, last_rescan: std::time::Instant::now(),
instances_dir_cache: None, instances_dir_cache: None,
was_live: false, was_live: false,
} }
@@ -77,6 +77,7 @@ impl LogsState {
self.viewer_scroll = 0; self.viewer_scroll = 0;
self.viewer_focused = false; self.viewer_focused = false;
self.selected_path = None; self.selected_path = None;
self.last_rescan = std::time::Instant::now();
let dir = instances_dir.to_path_buf(); let dir = instances_dir.to_path_buf();
let tag = instance_name.to_string(); let tag = instance_name.to_string();
@@ -92,6 +93,7 @@ impl LogsState {
if let Ok(mut slot) = pending.lock() { if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries)); *slot = Some((tag, entries));
crate::tui::request_redraw();
} }
}); });
} }
@@ -128,16 +130,25 @@ impl LogsState {
} }
// periodically re-scan log files in case new ones appeared while playing. // periodically re-scan log files in case new ones appeared while playing.
// only triggers every 120 ticks to avoid hammering the filesystem
pub fn try_rescan(&mut self) { pub fn try_rescan(&mut self) {
self.rescan_counter = self.rescan_counter.wrapping_add(1); if self.last_rescan.elapsed() < std::time::Duration::from_secs(2) {
if !self.rescan_counter.is_multiple_of(120) {
return; return;
} }
self.last_rescan = std::time::Instant::now();
let (Some(dir), Some(name)) = (&self.instances_dir_cache, &self.loaded_for) else { let (Some(dir), Some(name)) = (&self.instances_dir_cache, &self.loaded_for) else {
return; return;
}; };
if !matches!(
crate::running::get(name),
Some(
crate::running::RunState::Authenticating
| crate::running::RunState::Starting
| crate::running::RunState::Running
)
) {
return;
}
let dir = dir.clone(); let dir = dir.clone();
let tag = name.clone(); let tag = name.clone();
@@ -153,6 +164,7 @@ impl LogsState {
if let Ok(mut slot) = pending.lock() { if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries)); *slot = Some((tag, entries));
crate::tui::request_redraw();
} }
}); });
} }
@@ -228,6 +240,33 @@ impl LogsState {
self.viewer_scrollbar_state = self.viewer_scrollbar_state =
ScrollbarState::new(self.viewer_max_scroll).position(self.viewer_scroll); ScrollbarState::new(self.viewer_max_scroll).position(self.viewer_scroll);
} }
pub fn pending_delete(
&self,
) -> Option<crate::tui::widgets::content::list::PendingContentDelete> {
let index = self.file_index_for_selected()?;
let entry = self.entries.get(index)?;
Some(crate::tui::widgets::content::list::PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
pub fn remove_path(&mut self, path: &Path) {
self.entries.retain(|entry| entry.path != path);
let display_count = self.display_count();
if display_count == 0 {
self.list_state.selected = None;
self.viewer_focused = false;
self.selected_path = None;
self.viewer_lines.clear();
self.viewer_scroll = 0;
} else if let Some(sel) = self.list_state.selected {
self.list_state.selected = Some(sel.min(display_count.saturating_sub(1)));
self.load_selected_content();
}
self.update_scrollbar();
}
} }
pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
+82 -18
View File
@@ -1,4 +1,4 @@
// "are you sure?" popup for instance deletion. uses global state so the // "are you sure?" popup for destructive actions. uses global state so the
// confirmation target persists across render frames. // confirmation target persists across render frames.
use std::sync::LazyLock; use std::sync::LazyLock;
@@ -19,13 +19,57 @@ static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> =
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct ConfirmState { 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,
},
Account {
username: String,
index: usize,
},
ConfigProfile {
profile: String,
},
Content {
name: String,
path: std::path::PathBuf,
},
}
impl ConfirmTarget {
fn title(&self) -> String {
format!(" Delete '{}' ", self.name())
}
fn body(&self) -> &'static str {
match self {
ConfirmTarget::Instance { .. } => "This will permanently remove the instance",
ConfirmTarget::Account { .. } => "This will permanently remove this account",
ConfirmTarget::ConfigProfile { .. } => {
"This will permanently remove this config profile"
}
ConfirmTarget::Content { .. } => "This will permanently remove the selected item",
}
}
pub fn name(&self) -> &str {
match self {
ConfirmTarget::Instance { name } => name,
ConfirmTarget::Account { username, .. } => username,
ConfirmTarget::ConfigProfile { profile } => profile,
ConfirmTarget::Content { name, .. } => name,
}
}
}
pub fn set_pending(target: ConfirmTarget) {
match CONFIRM_STATE.lock() { match CONFIRM_STATE.lock() {
Ok(mut s) => { Ok(mut s) => {
s.instance_name = name.into(); s.target = Some(target);
} }
Err(e) => { Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e); tracing::error!("Confirm popup state lock poisoned: {}", e);
@@ -33,17 +77,32 @@ 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 set_pending_instance_delete(name: impl Into<String>) {
set_pending_delete(name);
}
pub fn set_pending_content_delete(name: impl Into<String>, path: impl Into<std::path::PathBuf>) {
set_pending(ConfirmTarget::Content {
name: name.into(),
path: path.into(),
});
}
pub fn pending_target() -> Option<ConfirmTarget> {
match CONFIRM_STATE.lock() { match CONFIRM_STATE.lock() {
Ok(s) => s.instance_name.clone(), Ok(s) => s.target.clone(),
Err(_) => String::new(), Err(_) => None,
} }
} }
pub fn clear_pending() { pub fn clear_pending() {
match CONFIRM_STATE.lock() { match CONFIRM_STATE.lock() {
Ok(mut s) => { Ok(mut s) => {
s.instance_name.clear(); s.target = None;
} }
Err(e) => { Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e); tracing::error!("Confirm popup state lock poisoned: {}", e);
@@ -52,15 +111,21 @@ pub fn clear_pending() {
} }
pub struct ConfirmPopup { pub struct ConfirmPopup {
instance_name: String, title: String,
body: &'static str,
} }
impl ConfirmPopup { impl ConfirmPopup {
pub fn new(instance_name: impl Into<String>) -> Self { pub fn new(title: impl Into<String>, body: &'static str) -> Self {
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 { impl Widget for ConfirmPopup {
@@ -69,7 +134,7 @@ impl Widget for ConfirmPopup {
let theme = THEME.as_ref(); let theme = THEME.as_ref();
let title = Line::from(vec![Span::styled( let title = Line::from(vec![Span::styled(
format!(" Delete '{}' ", self.instance_name), self.title,
Style::default() Style::default()
.fg(theme.text_dim()) .fg(theme.text_dim())
.add_modifier(Modifier::BOLD), .add_modifier(Modifier::BOLD),
@@ -86,7 +151,7 @@ impl Widget for ConfirmPopup {
keybinds: Some(kb), keybinds: Some(kb),
search_line: None, search_line: None,
content: Box::new(move |inner, buf| { content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove the instance") Paragraph::new(self.body)
.style(Style::default().fg(text_color)) .style(Style::default().fg(text_color))
.render(inner, buf); .render(inner, buf);
}), }),
@@ -96,15 +161,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 super::word_wrap_size;
use ratatui::layout::Constraint; use ratatui::layout::Constraint;
const MAX_W: usize = 48; const MAX_W: usize = 48;
const BODY: &str = "This will permanently remove the instance"; let title_w = target.name().len() + 12;
let title_w = name.len() + 12; let (body_w, _) = word_wrap_size(target.body(), MAX_W);
let (body_w, _) = word_wrap_size(BODY, MAX_W);
let inner_w = title_w.max(body_w).min(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_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)); 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)) frame_area.centered(Constraint::Length(popup_w), Constraint::Length(popup_h))
+26
View File
@@ -92,6 +92,7 @@ impl ScreenshotsState {
if let Ok(mut slot) = pending.lock() { if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries)); *slot = Some((tag, entries));
crate::tui::request_redraw();
} }
}); });
} }
@@ -148,6 +149,7 @@ impl ScreenshotsState {
&& let Ok(mut slot) = pending.lock() && let Ok(mut slot) = pending.lock()
{ {
slot.push((idx, img)); slot.push((idx, img));
crate::tui::request_redraw();
} }
}); });
} }
@@ -173,6 +175,30 @@ impl ScreenshotsState {
} }
self.entries.len().div_ceil(self.cols) self.entries.len().div_ceil(self.cols)
} }
pub fn pending_delete(
&self,
) -> Option<crate::tui::widgets::content::list::PendingContentDelete> {
let entry = self.entries.get(self.selected)?;
Some(crate::tui::widgets::content::list::PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
pub fn remove_path(&mut self, path: &Path) {
self.entries.retain(|entry| entry.path != path);
self.protocols.clear();
self.requested.clear();
if self.entries.is_empty() {
self.selected = 0;
self.scroll_row = 0;
} else {
self.selected = self.selected.min(self.entries.len().saturating_sub(1));
self.ensure_visible();
}
}
} }
pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool { pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
+460 -52
View File
@@ -1,13 +1,20 @@
// settings panel: shows instance config (memory, java, jvm args, resolution) // settings panel: manages config profiles and shows compact instance info.
// and provides keybinds to open config files in $EDITOR // also provides keybinds to open config files in $EDITOR.
use std::{
path::{Path, PathBuf},
process::Command,
};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{ use ratatui::{
Frame, Frame,
layout::Rect, layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, Borders, Paragraph}, widgets::{Block, Borders, Paragraph, Widget},
}; };
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::{ use crate::config::{
SETTINGS, SETTINGS,
@@ -18,13 +25,169 @@ use crate::tui::app::FocusedArea;
use super::styled_title; 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_key: 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_key: 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_key = instance.map(java_path_key);
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.java_key = java_key;
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 java_path_key(instance: &InstanceConfig) -> String {
instance
.java_path
.as_deref()
.filter(|path| !path.is_empty())
.or_else(|| SETTINGS.paths.effective_java_path())
.unwrap_or("<auto>")
.to_string()
}
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( pub fn render(
frame: &mut Frame, frame: &mut Frame,
area: Rect, area: Rect,
focused: FocusedArea, focused: FocusedArea,
state: &mut SettingsState,
instance: Option<&InstanceConfig>, instance: Option<&InstanceConfig>,
_instances_dir: &std::path::Path, _instances_dir: &Path,
) { ) {
state.update_for_instance(instance);
let theme = THEME.as_ref(); let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings { let color = if focused == FocusedArea::Settings {
theme.accent() theme.accent()
@@ -39,14 +202,22 @@ pub fn render(
.border_style(Style::default().fg(color)); .border_style(Style::default().fg(color));
if focused == FocusedArea::Settings { if focused == FocusedArea::Settings {
let lines = super::popups::keybind_lines_wrapped( let keybinds: &[(&str, &str)] = match state.pane {
&[ SettingsPane::Profile => &[
("e", " edit instance"), ("⏎", " select"),
("g", " edit global"), ("a", " add"),
("d", " desktop"), ("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 { for line in lines {
block = block.title_bottom(line); block = block.title_bottom(line);
} }
@@ -55,19 +226,62 @@ pub fn render(
let inner = block.inner(area); let inner = block.inner(area);
frame.render_widget(block, area); frame.render_widget(block, area);
let Some(inst) = instance else { if inner.width >= 42 {
frame.render_widget( let chunks = Layout::default()
Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())), .direction(Direction::Horizontal)
inner, .constraints([
); Constraint::Percentage(50),
return; 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 label_style = Style::default().fg(theme.text_dim());
let value_style = Style::default() let value_style = Style::default()
.fg(theme.text()) .fg(theme.text())
.add_modifier(Modifier::BOLD); .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 let memory_min = inst
.memory_min .memory_min
@@ -77,58 +291,252 @@ pub fn render(
.memory_max .memory_max
.as_deref() .as_deref()
.unwrap_or(&SETTINGS.defaults.memory_max); .unwrap_or(&SETTINGS.defaults.memory_max);
let java_path = inst let active_style = if focused == FocusedArea::Settings && state.pane == SettingsPane::Info {
.java_path value_style.fg(theme.accent())
.as_deref()
.or_else(|| SETTINGS.paths.effective_java_path())
.unwrap_or("system");
let jvm_args = if inst.jvm_args.is_empty() {
"none".to_string()
} else { } 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![ let lines = vec![
Line::from(vec![ Line::from(vec![
Span::styled("Memory ", label_style), Span::styled("Memory ", label_style),
Span::styled(format!("{memory_min} - {memory_max}"), value_style), Span::styled(format!("{memory_min} - {memory_max}"), active_style),
]), ]),
Line::from(vec![ Line::from(vec![
Span::styled("Java ", label_style), Span::styled("Java ", label_style),
Span::styled(java_path, value_style), Span::styled(state.java_label.as_str(), active_style),
]), ]),
Line::from(vec![ Line::from(vec![
Span::styled("JVM ", label_style), Span::styled("Desktop ", label_style),
Span::styled(jvm_args, dim_style), Span::styled(desktop, active_style),
]),
Line::from(vec![
Span::styled("Display ", label_style),
Span::styled(resolution, value_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 { pub enum SettingsAction {
None, None,
EditInstance(std::path::PathBuf), EditInstance(PathBuf),
EditGlobal(std::path::PathBuf), EditGlobal(PathBuf),
ToggleDesktop, ToggleDesktop,
SelectProfile(Option<String>),
ConfirmDeleteProfile(String),
Error(String),
} }
pub fn handle_key( pub fn handle_key(
key_event: &crossterm::event::KeyEvent, key_event: &KeyEvent,
state: &mut SettingsState,
instance: Option<&InstanceConfig>, instance: Option<&InstanceConfig>,
instances_dir: &std::path::Path, instances_dir: &Path,
) -> SettingsAction { ) -> 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 { 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 { if let Some(inst) = instance {
let path = instances_dir.join(&inst.name).join("instance.json"); let path = instances_dir.join(&inst.name).join("instance.json");
SettingsAction::EditInstance(path) SettingsAction::EditInstance(path)
@@ -136,11 +544,11 @@ pub fn handle_key(
SettingsAction::None 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"); let path = crate::config::get_config_path().join("config.toml");
SettingsAction::EditGlobal(path) SettingsAction::EditGlobal(path)
} }
crossterm::event::KeyCode::Char('d') => SettingsAction::ToggleDesktop, KeyCode::Char('d') if state.pane == SettingsPane::Info => SettingsAction::ToggleDesktop,
_ => SettingsAction::None, _ => SettingsAction::None,
} }
} }
+1
View File
@@ -52,6 +52,7 @@ fn make_config_with(
memory_min: None, memory_min: None,
jvm_args: Vec::new(), jvm_args: Vec::new(),
resolution: None, resolution: None,
config_sync_profile: None,
} }
} }