perf(tui): avoid redundant idle rendering

This commit is contained in:
objz committed 2026-07-11 17:13:02 +02:00
1 parent d10be1676e
commit c792e1cc11
9 files changed
+144 -63

No files matched your search

+8 -1
View File
@@ -38,6 +38,7 @@ pub fn push_error(event: ErrorEvent) {
while events.len() > MAX_ERROR_EVENTS {
events.pop_front();
}
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Error buffer lock poisoned: {}", e);
@@ -56,7 +57,13 @@ pub fn has_errors() -> bool {
#[must_use]
pub fn pop_error() -> Option<ErrorEvent> {
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,
}
}
+35 -15
View File
@@ -11,9 +11,13 @@ use crate::tui::error_buffer;
use crate::tui::progress;
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<()> {
let mut last_draw = std::time::Instant::now()
.checked_sub(Duration::from_secs(1))
.unwrap_or_else(std::time::Instant::now);
while !self.exit {
let redraw_requested = super::take_redraw_request();
// check if any popup wizard finished and wants to create/import
if let Some(params) = new_instance::take_result() {
self.spawn_create(params);
@@ -53,14 +57,26 @@ impl App {
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
// only advance the spinner every 8 ticks to keep it readable
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
let progress_active = progress::is_active();
if progress_active {
// only advance the spinner every 8 ticks to keep it readable
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))?;
self.handle_events().wrap_err("handle events failed")?;
let input_changed = 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()
&& Self::run_editor(terminal, &path)
@@ -73,22 +89,24 @@ impl App {
// polls for input with a 16ms timeout (~60fps). only key presses are handled,
// 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)) {
Ok(true) => match event::read() {
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => self
.handle_key_event(key_event)
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}")),
Ok(_) => Ok(()),
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => {
self.handle_key_event(key_event)
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}"))?;
Ok(true)
}
Ok(_) => Ok(true),
Err(e) => {
tracing::error!("Event read error: {}", e);
Ok(())
Ok(false)
}
},
Ok(false) => Ok(()),
Ok(false) => Ok(false),
Err(e) => {
tracing::error!("Event poll error: {}", e);
Ok(())
Ok(false)
}
}
}
@@ -115,6 +133,7 @@ impl App {
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
crate::tui::request_redraw();
}
}
Err(e) => {
@@ -141,6 +160,7 @@ impl App {
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
crate::tui::request_redraw();
}
}
Err(e) => {
+12
View File
@@ -9,6 +9,18 @@ pub mod progress;
mod render;
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 async fn show() -> color_eyre::Result<()> {
+10
View File
@@ -19,6 +19,7 @@ pub fn set_action(text: impl Into<String>) {
match PROGRESS.lock() {
Ok(mut state) => {
state.current_action = Some(text.clone());
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -31,6 +32,7 @@ pub fn set_progress(current: u64, total: u64) {
match PROGRESS.lock() {
Ok(mut state) => {
state.progress = Some((current, total));
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -43,6 +45,7 @@ pub fn set_sub_action(text: impl Into<String>) {
match PROGRESS.lock() {
Ok(mut state) => {
state.sub_action = Some(text.clone());
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -57,9 +60,16 @@ pub fn clear() {
state.current_action = None;
state.progress = None;
state.sub_action = None;
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
}
}
}
pub fn is_active() -> bool {
PROGRESS
.lock()
.is_ok_and(|state| state.current_action.is_some())
}
+55 -42
View File
@@ -22,14 +22,6 @@ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
type SnapshotRow = (
String,
String,
bool,
Option<Vec<Vec<IconCell>>>,
bool,
usize,
);
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
struct CachedList {
@@ -43,6 +35,11 @@ struct PendingContentImage {
image: Option<image::DynamicImage>,
}
struct DisplayMetadata {
description: String,
has_description: bool,
}
// result from the notify-triggered background diff
struct WatcherDiff {
toggled: Vec<(String, bool, std::path::PathBuf)>,
@@ -60,6 +57,7 @@ pub struct ContentListState {
requested_images: HashSet<std::path::PathBuf>,
pending_images: Arc<Mutex<Vec<PendingContentImage>>>,
images_dirty: bool,
display_metadata: HashMap<std::path::PathBuf, DisplayMetadata>,
pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>,
// streaming: individual entries arrive here during initial load
@@ -92,6 +90,7 @@ impl Default for ContentListState {
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(),
cache: HashMap::new(),
stream_rx: None,
@@ -169,6 +168,7 @@ impl ContentListState {
&& let Ok(mut pending) = pending.lock()
{
pending.push(result);
crate::tui::request_redraw();
}
});
}
@@ -211,6 +211,8 @@ impl ContentListState {
received = true;
self.images_dirty = true;
received_count += 1;
self.display_metadata
.insert(entry.path.clone(), display_metadata(&entry));
let pos = self
.entries
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
@@ -276,6 +278,9 @@ impl ContentListState {
);
for (stem, enabled, path) in &diff.toggled {
if let Some(entry) = self.entries.iter_mut().find(|e| &e.file_stem == stem) {
if let Some(metadata) = self.display_metadata.remove(&entry.path) {
self.display_metadata.insert(path.clone(), metadata);
}
entry.enabled = *enabled;
entry.path = path.clone();
}
@@ -285,10 +290,14 @@ impl ContentListState {
if !diff.removed.is_empty() {
self.entries
.retain(|e| !diff.removed.contains(&e.file_stem));
self.display_metadata
.retain(|path, _| self.entries.iter().any(|entry| &entry.path == path));
}
// insert new entries in sorted position
for entry in diff.added {
self.display_metadata
.insert(entry.path.clone(), display_metadata(&entry));
let pos = self
.entries
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
@@ -408,6 +417,7 @@ impl ContentListState {
&& let Ok(mut slot) = diff_slot.lock()
{
*slot = Some(diff);
crate::tui::request_redraw();
}
if !dirty.load(Ordering::Relaxed) {
@@ -560,6 +570,7 @@ impl ContentListState {
if tx.send(entry).is_err() {
break; // receiver dropped (instance switched)
}
crate::tui::request_redraw();
}
})
.await;
@@ -623,6 +634,7 @@ impl ContentListState {
self.entries.retain(|entry| entry.path != path);
self.image_protocols.remove(path);
self.requested_images.remove(path);
self.display_metadata.remove(path);
self.images_dirty = true;
if let Some(sel) = self.list_state.selected {
let visible_count = self.filtered_indices().len();
@@ -791,29 +803,23 @@ pub fn render(
state.list_state.selected = Some(count.saturating_sub(1));
}
let snapshot: Vec<SnapshotRow> = filtered
.iter()
.map(|&i| {
let entry = &state.entries[i];
(
entry.name.clone(),
entry.description.clone(),
entry.enabled,
entry.icon_lines.clone(),
entry.icon_bytes.is_some(),
protocol_icon_columns(entry, picker) as usize,
)
})
.collect();
let use_image_protocol =
picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
let entries = &state.entries;
let display_metadata = &state.display_metadata;
let filtered_rows = &filtered;
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let (name, description, enabled, icon_pixels, has_image, protocol_columns) =
&snapshot[context.index];
let entry = &entries[filtered_rows[context.index]];
let name = &entry.name;
let metadata = display_metadata.get(&entry.path);
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 use_mc_colors = *enabled;
let use_mc_colors = enabled;
let stripe_bg = if context.index % 2 == 0 {
theme.background()
@@ -821,7 +827,7 @@ pub fn render(
theme.stripe()
};
let (name_style, description_style, background) = match (*enabled, show_selected) {
let (name_style, description_style, background) = match (enabled, show_selected) {
(true, true) => (
Style::default()
.fg(theme.accent())
@@ -853,9 +859,8 @@ pub fn render(
};
let has_icon = icon_pixels.is_some();
let full_desc = strip_mc_codes(description);
let stripped_desc = full_desc.lines().next().unwrap_or("").trim().to_string();
let has_description = !stripped_desc.is_empty();
let stripped_desc = metadata.map_or("", |metadata| metadata.description.as_str());
let has_description = metadata.is_some_and(|metadata| metadata.has_description);
let compact = !has_icon && !has_description;
let selector = if show_selected {
@@ -890,8 +895,8 @@ pub fn render(
line_0.extend(icon_spans(
icon_pixels.as_ref(),
0,
use_image_protocol && *has_image,
*protocol_columns,
use_image_protocol && has_image,
protocol_columns,
));
line_0.push(Span::raw(" "));
if use_mc_colors {
@@ -907,11 +912,11 @@ pub fn render(
row.extend(icon_spans(
icon_pixels.as_ref(),
1,
use_image_protocol && *has_image,
*protocol_columns,
use_image_protocol && has_image,
protocol_columns,
));
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));
}
@@ -921,8 +926,8 @@ pub fn render(
row.extend(icon_spans(
icon_pixels.as_ref(),
r,
use_image_protocol && *has_image,
*protocol_columns,
use_image_protocol && has_image,
protocol_columns,
));
lines.push(Line::from(row));
}
@@ -948,7 +953,7 @@ pub fn render(
};
lines.push(Line::from(vec![
pad,
Span::styled(stripped_desc.clone(), description_style),
Span::styled(stripped_desc.to_string(), description_style),
]));
}
@@ -1004,11 +1009,10 @@ fn render_image_icons(
continue;
};
let icon_rows = entry.icon_lines.as_ref().map_or(0, Vec::len);
let description = strip_mc_codes(&entry.description);
let has_description = description
.lines()
.next()
.is_some_and(|line| !line.trim().is_empty());
let has_description = state
.display_metadata
.get(&entry.path)
.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 {
@@ -1148,6 +1152,15 @@ fn strip_mc_codes(text: &str) -> String {
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).
// each cell packs two vertical pixels via fg/bg colors, giving
// double the vertical resolution out of the terminal
+17 -5
View File
@@ -37,7 +37,7 @@ pub struct LogsState {
pub viewer_search: super::search::SearchState,
selected_path: Option<std::path::PathBuf>,
pending: PendingLogs,
rescan_counter: u8,
last_rescan: std::time::Instant,
instances_dir_cache: Option<std::path::PathBuf>,
was_live: bool,
}
@@ -59,7 +59,7 @@ impl Default for LogsState {
viewer_search: super::search::SearchState::default(),
selected_path: None,
pending: Arc::new(Mutex::new(None)),
rescan_counter: 0,
last_rescan: std::time::Instant::now(),
instances_dir_cache: None,
was_live: false,
}
@@ -77,6 +77,7 @@ impl LogsState {
self.viewer_scroll = 0;
self.viewer_focused = false;
self.selected_path = None;
self.last_rescan = std::time::Instant::now();
let dir = instances_dir.to_path_buf();
let tag = instance_name.to_string();
@@ -92,6 +93,7 @@ impl LogsState {
if let Ok(mut slot) = pending.lock() {
*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.
// only triggers every 120 ticks to avoid hammering the filesystem
pub fn try_rescan(&mut self) {
self.rescan_counter = self.rescan_counter.wrapping_add(1);
if !self.rescan_counter.is_multiple_of(120) {
if self.last_rescan.elapsed() < std::time::Duration::from_secs(2) {
return;
}
self.last_rescan = std::time::Instant::now();
let (Some(dir), Some(name)) = (&self.instances_dir_cache, &self.loaded_for) else {
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 tag = name.clone();
@@ -153,6 +164,7 @@ impl LogsState {
if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries));
crate::tui::request_redraw();
}
});
}
+2
View File
@@ -92,6 +92,7 @@ impl ScreenshotsState {
if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries));
crate::tui::request_redraw();
}
});
}
@@ -148,6 +149,7 @@ impl ScreenshotsState {
&& let Ok(mut slot) = pending.lock()
{
slot.push((idx, img));
crate::tui::request_redraw();
}
});
}