From 9a1fffae636b770b52cde0ceeebc9b325743fb6d Mon Sep 17 00:00:00 2001 From: letmutex <155220925+letmutex@users.noreply.github.com> Date: Mon, 20 Jul 2026 12:40:57 +0800 Subject: [PATCH 1/2] Fix terminal loader flicker and layout shifts --- src/commands/list.rs | 116 +++++++++++++++++++++++++++++++------ src/tui.rs | 133 +++++++++++++++++++++++++++++++++++++++---- 2 files changed, 221 insertions(+), 28 deletions(-) diff --git a/src/commands/list.rs b/src/commands/list.rs index 6e74bbe..365a50b 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -1,6 +1,7 @@ use crate::models::{Config, save_config}; use crate::tui::{ raw_confirm, raw_input, raw_password, raw_select, raw_show_status, raw_with_loader, + truncate_rendered_line, }; use crate::utils::{git_config_get, git_config_set, git_config_unset, git_credential_approve}; use colored::Colorize; @@ -8,7 +9,7 @@ use crossterm::{ cursor, event::{self, Event, KeyCode, KeyEventKind}, execute, - terminal::{self, ClearType}, + terminal::{self, BeginSynchronizedUpdate, ClearType, EndSynchronizedUpdate, ScrollUp}, }; use std::cmp::min; use std::io::{Write, stdout}; @@ -40,16 +41,21 @@ impl<'a> ListState<'a> { } fn run_loop(&mut self) { - // Setup raw mode terminal::enable_raw_mode().ok(); execute!(stdout(), cursor::Hide).ok(); + self.reserve_transient_space(); self.render(); loop { - let Ok(Event::Key(key)) = event::read() else { + let Ok(event) = event::read() else { continue }; + + if matches!(event, Event::Resize(_, _)) { + self.render(); continue; - }; + } + + let Event::Key(key) = event else { continue }; if key.kind != KeyEventKind::Press { continue; @@ -102,6 +108,38 @@ impl<'a> ListState<'a> { terminal::disable_raw_mode().ok(); } + fn reserve_transient_space(&self) { + const TRANSIENT_ROWS: usize = 4; + + let Ok((_, cursor_row)) = cursor::position() else { + return; + }; + let Ok((_, terminal_rows)) = terminal::size() else { + return; + }; + + let frame_rows = self.build_frame(&self.unmanaged).len(); + let available_rows = usize::from(terminal_rows.saturating_sub(cursor_row)); + let scroll_rows = (frame_rows + TRANSIENT_ROWS) + .saturating_sub(available_rows) + .min(usize::from(cursor_row)); + + if scroll_rows == 0 { + return; + } + + let mut stdout = stdout(); + crossterm::queue!( + stdout, + BeginSynchronizedUpdate, + ScrollUp(scroll_rows as u16), + cursor::MoveUp(scroll_rows as u16), + EndSynchronizedUpdate + ) + .ok(); + stdout.flush().ok(); + } + fn refresh_git(&mut self) { self.git = GitIdentity::fetch(); self.unmanaged = Self::compute_unmanaged(&self.git, self.config); @@ -126,7 +164,7 @@ impl<'a> ListState<'a> { let frame = self.build_frame(unmanaged); let mut stdout = stdout(); - // Move to start of previous frame + crossterm::queue!(stdout, BeginSynchronizedUpdate).ok(); if self.last_rendered_lines > 0 { crossterm::queue!(stdout, cursor::MoveUp(self.last_rendered_lines as u16)).ok(); } @@ -135,14 +173,14 @@ impl<'a> ListState<'a> { for line in &frame { crossterm::queue!( stdout, - terminal::Clear(ClearType::CurrentLine), + cursor::MoveToColumn(0), crossterm::style::Print(line), + terminal::Clear(ClearType::UntilNewLine), crossterm::style::Print("\r\n") ) .ok(); } - // If previous frame was taller, clear leftover lines if frame.len() < self.last_rendered_lines { let extra = self.last_rendered_lines - frame.len(); for _ in 0..extra { @@ -156,23 +194,29 @@ impl<'a> ListState<'a> { crossterm::queue!(stdout, cursor::MoveUp(extra as u16)).ok(); } - // Clear any stale content below the frame (leftover from submenus) - crossterm::queue!(stdout, terminal::Clear(ClearType::FromCursorDown)).ok(); + crossterm::queue!( + stdout, + terminal::Clear(ClearType::FromCursorDown), + EndSynchronizedUpdate + ) + .ok(); stdout.flush().ok(); self.last_rendered_lines = frame.len(); } fn clear_frame(&mut self) { - if self.last_rendered_lines > 0 { - execute!( - stdout(), - cursor::MoveUp(self.last_rendered_lines as u16), - terminal::Clear(ClearType::FromCursorDown) - ) - .ok(); - self.last_rendered_lines = 0; + if self.last_rendered_lines == 0 { + return; } + + execute!( + stdout(), + cursor::MoveUp(self.last_rendered_lines as u16), + terminal::Clear(ClearType::FromCursorDown) + ) + .ok(); + self.last_rendered_lines = 0; } fn compute_unmanaged(git: &GitIdentity, config: &Config) -> Vec<(String, String, String)> { @@ -285,7 +329,15 @@ impl<'a> ListState<'a> { frame.push(format!(" {}", "─".repeat(safe_sep_len).dimmed())); frame.push(String::new()); + + // Leave the rightmost cell untouched to avoid the terminal's automatic + // wrap behavior. This also keeps resize events from changing the number + // of physical rows occupied by a logical frame. + let line_width = (term_cols as usize).saturating_sub(1); frame + .into_iter() + .map(|line| truncate_rendered_line(&line, line_width)) + .collect() } fn format_account_line( @@ -537,7 +589,9 @@ impl<'a> ListState<'a> { return false; } - status_lines.push(String::new()); + if !status_lines.is_empty() { + status_lines.push(String::new()); + } status_lines.push(format!( "{} Switched to '{}' ({})", "✔".green(), @@ -749,3 +803,29 @@ impl GitIdentity { self.local_name.is_some() || self.local_email.is_some() } } + +#[cfg(test)] +mod tests { + use crate::tui::{truncate_rendered_line, visible_line_width}; + + #[test] + fn truncates_rows_before_the_terminal_wrap_column() { + let line = truncate_rendered_line("0123456789", 6); + + assert_eq!(visible_line_width(&line), 6); + assert!(line.starts_with("01234…")); + } + + #[test] + fn ignores_ansi_sequences_when_measuring_rows() { + let line = truncate_rendered_line("\x1b[32mabcdefgh\x1b[0m", 5); + + assert_eq!(visible_line_width(&line), 5); + assert!(line.contains("abcd…")); + } + + #[test] + fn leaves_rows_that_already_fit_untouched() { + assert_eq!(truncate_rendered_line("account", 12), "account"); + } +} diff --git a/src/tui.rs b/src/tui.rs index 717bc6c..31ded3b 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -3,12 +3,97 @@ use crossterm::{ cursor, event::{self, Event, KeyCode, KeyEventKind}, execute, - terminal::{self, ClearType}, + terminal::{self, BeginSynchronizedUpdate, ClearType, EndSynchronizedUpdate}, }; use std::io::{Write, stdout}; use std::thread; use std::time::{Duration, Instant}; +fn character_width(character: char) -> usize { + match character as u32 { + 0x0000..=0x001f | 0x007f..=0x009f | 0x0300..=0x036f => 0, + 0x1100..=0x115f + | 0x2329..=0x232a + | 0x2e80..=0xa4cf + | 0xac00..=0xd7a3 + | 0xf900..=0xfaff + | 0xfe10..=0xfe19 + | 0xfe30..=0xfe6f + | 0xff00..=0xff60 + | 0xffe0..=0xffe6 + | 0x1f300..=0x1faff + | 0x20000..=0x3fffd => 2, + _ => 1, + } +} + +pub(crate) fn visible_line_width(line: &str) -> usize { + let mut in_escape = false; + line.chars() + .filter_map(|character| { + if in_escape { + if character.is_ascii_alphabetic() { + in_escape = false; + } + None + } else if character == '\x1b' { + in_escape = true; + None + } else { + Some(character_width(character)) + } + }) + .sum() +} + +/// Keep a rendered row away from the terminal's last column. Writing into that +/// column can trigger an implicit wrap, which breaks logical-line cursor math. +pub(crate) fn truncate_rendered_line(line: &str, max_width: usize) -> String { + if visible_line_width(line) <= max_width { + return line.to_string(); + } + if max_width == 0 { + return String::new(); + } + + let content_width = max_width - 1; + let mut result = String::new(); + let mut width = 0; + let mut in_escape = false; + + for character in line.chars() { + if in_escape { + result.push(character); + if character.is_ascii_alphabetic() { + in_escape = false; + } + continue; + } + if character == '\x1b' { + in_escape = true; + result.push(character); + continue; + } + + let character_width = character_width(character); + if width + character_width > content_width { + break; + } + result.push(character); + width += character_width; + } + + result.push('…'); + result.push_str("\x1b[0m"); + result +} + +fn terminal_line_width() -> usize { + terminal::size() + .map(|(columns, _)| usize::from(columns).saturating_sub(1)) + .unwrap_or(79) +} + fn prev_char_boundary(value: &str, index: usize) -> usize { value[..index].char_indices().last().map_or(0, |(i, _)| i) } @@ -72,8 +157,10 @@ where F: FnOnce() -> T + Send + 'static, { const FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; - const SHOW_DELAY: Duration = Duration::from_millis(100); - const MIN_VISIBLE_DURATION: Duration = Duration::from_millis(200); + // Fast operations should complete without flashing a loader for a handful of + // frames. Once shown, keep it around long enough to read as intentional UI. + const SHOW_DELAY: Duration = Duration::from_millis(200); + const MIN_VISIBLE_DURATION: Duration = Duration::from_millis(300); const FRAME_INTERVAL: Duration = Duration::from_millis(80); let handle = thread::spawn(work); let mut stdout = stdout(); @@ -89,28 +176,43 @@ where } let shown_at = Instant::now(); + let max_width = terminal_line_width(); while !handle.is_finished() || shown_at.elapsed() < MIN_VISIBLE_DURATION { let line = format!(" {} {}", FRAMES[frame].cyan(), message); - raw_render_lines(&mut stdout, &[line], usize::from(frame > 0)); + let line = truncate_rendered_line(&line, max_width); + // Rewrite only the spinner row. Clearing it and printing a newline on + // every frame caused flashes on terminals without sync support. + crossterm::queue!( + stdout, + cursor::MoveToColumn(0), + crossterm::style::Print(&line) + ) + .ok(); + stdout.flush().ok(); frame = (frame + 1) % FRAMES.len(); thread::sleep(FRAME_INTERVAL); } - raw_clear_lines(&mut stdout, 1); + // Leave the last frame in place. raw_show_status replaces it in the same + // buffered update, avoiding a blank frame between loader and result. handle.join() } /// Render lines at current position using per-line clear (flicker-free). fn raw_render_lines(stdout: &mut impl Write, lines: &[String], prev_count: usize) { + let max_width = terminal_line_width(); + crossterm::queue!(stdout, BeginSynchronizedUpdate).ok(); if prev_count > 0 { crossterm::queue!(stdout, cursor::MoveUp(prev_count as u16)).ok(); } for line in lines { + let line = truncate_rendered_line(line, max_width); crossterm::queue!( stdout, - terminal::Clear(ClearType::CurrentLine), - crossterm::style::Print(line), + cursor::MoveToColumn(0), + crossterm::style::Print(&line), + terminal::Clear(ClearType::UntilNewLine), crossterm::style::Print("\r\n") ) .ok(); @@ -127,6 +229,7 @@ fn raw_render_lines(stdout: &mut impl Write, lines: &[String], prev_count: usize } crossterm::queue!(stdout, cursor::MoveUp(extra as u16)).ok(); } + crossterm::queue!(stdout, EndSynchronizedUpdate).ok(); stdout.flush().ok(); } @@ -135,7 +238,12 @@ pub fn raw_clear_lines(stdout: &mut impl Write, count: usize) { if count == 0 { return; } - crossterm::queue!(stdout, cursor::MoveUp(count as u16)).ok(); + crossterm::queue!( + stdout, + BeginSynchronizedUpdate, + cursor::MoveUp(count as u16) + ) + .ok(); for _ in 0..count { crossterm::queue!( stdout, @@ -144,7 +252,7 @@ pub fn raw_clear_lines(stdout: &mut impl Write, count: usize) { ) .ok(); } - crossterm::queue!(stdout, cursor::MoveUp(count as u16)).ok(); + crossterm::queue!(stdout, cursor::MoveUp(count as u16), EndSynchronizedUpdate).ok(); stdout.flush().ok(); } @@ -448,15 +556,20 @@ pub fn raw_password(prompt: &str) -> Option { /// Show status message lines, sleep, then clear them. pub fn raw_show_status(lines: &[String], has_issue: bool) { let mut stdout = stdout(); + let max_width = terminal_line_width(); + crossterm::queue!(stdout, BeginSynchronizedUpdate, cursor::MoveToColumn(0)).ok(); for line in lines { + let line = truncate_rendered_line(line, max_width); crossterm::queue!( stdout, - crossterm::style::Print(line), + crossterm::style::Print(&line), + terminal::Clear(ClearType::UntilNewLine), crossterm::style::Print("\r\n") ) .ok(); } + crossterm::queue!(stdout, EndSynchronizedUpdate).ok(); stdout.flush().ok(); let duration = Duration::from_millis(status_display_duration_ms(lines.len(), has_issue)); From 12e8a1eafcb17fa62cee990151ef6842c61de787 Mon Sep 17 00:00:00 2001 From: letmutex <155220925+letmutex@users.noreply.github.com> Date: Mon, 20 Jul 2026 15:19:05 +0800 Subject: [PATCH 2/2] Recompute loader width and simplify frame clearing --- src/commands/list.rs | 13 ------------- src/tui.rs | 2 +- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/src/commands/list.rs b/src/commands/list.rs index 365a50b..ab609e6 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -181,19 +181,6 @@ impl<'a> ListState<'a> { .ok(); } - if frame.len() < self.last_rendered_lines { - let extra = self.last_rendered_lines - frame.len(); - for _ in 0..extra { - crossterm::queue!( - stdout, - terminal::Clear(ClearType::CurrentLine), - crossterm::style::Print("\r\n") - ) - .ok(); - } - crossterm::queue!(stdout, cursor::MoveUp(extra as u16)).ok(); - } - crossterm::queue!( stdout, terminal::Clear(ClearType::FromCursorDown), diff --git a/src/tui.rs b/src/tui.rs index 31ded3b..75b6194 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -176,9 +176,9 @@ where } let shown_at = Instant::now(); - let max_width = terminal_line_width(); while !handle.is_finished() || shown_at.elapsed() < MIN_VISIBLE_DURATION { + let max_width = terminal_line_width(); let line = format!(" {} {}", FRAMES[frame].cyan(), message); let line = truncate_rendered_line(&line, max_width); // Rewrite only the spinner row. Clearing it and printing a newline on