fix(tui): harden rendering and centralize tests

This commit is contained in:
objz committed 2026-07-27 01:09:33 +02:00
1 parent 9b17ec96c5
commit 64bb5e2d16
66 files changed
+271 -48

No files matched your search

+1
View File
@@ -86,4 +86,5 @@ pub fn peek_all_errors() -> Vec<ErrorEvent> {
}
#[cfg(test)]
#[path = "tests/error_buffer.rs"]
mod tests;
+1
View File
@@ -616,4 +616,5 @@ fn editor_runs_in_terminal(editor: &str) -> bool {
}
#[cfg(test)]
#[path = "tests/event.rs"]
mod tests;
+26 -14
View File
@@ -3,11 +3,12 @@
// also keeps an in-memory ring buffer of log lines for the log overlay viewer.
use std::fmt;
use std::path::Path;
use std::sync::{Arc, Mutex};
use tracing::field::{Field, Visit};
use tracing::{Level, Subscriber};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};
use tracing_subscriber::filter::filter_fn;
use tracing_subscriber::layer::Context;
use tracing_subscriber::prelude::*;
@@ -47,20 +48,8 @@ pub fn init() -> WorkerGuard {
Some(d) => d.join("rmcl"),
None => std::path::PathBuf::from("./cache"),
};
match std::fs::create_dir_all(&log_dir) {
Ok(_) => {}
Err(e) => {
eprintln!(
"Warning: failed to create log directory {}: {}",
log_dir.display(),
e
);
}
}
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
let file_appender = tracing_appender::rolling::never(&log_dir, format!("rmcl_{now}.log"));
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let (non_blocking, guard) = open_log_writer(&log_dir);
let file_filter =
EnvFilter::try_from_env("RUST_LOG").unwrap_or_else(|_| EnvFilter::new(DEFAULT_FILE_FILTER));
@@ -104,6 +93,28 @@ pub fn init() -> WorkerGuard {
guard
}
fn open_log_writer(log_dir: &Path) -> (NonBlocking, WorkerGuard) {
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
let file = std::fs::create_dir_all(log_dir).and_then(|_| {
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log_dir.join(format!("rmcl_{now}.log")))
});
match file {
Ok(file) => tracing_appender::non_blocking(file),
Err(error) => {
eprintln!(
"Warning: failed to open log file in {}: {}",
log_dir.display(),
error
);
tracing_appender::non_blocking(std::io::sink())
}
}
}
// custom tracing layer that intercepts all log events:
// - everything gets appended to the in-memory log buffer for the overlay viewer
// - WARN and ERROR additionally get pushed as error toasts
@@ -190,4 +201,5 @@ impl Visit for MessageVisitor {
}
#[cfg(test)]
#[path = "tests/logging.rs"]
mod tests;
+1
View File
@@ -216,4 +216,5 @@ pub fn is_active() -> bool {
}
#[cfg(test)]
#[path = "tests/progress.rs"]
mod tests;
File renamed without changes.
File renamed without changes.
+2
View File
@@ -25,6 +25,8 @@ impl UiHarness {
.lock()
.unwrap_or_else(|error| error.into_inner());
widgets::popups::confirm::clear_pending();
widgets::popups::new_instance::reset_for_test();
widgets::popups::import_modpack::reset_for_test();
crate::tui::error_buffer::ERROR_EVENTS
.lock()
.expect("error buffer")
@@ -28,3 +28,12 @@ fn svg_renderer_warnings_do_not_interrupt_the_ui() {
assert!(!should_record_app_log("usvg::text", Level::WARN));
assert!(!should_record_app_log("usvg::parser::filter", Level::WARN));
}
#[test]
fn unwritable_log_path_falls_back_without_panicking() {
let temp = tempfile::tempdir().unwrap();
let file = temp.path().join("not-a-directory");
std::fs::write(&file, b"block nested directory creation").unwrap();
let (_writer, _guard) = open_log_writer(&file.join("rmcl"));
}
File renamed without changes.
+39
View File
@@ -1,4 +1,7 @@
use super::harness::UiHarness;
use crate::instance::ProviderProject;
use crate::tui::app::ProviderConflictState;
use crossterm::event::KeyCode;
#[test]
fn empty_app_renders_the_complete_frame() {
@@ -21,3 +24,39 @@ fn active_progress_is_visible_in_the_complete_frame() {
assert!(screen.contains("one.jar"));
crate::tui::progress::clear();
}
#[test]
fn instance_delete_confirmation_renders_the_complete_frame() {
let mut ui = UiHarness::new();
ui.add_instance("Snapshot Instance");
ui.key(KeyCode::Char('d'));
ui.draw();
insta::assert_snapshot!(ui.screen());
}
#[test]
fn provider_conflict_renders_the_complete_frame() {
let mut ui = UiHarness::new();
ui.app.provider_conflict = Some(ProviderConflictState {
relative_path: "mods/example.jar".into(),
candidates: vec![
ProviderProject {
provider: "modrinth".to_owned(),
project_id: "first".to_owned(),
version_id: "1".to_owned(),
},
ProviderProject {
provider: "curseforge".to_owned(),
project_id: "second".to_owned(),
version_id: "2".to_owned(),
},
],
selected: 0,
});
ui.draw();
insta::assert_snapshot!(ui.screen());
}
@@ -0,0 +1,34 @@
---
source: src/tui/tests/snapshots.rs
expression: ui.screen()
---
"╭Instances─────────╮╭Content───────────────────────────────────────────────────────────────────────╮"
"│▌ Snapshot Instanc││Snapshot Instance 1.21.1 · Fabric 0.16.14│"
"│▌ Never played │╰──────────────────────────────────────────────────────────────────────────────╯"
"│ │╭ Installed Mods • Resource Packs • Shaders • Screenshots • Worlds • Logs ───╮"
"│ ││Loading mods... │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ ╭ Delete 'Snapshot Instance' ─────────────╮ │"
"│ ││ │This will permanently remove the instance│ │"
"│ ││ ╰──────────────────────────[Enter] confirm╯ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ │╰──────────────────────────────────────────────────────────────────────────────╯"
"│ │╭Accounts─────────╮╭Settings───────────────────────────╮╭Overview──────────────╮"
"│ ││No accounts. ││▸ instance default ││Ready │"
"│ ││ ││ ││ │"
"│ ││ ││ ││ │"
"╰──────────────────╯╰─────────────────╯╰───────────────────────────────────╯╰──────────────────────╯"
@@ -0,0 +1,34 @@
---
source: src/tui/tests/snapshots.rs
expression: ui.screen()
---
"╭Instances─────────╮╭Content───────────────────────────────────────────────────────────────────────╮"
"│ ││No instance selected │"
"│ │╰──────────────────────────────────────────────────────────────────────────────╯"
"│ │╭ Installed Mods • Resource Packs • Shaders • Screenshots • Worlds • Logs ───╮"
"│ ││No instance selected. │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││╭ Choose provider for example.jar ───────────────────────╮ │"
"│ │││▌modrinth first 1 │ │"
"│ │││ curseforge second 2 │ │"
"│ │││ │ │"
"│ │││ │ │"
"│ ││╰ [j/k] select [Enter] use [Esc] later ────────────────╯ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ [l] launch [⏎] content [Shift+⏎] open dir [Esc] kill [a] add [i] import│"
"│ │╰────────────────────────────────────────────[d] delete [r] rename [/] search╯"
"│ │╭Accounts─────────╮╭Settings───────────────────────────╮╭Overview──────────────╮"
"│ ││No accounts. ││▸ instance default ││Ready │"
"│ ││ ││ ││ │"
"│ ││ ││ ││ │"
"╰──────────────────╯╰─────────────────╯╰───────────────────────────────────╯╰──────────────────────╯"
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/error/render_tests.rs
source: src/tui/tests/widgets/popups/error/render.rs
expression: term.backend()
---
"╭ ERROR ───────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/error/render_tests.rs
source: src/tui/tests/widgets/popups/error/render.rs
expression: term.backend()
---
"╭ INFO ────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/error/render_tests.rs
source: src/tui/tests/widgets/popups/error/render.rs
expression: term.backend()
---
"╭ ERROR ───────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/error/render_tests.rs
source: src/tui/tests/widgets/popups/error/render.rs
expression: term.backend()
---
"╭ WARN ──────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/error/render_tests.rs
source: src/tui/tests/widgets/popups/error/render.rs
expression: term.backend()
---
"╭ WARN ────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/import_modpack/render/tests.rs
source: src/tui/tests/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/import_modpack/render/tests.rs
source: src/tui/tests/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/import_modpack/render/tests.rs
source: src/tui/tests/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/import_modpack/render/tests.rs
source: src/tui/tests/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/import_modpack/render/tests.rs
source: src/tui/tests/widgets/popups/import_modpack/render.rs
expression: terminal.backend()
---
"╭Import Modpack────────────────────────────────────────────╮"
+34
View File
@@ -0,0 +1,34 @@
use super::{
confirm::{ConfirmTarget, confirm_popup_area},
keybind_lines_wrapped, word_wrap_size,
};
#[test]
fn keybind_wrapping_uses_terminal_width_for_unicode_keys() {
let lines = keybind_lines_wrapped(&[("⏎", " select"), ("a", " add")], 19);
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].width(), 19);
}
#[test]
fn word_wrap_size_uses_terminal_width_for_unicode_text() {
assert_eq!(word_wrap_size("Übergröße", 20), (9, 1));
assert_eq!(word_wrap_size("世界 test", 6), (4, 2));
}
#[test]
fn confirmation_area_uses_display_width_for_unicode_names() {
let frame = ratatui::layout::Rect::new(0, 0, 100, 30);
let ascii = ConfirmTarget::Instance {
name: "a".repeat(30),
};
let unicode = ConfirmTarget::Instance {
name: format!("é{}", "a".repeat(29)),
};
assert_eq!(
confirm_popup_area(frame, &ascii),
confirm_popup_area(frame, &unicode)
);
}
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/new_instance/render/tests.rs
source: src/tui/tests/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/new_instance/render/tests.rs
source: src/tui/tests/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/new_instance/render/tests.rs
source: src/tui/tests/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/new_instance/render/tests.rs
source: src/tui/tests/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/popups/new_instance/render/tests.rs
source: src/tui/tests/widgets/popups/new_instance/render.rs
expression: terminal.backend()
---
"╭New Instance──────────────────────────────────────────────╮"
@@ -1,4 +1,5 @@
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{Terminal, backend::TestBackend};
use super::*;
@@ -46,3 +47,19 @@ fn grid_navigation_and_search_clamp_the_selection() {
assert_eq!(state.selected, 0);
assert_eq!(state.search.query, "t");
}
#[test]
fn unicode_filename_truncation_renders_without_panicking() {
let mut state = ScreenshotsState {
entries: vec![entry(&format!("{}é.png", "a".repeat(23)))],
..Default::default()
};
let backend = TestBackend::new(24, 8);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|frame| render(frame, frame.area(), &mut state, true))
.unwrap();
assert!(terminal.backend().to_string().contains("aaaa"));
}
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/instances/tests.rs
source: src/tui/tests/widgets/instances.rs
expression: terminal.backend()
---
"╭Instances─────────────────────────────╮"
@@ -1,5 +1,5 @@
---
source: src/tui/widgets/instances/tests.rs
source: src/tui/tests/widgets/instances.rs
expression: terminal.backend()
---
"╭Instances─────────────────────────────╮"
+1
View File
@@ -534,4 +534,5 @@ fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
}
#[cfg(test)]
#[path = "../tests/widgets/account.rs"]
mod tests;
+1
View File
@@ -872,4 +872,5 @@ fn format_downloads(downloads: u64) -> String {
}
#[cfg(test)]
#[path = "../../tests/widgets/content/discovery.rs"]
mod tests;
+1
View File
@@ -2218,4 +2218,5 @@ fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::pat
}
#[cfg(test)]
#[path = "../../tests/widgets/content/list.rs"]
mod tests;
+1
View File
@@ -867,4 +867,5 @@ pub fn title(
}
#[cfg(test)]
#[path = "../../tests/widgets/content/tabs.rs"]
mod tests;
+1
View File
@@ -338,4 +338,5 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
}
#[cfg(test)]
#[path = "../tests/widgets/instances.rs"]
mod tests;
+1
View File
@@ -689,4 +689,5 @@ fn line_level_style(line: &str) -> Style {
}
#[cfg(test)]
#[path = "../tests/widgets/logs_viewer.rs"]
mod tests;
+1
View File
@@ -1583,4 +1583,5 @@ fn render_raster(frame: &mut Frame, area: Rect, raster: &[Vec<IconCell>], hidden
}
#[cfg(test)]
#[path = "../tests/widgets/markdown.rs"]
mod tests;
+1 -1
View File
@@ -165,7 +165,7 @@ pub fn confirm_popup_area(frame_area: Rect, target: &ConfirmTarget) -> Rect {
use super::word_wrap_size;
use ratatui::layout::Constraint;
const MAX_W: usize = 48;
let title_w = target.name().len() + 12;
let title_w = Span::raw(target.name()).width() + 12;
let (body_w, _) = word_wrap_size(target.body(), MAX_W);
let inner_w = title_w.max(body_w).min(MAX_W);
let (_, lines) = word_wrap_size(target.body(), inner_w);
+2
View File
@@ -96,7 +96,9 @@ pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128
}
#[cfg(test)]
#[path = "../../tests/widgets/popups/error/render.rs"]
mod render_tests;
#[cfg(test)]
#[path = "../../tests/widgets/popups/error/area.rs"]
mod area_tests;
@@ -3,3 +3,12 @@ mod state;
pub use render::{popup_rect, render};
pub use state::{ImportResult, ImportStep, ImportWizardState, handle_key, take_result};
#[cfg(test)]
pub(crate) fn reset_for_test() {
state::IMPORT_STATE
.lock()
.expect("import wizard state")
.reset();
*state::IMPORT_RESULT.lock().expect("import wizard result") = None;
}
@@ -240,4 +240,5 @@ fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
}
#[cfg(test)]
#[path = "../../../tests/widgets/popups/import_modpack/render.rs"]
mod tests;
@@ -467,4 +467,5 @@ fn clamp_version_index(state: &mut ImportWizardState) {
}
#[cfg(test)]
#[path = "../../../tests/widgets/popups/import_modpack/state.rs"]
mod tests;
+3 -2
View File
@@ -10,7 +10,7 @@ pub mod new_instance;
use ratatui::{
Frame,
layout::{Alignment, Constraint, Layout, Rect},
text::Line,
text::{Line, Span},
widgets::Paragraph,
};
@@ -26,7 +26,7 @@ pub fn word_wrap_size(text: &str, max_inner_width: usize) -> (usize, usize) {
let mut widest_line: usize = 0;
for word in text.split_whitespace() {
let word_len = word.len().min(max_inner_width);
let word_len = Span::raw(word).width().min(max_inner_width);
if current_line_len == 0 {
current_line_len = word_len;
} else if current_line_len + 1 + word_len <= max_inner_width {
@@ -153,4 +153,5 @@ pub fn render_keybind_overflow(frame: &mut Frame, area: Rect, lines: &[Line<'sta
}
#[cfg(test)]
#[path = "../../tests/widgets/popups/mod.rs"]
mod tests;
@@ -4,3 +4,9 @@ mod state;
pub(crate) use render::render_select_list;
pub use render::{popup_rect, render};
pub use state::{LoadState, WizardParams, WizardState, WizardStep, handle_key, take_result};
#[cfg(test)]
pub(crate) fn reset_for_test() {
state::WIZARD_STATE.lock().expect("wizard state").reset();
*state::WIZARD_RESULT.lock().expect("wizard result") = None;
}
@@ -320,4 +320,5 @@ fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffe
}
#[cfg(test)]
#[path = "../../../tests/widgets/popups/new_instance/render.rs"]
mod tests;
@@ -482,4 +482,5 @@ fn sort_versions_semver(versions: &mut [GameVersion]) {
}
#[cfg(test)]
#[path = "../../../tests/widgets/popups/new_instance/state.rs"]
mod tests;
-9
View File
@@ -1,9 +0,0 @@
use super::keybind_lines_wrapped;
#[test]
fn keybind_wrapping_uses_terminal_width_for_unicode_keys() {
let lines = keybind_lines_wrapped(&[("⏎", " select"), ("a", " add")], 19);
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].width(), 19);
}
+22 -5
View File
@@ -11,9 +11,11 @@ use ratatui::{
Frame,
layout::{Constraint, Layout, Rect},
style::{Modifier, Style},
text::Span,
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
};
use ratatui_image::{Resize, StatefulImage, protocol::StatefulProtocol};
use unicode_segmentation::UnicodeSegmentation;
use crate::config::theme::THEME;
use crate::instance::screenshots::ScreenshotEntry;
@@ -28,6 +30,24 @@ const GAP: u16 = 1;
type PendingScreenshots = Arc<Mutex<Option<(String, Vec<ScreenshotEntry>)>>>;
fn truncate_to_width(text: &str, max_width: usize) -> &str {
if Span::raw(text).width() <= max_width {
return text;
}
let mut end = 0;
let mut width = 0;
for (offset, grapheme) in text.grapheme_indices(true) {
let grapheme_width = Span::raw(grapheme).width();
if width + grapheme_width > max_width {
break;
}
width += grapheme_width;
end = offset + grapheme.len();
}
&text[..end]
}
pub struct ScreenshotsState {
pub entries: Vec<ScreenshotEntry>,
protocols: HashMap<usize, StatefulProtocol>,
@@ -415,11 +435,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
Style::default().fg(theme.text_dim())
};
let truncated = if name.len() > cell_width as usize {
&name[..cell_width as usize]
} else {
name
};
let truncated = truncate_to_width(name, name_area.width as usize);
frame.render_widget(
Paragraph::new(state.search.highlight_line(truncated, name_style)),
name_area,
@@ -451,4 +467,5 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
}
#[cfg(test)]
#[path = "../tests/widgets/screenshots_grid.rs"]
mod tests;
+1
View File
@@ -118,4 +118,5 @@ impl SearchState {
}
#[cfg(test)]
#[path = "../tests/widgets/search.rs"]
mod tests;
+1
View File
@@ -568,4 +568,5 @@ pub fn handle_key(
}
#[cfg(test)]
#[path = "../tests/widgets/settings.rs"]
mod tests;