Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

Improve TUI resizing, selection, and pane chrome

RoversXc6685c3e9ee8
diff --git a/thinkterm-tui/src/action.rs b/thinkterm-tui/src/action.rs
index f3fda20a..d2cb1be3 100644
--- a/thinkterm-tui/src/action.rs
+++ b/thinkterm-tui/src/action.rs
@@ -73,6 +73,7 @@ pub enum Action {
split_index: usize,
delta: isize,
},
+ FinishSplitResize,
EnterCopyMode,
LeaveCopyMode,
ScrollPane {
diff --git a/thinkterm-tui/src/backend.rs b/thinkterm-tui/src/backend.rs
index 50ac9f21..684cbd2c 100644
--- a/thinkterm-tui/src/backend.rs
+++ b/thinkterm-tui/src/backend.rs
@@ -4,7 +4,7 @@ use ratatui::layout::{Position, Size};
use ratatui::style::{Color, Modifier};
use std::io;
use std::time::Duration;
-use termwiz::cell::{unicode_column_width, AttributeChange, Blink, Intensity, Underline};
+use termwiz::cell::{AttributeChange, Blink, Intensity, Underline};
use termwiz::color::{AnsiColor, ColorAttribute, SrgbaTuple};
use termwiz::input::InputEvent;
use termwiz::surface::{Change, CursorVisibility, Position as TermwizPosition};
@@ -61,6 +61,26 @@ impl<T: Terminal> TermwizBackend<T> {
pub fn waker(&mut self) -> TerminalWaker {
self.terminal.terminal().waker()
}
+
+ /// Re-send the complete buffered surface. Ratatui and Termwiz both keep a
+ /// local model, so an out-of-band host-terminal wrap or width disagreement
+ /// otherwise survives indefinitely because neither model sees a diff.
+ pub fn repaint(&mut self) -> anyhow::Result<()> {
+ Ok(self.terminal.repaint()?)
+ }
+}
+
+fn contiguous_ascii_cursor(x: u16, y: u16, symbol: &str, columns: usize) -> Option<(u16, u16)> {
+ let [byte] = symbol.as_bytes() else {
+ return None;
+ };
+ if !byte.is_ascii_graphic() && *byte != b' ' {
+ return None;
+ }
+ let next = x.saturating_add(1);
+ // Never predict through the right margin. Terminals disagree over whether
+ // the cursor is already wrapped or is in a pending-wrap state there.
+ (next < columns.min(u16::MAX as usize) as u16).then_some((next, y))
}
impl<T: Terminal> Backend for TermwizBackend<T> {
@@ -78,6 +98,7 @@ impl<T: Terminal> Backend for TermwizBackend<T> {
// does not. Emit each only where it actually differs.
let mut pen: Option<Pen> = None;
let mut cursor: Option<(u16, u16)> = None;
+ let (columns, _) = self.terminal.dimensions();
for (x, y, cell) in content {
if cursor != Some((x, y)) {
self.terminal.add_change(Change::CursorPosition {
@@ -88,14 +109,7 @@ impl<T: Terminal> Backend for TermwizBackend<T> {
let next = Pen::of(cell);
let changed = pen != Some(next);
pen = Some(next);
- cursor = Some((
- x.saturating_add(
- unicode_column_width(cell.symbol(), None)
- .max(1)
- .min(u16::MAX as usize) as u16,
- ),
- y,
- ));
+ cursor = contiguous_ascii_cursor(x, y, cell.symbol(), columns);
if !changed {
self.terminal
.add_change(Change::Text(cell.symbol().to_string()));
@@ -302,4 +316,13 @@ mod tests {
ColorAttribute::TrueColorWithPaletteFallback(_, _)
));
}
+
+ #[test]
+ fn cursor_elision_is_limited_to_safe_ascii_before_the_margin() {
+ assert_eq!(contiguous_ascii_cursor(4, 2, "x", 20), Some((5, 2)));
+ assert_eq!(contiguous_ascii_cursor(4, 2, " ", 20), Some((5, 2)));
+ assert_eq!(contiguous_ascii_cursor(19, 2, "x", 20), None);
+ assert_eq!(contiguous_ascii_cursor(4, 2, "界", 20), None);
+ assert_eq!(contiguous_ascii_cursor(4, 2, "e\u{301}", 20), None);
+ }
}
diff --git a/thinkterm-tui/src/lib.rs b/thinkterm-tui/src/lib.rs
index 4880cfbe..2da1d484 100644
--- a/thinkterm-tui/src/lib.rs
+++ b/thinkterm-tui/src/lib.rs
@@ -22,8 +22,8 @@ use mux::domain::{Domain, DomainState, SplitSource};
use mux::pane::{Pane, PaneId, Pattern};
use mux::tab::{SplitDirection, SplitRequest, SplitSize, Tab, TabId};
use mux::{Mux, MuxNotification};
-use ratatui::Terminal;
use ratatui::backend::Backend;
+use ratatui::Terminal;
use settings::{TuiConfig, TuiPersistentState};
use state::{
AppMode, ConfirmationState, ConnectionItem, ConnectionStatus, ContextMenuState, CopyState,
@@ -39,7 +39,7 @@ use termwiz::caps::{Capabilities, ProbeHints};
use termwiz::input::{
InputEvent, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseEvent as TermwizMouseEvent,
};
-use termwiz::terminal::{ScreenSize, TerminalWaker, new_terminal};
+use termwiz::terminal::{new_terminal, ScreenSize, TerminalWaker};
use uuid::Uuid;
use view::{HitTarget, PaneTool, TabBarControl, TreeAction, ViewLayout};
use wezterm_client::client::Client;
@@ -47,8 +47,8 @@ use wezterm_client::domain::{
ClientDomain, ClientDomainConfig, FrontendRecoverySlot, RemoteFrontendGate,
};
use wezterm_client::pane::ClientPane;
-use wezterm_term::TerminalSize;
use wezterm_term::input::{MouseButton, MouseEvent, MouseEventKind};
+use wezterm_term::TerminalSize;
static EVENT_SENDER: OnceLock<Sender<AppEvent>> = OnceLock::new();
static TERMINAL_WAKER: OnceLock<TerminalWaker> = OnceLock::new();
@@ -91,6 +91,27 @@ const TAKEOVER_RESYNC_RETRY_DELAY: Duration = Duration::from_millis(250);
/// takeover surface opaque until the acknowledged grid and all of its visible
/// rows have stayed ready long enough for that redraw to land.
const TAKEOVER_GEOMETRY_SETTLE: Duration = Duration::from_millis(200);
+/// After the final divider target is acknowledged, give the PTYs enough time
+/// to echo that geometry and refill the visible row cache before unpinning the
+/// local preview.
+const SPLIT_DRAG_CONFIRM_TIMEOUT: Duration = Duration::from_secs(2);
+/// A local divider follows every mouse event, while PTY resizes are capped at
+/// one per display-frame interval. The final release target bypasses this cap.
+const SPLIT_DRAG_RPC_INTERVAL: Duration = Duration::from_millis(16);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum NativeViewportPreview {
+ Takeover(u64),
+ SplitDrag(u64),
+}
+
+impl NativeViewportPreview {
+ fn epoch(self) -> u64 {
+ match self {
+ Self::Takeover(epoch) | Self::SplitDrag(epoch) => epoch,
+ }
+ }
+}
#[derive(Default)]
struct TakeoverEpochs {
@@ -198,6 +219,7 @@ impl TakeoverPreviews {
#[derive(Clone, Debug)]
struct TakeoverGeometryConfirmation {
epoch: u64,
+ started_at: Instant,
screen_size: ScreenSize,
root_size: TerminalSize,
/// Visible panes whose rendered rows must be fetched before the handoff
@@ -209,6 +231,79 @@ struct TakeoverGeometryConfirmation {
acknowledged_panes: Vec<(PaneId, TerminalSize)>,
access_generation: u64,
ready_since: Option<Instant>,
+ last_wait_reason: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct PreparedSplitDragGeometry {
+ viewport: ClientViewport,
+ visible_panes: Vec<(PaneId, TerminalSize)>,
+ acknowledged_panes: Vec<(PaneId, TerminalSize)>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum SplitDragGeometryPhase {
+ Dragging,
+ Finishing,
+ Confirming {
+ committed_at: Instant,
+ ready_since: Option<Instant>,
+ },
+}
+
+fn split_drag_target_is_owed(
+ in_flight: Option<&ClientViewport>,
+ acknowledged: Option<&ClientViewport>,
+ target: &ClientViewport,
+) -> bool {
+ in_flight != Some(target) && acknowledged != Some(target)
+}
+
+fn split_drag_can_pump(phase: SplitDragGeometryPhase, in_flight: bool, has_pending: bool) -> bool {
+ !matches!(phase, SplitDragGeometryPhase::Confirming { .. }) && !in_flight && has_pending
+}
+
+fn split_drag_pump_delay(state: &TuiState, now: Instant) -> Option<Duration> {
+ let preview = state.split_drag_geometry.as_ref()?;
+ if !split_drag_can_pump(
+ preview.phase,
+ preview.in_flight.is_some(),
+ preview.pending.is_some(),
+ ) {
+ return None;
+ }
+ if preview.phase == SplitDragGeometryPhase::Finishing {
+ return Some(Duration::ZERO);
+ }
+ Some(preview.last_sent_at.map_or(Duration::ZERO, |sent| {
+ SPLIT_DRAG_RPC_INTERVAL.saturating_sub(now.saturating_duration_since(sent))
+ }))
+}
+
+#[derive(Clone, Debug)]
+struct SplitDragGeometryPreview {
+ epoch: u64,
+ cache_key: (String, TabId),
+ local_tab_id: TabId,
+ connection_generation: u64,
+ phase: SplitDragGeometryPhase,
+ latest: Option<PreparedSplitDragGeometry>,
+ pending: Option<PreparedSplitDragGeometry>,
+ in_flight: Option<ClientViewport>,
+ last_acknowledged: Option<ClientViewport>,
+ last_sent_at: Option<Instant>,
+ /// A pane can enter or leave a stack while a drag is in progress. Remember
+ /// the newest previewed size for every touched surface so cancellation
+ /// cannot leave an old epoch pinned behind.
+ touched_panes: HashMap<PaneId, TerminalSize>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct SplitDragResyncKey {
+ cache_key: (String, TabId),
+ local_tab_id: TabId,
+ epoch: u64,
+ connection_generation: u64,
}
fn takeover_geometry_settled(ready: bool, now: Instant, ready_since: &mut Option<Instant>) -> bool {
@@ -278,6 +373,18 @@ enum AppEvent {
domain_name: String,
connection_generation: u64,
},
+ SplitDragViewportFinished {
+ cache_key: (String, TabId),
+ local_tab_id: TabId,
+ epoch: u64,
+ connection_generation: u64,
+ sent: ClientViewport,
+ result: std::result::Result<codec::ClientViewportState, String>,
+ },
+ SplitDragResyncFinished {
+ key: SplitDragResyncKey,
+ result: std::result::Result<(), String>,
+ },
}
/// Whether a wake has been delivered that the loop has not yet acted on.
@@ -801,6 +908,17 @@ struct TuiState {
/// The latest size is required to clear ClientPane::requested_size on a
/// failed/cancelled preview without disturbing a newer epoch.
takeover_previews: TakeoverPreviews,
+ /// Divider drags render immediately against a local ClientPane preview and
+ /// stream Native viewports without blocking input: one request may be in
+ /// flight and one replaceable latest target may wait behind it. That keeps
+ /// live PTY resize while preventing an unbounded stale-request queue.
+ split_drag_geometry: Option<SplitDragGeometryPreview>,
+ /// Identifies the only divider recovery whose completion may update the
+ /// UI. Late results from an older connection or drag epoch are ignored.
+ split_drag_resync: Option<SplitDragResyncKey>,
+ /// Split previews occupy the high half of the epoch space so they cannot
+ /// collide with takeover epochs on the same ClientPane.
+ next_split_drag_epoch: u64,
/// When the panes were last asked for new content, so the loop keeps asking
/// even while nothing local has changed.
last_pane_poll: Instant,
@@ -831,6 +949,10 @@ struct TuiState {
/// the whole window. Only the forced redraw consults this — a frame that
/// something actually asked for still draws at once.
last_draw: Instant,
+ /// Request one complete Termwiz surface repaint after a live resize has
+ /// converged. This repairs any host-terminal cursor/wrap divergence that a
+ /// normal Ratatui diff cannot observe.
+ terminal_repaint_pending: bool,
/// Current transport generation accepted for each domain. Session pushes
/// from any other generation are stale even when the restarted server has
/// the same runtime id and a numerically newer snapshot generation.
@@ -904,6 +1026,7 @@ impl TuiState {
ui.touch_targets = settings.touch_targets;
ui.pane_scrollbars = settings.pane_scrollbars;
ui.pane_borders = settings.pane_borders;
+ ui.show_status_bar = settings.show_status_bar;
ui.pane_nav_bar = settings.pane_nav_bar;
ui.connections = connections;
if no_attached_domain {
@@ -920,6 +1043,9 @@ impl TuiState {
takeover_epochs: TakeoverEpochs::default(),
takeover_geometry_confirmations: HashMap::new(),
takeover_previews: TakeoverPreviews::default(),
+ split_drag_geometry: None,
+ split_drag_resync: None,
+ next_split_drag_epoch: 1 << 63,
last_pane_poll: Instant::now(),
shared_views: HashMap::new(),
shared_view_at: HashMap::new(),
@@ -929,6 +1055,7 @@ impl TuiState {
resize_settles_at: None,
redraw_until: None,
last_draw: Instant::now(),
+ terminal_repaint_pending: false,
connection_generations,
refresh_sessions: HashSet::new(),
actions: VecDeque::new(),
@@ -960,6 +1087,26 @@ impl TuiState {
Some((domain_name, remote_tab_id))
}
+ fn allocate_split_drag_epoch(&mut self) -> u64 {
+ let epoch = self.next_split_drag_epoch;
+ self.next_split_drag_epoch = self.next_split_drag_epoch.wrapping_add(1) | (1 << 63);
+ epoch
+ }
+
+ fn active_split_drag_epoch(&self) -> Option<u64> {
+ let preview = self.split_drag_geometry.as_ref()?;
+ if self.active_view_cache_key().as_ref() != Some(&preview.cache_key) {
+ return None;
+ }
+ let domain = self.domains.get(&preview.cache_key.0)?;
+ if domain.connection_generation() != Some(preview.connection_generation)
+ || domain.owns_remote_viewport(preview.local_tab_id) != Some(true)
+ {
+ return None;
+ }
+ Some(preview.epoch)
+ }
+
fn active_pane(&self) -> Option<Arc<dyn Pane>> {
self.active_tab()?.2.get_active_pane()
}
@@ -1172,7 +1319,8 @@ async fn run_terminal(
WAKE_PENDING.store(false, Ordering::Release);
drain_events(&receiver, &mut state);
refresh_sessions(&mut state).await;
- if state.ui.expire_toast(std::time::Instant::now()) {
+ let notice_now = Instant::now();
+ if state.ui.expire_toast(notice_now) | state.ui.expire_status(notice_now) {
state.dirty = true;
}
@@ -1242,8 +1390,13 @@ async fn run_terminal(
}
}
+ if split_drag_pump_delay(&state, Instant::now()) == Some(Duration::ZERO) {
+ pump_split_drag_geometry(&mut state);
+ }
+
if state.dirty {
cancel_inactive_takeover_geometry(&mut state);
+ cancel_inactive_split_drag_geometry(&mut state);
if let Ok(screen) = terminal.backend_mut().screen_size() {
state.screen_size = Some(screen);
let area: ratatui::layout::Rect = terminal.size()?.into();
@@ -1252,14 +1405,26 @@ async fn run_terminal(
.pending_frontend_recovery(FrontendRecoverySlot::Primary, tab.tab_id())
.is_some()
});
- let preview_epoch = state.ensure_active_handoff_geometry_epoch();
- prepare_active_native_viewport(
+ let preview = if let Some(epoch) = state.active_split_drag_epoch() {
+ Some(NativeViewportPreview::SplitDrag(epoch))
+ } else {
+ state
+ .ensure_active_handoff_geometry_epoch()
+ .map(NativeViewportPreview::Takeover)
+ };
+ let viewport = prepare_active_native_viewport(
&mut state,
area,
screen,
recovery_pending,
- preview_epoch,
+ preview,
);
+ if matches!(preview, Some(NativeViewportPreview::SplitDrag(_))) {
+ if let Some(viewport) = viewport.as_ref() {
+ record_split_drag_geometry(&mut state, viewport);
+ pump_split_drag_geometry(&mut state);
+ }
+ }
}
let active = state.active_tab();
let local_tab = active.as_ref().map(|(_, _, tab, _)| Arc::clone(tab));
@@ -1288,6 +1453,12 @@ async fn run_terminal(
&state.settings,
);
})?;
+ if std::mem::take(&mut state.terminal_repaint_pending) {
+ terminal
+ .backend_mut()
+ .repaint()
+ .context("repainting the converged divider surface")?;
+ }
state.layout = next_layout;
state.last_draw = Instant::now();
// Cleared before the trip to the server, never after — the same
@@ -1299,10 +1470,15 @@ async fn run_terminal(
report_viewport_if_changed(&mut state, rendered.selected_tab, terminal.backend_mut())
.await;
advance_takeover_geometry_confirmation(&mut state);
+ advance_split_drag_geometry_confirmation(&mut state);
}
let now = Instant::now();
- let mut wait = input_progress_wait(state.ui.toast_timeout(now), input_progress_until, now);
+ let notice_wait = match (state.ui.toast_timeout(now), state.ui.status_timeout(now)) {
+ (Some(toast), Some(status)) => Some(toast.min(status)),
+ (toast, status) => toast.or(status),
+ };
+ let mut wait = input_progress_wait(notice_wait, input_progress_until, now);
// Nothing external will wake the loop to ask again, so the next ask has
// to be one of the things the input poll waits on.
let until_poll =
@@ -1338,6 +1514,9 @@ async fn run_terminal(
let remaining = deadline.saturating_duration_since(now);
wait = Some(wait.map_or(remaining, |wait| wait.min(remaining)));
}
+ if let Some(remaining) = split_drag_pump_delay(&state, now) {
+ wait = Some(wait.map_or(remaining, |wait| wait.min(remaining)));
+ }
if let Some(first) = terminal.backend_mut().poll_input(wait)? {
// Termwiz may decode a single tty read into many key events. Drain
// that ready queue before drawing so fast typing costs one frame
@@ -1499,6 +1678,23 @@ fn drain_events(receiver: &Receiver<AppEvent>, state: &mut TuiState) {
});
if current {
cancel_takeover_geometry_for_domain(state, &domain_name);
+ if state
+ .split_drag_resync
+ .as_ref()
+ .is_some_and(|resync| resync.cache_key.0 == domain_name)
+ {
+ state.split_drag_resync = None;
+ if state.ui.status == "Divider resize is resyncing" {
+ state.ui.status.clear();
+ }
+ }
+ if state
+ .split_drag_geometry
+ .as_ref()
+ .is_some_and(|preview| preview.cache_key.0 == domain_name)
+ {
+ cancel_split_drag_geometry(state, false);
+ }
connection_changed = true;
state
.connection_generations
@@ -1526,6 +1722,46 @@ fn drain_events(receiver: &Receiver<AppEvent>, state: &mut TuiState) {
state.dirty = true;
}
}
+ AppEvent::SplitDragViewportFinished {
+ cache_key,
+ local_tab_id,
+ epoch,
+ connection_generation,
+ sent,
+ result,
+ } => finish_split_drag_viewport_request(
+ state,
+ cache_key,
+ local_tab_id,
+ epoch,
+ connection_generation,
+ sent,
+ result,
+ ),
+ AppEvent::SplitDragResyncFinished { key, result } => {
+ if state.split_drag_resync.as_ref() == Some(&key) {
+ state.split_drag_resync = None;
+ let current_generation = state
+ .domains
+ .get(&key.cache_key.0)
+ .and_then(|domain| domain.connection_generation());
+ if current_generation != Some(key.connection_generation) {
+ continue;
+ }
+ match result {
+ Ok(()) => {
+ if state.ui.status == "Divider resize is resyncing" {
+ state.ui.status.clear();
+ }
+ state.terminal_repaint_pending = true;
+ }
+ Err(err) => {
+ state.ui.status = format!("Divider resize recovery failed: {err}");
+ }
+ }
+ state.dirty = true;
+ }
+ }
AppEvent::Mux(notification) => {
if notification_refreshes_session(&notification) {
state.refresh_sessions.extend(state.domains.keys().cloned());
@@ -1605,7 +1841,7 @@ fn prepare_active_native_viewport(
area: ratatui::layout::Rect,
screen: ScreenSize,
force: bool,
- preview_epoch: Option<u64>,
+ preview: Option<NativeViewportPreview>,
) -> Option<ClientViewport> {
let (domain_name, domain, tab, remote_tab_id) = state.active_tab()?;
if !force && domain.owns_remote_viewport(tab.tab_id()) != Some(true) {
@@ -1651,14 +1887,22 @@ fn prepare_active_native_viewport(
for pane in &panes {
let handle = Mux::get().get_pane(pane.pane_id)?;
let client = handle.downcast_ref::<ClientPane>()?;
- if let Some(epoch) = preview_epoch {
- client.preview_frontend_geometry(epoch, pane.size);
- state.takeover_previews.record(
- &(domain_name.clone(), remote_tab_id),
- epoch,
- pane.pane_id,
- pane.size,
- );
+ if let Some(preview) = preview {
+ let epoch = preview.epoch();
+ match preview {
+ NativeViewportPreview::Takeover(_) => {
+ client.preview_frontend_geometry(epoch, pane.size);
+ state.takeover_previews.record(
+ &(domain_name.clone(), remote_tab_id),
+ epoch,
+ pane.pane_id,
+ pane.size,
+ );
+ }
+ NativeViewportPreview::SplitDrag(_) => {
+ client.preview_live_frontend_geometry(epoch, pane.size);
+ }
+ }
} else {
client.adopt_frontend_geometry(pane.size);
}
@@ -1759,6 +2003,7 @@ fn begin_takeover_geometry_confirmation(
let ClientViewport::Native { size, panes } = viewport else {
return;
};
+ let started_at = Instant::now();
let visible_pane_ids = state
.layout
.panes
@@ -1767,17 +2012,32 @@ fn begin_takeover_geometry_confirmation(
.collect::<Vec<_>>();
let visible_panes = visible_takeover_targets(&visible_pane_ids, panes);
state.takeover_geometry_confirmations.insert(
- cache_key,
+ cache_key.clone(),
TakeoverGeometryConfirmation {
epoch,
+ started_at,
screen_size,
root_size: *size,
- panes: visible_panes,
+ panes: visible_panes.clone(),
acknowledged_panes: panes.iter().map(|pane| (pane.pane_id, pane.size)).collect(),
access_generation,
ready_since: None,
+ last_wait_reason: None,
},
);
+ mux::zoom_trace!(
+ "tui.takeover.begin tab={}/r{} epoch={} access_gen={} root={} panes=[{}]",
+ cache_key.0,
+ cache_key.1,
+ epoch,
+ access_generation,
+ mux::geometrytrace::size(size),
+ visible_panes
+ .iter()
+ .map(|(pane_id, size)| format!("{}:{}", pane_id, mux::geometrytrace::size(size)))
+ .collect::<Vec<_>>()
+ .join(" ")
+ );
state.redraw_until = Some(Instant::now() + RESIZE_REDRAW_WINDOW);
state.dirty = true;
}
@@ -1797,6 +2057,510 @@ fn visible_takeover_targets(
.collect()
}
+fn finish_split_drag_preview_panes(
+ preview: &SplitDragGeometryPreview,
+ confirmed: Option<&[(PaneId, TerminalSize)]>,
+) {
+ for (pane_id, size) in &preview.touched_panes {
+ let succeeded = confirmed.is_some_and(|panes| {
+ panes.iter().any(|(confirmed_id, confirmed_size)| {
+ confirmed_id == pane_id && confirmed_size == size
+ })
+ });
+ if let Some(handle) = Mux::get().get_pane(*pane_id) {
+ if let Some(client) = handle.downcast_ref::<ClientPane>() {
+ client.finish_frontend_geometry_preview(preview.epoch, *size, succeeded);
+ }
+ }
+ }
+}
+
+fn schedule_split_drag_resync(preview: &SplitDragGeometryPreview, state: &mut TuiState) {
+ let Some(domain) = state.domains.get(&preview.cache_key.0).cloned() else {
+ return;
+ };
+ if domain.connection_generation() != Some(preview.connection_generation) {
+ return;
+ }
+ let key = SplitDragResyncKey {
+ cache_key: preview.cache_key.clone(),
+ local_tab_id: preview.local_tab_id,
+ epoch: preview.epoch,
+ connection_generation: preview.connection_generation,
+ };
+ state.split_drag_resync = Some(key.clone());
+ state
+ .ui
+ .set_persistent_status("Divider resize is resyncing");
+ promise::spawn::spawn(async move {
+ let result = domain.resync().await.map_err(|err| format!("{err:#}"));
+ send_event(AppEvent::SplitDragResyncFinished { key, result });
+ Ok::<(), anyhow::Error>(())
+ })
+ .detach();
+}
+
+fn cancel_split_drag_geometry(state: &mut TuiState, resync: bool) {
+ let Some(preview) = state.split_drag_geometry.take() else {
+ return;
+ };
+ finish_split_drag_preview_panes(&preview, None);
+ if resync {
+ schedule_split_drag_resync(&preview, state);
+ }
+ log::debug!(
+ target: "zoomtrace",
+ "tui.split_drag.cancel tab={}/r{} epoch={} resync={resync}",
+ preview.local_tab_id,
+ preview.cache_key.1,
+ preview.epoch,
+ );
+ state.dirty = true;
+}
+
+fn complete_split_drag_geometry(state: &mut TuiState, epoch: u64) {
+ let Some(preview) = state.split_drag_geometry.take() else {
+ return;
+ };
+ if preview.epoch != epoch {
+ state.split_drag_geometry = Some(preview);
+ return;
+ }
+ let confirmed = preview
+ .latest
+ .as_ref()
+ .map(|latest| latest.acknowledged_panes.as_slice());
+ finish_split_drag_preview_panes(&preview, confirmed);
+ log::debug!(
+ target: "zoomtrace",
+ "tui.split_drag.complete tab={}/r{} epoch={}",
+ preview.local_tab_id,
+ preview.cache_key.1,
+ preview.epoch,
+ );
+ state.terminal_repaint_pending = true;
+ state.dirty = true;
+}
+
+fn begin_split_drag_geometry(state: &mut TuiState) -> Result<u64> {
+ let (domain_name, domain, tab, remote_tab_id) =
+ state.active_tab().context("no live tab selected")?;
+ let connection_generation = domain
+ .connection_generation()
+ .context("terminal connection generation is unavailable")?;
+ let cache_key = (domain_name, remote_tab_id);
+ if let Some(preview) = state.split_drag_geometry.as_ref() {
+ if preview.cache_key == cache_key
+ && preview.local_tab_id == tab.tab_id()
+ && preview.connection_generation == connection_generation
+ && preview.phase == SplitDragGeometryPhase::Dragging
+ {
+ return Ok(preview.epoch);
+ }
+ }
+
+ if let Some(prior) = state.split_drag_geometry.take() {
+ if matches!(prior.phase, SplitDragGeometryPhase::Confirming { .. }) {
+ let confirmed = prior
+ .latest
+ .as_ref()
+ .map(|latest| latest.acknowledged_panes.as_slice());
+ finish_split_drag_preview_panes(&prior, confirmed);
+ } else {
+ finish_split_drag_preview_panes(&prior, None);
+ schedule_split_drag_resync(&prior, state);
+ }
+ }
+
+ let epoch = state.allocate_split_drag_epoch();
+ state.split_drag_geometry = Some(SplitDragGeometryPreview {
+ epoch,
+ cache_key: cache_key.clone(),
+ local_tab_id: tab.tab_id(),
+ connection_generation,
+ phase: SplitDragGeometryPhase::Dragging,
+ latest: None,
+ pending: None,
+ in_flight: None,
+ last_acknowledged: None,
+ last_sent_at: None,
+ touched_panes: HashMap::new(),
+ });
+ log::debug!(
+ target: "zoomtrace",
+ "tui.split_drag.begin tab={}/r{} epoch={} gen={connection_generation}",
+ tab.tab_id(),
+ remote_tab_id,
+ epoch,
+ );
+ Ok(epoch)
+}
+
+fn record_split_drag_geometry(state: &mut TuiState, viewport: &ClientViewport) {
+ let ClientViewport::Native { panes, .. } = viewport else {
+ return;
+ };
+ let visible_pane_ids = state
+ .layout
+ .panes
+ .iter()
+ .map(|pane| pane.pane_id)
+ .collect::<Vec<_>>();
+ let prepared = PreparedSplitDragGeometry {
+ viewport: viewport.clone(),
+ visible_panes: visible_takeover_targets(&visible_pane_ids, panes),
+ acknowledged_panes: panes.iter().map(|pane| (pane.pane_id, pane.size)).collect(),
+ };
+ let Some(preview) = state.split_drag_geometry.as_mut() else {
+ return;
+ };
+ if matches!(preview.phase, SplitDragGeometryPhase::Confirming { .. }) {
+ return;
+ }
+ for (pane_id, size) in &prepared.acknowledged_panes {
+ preview.touched_panes.insert(*pane_id, *size);
+ }
+ preview.latest = Some(prepared.clone());
+ preview.pending = split_drag_target_is_owed(
+ preview.in_flight.as_ref(),
+ preview.last_acknowledged.as_ref(),
+ &prepared.viewport,
+ )
+ .then_some(prepared);
+}
+
+fn finish_split_drag(state: &mut TuiState) {
+ let active_epoch = state.active_split_drag_epoch();
+ let Some(preview) = state.split_drag_geometry.as_mut() else {
+ return;
+ };
+ if active_epoch != Some(preview.epoch) {
+ cancel_split_drag_geometry(state, true);
+ return;
+ }
+ if preview.phase == SplitDragGeometryPhase::Dragging {
+ preview.phase = SplitDragGeometryPhase::Finishing;
+ if let Some(latest) = preview.latest.as_ref() {
+ if split_drag_target_is_owed(
+ preview.in_flight.as_ref(),
+ preview.last_acknowledged.as_ref(),
+ &latest.viewport,
+ ) {
+ preview.pending = Some(latest.clone());
+ }
+ }
+ state.dirty = true;
+ }
+}
+
+fn maybe_begin_split_drag_confirmation(state: &mut TuiState) {
+ let Some(preview) = state.split_drag_geometry.as_mut() else {
+ return;
+ };
+ if preview.phase != SplitDragGeometryPhase::Finishing
+ || preview.in_flight.is_some()
+ || preview.pending.is_some()
+ || preview.latest.as_ref().map(|latest| &latest.viewport)
+ != preview.last_acknowledged.as_ref()
+ {
+ return;
+ }
+ let now = Instant::now();
+ preview.phase = SplitDragGeometryPhase::Confirming {
+ committed_at: now,
+ ready_since: None,
+ };
+ let redraw_until = now + SPLIT_DRAG_CONFIRM_TIMEOUT;
+ state.redraw_until = Some(
+ state
+ .redraw_until
+ .map_or(redraw_until, |existing| existing.max(redraw_until)),
+ );
+ state.dirty = true;
+}
+
+fn pump_split_drag_geometry(state: &mut TuiState) {
+ let Some(preview) = state.split_drag_geometry.as_mut() else {
+ return;
+ };
+ if !split_drag_can_pump(
+ preview.phase,
+ preview.in_flight.is_some(),
+ preview.pending.is_some(),
+ ) {
+ maybe_begin_split_drag_confirmation(state);
+ return;
+ }
+ let now = Instant::now();
+ let release_is_waiting = preview.phase == SplitDragGeometryPhase::Finishing;
+ if !release_is_waiting
+ && preview
+ .last_sent_at
+ .is_some_and(|sent| now.duration_since(sent) < SPLIT_DRAG_RPC_INTERVAL)
+ {
+ return;
+ }
+ let Some(prepared) = preview.pending.take() else {
+ return;
+ };
+ let cache_key = preview.cache_key.clone();
+ let local_tab_id = preview.local_tab_id;
+ let epoch = preview.epoch;
+ let connection_generation = preview.connection_generation;
+ let sent = prepared.viewport;
+ preview.in_flight = Some(sent.clone());
+ preview.last_sent_at = Some(now);
+
+ let Some(domain) = state.domains.get(&cache_key.0).cloned() else {
+ cancel_split_drag_geometry(state, false);
+ return;
+ };
+ if domain.connection_generation() != Some(connection_generation) {
+ cancel_split_drag_geometry(state, false);
+ return;
+ }
+ for candidate in state.domains.values() {
+ if candidate.domain_id() != domain.domain_id() {
+ candidate.clear_frontend_recovery_intent(FrontendRecoverySlot::Primary);
+ }
+ }
+ if let Err(err) =
+ domain.set_frontend_recovery_intent(FrontendRecoverySlot::Primary, local_tab_id, &sent)
+ {
+ log::trace!("recording TUI divider recovery intent: {err:#}");
+ }
+ log::debug!(
+ target: "zoomtrace",
+ "tui.split_drag.send tab={}/r{} epoch={} finishing={}",
+ local_tab_id,
+ cache_key.1,
+ epoch,
+ matches!(
+ state
+ .split_drag_geometry
+ .as_ref()
+ .map(|preview| preview.phase),
+ Some(SplitDragGeometryPhase::Finishing)
+ ),
+ );
+ promise::spawn::spawn(async move {
+ let result = domain
+ .set_client_viewport(local_tab_id, sent.clone())
+ .await
+ .map_err(|err| format!("{err:#}"));
+ send_event(AppEvent::SplitDragViewportFinished {
+ cache_key,
+ local_tab_id,
+ epoch,
+ connection_generation,
+ sent,
+ result,
+ });
+ Ok::<(), anyhow::Error>(())
+ })
+ .detach();
+}
+
+fn finish_split_drag_viewport_request(
+ state: &mut TuiState,
+ cache_key: (String, TabId),
+ local_tab_id: TabId,
+ epoch: u64,
+ connection_generation: u64,
+ sent: ClientViewport,
+ result: std::result::Result<codec::ClientViewportState, String>,
+) {
+ let valid = state.split_drag_geometry.as_ref().is_some_and(|preview| {
+ preview.cache_key == cache_key
+ && preview.local_tab_id == local_tab_id
+ && preview.epoch == epoch
+ && preview.connection_generation == connection_generation
+ && preview.in_flight.as_ref() == Some(&sent)
+ });
+ if !valid {
+ return;
+ }
+ let Some(domain) = state.domains.get(&cache_key.0).cloned() else {
+ cancel_split_drag_geometry(state, false);
+ return;
+ };
+ let Ok(response) = result else {
+ let err = result.unwrap_err();
+ cancel_split_drag_geometry(state, true);
+ state.ui.status = format!("Divider resize: {err}");
+ return;
+ };
+ if domain.connection_generation() != Some(connection_generation)
+ || domain.owns_remote_viewport(local_tab_id) != Some(true)
+ {
+ cancel_split_drag_geometry(state, true);
+ state.ui.status = "Divider resize lost terminal ownership".to_string();
+ return;
+ }
+
+ state.last_viewports.insert(
+ cache_key.clone(),
+ Some((sent.clone(), true, Some(response.access.mode))),
+ );
+ adopt_local_tab_size(
+ local_tab_id,
+ local_tab_size(&domain, local_tab_id, sent.size(), response.canonical_size),
+ );
+ if response.access.mode == codec::FrontendAccessMode::Handoff {
+ state
+ .handoff_geometry_ready
+ .insert(cache_key.clone(), response.access.generation);
+ }
+ let final_target_was_acknowledged = state.split_drag_geometry.as_ref().is_some_and(|preview| {
+ preview.phase == SplitDragGeometryPhase::Finishing
+ && preview
+ .latest
+ .as_ref()
+ .is_some_and(|latest| latest.viewport == sent)
+ });
+ // A TabResized-triggered resync can finish beside the final viewport ack.
+ // For an unchanged topology it normally preserves local split geometry,
+ // but the TUI's per-pane chrome can leave a one-cell reconstruction
+ // difference. Reapply only the *final* acknowledged frame set; doing this
+ // for intermediate live acks would pull the divider backwards under the
+ // pointer.
+ if final_target_was_acknowledged {
+ if let (Some(tab), ClientViewport::Native { panes, .. }) =
+ (Mux::get().get_tab(local_tab_id), &sent)
+ {
+ let frames = panes
+ .iter()
+ .map(|pane| (pane.pane_id, pane.frame))
+ .collect::<Vec<_>>();
+ if let Err(err) = tab.rebuild_splits_sizes_from_frontend_frames(&frames) {
+ log::warn!("restoring final TUI divider geometry: {err:#}");
+ }
+ }
+ }
+ if let Some(preview) = state
+ .split_drag_geometry
+ .as_mut()
+ .filter(|preview| preview.epoch == epoch)
+ {
+ preview.in_flight = None;
+ preview.last_acknowledged = Some(sent);
+ }
+ state.dirty = true;
+ pump_split_drag_geometry(state);
+}
+
+fn cancel_inactive_split_drag_geometry(state: &mut TuiState) {
+ let Some(epoch) = state
+ .split_drag_geometry
+ .as_ref()
+ .map(|preview| preview.epoch)
+ else {
+ return;
+ };
+ if state.active_split_drag_epoch() != Some(epoch) {
+ cancel_split_drag_geometry(state, true);
+ }
+}
+
+fn active_layout_matches_split_drag(
+ state: &TuiState,
+ tab: &Arc<Tab>,
+ prepared: &PreparedSplitDragGeometry,
+) -> bool {
+ if tab.get_size() != prepared.viewport.size() {
+ return false;
+ }
+ let Some(screen) = state.screen_size else {
+ return false;
+ };
+ let current = state
+ .layout
+ .panes
+ .iter()
+ .map(|pane| {
+ (
+ pane.pane_id,
+ terminal_size(pane.rect.width as usize, pane.rect.height as usize, screen),
+ )
+ })
+ .collect::<HashMap<_, _>>();
+ pane_geometry_matches_confirmation(&current, &prepared.visible_panes)
+}
+
+fn advance_split_drag_geometry_confirmation(state: &mut TuiState) {
+ let Some(preview) = state.split_drag_geometry.clone() else {
+ return;
+ };
+ let SplitDragGeometryPhase::Confirming {
+ committed_at,
+ mut ready_since,
+ } = preview.phase
+ else {
+ return;
+ };
+ let Some(prepared) = preview.latest.as_ref() else {
+ cancel_split_drag_geometry(state, true);
+ return;
+ };
+ let Some((_, _, tab, _)) = state.active_tab() else {
+ cancel_split_drag_geometry(state, true);
+ return;
+ };
+ if state.active_split_drag_epoch() != Some(preview.epoch)
+ || !active_layout_matches_split_drag(state, &tab, prepared)
+ {
+ cancel_split_drag_geometry(state, true);
+ return;
+ }
+
+ let mut geometry_ready = !prepared.visible_panes.is_empty();
+ let mut snapshot_ready = geometry_ready;
+ for (pane_id, size) in &prepared.visible_panes {
+ let readiness = Mux::get()
+ .get_pane(*pane_id)
+ .and_then(|pane| {
+ pane.downcast_ref::<ClientPane>().map(|client| {
+ (
+ client.server_geometry_matches(*size),
+ client.prime_frontend_geometry(*size),
+ )
+ })
+ })
+ .unwrap_or((false, false));
+ geometry_ready &= readiness.0;
+ snapshot_ready &= readiness.1;
+ }
+
+ let now = Instant::now();
+ if takeover_geometry_settled(snapshot_ready, now, &mut ready_since) {
+ complete_split_drag_geometry(state, preview.epoch);
+ return;
+ }
+ if now.duration_since(committed_at) >= SPLIT_DRAG_CONFIRM_TIMEOUT {
+ if geometry_ready {
+ // The server has committed the final PTY size. A slow line fetch is
+ // not a geometry failure and must not launch a whole-domain resync:
+ // the live preview has already normalized retained rows to this
+ // width, and the normal pane poll will replace them as they arrive.
+ complete_split_drag_geometry(state, preview.epoch);
+ } else {
+ state.ui.status = "Divider resize is resyncing".to_string();
+ cancel_split_drag_geometry(state, true);
+ }
+ return;
+ }
+ if let Some(current) = state
+ .split_drag_geometry
+ .as_mut()
+ .filter(|current| current.epoch == preview.epoch)
+ {
+ current.phase = SplitDragGeometryPhase::Confirming {
+ committed_at,
+ ready_since,
+ };
+ }
+}
+
fn cancel_takeover_geometry_confirmation(
state: &mut TuiState,
cache_key: &(String, TabId),
@@ -1939,11 +2703,46 @@ fn advance_takeover_geometry_confirmation(state: &mut TuiState) {
})
&& state.takeover_epochs.current(&cache_key.0, cache_key.1) == Some(confirmation.epoch);
if !still_owned {
+ mux::zoom_trace!(
+ "tui.takeover.cancel tab={}/r{} epoch={} reason=ownership access={:?} owns={:?}",
+ cache_key.0,
+ cache_key.1,
+ confirmation.epoch,
+ access,
+ domain.owns_remote_viewport(tab.tab_id())
+ );
cancel_takeover_geometry_confirmation(state, &cache_key, &confirmation);
return;
}
if !active_layout_matches_takeover(state, &tab, &confirmation) {
+ if mux::geometrytrace::trace_enabled() {
+ let screen = state.screen_size;
+ let current = state
+ .layout
+ .panes
+ .iter()
+ .map(|pane| {
+ let size = screen.map(|screen| {
+ terminal_size(pane.rect.width as usize, pane.rect.height as usize, screen)
+ });
+ format!("{}:{size:?}", pane.pane_id)
+ })
+ .collect::<Vec<_>>()
+ .join(" ");
+ mux::zoom_trace!(
+ "tui.takeover.cancel tab={}/r{} epoch={} reason=layout root={:?}/{:?} screen={:?}/{:?} current=[{}] expected={:?}",
+ cache_key.0,
+ cache_key.1,
+ confirmation.epoch,
+ tab.get_size(),
+ confirmation.root_size,
+ state.screen_size,
+ confirmation.screen_size,
+ current,
+ confirmation.panes
+ );
+ }
cancel_takeover_geometry_confirmation(state, &cache_key, &confirmation);
let now = Instant::now();
state.resize_settles_at = Some(now + RESIZE_SETTLE);
@@ -1952,17 +2751,73 @@ fn advance_takeover_geometry_confirmation(state: &mut TuiState) {
}
let mut ready = !confirmation.panes.is_empty();
+ let mut waiting = Vec::new();
for (pane_id, size) in &confirmation.panes {
- let pane_ready = Mux::get()
- .get_pane(*pane_id)
- .and_then(|pane| {
- pane.downcast_ref::<ClientPane>()
- .map(|client| client.prime_frontend_geometry(*size))
- })
+ let pane = Mux::get().get_pane(*pane_id);
+ let client = pane
+ .as_ref()
+ .and_then(|pane| pane.downcast_ref::<ClientPane>());
+ let pane_ready = client
+ .map(|client| client.prime_frontend_geometry(*size))
.unwrap_or(false);
+ if !pane_ready {
+ let reason = client
+ .and_then(|client| client.frontend_geometry_mismatch(*size))
+ .unwrap_or_else(|| {
+ if pane.is_some() {
+ "render rows pending".to_string()
+ } else {
+ "pane missing".to_string()
+ }
+ });
+ waiting.push(format!("{pane_id}:{reason}"));
+ }
ready &= pane_ready;
}
+ if !ready {
+ let reason = if confirmation.panes.is_empty() {
+ "no visible pane targets".to_string()
+ } else {
+ waiting.join("; ")
+ };
+ if confirmation.last_wait_reason.as_deref() != Some(reason.as_str()) {
+ log::warn!(
+ "TUI takeover waiting tab={}/r{} epoch={} elapsed={:?}: {}",
+ cache_key.0,
+ cache_key.1,
+ confirmation.epoch,
+ confirmation.started_at.elapsed(),
+ reason
+ );
+ mux::zoom_trace!(
+ "tui.takeover.wait tab={}/r{} epoch={} elapsed={:?} reason={}",
+ cache_key.0,
+ cache_key.1,
+ confirmation.epoch,
+ confirmation.started_at.elapsed(),
+ reason
+ );
+ confirmation.last_wait_reason = Some(reason);
+ }
+ } else if confirmation.ready_since.is_none() {
+ log::warn!(
+ "TUI takeover ready tab={}/r{} epoch={} elapsed={:?}",
+ cache_key.0,
+ cache_key.1,
+ confirmation.epoch,
+ confirmation.started_at.elapsed()
+ );
+ mux::zoom_trace!(
+ "tui.takeover.ready tab={}/r{} epoch={} elapsed={:?}",
+ cache_key.0,
+ cache_key.1,
+ confirmation.epoch,
+ confirmation.started_at.elapsed()
+ );
+ confirmation.last_wait_reason = None;
+ }
+
if !takeover_geometry_settled(ready, Instant::now(), &mut confirmation.ready_since) {
state
.takeover_geometry_confirmations
@@ -1983,6 +2838,20 @@ fn advance_takeover_geometry_confirmation(state: &mut TuiState) {
.handoff_geometry_ready
.insert(cache_key.clone(), confirmation.access_generation);
state.takeover_geometry_confirmations.remove(&cache_key);
+ log::warn!(
+ "TUI takeover complete tab={}/r{} epoch={} elapsed={:?}",
+ cache_key.0,
+ cache_key.1,
+ confirmation.epoch,
+ confirmation.started_at.elapsed()
+ );
+ mux::zoom_trace!(
+ "tui.takeover.complete tab={}/r{} epoch={} elapsed={:?}",
+ cache_key.0,
+ cache_key.1,
+ confirmation.epoch,
+ confirmation.started_at.elapsed()
+ );
state.dirty = true;
}
@@ -2058,6 +2927,12 @@ async fn report_viewport_if_changed<T: termwiz::terminal::Terminal>(
ClientViewport::CellGrid { size }
};
let cache_key = (domain_name.clone(), remote_tab_id);
+ // Divider geometry has its own non-blocking latest-only stream. Letting
+ // the ordinary reporter run as well would create a second ordered path
+ // and allow stale mouse positions to alternate on screen.
+ if state.split_drag_geometry.is_some() {
+ return;
+ }
let handoff_generation = domain
.remote_access_state()
.filter(|access| access.mode == codec::FrontendAccessMode::Handoff)
@@ -2432,7 +3307,13 @@ async fn claim_active_viewport(state: &mut TuiState) -> Result<Arc<Tab>> {
let cache_key = (domain_name.clone(), remote_tab_id);
let viewport = if handoff {
let area = state.layout.screen;
- match prepare_active_native_viewport(state, area, screen, true, Some(epoch)) {
+ match prepare_active_native_viewport(
+ state,
+ area,
+ screen,
+ true,
+ Some(NativeViewportPreview::Takeover(epoch)),
+ ) {
Some(viewport) => viewport,
None => {
state
@@ -2683,8 +3564,12 @@ async fn dispatch_action(state: &mut TuiState, action: Action) -> Result<()> {
}
Action::ResizeSplit { split_index, delta } => {
let tab = claim_active_viewport(state).await?;
+ begin_split_drag_geometry(state)?;
tab.resize_split_by(split_index, delta);
- state.clear_selected_viewport_cache();
+ }
+ Action::FinishSplitResize => {
+ finish_split_drag(state);
+ pump_split_drag_geometry(state);
}
Action::EnterCopyMode => enter_copy_mode(state),
Action::LeaveCopyMode => {
@@ -2797,12 +3682,13 @@ async fn dispatch_action(state: &mut TuiState, action: Action) -> Result<()> {
/// Drawing, moving the cursor and changing a value all index this one list.
/// They used to agree only by hand-counted index, which is why three settings
/// added since could be changed by nobody: the cursor stopped at four.
-pub const SETTINGS: [(&str, &str); 9] = [
+pub const SETTINGS: [(&str, &str); 10] = [
("Appearance", "Theme"),
("Appearance", "Sidebar"),
("Appearance", "Pane nav bar"),
("Appearance", "Pane borders"),
("Appearance", "Pane scrollbars"),
+ ("Appearance", "Bottom status bar"),
("Input", "Application mouse"),
("Input", "Copy on select"),
("Input", "Touch targets"),
@@ -2817,15 +3703,16 @@ pub fn setting_value(settings: &TuiConfig, sidebar_visible: bool, index: usize)
2 => (String::new(), settings.pane_nav_bar),
3 => (String::new(), settings.pane_borders),
4 => (String::new(), settings.pane_scrollbars),
- 5 => (String::new(), settings.mouse),
- 6 => (String::new(), settings.copy_on_select),
+ 5 => (String::new(), settings.show_status_bar),
+ 6 => (String::new(), settings.mouse),
+ 7 => (String::new(), settings.copy_on_select),
// Undecided is a real state here: it means "follow the layout", which
// is neither on nor off and has to say so.
- 7 => match settings.touch_targets {
+ 8 => match settings.touch_targets {
None => ("Auto".to_string(), false),
Some(value) => (String::new(), value),
},
- 8 => (settings.scroll_lines.to_string(), false),
+ 9 => (settings.scroll_lines.to_string(), false),
_ => (String::new(), false),
}
}
@@ -2858,11 +3745,16 @@ fn adjust_setting(state: &mut TuiState, index: usize, delta: isize) -> Result<()
state.ui.pane_scrollbars = state.settings.pane_scrollbars;
state.clear_selected_viewport_cache();
}
- 5 => state.settings.mouse = !state.settings.mouse,
- 6 => state.settings.copy_on_select = !state.settings.copy_on_select,
+ 5 => {
+ state.settings.show_status_bar = !state.settings.show_status_bar;
+ state.ui.show_status_bar = state.settings.show_status_bar;
+ state.clear_selected_viewport_cache();
+ }
+ 6 => state.settings.mouse = !state.settings.mouse,
+ 7 => state.settings.copy_on_select = !state.settings.copy_on_select,
// Cycles through the third state rather than skipping it: following the
// layout is the default and has to be reachable again.
- 7 => {
+ 8 => {
state.settings.touch_targets = match state.settings.touch_targets {
None => Some(true),
Some(true) => Some(false),
@@ -2871,7 +3763,7 @@ fn adjust_setting(state: &mut TuiState, index: usize, delta: isize) -> Result<()
state.ui.touch_targets = state.settings.touch_targets;
state.clear_selected_viewport_cache();
}
- 8 => {
+ 9 => {
state.settings.scroll_lines =
(state.settings.scroll_lines as isize + delta).clamp(1, 20) as usize;
}
@@ -5105,6 +5997,42 @@ fn handle_mouse(event: TermwizMouseEvent, state: &mut TuiState) {
}
if wheel {
+ let direction = if current.contains(MouseButtons::WHEEL_POSITIVE) {
+ -1
+ } else {
+ 1
+ };
+ if state.layout.tab_bar.contains((x, y).into())
+ && !state
+ .layout
+ .sidebar_toggle
+ .is_some_and(|toggle| toggle.contains((x, y).into()))
+ {
+ state.ui.tab_scroll = state
+ .layout
+ .tab_scroll_start
+ .saturating_add_signed(direction);
+ state.queue(Action::SelectRelativeTab(direction));
+ state.last_mouse_buttons = current;
+ state.dirty = true;
+ return;
+ }
+ if let Some((pane_id, start)) = state.layout.panes.iter().find_map(|pane| {
+ pane.nav.as_ref().and_then(|nav| {
+ nav.rect
+ .contains((x, y).into())
+ .then_some((pane.pane_id, nav.scroll_start))
+ })
+ }) {
+ state
+ .ui
+ .pane_nav_scroll
+ .insert(pane_id, start.saturating_add_signed(direction));
+ activate_relative_pane_in_stack(state, pane_id, direction);
+ state.last_mouse_buttons = current;
+ state.dirty = true;
+ return;
+ }
if state
.layout
.sidebar_body
@@ -5179,6 +6107,13 @@ fn handle_mouse(event: TermwizMouseEvent, state: &mut TuiState) {
TabBarControl::Menu => open_main_menu(state, x, y),
TabBarControl::NewTab => state.queue(Action::NewTab),
},
+ Some(HitTarget::TabScroll(direction)) => {
+ state.ui.tab_scroll = state
+ .layout
+ .tab_scroll_start
+ .saturating_add_signed(direction);
+ state.queue(Action::SelectRelativeTab(direction));
+ }
// Closing a tab takes the same confirmation the menu entry does.
Some(HitTarget::CloseTab(tab_id)) => {
state.queue(Action::Confirm(DestructiveAction::CloseTab { tab_id }))
@@ -5211,6 +6146,20 @@ fn handle_mouse(event: TermwizMouseEvent, state: &mut TuiState) {
Some(HitTarget::PaneNavClose(pane_id)) => {
state.queue(Action::Confirm(DestructiveAction::ClosePane { pane_id }))
}
+ Some(HitTarget::PaneNavScroll(pane_id, direction)) => {
+ let start = state
+ .layout
+ .panes
+ .iter()
+ .find(|pane| pane.pane_id == pane_id)
+ .and_then(|pane| pane.nav.as_ref())
+ .map_or(0, |nav| nav.scroll_start);
+ state
+ .ui
+ .pane_nav_scroll
+ .insert(pane_id, start.saturating_add_signed(direction));
+ activate_relative_pane_in_stack(state, pane_id, direction);
+ }
Some(HitTarget::PaneTool(pane_id, tool)) => pane_tool(state, pane_id, tool),
Some(HitTarget::Scrollbar(pane_id)) => {
scroll_to_scrollbar_position(state, pane_id, y);
@@ -5368,6 +6317,8 @@ fn handle_mouse(event: TermwizMouseEvent, state: &mut TuiState) {
if let Err(err) = save_tui_settings(state) {
state.ui.status = format!("Saving TUI settings: {err:#}");
}
+ } else if matches!(state.drag, Some(DragState::SplitResize { .. })) {
+ state.queue(Action::FinishSplitResize);
} else if state.layout.content.contains((x, y).into()) {
forward_mouse_to_pane(event.clone(), x, y, None, state);
}
@@ -5463,6 +6414,23 @@ fn activate_pane_in_stack(state: &mut TuiState, pane_id: PaneId) {
state.queue(Action::FocusPaneId(pane_id));
}
+fn activate_relative_pane_in_stack(state: &mut TuiState, pane_id: PaneId, delta: isize) {
+ let Some((_, _, tab, _)) = state.active_tab() else {
+ return;
+ };
+ let stack = tab.pane_stack_tabs(pane_id);
+ if stack.len() < 2 {
+ return;
+ }
+ let current = stack.iter().position(|entry| entry.is_active).unwrap_or(0);
+ let target = current
+ .saturating_add_signed(delta.signum())
+ .min(stack.len() - 1);
+ if target != current {
+ activate_pane_in_stack(state, stack[target].pane_id);
+ }
+}
+
/// Every pane tool acts on "the" pane, so the pane whose button was pressed has
/// to become that pane first. Two actions rather than one, drained in order.
fn pane_tool(state: &mut TuiState, pane_id: PaneId, tool: PaneTool) {
@@ -5915,6 +6883,39 @@ mod tests {
assert!(ready_since.is_none());
}
+ #[test]
+ fn split_drag_stream_keeps_one_request_in_flight_and_replaces_pending_with_latest() {
+ let now = Instant::now();
+ let first = ClientViewport::CellGrid {
+ size: takeover_test_size(80, 24),
+ };
+ let latest = ClientViewport::CellGrid {
+ size: takeover_test_size(100, 24),
+ };
+
+ assert!(split_drag_can_pump(
+ SplitDragGeometryPhase::Dragging,
+ false,
+ true
+ ));
+ assert!(!split_drag_can_pump(
+ SplitDragGeometryPhase::Dragging,
+ true,
+ true
+ ));
+ assert!(!split_drag_can_pump(
+ SplitDragGeometryPhase::Confirming {
+ committed_at: now,
+ ready_since: None,
+ },
+ false,
+ true
+ ));
+ assert!(!split_drag_target_is_owed(Some(&first), None, &first));
+ assert!(split_drag_target_is_owed(Some(&first), None, &latest));
+ assert!(!split_drag_target_is_owed(None, Some(&latest), &latest));
+ }
+
#[test]
fn handoff_reveals_each_tab_only_after_its_geometry_generation_is_ready() {
let access = codec::FrontendAccessState {
diff --git a/thinkterm-tui/src/render.rs b/thinkterm-tui/src/render.rs
index 4f91ce02..689a6825 100644
--- a/thinkterm-tui/src/render.rs
+++ b/thinkterm-tui/src/render.rs
@@ -9,6 +9,7 @@ use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line as TextLine, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use ratatui::Frame;
+use std::collections::HashMap;
use std::sync::Arc;
use termwiz::cell::{unicode_column_width, Blink, CellAttributes, Intensity, Underline};
use termwiz::color::ColorAttribute;
@@ -74,7 +75,11 @@ pub fn render(
render_tabs(frame, view);
render_status(frame, model, ui, view, viewport_status);
- if let Some((title, hint)) = handoff_message {
+ if view.terminal_obscured {
+ // The sidebar was drawn first and owns the whole narrow screen. Pane
+ // geometry still exists for viewport negotiation, but terminal output
+ // must not paint back over the overlay.
+ } else if let Some((title, hint)) = handoff_message {
render_handoff(frame, view.content, title, hint, handoff_animation);
} else if let Some(tab) = local_tab {
result.active_pane = tab.get_active_pane().map(|pane| pane.pane_id());
@@ -268,6 +273,20 @@ fn render_tabs(frame: &mut Frame<'_>, view: &ViewLayout) {
for (rect, control) in &view.tab_controls {
draw_text(frame, *rect, control.glyph(), chrome_dim());
}
+ for button in &view.tab_overflow {
+ let style = if button.hidden > 0 {
+ chrome_accent_text()
+ } else {
+ chrome_dim()
+ };
+ let label = if button.direction < 0 {
+ format!("< …{}", button.hidden)
+ } else {
+ format!("{}… >", button.hidden)
+ };
+ fill(frame, button.rect, " ", chrome());
+ draw_text(frame, button.rect, &label, style);
+ }
if view.tabs.is_empty() {
draw_text(frame, view.tab_bar, " Opening terminal…", chrome_dim());
return;
@@ -287,10 +306,18 @@ fn render_tabs(frame: &mut Frame<'_>, view: &ViewLayout) {
}
}
let used = view
- .tabs
+ .tab_overflow
.last()
- .map_or(view.tab_bar.x, |tab| tab.rect.right());
- if used < view.tab_bar.right() {
+ .map(|button| button.rect.right())
+ .or_else(|| view.tabs.last().map(|tab| tab.rect.right()))
+ .unwrap_or(view.tab_bar.x);
+ let controls_left = view
+ .tab_controls
+ .iter()
+ .map(|(rect, _)| rect.x)
+ .min()
+ .unwrap_or(view.tab_bar.right());
+ if used < controls_left {
let separator = Rect::new(used, view.tab_bar.y, 1, view.tab_bar.height);
fill(frame, separator, "│", chrome_border());
}
@@ -316,20 +343,6 @@ fn render_panes(frame: &mut Frame<'_>, tab: &Arc<Tab>, ui: &UiState, view: &View
);
continue;
}
- if let Some(border) = pane_view.border {
- let focused = tab
- .get_active_pane()
- .is_some_and(|active| active.pane_id() == pane_view.pane_id);
- let style = if focused {
- chrome_accent_text()
- } else {
- chrome_border()
- };
- frame.render_widget(
- Block::default().borders(Borders::ALL).border_style(style),
- border,
- );
- }
if let Some(nav) = &pane_view.nav {
let focused = tab
.get_active_pane()
@@ -342,26 +355,11 @@ fn render_panes(frame: &mut Frame<'_>, tab: &Arc<Tab>, ui: &UiState, view: &View
}
}
- // Framed panes already show where each one ends, and a divider between two
- // frames is a third line of chrome in a row that has two. When the frames
- // were not drawn — too small, or turned off — the divider is the only thing
- // separating them.
- for split in &view.splits {
- let symbol = match split.direction {
- SplitDirection::Horizontal => "│",
- SplitDirection::Vertical => "─",
- };
- for y in split.rect.y..split.rect.bottom() {
- for x in split.rect.x..split.rect.right() {
- if !split_cell_needs_divider(view, split, x, y) {
- continue;
- }
- frame.buffer_mut()[(x, y)]
- .set_symbol(symbol)
- .set_style(chrome_border());
- }
- }
- }
+ paint_pane_chrome(
+ frame,
+ tab.get_active_pane().map(|pane| pane.pane_id()),
+ view,
+ );
if let Some(active) = tab.get_active_pane() {
if let Some(pane_view) = view
@@ -388,30 +386,239 @@ fn render_panes(frame: &mut Frame<'_>, tab: &Arc<Tab>, ui: &UiState, view: &View
}
}
+const LINE_NORTH: u8 = 1 << 0;
+const LINE_EAST: u8 = 1 << 1;
+const LINE_SOUTH: u8 = 1 << 2;
+const LINE_WEST: u8 = 1 << 3;
+const LINE_NS: u8 = LINE_NORTH | LINE_SOUTH;
+const LINE_EW: u8 = LINE_EAST | LINE_WEST;
+const LINE_ES: u8 = LINE_EAST | LINE_SOUTH;
+const LINE_SW: u8 = LINE_SOUTH | LINE_WEST;
+const LINE_NE: u8 = LINE_NORTH | LINE_EAST;
+const LINE_NW: u8 = LINE_NORTH | LINE_WEST;
+const LINE_NES: u8 = LINE_NORTH | LINE_EAST | LINE_SOUTH;
+const LINE_NSW: u8 = LINE_NORTH | LINE_SOUTH | LINE_WEST;
+const LINE_ESW: u8 = LINE_EAST | LINE_SOUTH | LINE_WEST;
+const LINE_NEW: u8 = LINE_NORTH | LINE_EAST | LINE_WEST;
+const LINE_NESW: u8 = LINE_NORTH | LINE_EAST | LINE_SOUTH | LINE_WEST;
+
+#[derive(Clone, Copy)]
+struct PaneChromeCell {
+ connections: u8,
+ style: Style,
+ style_priority: u8,
+}
+
+#[derive(Default)]
+struct PaneChromeLines {
+ cells: HashMap<(u16, u16), PaneChromeCell>,
+}
+
+impl PaneChromeLines {
+ fn add(&mut self, x: u16, y: u16, connections: u8, style: Style, style_priority: u8) {
+ self.cells
+ .entry((x, y))
+ .and_modify(|cell| {
+ cell.connections |= connections;
+ if style_priority > cell.style_priority {
+ cell.style = style;
+ cell.style_priority = style_priority;
+ }
+ })
+ .or_insert(PaneChromeCell {
+ connections,
+ style,
+ style_priority,
+ });
+ }
+
+ fn horizontal(&mut self, y: u16, start: u16, end: u16, style: Style, priority: u8) {
+ if start >= end {
+ return;
+ }
+ for x in start..end {
+ let connections = if end - start == 1 {
+ LINE_EW
+ } else {
+ let mut connections = 0;
+ if x > start {
+ connections |= LINE_WEST;
+ }
+ if x + 1 < end {
+ connections |= LINE_EAST;
+ }
+ connections
+ };
+ self.add(x, y, connections, style, priority);
+ }
+ }
+
+ fn vertical(&mut self, x: u16, start: u16, end: u16, style: Style, priority: u8) {
+ if start >= end {
+ return;
+ }
+ for y in start..end {
+ let connections = if end - start == 1 {
+ LINE_NS
+ } else {
+ let mut connections = 0;
+ if y > start {
+ connections |= LINE_NORTH;
+ }
+ if y + 1 < end {
+ connections |= LINE_SOUTH;
+ }
+ connections
+ };
+ self.add(x, y, connections, style, priority);
+ }
+ }
+
+ fn border(&mut self, rect: Rect, style: Style, priority: u8) {
+ if rect.is_empty() {
+ return;
+ }
+ if rect.width == 1 {
+ self.vertical(rect.x, rect.y, rect.bottom(), style, priority);
+ return;
+ }
+ if rect.height == 1 {
+ self.horizontal(rect.y, rect.x, rect.right(), style, priority);
+ return;
+ }
+ self.horizontal(rect.y, rect.x, rect.right(), style, priority);
+ self.horizontal(rect.bottom() - 1, rect.x, rect.right(), style, priority);
+ self.vertical(rect.x, rect.y, rect.bottom(), style, priority);
+ self.vertical(rect.right() - 1, rect.y, rect.bottom(), style, priority);
+ }
+
+ fn paint(self, frame: &mut Frame<'_>) {
+ for ((x, y), cell) in self.cells {
+ frame.buffer_mut()[(x, y)]
+ .set_symbol(pane_chrome_symbol(cell.connections))
+ .set_style(cell.style);
+ }
+ }
+}
+
+fn pane_chrome_symbol(connections: u8) -> &'static str {
+ match connections {
+ LINE_ES => "┌",
+ LINE_SW => "┐",
+ LINE_NE => "└",
+ LINE_NW => "┘",
+ LINE_NES => "├",
+ LINE_NSW => "┤",
+ LINE_ESW => "┬",
+ LINE_NEW => "┴",
+ LINE_NESW => "┼",
+ LINE_NS => "│",
+ LINE_EW => "─",
+ mask if mask & (LINE_NORTH | LINE_SOUTH) != 0 => "│",
+ _ => "─",
+ }
+}
+
+fn paint_pane_chrome(frame: &mut Frame<'_>, active_pane_id: Option<PaneId>, view: &ViewLayout) {
+ let mut lines = PaneChromeLines::default();
+ for pane in &view.panes {
+ let Some(border) = painted_pane_border_rect(view, pane) else {
+ continue;
+ };
+ let focused = active_pane_id == Some(pane.pane_id);
+ lines.border(
+ border,
+ if focused {
+ chrome_accent_text()
+ } else {
+ chrome_border()
+ },
+ if focused { 2 } else { 1 },
+ );
+ }
+
+ // Frames and split dividers feed one connection map. Crossings therefore
+ // become real junction glyphs rather than whichever independent draw ran
+ // last, while a divider between two complete frames remains suppressed to
+ // avoid a third parallel rule.
+ for split in &view.splits {
+ for y in split.rect.y..split.rect.bottom() {
+ for x in split.rect.x..split.rect.right() {
+ if !split_cell_needs_divider(view, split, x, y) {
+ continue;
+ }
+ let connections = match split.direction {
+ SplitDirection::Horizontal => {
+ let mut connections = 0;
+ if y > split.rect.y && split_cell_needs_divider(view, split, x, y - 1) {
+ connections |= LINE_NORTH;
+ }
+ if y + 1 < split.rect.bottom()
+ && split_cell_needs_divider(view, split, x, y + 1)
+ {
+ connections |= LINE_SOUTH;
+ }
+ if connections == 0 {
+ LINE_NS
+ } else {
+ connections
+ }
+ }
+ SplitDirection::Vertical => {
+ let mut connections = 0;
+ if x > split.rect.x && split_cell_needs_divider(view, split, x - 1, y) {
+ connections |= LINE_WEST;
+ }
+ if x + 1 < split.rect.right()
+ && split_cell_needs_divider(view, split, x + 1, y)
+ {
+ connections |= LINE_EAST;
+ }
+ if connections == 0 {
+ LINE_EW
+ } else {
+ connections
+ }
+ }
+ };
+ lines.add(x, y, connections, chrome_border(), 0);
+ }
+ }
+ }
+ lines.paint(frame);
+}
+
fn split_cell_needs_divider(view: &ViewLayout, split: &SplitView, x: u16, y: u16) -> bool {
+ // A pane nav is part of the pane's outer chrome even though its frame
+ // deliberately starts one row lower. Looking only at `border` resurrects
+ // the split divider for exactly that nav row, leaving a short, detached
+ // line beside a level-2 tab bar. Compare against the complete framed pane
+ // instead, so a divider is either replaced by the two pane frames for its
+ // whole span or remains available where one side is genuinely unframed.
let framed_on_both_sides = match split.direction {
SplitDirection::Horizontal => {
let left = view.panes.iter().any(|pane| {
- pane.border.is_some_and(|border| {
- border.right() == x && y >= border.y && y < border.bottom()
+ framed_pane_outer_rect(pane).is_some_and(|outer| {
+ outer.right() == x && rect_vertical_span_covers_or_touches(outer, y)
})
});
let right = view.panes.iter().any(|pane| {
- pane.border.is_some_and(|border| {
- border.x == x.saturating_add(1) && y >= border.y && y < border.bottom()
+ framed_pane_outer_rect(pane).is_some_and(|outer| {
+ outer.x == x.saturating_add(1) && rect_vertical_span_covers_or_touches(outer, y)
})
});
left && right
}
SplitDirection::Vertical => {
let above = view.panes.iter().any(|pane| {
- pane.border.is_some_and(|border| {
- border.bottom() == y && x >= border.x && x < border.right()
+ framed_pane_outer_rect(pane).is_some_and(|outer| {
+ outer.bottom() == y && rect_horizontal_span_covers_or_touches(outer, x)
})
});
let below = view.panes.iter().any(|pane| {
- pane.border.is_some_and(|border| {
- border.y == y.saturating_add(1) && x >= border.x && x < border.right()
+ framed_pane_outer_rect(pane).is_some_and(|outer| {
+ outer.y == y.saturating_add(1)
+ && rect_horizontal_span_covers_or_touches(outer, x)
})
});
above && below
@@ -420,6 +627,66 @@ fn split_cell_needs_divider(view: &ViewLayout, split: &SplitView, x: u16, y: u16
!framed_on_both_sides
}
+fn rect_vertical_span_covers_or_touches(rect: Rect, y: u16) -> bool {
+ (y >= rect.y && y < rect.bottom()) || y.saturating_add(1) == rect.y || y == rect.bottom()
+}
+
+fn rect_horizontal_span_covers_or_touches(rect: Rect, x: u16) -> bool {
+ (x >= rect.x && x < rect.right()) || x.saturating_add(1) == rect.x || x == rect.right()
+}
+
+fn framed_pane_outer_rect(pane: &PaneView) -> Option<Rect> {
+ let border = pane.border?;
+ let Some(nav) = pane.nav.as_ref() else {
+ return Some(border);
+ };
+ let x = border.x.min(nav.rect.x);
+ let y = border.y.min(nav.rect.y);
+ let right = border.right().max(nav.rect.right());
+ let bottom = border.bottom().max(nav.rect.bottom());
+ Some(Rect::new(
+ x,
+ y,
+ right.saturating_sub(x),
+ bottom.saturating_sub(y),
+ ))
+}
+
+fn painted_pane_border_rect(view: &ViewLayout, pane: &PaneView) -> Option<Rect> {
+ let border = pane.border?;
+ let bottom = view
+ .splits
+ .iter()
+ .filter(|split| {
+ split.direction == SplitDirection::Vertical
+ && split.rect.y == border.bottom()
+ && split.rect.x <= border.x
+ && split.rect.right() >= border.right()
+ && view.panes.iter().any(|below| {
+ below.border.is_some()
+ && below.nav.as_ref().is_some_and(|nav| {
+ nav.rect.y == split.rect.bottom()
+ && nav.rect.x <= border.x
+ && nav.rect.right() >= border.right()
+ })
+ })
+ })
+ .map(|split| split.rect.bottom())
+ .max()
+ .unwrap_or_else(|| border.bottom());
+
+ // The split gutter immediately above a lower pane's nav is visual chrome,
+ // not terminal space. Use it as the upper frame's bottom edge: the upper
+ // pane keeps a complete box, the lower nav remains its own layer, and no
+ // third detached divider is painted between them.
+ Some(Rect::new(
+ border.x,
+ border.y,
+ border.width,
+ bottom.saturating_sub(border.y),
+ ))
+}
+
fn paint_collapsed_pane(
frame: &mut Frame<'_>,
pane: &Arc<dyn Pane>,
@@ -454,34 +721,32 @@ fn paint_collapsed_pane(
/// Draw one pane's own strip: what is stacked behind it, and what can be done
/// to it.
///
-/// The focused pane's bar is the only one drawn in the accent, which is what
-/// says where typing goes — a job the frame used to do alone, and only when the
-/// pane was wide enough to afford one.
+/// The bar is a layer of its own between the window tabs and terminal content.
+/// The active stack tab opens back onto the content background; accent text on
+/// that tab says which pane owns keyboard focus.
fn paint_pane_nav(frame: &mut Frame<'_>, nav: &PaneNav, focused: bool) {
if nav.rect.is_empty() {
return;
}
- // No fill. A band of surface behind every pane turned the screen into
- // stacked grey slabs — and because every style below sets its own
- // background, the glyphs punched the plain background back through it in
- // streaks. The bar sits on the background like everything else; which pane
- // has the focus is said by the colour of its name, which is where the eye
- // already is.
- let base = chrome();
- // No fill. On a framed pane this row *is* the frame's top edge, and filling
- // it with spaces rubs the line out between the corners, leaving `┌` and `┐`
- // floating either side of a gap. Leaving it alone lets the line run behind
- // the names and buttons, which is what a titled box looks like.
- for entry in &nav.tabs {
- // Each item clears its own cells. Filling the whole row would rub out
- // the frame's top edge; filling none of it lets the line run through
- // the gaps inside a name and between the buttons.
- fill(frame, entry.rect, " ", base);
- let style = match (entry.active, focused) {
- (true, true) => chrome_accent_text().add_modifier(Modifier::BOLD),
- (true, false) => chrome_bold(),
- (false, _) => chrome_dim(),
+ let surface = pane_nav_surface_style();
+ fill(frame, nav.rect, " ", surface);
+ for button in &nav.overflow {
+ let style = if button.hidden > 0 {
+ pane_nav_tool_style(focused)
+ } else {
+ surface.add_modifier(Modifier::DIM)
};
+ let label = if button.direction < 0 {
+ format!("< …{}", button.hidden)
+ } else {
+ format!("{}… >", button.hidden)
+ };
+ fill(frame, button.rect, " ", surface);
+ draw_text(frame, button.rect, &label, style);
+ }
+ for entry in &nav.tabs {
+ let style = pane_nav_tab_style(entry.active, focused);
+ fill(frame, entry.rect, " ", style);
// Clipped to where the close button starts, so a long title is
// shortened rather than drawn underneath it.
// One column short of the close button, so a title long enough to be
@@ -499,49 +764,134 @@ fn paint_pane_nav(frame: &mut Frame<'_>, nav: &PaneNav, focused: bool) {
draw_text(frame, close, "✕", style);
}
}
- let tool_style = if focused { chrome_bold() } else { chrome_dim() };
+ let tool_style = pane_nav_tool_style(focused);
for (rect, tool) in &nav.tools {
- fill(frame, *rect, " ", base);
+ fill(frame, *rect, " ", tool_style);
draw_text(frame, *rect, tool.glyph(), tool_style);
}
}
+fn pane_nav_surface_style() -> Style {
+ let palette = crate::settings::palette();
+ if palette.reset_chrome {
+ Style::reset().add_modifier(Modifier::REVERSED)
+ } else {
+ Style::reset().fg(palette.foreground).bg(palette.surface)
+ }
+}
+
+fn pane_nav_tab_style(active: bool, focused: bool) -> Style {
+ let palette = crate::settings::palette();
+ if palette.reset_chrome {
+ return if active {
+ let selected = Style::reset().add_modifier(Modifier::UNDERLINED);
+ if focused {
+ selected.add_modifier(Modifier::BOLD)
+ } else {
+ selected
+ }
+ } else {
+ pane_nav_surface_style().add_modifier(Modifier::DIM)
+ };
+ }
+ if active {
+ Style::reset()
+ .fg(if focused {
+ palette.accent
+ } else {
+ palette.foreground
+ })
+ .bg(palette.background)
+ .add_modifier(Modifier::BOLD)
+ } else {
+ Style::reset().fg(palette.border).bg(palette.surface)
+ }
+}
+
+fn pane_nav_tool_style(focused: bool) -> Style {
+ let palette = crate::settings::palette();
+ let style = pane_nav_surface_style();
+ if palette.reset_chrome {
+ style.add_modifier(if focused {
+ Modifier::BOLD
+ } else {
+ Modifier::DIM
+ })
+ } else {
+ style.fg(if focused {
+ palette.foreground
+ } else {
+ palette.border
+ })
+ }
+}
+
/// Draw a pane's position in its own scrollback.
///
/// The thumb is sized by how much of the scrollback is on screen and placed by
/// how far back the view has been pulled, so its length says how much there is
-/// and its position says where you are. A pane with nothing to scroll gets a
-/// plain track rather than a full-height thumb, which would otherwise read as
-/// "there is more here" on a screen that has none.
+/// and its position says where you are. The gutter remains reserved to avoid a
+/// PTY resize when scrollback first appears, but stays visually empty until it
+/// has real scroll position to communicate.
fn paint_scrollbar(frame: &mut Frame<'_>, pane: &Arc<dyn Pane>, area: Rect, ui: &UiState) {
if area.is_empty() {
return;
}
- fill(frame, area, "│", chrome_border());
+ fill(frame, area, " ", Style::reset());
let dims = pane.get_dimensions();
- let scrollable = dims.scrollback_rows.saturating_sub(dims.viewport_rows);
- if scrollable == 0 {
+ let Some((from_top, thumb)) = scrollbar_thumb(
+ dims.viewport_rows,
+ dims.scrollback_rows,
+ area.height as usize,
+ ui.scroll_offset(pane.pane_id()),
+ ) else {
return;
- }
- let height = area.height as usize;
- let thumb = ((dims.viewport_rows * height) / dims.scrollback_rows.max(1)).clamp(1, height);
- let offset = ui.scroll_offset(pane.pane_id()).min(scrollable);
- // Offset counts backwards from the live screen, and the bar runs forwards.
- let travel = height - thumb;
- let from_top = travel - (offset * travel) / scrollable.max(1);
+ };
+ fill(frame, area, "│", chrome_border());
fill(
frame,
- Rect::new(
- area.x,
- area.y + from_top as u16,
- area.width,
- thumb.min(height) as u16,
- ),
+ Rect::new(area.x, area.y + from_top as u16, area.width, thumb as u16),
"█",
chrome_accent_text(),
);
}
+fn scrollbar_thumb(
+ viewport_rows: usize,
+ scrollback_rows: usize,
+ height: usize,
+ offset: usize,
+) -> Option<(usize, usize)> {
+ let scrollable = scrollback_rows.saturating_sub(viewport_rows);
+ if scrollable == 0 || height == 0 {
+ return None;
+ }
+ let thumb = ((viewport_rows * height) / scrollback_rows.max(1)).clamp(1, height);
+ let offset = offset.min(scrollable);
+ // Offset counts backwards from the live screen, and the bar runs forwards.
+ let travel = height - thumb;
+ let from_top = travel - (offset * travel) / scrollable;
+ Some((from_top, thumb))
+}
+
+fn painted_viewport_top(
+ physical_top: StableRowIndex,
+ viewport_rows: usize,
+ height: usize,
+ offset: usize,
+ scrollback_rows: usize,
+ earliest: StableRowIndex,
+) -> StableRowIndex {
+ let live_top = physical_top.saturating_add(
+ viewport_rows
+ .saturating_sub(height)
+ .min(StableRowIndex::MAX as usize) as StableRowIndex,
+ );
+ live_top
+ .saturating_sub(offset.min(scrollback_rows) as StableRowIndex)
+ .max(earliest)
+}
+
fn paint_pane(frame: &mut Frame<'_>, pane: &Arc<dyn Pane>, area: Rect, ui: &UiState) {
if area.is_empty() {
return;
@@ -556,10 +906,18 @@ fn paint_pane(frame: &mut Frame<'_>, pane: &Arc<dyn Pane>, area: Rect, ui: &UiSt
let height = (area.height as usize).min(dims.scrollback_rows.max(dims.viewport_rows));
let offset = ui.scroll_offset(pane.pane_id());
let earliest = dims.scrollback_top;
- let top = dims
- .physical_top
- .saturating_sub(offset.min(dims.scrollback_rows) as StableRowIndex)
- .max(earliest);
+ // If chrome or an in-flight geometry update temporarily gives this pane a
+ // shorter rectangle than its PTY viewport, keep the live bottom anchored.
+ // Losing an old row at the top is harmless; losing the prompt, cursor or a
+ // full-screen application's status line is not.
+ let top = painted_viewport_top(
+ dims.physical_top,
+ dims.viewport_rows,
+ height,
+ offset,
+ dims.scrollback_rows,
+ earliest,
+ );
let (resolved_top, lines) = pane.get_lines(top..top + height as StableRowIndex);
// Named and indexed colors are forwarded as themselves rather than looked
// up in the pane's palette, so the host terminal resolves them the way it
@@ -697,17 +1055,7 @@ fn render_status(
// heaviest thing on it, and it is spending that weight on a hint. The bar
// keeps the background; only a mode worth noticing gets picked out.
fill(frame, view.status, " ", chrome());
- let left = match ui.mode {
- AppMode::Prefix => " PREFIX ? help b sidebar g go c tab v/- split x close ",
- AppMode::Navigate => " NAVIGATE ↑↓ thread hjkl pane Enter open Esc back ",
- AppMode::Resize => " RESIZE hjkl/arrows resize Enter/Esc finish ",
- AppMode::Copy => " COPY hjkl move Space select / search y copy Esc back ",
- AppMode::Search => " SEARCH Enter apply Esc cancel ",
- AppMode::Connections => " CONNECTIONS ↑↓ select Enter connect Esc back ",
- AppMode::Settings => " SETTINGS ↑↓ select ←→ change Esc close ",
- AppMode::Help => " HELP Esc close ",
- _ => " Ctrl-b commands ",
- };
+ let left = mode_hint(ui.mode);
let mode_style = if ui.mode == AppMode::Terminal {
chrome_dim()
} else {
@@ -778,6 +1126,20 @@ fn render_status(
}
}
+fn mode_hint(mode: AppMode) -> &'static str {
+ match mode {
+ AppMode::Prefix => " PREFIX ? help b sidebar g go c tab v/- split x close ",
+ AppMode::Navigate => " NAVIGATE ↑↓ thread hjkl pane Enter open Esc back ",
+ AppMode::Resize => " RESIZE hjkl/arrows resize Enter/Esc finish ",
+ AppMode::Copy => " COPY hjkl move Space select / search y copy Esc back ",
+ AppMode::Search => " SEARCH Enter apply Esc cancel ",
+ AppMode::Connections => " CONNECTIONS ↑↓ select Enter connect Esc back ",
+ AppMode::Settings => " SETTINGS ↑↓ select ←→ change Esc close ",
+ AppMode::Help => " HELP Esc close ",
+ _ => " Ctrl-b commands ",
+ }
+}
+
fn render_overlays(frame: &mut Frame<'_>, ui: &UiState, view: &ViewLayout, settings: &TuiConfig) {
if ui.mode == AppMode::Help {
render_help(frame, view.screen);
@@ -880,8 +1242,34 @@ fn render_overlays(frame: &mut Frame<'_>, ui: &UiState, view: &ViewLayout, setti
}
}
- if let Some(toast) = &ui.toast {
- let width = (unicode_column_width(&toast.message, None) as u16 + 4)
+ let floating_message = if !settings.show_status_bar {
+ ui.toast
+ .as_ref()
+ .map(|toast| (toast.message.as_str(), true))
+ .or_else(|| {
+ ui.pending.as_ref().map(|pending| {
+ // The allocation only lives for this draw, so keep pending
+ // rendering below where it can own the String.
+ (pending.label.as_str(), false)
+ })
+ })
+ .or_else(|| (!ui.status.is_empty()).then_some((ui.status.as_str(), false)))
+ } else {
+ ui.toast
+ .as_ref()
+ .map(|toast| (toast.message.as_str(), true))
+ };
+ if let Some((message, success)) = floating_message {
+ let pending_message = ui
+ .pending
+ .as_ref()
+ .map(|pending| format!("{} on {}…", pending.label, pending.domain_name));
+ let message = if !settings.show_status_bar && ui.toast.is_none() {
+ pending_message.as_deref().unwrap_or(message)
+ } else {
+ message
+ };
+ let width = (unicode_column_width(message, None) as u16 + 4)
.min(view.screen.width)
.max(4);
let rect = Rect::new(
@@ -894,8 +1282,15 @@ fn render_overlays(frame: &mut Frame<'_>, ui: &UiState, view: &ViewLayout, setti
fill(frame, rect, " ", chrome());
frame.render_widget(
Paragraph::new(TextLine::from(vec![
- Span::styled(" + ", chrome_success().add_modifier(Modifier::BOLD)),
- Span::raw(toast.message.as_str()),
+ Span::styled(
+ if success { " + " } else { " · " },
+ if success {
+ chrome_success().add_modifier(Modifier::BOLD)
+ } else {
+ chrome_accent_text().add_modifier(Modifier::BOLD)
+ },
+ ),
+ Span::raw(message),
]))
.style(chrome())
.block(
@@ -907,6 +1302,31 @@ fn render_overlays(frame: &mut Frame<'_>, ui: &UiState, view: &ViewLayout, setti
rect,
);
}
+
+ if !settings.show_status_bar
+ && matches!(
+ ui.mode,
+ AppMode::Prefix | AppMode::Navigate | AppMode::Resize | AppMode::Copy | AppMode::Search
+ )
+ && view.screen.height > 0
+ {
+ let hint = mode_hint(ui.mode);
+ let width = unicode_column_width(hint, None).min(view.screen.width as usize) as u16;
+ let rect = Rect::new(
+ view.screen.x,
+ view.screen.bottom().saturating_sub(1),
+ width,
+ 1,
+ );
+ frame.render_widget(Clear, rect);
+ fill(frame, rect, " ", chrome());
+ draw_text(
+ frame,
+ rect,
+ hint,
+ chrome_accent_text().add_modifier(Modifier::BOLD),
+ );
+ }
}
fn render_settings(frame: &mut Frame<'_>, ui: &UiState, view: &ViewLayout, settings: &TuiConfig) {
@@ -1317,12 +1737,121 @@ mod tests {
assert!(split_cell_needs_divider(&view, &split, 5, 2));
}
+ #[test]
+ fn pane_nav_rows_do_not_resurrect_detached_split_lines() {
+ let nav = |rect| PaneNav {
+ rect,
+ scroll_start: 0,
+ tabs: vec![],
+ overflow: vec![],
+ tools: vec![],
+ };
+
+ let side_split = SplitView {
+ index: 0,
+ rect: Rect::new(5, 0, 1, 4),
+ direction: SplitDirection::Horizontal,
+ };
+ let mut side_view = ViewLayout::default();
+ side_view.panes = vec![
+ PaneView {
+ nav: Some(nav(Rect::new(0, 0, 5, 1))),
+ ..divider_test_pane(1, Some(Rect::new(0, 1, 5, 3)))
+ },
+ PaneView {
+ nav: Some(nav(Rect::new(6, 0, 5, 1))),
+ ..divider_test_pane(2, Some(Rect::new(6, 1, 5, 3)))
+ },
+ ];
+ assert!(
+ !split_cell_needs_divider(&side_view, &side_split, 5, 0),
+ "the nav row is still covered by both framed pane outers"
+ );
+
+ side_view.panes = vec![
+ divider_test_pane(1, Some(Rect::new(0, 0, 5, 2))),
+ divider_test_pane(2, Some(Rect::new(0, 3, 5, 1))),
+ divider_test_pane(3, Some(Rect::new(6, 0, 5, 4))),
+ ];
+ assert!(
+ !split_cell_needs_divider(&side_view, &side_split, 5, 2),
+ "an orthogonal split gap must not leave a detached divider cell"
+ );
+
+ let row_split = SplitView {
+ index: 1,
+ rect: Rect::new(0, 4, 5, 1),
+ direction: SplitDirection::Vertical,
+ };
+ let mut row_view = ViewLayout::default();
+ row_view.splits = vec![row_split.clone()];
+ row_view.panes = vec![
+ divider_test_pane(1, Some(Rect::new(0, 0, 5, 4))),
+ PaneView {
+ nav: Some(nav(Rect::new(0, 5, 5, 1))),
+ ..divider_test_pane(2, Some(Rect::new(0, 6, 5, 3)))
+ },
+ ];
+ assert!(
+ !split_cell_needs_divider(&row_view, &row_split, 2, 4),
+ "a lower pane nav is the beginning of that framed pane"
+ );
+ assert_eq!(
+ painted_pane_border_rect(&row_view, &row_view.panes[0]),
+ Some(Rect::new(0, 0, 5, 5)),
+ "the upper frame uses the split gutter as its bottom edge"
+ );
+ }
+
+ #[test]
+ fn pane_chrome_composes_a_complete_box_and_real_junctions() {
+ let mut lines = PaneChromeLines::default();
+ lines.border(Rect::new(2, 1, 5, 4), Style::default(), 1);
+
+ let symbol = |x, y| {
+ pane_chrome_symbol(
+ lines
+ .cells
+ .get(&(x, y))
+ .expect("expected a chrome cell")
+ .connections,
+ )
+ };
+ assert_eq!(symbol(2, 1), "┌");
+ assert_eq!(symbol(6, 1), "┐");
+ assert_eq!(symbol(2, 4), "└");
+ assert_eq!(symbol(6, 4), "┘");
+ assert_eq!(symbol(4, 1), "─");
+ assert_eq!(symbol(2, 2), "│");
+
+ lines.add(4, 1, LINE_SOUTH, Style::default(), 0);
+ assert_eq!(
+ pane_chrome_symbol(lines.cells[&(4, 1)].connections),
+ "┬",
+ "a divider and frame edge must join instead of overwriting"
+ );
+ }
+
#[test]
fn fit_text_respects_cell_width() {
assert_eq!(fit_text("abc", 2), "ab");
assert_eq!(fit_text("你好x", 4), "你好");
}
+ #[test]
+ fn a_shorter_pane_rectangle_keeps_the_live_bottom_visible() {
+ assert_eq!(painted_viewport_top(100, 24, 20, 0, 200, 0), 104);
+ assert_eq!(painted_viewport_top(100, 24, 20, 3, 200, 0), 101);
+ assert_eq!(painted_viewport_top(2, 24, 20, 20, 24, 0), 0);
+ }
+
+ #[test]
+ fn scrollbar_has_no_visual_track_without_scrollback() {
+ assert_eq!(scrollbar_thumb(20, 20, 20, 0), None);
+ assert_eq!(scrollbar_thumb(20, 100, 20, 0), Some((16, 4)));
+ assert_eq!(scrollbar_thumb(20, 100, 20, 80), Some((0, 4)));
+ }
+
#[test]
fn terminal_default_chrome_uses_host_colors() {
let _guard = THEME_TEST_LOCK.lock().unwrap();
@@ -1351,6 +1880,79 @@ mod tests {
assert_eq!(chrome_selected().bg, Some(Color::Rgb(137, 180, 250)));
}
+ #[test]
+ fn level_two_tabs_separate_stack_selection_from_pane_focus() {
+ let _guard = THEME_TEST_LOCK.lock().unwrap();
+ crate::settings::set_active_theme(crate::settings::ThemeName::Dracula);
+
+ let surface = pane_nav_surface_style();
+ assert_eq!(surface.bg, Some(Color::Rgb(68, 71, 90)));
+
+ let focused = pane_nav_tab_style(true, true);
+ assert_eq!(focused.bg, Some(Color::Reset));
+ assert_eq!(focused.fg, Some(Color::Rgb(189, 147, 249)));
+ assert!(focused.add_modifier.contains(Modifier::BOLD));
+
+ let unfocused = pane_nav_tab_style(true, false);
+ assert_eq!(unfocused.bg, Some(Color::Reset));
+ assert_eq!(unfocused.fg, Some(Color::Rgb(248, 248, 242)));
+ assert!(unfocused.add_modifier.contains(Modifier::BOLD));
+
+ let inactive = pane_nav_tab_style(false, true);
+ assert_eq!(inactive.bg, Some(Color::Rgb(68, 71, 90)));
+ assert_eq!(inactive.fg, Some(Color::Rgb(98, 114, 164)));
+
+ crate::settings::set_active_theme(crate::settings::ThemeName::Terminal);
+ let surface = pane_nav_surface_style();
+ assert!(surface.add_modifier.contains(Modifier::REVERSED));
+ let terminal = pane_nav_tab_style(true, true);
+ assert!(terminal.add_modifier.contains(Modifier::UNDERLINED));
+ assert!(!terminal.add_modifier.contains(Modifier::REVERSED));
+ let inactive = pane_nav_tab_style(false, true);
+ assert!(inactive.add_modifier.contains(Modifier::REVERSED));
+ }
+
+ #[test]
+ fn level_two_bar_paints_a_full_width_layer() {
+ let _guard = THEME_TEST_LOCK.lock().unwrap();
+ use crate::view::{PaneNavTab, PaneTool};
+ use ratatui::backend::TestBackend;
+ use ratatui::Terminal;
+
+ crate::settings::set_active_theme(crate::settings::ThemeName::Dracula);
+ let nav = PaneNav {
+ rect: Rect::new(0, 0, 12, 1),
+ scroll_start: 0,
+ tabs: vec![PaneNavTab {
+ rect: Rect::new(0, 0, 5, 1),
+ pane_id: 1,
+ label: " zsh ".to_string(),
+ active: true,
+ close: None,
+ }],
+ overflow: vec![],
+ tools: vec![(Rect::new(10, 0, 2, 1), PaneTool::NewTab)],
+ };
+ let backend = TestBackend::new(12, 1);
+ let mut terminal = Terminal::new(backend).unwrap();
+ terminal
+ .draw(|frame| paint_pane_nav(frame, &nav, true))
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ assert_eq!(buffer[(1, 0)].bg, Color::Reset, "active tab opens below");
+ assert_eq!(
+ buffer[(7, 0)].bg,
+ Color::Rgb(68, 71, 90),
+ "unused space belongs to the nav layer"
+ );
+ assert_eq!(
+ buffer[(11, 0)].bg,
+ Color::Rgb(68, 71, 90),
+ "tools stay on the nav layer"
+ );
+ }
+
#[test]
fn handoff_overlay_clears_previously_rendered_terminal_cells() {
let _guard = THEME_TEST_LOCK.lock().unwrap();
diff --git a/thinkterm-tui/src/settings.rs b/thinkterm-tui/src/settings.rs
index fb8c3a07..64053dff 100644
--- a/thinkterm-tui/src/settings.rs
+++ b/thinkterm-tui/src/settings.rs
@@ -88,14 +88,17 @@ pub struct TuiConfig {
/// the server. Until the two agree, the bar is worth having only where the
/// last column can be spared.
pub pane_scrollbars: bool,
- /// Draw a frame around each pane, with the focused one picked out.
+ /// Draw a frame around each pane.
///
- /// On, and cheaper than it sounds: the pane's nav bar is drawn on the
- /// frame's top edge rather than under it, so the frame costs one row and
- /// two columns beyond what the bar already spends. What it buys is the
- /// thing a split screen most needs — an unambiguous edge, and somewhere for
- /// "this is the pane you are typing into" to live.
+ /// On by default for split layouts. The pane nav remains a separate layer
+ /// above the frame, so the terminal surface has one unambiguous, complete
+ /// outline rather than borrowing disconnected pieces of split dividers.
pub pane_borders: bool,
+ /// Keep the command/status strip at the bottom of the screen.
+ ///
+ /// Off by default: transient messages and non-terminal mode hints are
+ /// overlays, so showing or expiring one never changes the PTY grid.
+ pub show_status_bar: bool,
/// Give each pane a strip of its own carrying the panes stacked behind it
/// and what can be done to it.
///
@@ -119,6 +122,7 @@ impl Default for TuiConfig {
touch_targets: None,
pane_scrollbars: false,
pane_borders: true,
+ show_status_bar: false,
pane_nav_bar: true,
}
}
@@ -473,6 +477,7 @@ mod tests {
assert_eq!(config.sidebar_width, 18);
assert_eq!(config.scroll_lines, 20);
assert_eq!(config.theme, ThemeName::MonochromeDark);
+ assert!(config.pane_borders);
}
#[test]
diff --git a/thinkterm-tui/src/state.rs b/thinkterm-tui/src/state.rs
index 61735fe1..4d7c8b98 100644
--- a/thinkterm-tui/src/state.rs
+++ b/thinkterm-tui/src/state.rs
@@ -165,9 +165,16 @@ pub struct UiState {
pub pane_scrollbars: bool,
/// Mirrors `TuiConfig::pane_borders`.
pub pane_borders: bool,
+ /// Mirrors `TuiConfig::show_status_bar`.
+ pub show_status_bar: bool,
/// Mirrors `TuiConfig::pane_nav_bar`.
pub pane_nav_bar: bool,
pub sidebar_scroll: usize,
+ /// First preferred level-1 tab. Layout adjusts it as needed to keep the
+ /// active tab visible.
+ pub tab_scroll: usize,
+ /// First preferred level-2 tab for each pane stack.
+ pub pane_nav_scroll: HashMap<PaneId, usize>,
pub tree_collapsed: BTreeSet<TreeNodeKey>,
/// Lines above the physical screen for each pane. Zero follows output.
pub scroll_offsets: HashMap<PaneId, usize>,
@@ -181,6 +188,9 @@ pub struct UiState {
pub connection_index: usize,
pub settings_index: usize,
pub status: String,
+ status_observed: String,
+ status_expires_at: Option<Instant>,
+ status_persistent: bool,
pub toast: Option<Toast>,
pub exit: bool,
pub frame_number: u64,
@@ -188,6 +198,8 @@ pub struct UiState {
impl UiState {
pub fn new(status: String) -> Self {
+ let status_expires_at =
+ (!status.is_empty()).then(|| Instant::now() + Duration::from_secs(8));
Self {
sidebar_visible: true,
sidebar_width: 26,
@@ -195,7 +207,10 @@ impl UiState {
touch_targets: None,
pane_scrollbars: false,
pane_borders: true,
+ show_status_bar: false,
pane_nav_bar: true,
+ status_observed: status.clone(),
+ status_expires_at,
status,
..Default::default()
}
@@ -231,6 +246,46 @@ impl UiState {
.map(|toast| toast.expires_at.saturating_duration_since(now))
}
+ fn synchronize_status_deadline(&mut self, now: Instant) {
+ if self.status_observed == self.status {
+ return;
+ }
+ self.status_observed.clone_from(&self.status);
+ self.status_persistent = false;
+ self.status_expires_at = (!self.status.is_empty()).then(|| now + Duration::from_secs(8));
+ }
+
+ pub fn set_persistent_status(&mut self, message: impl Into<String>) {
+ self.status = message.into();
+ self.status_observed.clone_from(&self.status);
+ self.status_persistent = true;
+ self.status_expires_at = None;
+ }
+
+ pub fn expire_status(&mut self, now: Instant) -> bool {
+ self.synchronize_status_deadline(now);
+ if !self.status_persistent
+ && self
+ .status_expires_at
+ .is_some_and(|expires_at| expires_at <= now)
+ {
+ self.status.clear();
+ self.status_observed.clear();
+ self.status_expires_at = None;
+ true
+ } else {
+ false
+ }
+ }
+
+ pub fn status_timeout(&mut self, now: Instant) -> Option<Duration> {
+ self.synchronize_status_deadline(now);
+ (!self.status_persistent)
+ .then_some(self.status_expires_at)
+ .flatten()
+ .map(|expires_at| expires_at.saturating_duration_since(now))
+ }
+
pub fn scroll_offset(&self, pane_id: PaneId) -> usize {
self.scroll_offsets.get(&pane_id).copied().unwrap_or(0)
}
@@ -276,4 +331,19 @@ mod tests {
assert!(ui.expire_toast(now + Duration::from_secs(3)));
assert!(ui.toast.is_none());
}
+
+ #[test]
+ fn ordinary_status_expires_but_progress_waits_for_explicit_completion() {
+ let now = Instant::now();
+ let mut ui = UiState::new(String::new());
+ ui.status = "something failed".into();
+ assert_eq!(ui.status_timeout(now), Some(Duration::from_secs(8)));
+ assert!(!ui.expire_status(now + Duration::from_secs(7)));
+ assert!(ui.expire_status(now + Duration::from_secs(8)));
+
+ ui.set_persistent_status("resyncing");
+ assert_eq!(ui.status_timeout(now), None);
+ assert!(!ui.expire_status(now + Duration::from_secs(60)));
+ assert_eq!(ui.status, "resyncing");
+ }
}
diff --git a/thinkterm-tui/src/view.rs b/thinkterm-tui/src/view.rs
index c3f58954..c0e31354 100644
--- a/thinkterm-tui/src/view.rs
+++ b/thinkterm-tui/src/view.rs
@@ -83,11 +83,20 @@ impl PaneTool {
#[derive(Clone, Debug)]
pub struct PaneNav {
pub rect: Rect,
+ pub scroll_start: usize,
/// One entry per pane in this pane's stack, already positioned.
pub tabs: Vec<PaneNavTab>,
+ pub overflow: Vec<TabOverflowButton>,
pub tools: Vec<(Rect, PaneTool)>,
}
+#[derive(Clone, Debug)]
+pub struct TabOverflowButton {
+ pub rect: Rect,
+ pub direction: isize,
+ pub hidden: usize,
+}
+
#[derive(Clone, Debug)]
pub struct PaneNavTab {
pub rect: Rect,
@@ -113,10 +122,12 @@ pub enum HitTarget {
Tab(TabId),
CloseTab(TabId),
TabControl(TabBarControl),
+ TabScroll(isize),
Pane(PaneId),
/// Show this pane, which is stacked behind the one currently drawn there.
PaneNavTab(PaneId),
PaneNavClose(PaneId),
+ PaneNavScroll(PaneId, isize),
PaneTool(PaneId, PaneTool),
Scrollbar(PaneId),
Split(usize),
@@ -174,8 +185,8 @@ pub struct PaneView {
pub scrollbar: Option<Rect>,
/// The pane's own strip, when it had a row to spare for one.
pub nav: Option<PaneNav>,
- /// The frame drawn around the pane, when it has one. Encloses the grid, its
- /// scrollbar and its nav bar.
+ /// The frame drawn around the pane, when it has one. It starts below the
+ /// pane nav layer and encloses only the grid and scrollbar.
pub border: Option<Rect>,
/// A split branch too short to show normal chrome and a useful grid. It is
/// painted as an explicit compact pane instead of an orphaned output row.
@@ -208,8 +219,14 @@ pub struct ViewLayout {
pub tab_bar: Rect,
pub content: Rect,
pub status: Rect,
+ /// The narrow-screen tree is painted over this terminal surface. Pane
+ /// geometry remains populated for viewport negotiation, but is neither
+ /// painted nor interactive until the tree is dismissed.
+ pub terminal_obscured: bool,
pub tree_lines: Vec<TreeLine>,
pub tabs: Vec<TabLine>,
+ pub tab_scroll_start: usize,
+ pub tab_overflow: Vec<TabOverflowButton>,
/// Trailing tab-bar buttons, already positioned.
pub tab_controls: Vec<(Rect, TabBarControl)>,
pub panes: Vec<PaneView>,
@@ -236,8 +253,11 @@ impl Default for ViewLayout {
tab_bar: Rect::default(),
content: Rect::default(),
status: Rect::default(),
+ terminal_obscured: false,
tree_lines: vec![],
tabs: vec![],
+ tab_scroll_start: 0,
+ tab_overflow: vec![],
tab_controls: vec![],
panes: vec![],
splits: vec![],
@@ -293,9 +313,8 @@ pub fn compute_view(
let narrow = view.class == ViewClass::Narrow;
// A finger needs more than one row to land on reliably, so a screen being
// pointed at with one spends a second row on the bar that carries every
- // button — and buys that row back from the footer, which without a keyboard
- // was spending it to name key chords. Messages still get a row, but only
- // while there is a message to put in it.
+ // button. Transient messages and mode hints are overlays; only the explicit
+ // bottom-bar preference may reserve a footer row.
//
// Tying this to the layout being narrow is only ever a guess: the same
// phone turned sideways reports enough columns to look like a desktop and
@@ -306,11 +325,7 @@ pub fn compute_view(
} else {
u16::from(area.height >= 3)
};
- let status_height = if touch {
- u16::from(area.height >= 2 && (!ui.status.is_empty() || ui.toast.is_some()))
- } else {
- u16::from(area.height >= 2)
- };
+ let status_height = u16::from(ui.show_status_bar && area.height >= 2);
view.status = Rect::new(
area.x,
area.bottom().saturating_sub(status_height),
@@ -468,14 +483,25 @@ pub fn compute_view(
} else {
view.tab_bar
};
- compute_tabs(model, tabs_area, &mut view);
- // Skipped only when the tree is genuinely on top of them. Testing `overlay`
- // alone was wrong: a narrow screen with the tree *dismissed* is the normal
- // way to use a phone zoomed in, and it left the terminal undrawn — a tab
- // bar over an empty screen. `content` still says how big the panes are
- // either way, which is what gets advertised to the server.
- if let (Some(tab), false) = (tab, tree_covers_terminal(&view)) {
- compute_panes(tab, ui, view.content, &mut view);
+ compute_tabs(model, ui, tabs_area, &mut view);
+ view.terminal_obscured = tree_covers_terminal(&view);
+ if let Some(tab) = tab {
+ if view.terminal_obscured {
+ // Drawing and sizing are separate decisions. Keep the hidden
+ // terminal's exact pane geometry current so opening/closing the
+ // tree does not advertise an empty viewport and then resize every
+ // PTY one frame later. Discard the scratch hit regions because the
+ // tree owns pointer input while it covers the terminal.
+ let mut geometry = ViewLayout {
+ class: view.class,
+ ..Default::default()
+ };
+ compute_panes(tab, ui, view.content, &mut geometry);
+ view.panes = geometry.panes;
+ view.splits = geometry.splits;
+ } else {
+ compute_panes(tab, ui, view.content, &mut view);
+ }
}
if view.status.width >= 8 {
@@ -699,7 +725,45 @@ fn compute_tree(model: &AppModel, ui: &UiState, body: Rect, view: &mut ViewLayou
/// Columns a tree row keeps for its own name before it will host any buttons.
const MIN_LABEL_COLUMNS: u16 = 12;
-fn compute_tabs(model: &AppModel, area: Rect, view: &mut ViewLayout) {
+fn visible_item_window(
+ widths: &[u16],
+ requested_start: usize,
+ selected: usize,
+ budget: u16,
+) -> (usize, usize) {
+ if widths.is_empty() || budget == 0 {
+ return (0, 0);
+ }
+ let mut start = requested_start.min(widths.len() - 1);
+ if selected < start {
+ start = selected;
+ }
+ loop {
+ let mut used = 0u16;
+ let mut end = start;
+ while end < widths.len() {
+ let width = widths[end].min(budget);
+ if end > start && used.saturating_add(width) > budget {
+ break;
+ }
+ used = used.saturating_add(width);
+ end += 1;
+ if used >= budget {
+ break;
+ }
+ }
+ if selected < end || start >= selected {
+ return (start, end.max(start + 1).min(widths.len()));
+ }
+ start += 1;
+ }
+}
+
+fn overflow_button_width(available: u16) -> u16 {
+ 5.min((available / 3).max(1))
+}
+
+fn compute_tabs(model: &AppModel, ui: &UiState, area: Rect, view: &mut ViewLayout) {
if area.height == 0 || area.width == 0 {
return;
}
@@ -722,39 +786,78 @@ fn compute_tabs(model: &AppModel, area: Rect, view: &mut ViewLayout) {
}
let tabs_right = edge;
let selected = model.selected_tab().map(|tab| tab.tab_id);
+ let close_width = tab_bar_control_width(area.height);
+ let candidates = model
+ .tabs_for_selected_thread()
+ .iter()
+ .enumerate()
+ .map(|(index, tab)| {
+ let title = if tab.title.trim().is_empty() {
+ "shell"
+ } else {
+ tab.title.trim()
+ };
+ let label = format!(" {}:{} ", index + 1, title);
+ let label_width =
+ unicode_column_width(&label, None).min(TAB_MAX_COLUMNS as usize) as u16;
+ (tab.tab_id, label, label_width.saturating_add(close_width))
+ })
+ .collect::<Vec<_>>();
+ if candidates.is_empty() {
+ return;
+ }
+ let widths = candidates
+ .iter()
+ .map(|(_, _, width)| *width)
+ .collect::<Vec<_>>();
+ let outer_width = tabs_right.saturating_sub(area.x);
+ let overflowing = widths.iter().map(|width| *width as u32).sum::<u32>() > outer_width as u32;
+ let overflow_width =
+ (overflowing && outer_width >= 3).then(|| overflow_button_width(outer_width));
+ let tab_budget = outer_width.saturating_sub(overflow_width.unwrap_or(0).saturating_mul(2));
+ let selected_index = selected
+ .and_then(|selected| candidates.iter().position(|(id, _, _)| *id == selected))
+ .unwrap_or(0);
+ let requested_start = if overflowing { ui.tab_scroll } else { 0 };
+ let (start, end) = visible_item_window(&widths, requested_start, selected_index, tab_budget);
+ view.tab_scroll_start = start;
let mut x = area.x;
- for (index, tab) in model.tabs_for_selected_thread().iter().enumerate() {
- if x >= tabs_right {
- break;
+ if let Some(button_width) = overflow_width {
+ let rect = Rect::new(x, area.y, button_width, area.height);
+ let hidden = start;
+ if hidden > 0 {
+ view.hits.push(HitRegion {
+ rect,
+ target: HitTarget::TabScroll(-1),
+ });
}
- let title = if tab.title.trim().is_empty() {
- "shell"
- } else {
- tab.title.trim()
- };
- let label = format!(" {}:{} ", index + 1, title);
- let desired = unicode_column_width(&label, None).min(u16::MAX as usize) as u16;
- // Room for the tab's own close button, but only where the name still
- // has somewhere to go afterwards.
- let close_width = tab_bar_control_width(area.height);
- let want_close = tabs_right.saturating_sub(x) >= desired + close_width;
- let width = (desired + if want_close { close_width } else { 0 }).min(tabs_right - x);
+ view.tab_overflow.push(TabOverflowButton {
+ rect,
+ direction: -1,
+ hidden,
+ });
+ x += button_width;
+ }
+ let visible_right = tabs_right.saturating_sub(overflow_width.unwrap_or(0));
+ for (tab_id, label, desired) in &candidates[start..end] {
+ let width = (*desired).min(visible_right.saturating_sub(x));
if width == 0 {
break;
}
let rect = Rect::new(x, area.y, width, area.height);
+ let want_close = width >= close_width.saturating_add(3);
let close = want_close.then(|| {
let rect = Rect::new(rect.right() - close_width, rect.y, close_width, rect.height);
view.hits.push(HitRegion {
rect,
- target: HitTarget::CloseTab(tab.tab_id),
+ target: HitTarget::CloseTab(*tab_id),
});
rect
});
view.tabs.push(TabLine {
rect,
- label,
- selected: selected == Some(tab.tab_id),
+ label: label.clone(),
+ selected: selected == Some(*tab_id),
close,
});
// Pushed before the close button above so the narrower target wins the
@@ -763,11 +866,26 @@ fn compute_tabs(model: &AppModel, area: Rect, view: &mut ViewLayout) {
view.hits.len().saturating_sub(usize::from(close.is_some())),
HitRegion {
rect,
- target: HitTarget::Tab(tab.tab_id),
+ target: HitTarget::Tab(*tab_id),
},
);
x = x.saturating_add(width);
}
+ if let Some(button_width) = overflow_width {
+ let rect = Rect::new(visible_right, area.y, button_width, area.height);
+ let hidden = candidates.len().saturating_sub(end);
+ if hidden > 0 {
+ view.hits.push(HitRegion {
+ rect,
+ target: HitTarget::TabScroll(1),
+ });
+ }
+ view.tab_overflow.push(TabOverflowButton {
+ rect,
+ direction: 1,
+ hidden,
+ });
+ }
}
/// Trailing tab-bar controls, most worth keeping first. A bar too narrow for
@@ -778,6 +896,10 @@ pub const TAB_BAR_CONTROLS: [TabBarControl; 2] = [TabBarControl::Menu, TabBarCon
/// Columns the tab bar keeps for tabs before it will host any control.
const MIN_TAB_COLUMNS: u16 = 10;
+/// Natural tab titles remain readable without allowing one command line to
+/// consume the whole row. Overflow scrolls by complete tabs.
+const TAB_MAX_COLUMNS: u16 = 28;
+
/// Width of one tab-bar control. A bar with room for two rows is a bar meant to
/// be touched, so its buttons widen to match their new height.
pub fn tab_bar_control_width(height: u16) -> u16 {
@@ -797,16 +919,10 @@ pub fn tab_bar_control_width(height: u16) -> u16 {
/// half. The thresholds are what "there is room to spare" means here.
const SCROLLBAR_MIN_COLUMNS: u16 = 34;
/// A frame is cheaper than it looks, because the pane's nav bar is drawn *on*
-/// its top edge rather than under it — the way a titled box works. So the frame
-/// costs one row (the bottom edge) and two columns beyond what the bar already
-/// spends, not two rows and two columns. That is affordable on a phone, which
-/// is why these are low.
-/// Tied to what the nav bar already needs, plus the one row and two columns the
-/// frame adds. A pane that can afford a bar can afford a frame, so the two
-/// never disagree — a split where one half is framed and the other is not reads
-/// as broken rather than as economical.
+/// The nav is a separate row above the frame. A framed pane therefore needs
+/// two frame rows in addition to the nav and at least two rows of grid.
const BORDER_MIN_COLUMNS: u16 = MIN_LABEL_COLUMNS + 2;
-const BORDER_MIN_ROWS: u16 = PANE_NAV_MIN_ROWS + 1;
+const BORDER_MIN_ROWS: u16 = PANE_NAV_MIN_ROWS + 2;
/// Rows a pane keeps for its grid before it will spend one on its own nav bar.
///
@@ -823,6 +939,33 @@ const PANE_NAV_MIN_ROWS: u16 = 3;
/// the rest of the stack.
const PANE_NAV_TAB_MAX_COLUMNS: u16 = 18;
+fn pane_frame_and_grid(rect: Rect, bar_rows: u16, framed: bool) -> (Option<Rect>, Rect) {
+ if !framed {
+ return (
+ None,
+ Rect::new(
+ rect.x,
+ rect.y + bar_rows,
+ rect.width,
+ rect.height.saturating_sub(bar_rows),
+ ),
+ );
+ }
+ let border = Rect::new(
+ rect.x,
+ rect.y + bar_rows,
+ rect.width,
+ rect.height.saturating_sub(bar_rows),
+ );
+ let grid = Rect::new(
+ rect.x + 1,
+ rect.y + bar_rows + 1,
+ rect.width.saturating_sub(2),
+ rect.height.saturating_sub(bar_rows + 2),
+ );
+ (Some(border), grid)
+}
+
fn compute_panes(tab: &Arc<Tab>, ui: &UiState, area: Rect, view: &mut ViewLayout) {
if area.width == 0 || area.height == 0 {
return;
@@ -849,28 +992,12 @@ fn compute_panes(tab: &Arc<Tab>, ui: &UiState, area: Rect, view: &mut ViewLayout
continue;
}
let collapsed = (pane_count > 1 && rect.height < PANE_NAV_MIN_ROWS).then_some(rect);
- // Only where there is another pane to be told apart from. A lone pane
- // already has the window's own edges; framing it spends a row and two
- // columns to draw a line around the only thing on screen.
- let framed = ui.pane_borders
- && pane_count > 1
- && rect.width >= BORDER_MIN_COLUMNS
- && rect.height >= BORDER_MIN_ROWS;
- let border = framed.then_some(rect);
let pane_id = positioned.pane.pane_id();
- // The bar sits *on* the frame's top edge, between its corners, so a
- // framed pane pays one row for the bar and one for the bottom edge
- // rather than one for each of three lines.
- let bar_area = if framed {
- Rect::new(rect.x + 1, rect.y, rect.width - 2, rect.height)
- } else {
- rect
- };
// Above the grid, never over it, for the same reason as the scrollbar:
// the row it takes is a row the terminal is then told it does not have.
let stack = tab.pane_stack_tabs(pane_id);
let nav = if collapsed.is_some() && ui.pane_nav_bar {
- compute_collapsed_pane_nav(pane_id, &stack, positioned.is_zoomed, touch, bar_area, view)
+ compute_collapsed_pane_nav(pane_id, &stack, positioned.is_zoomed, touch, rect, view)
} else {
compute_pane_nav(
pane_id,
@@ -878,28 +1005,21 @@ fn compute_panes(tab: &Arc<Tab>, ui: &UiState, area: Rect, view: &mut ViewLayout
positioned.is_zoomed,
ui.pane_nav_bar,
touch,
- bar_area,
+ ui.pane_nav_scroll.get(&pane_id).copied().unwrap_or(0),
+ rect,
view,
)
};
let bar_rows = nav.as_ref().map_or(0, |nav| nav.rect.height);
- let rect = if framed {
- // The top edge is already spent on the bar (or is a plain edge when
- // there is no bar), so the grid starts one row down either way.
- Rect::new(
- rect.x + 1,
- rect.y + 1,
- rect.width - 2,
- rect.height.saturating_sub(2),
- )
- } else {
- Rect::new(
- rect.x,
- rect.y + bar_rows,
- rect.width,
- rect.height - bar_rows,
- )
- };
+ // Only where there is another pane to be told apart from. The nav is a
+ // sibling above the frame, not a title punched through its top edge;
+ // this keeps all four frame edges complete and visually coherent.
+ let framed = ui.pane_borders
+ && pane_count > 1
+ && rect.width >= BORDER_MIN_COLUMNS
+ && rect.height >= BORDER_MIN_ROWS
+ && rect.height.saturating_sub(bar_rows) >= 3;
+ let (border, rect) = pane_frame_and_grid(rect, bar_rows, framed);
// The scrollbar lives beside the grid, never over it: the column it
// takes is a column the terminal is then told it does not have, so a
// program's own right margin still lands where it drew it.
@@ -1007,7 +1127,9 @@ fn compute_collapsed_pane_nav(
Some(PaneNav {
rect: bar,
+ scroll_start: 0,
tabs,
+ overflow: vec![],
tools: vec![(tool, zoom)],
})
}
@@ -1018,6 +1140,7 @@ fn compute_pane_nav(
zoomed: bool,
enabled: bool,
touch: bool,
+ requested_start: usize,
rect: Rect,
view: &mut ViewLayout,
) -> Option<PaneNav> {
@@ -1059,26 +1182,59 @@ fn compute_pane_nav(
}
tools.reverse();
- let mut tabs = Vec::new();
+ let candidates = stack
+ .iter()
+ .map(|entry| {
+ let title = if entry.title.trim().is_empty() {
+ "shell"
+ } else {
+ entry.title.trim()
+ };
+ // No icon before the name. `▯` was there to mark a terminal, and on a
+ // phone whose font does not carry U+25AF it drew a tofu box that read
+ // as a bug. The name is doing the naming already.
+ let label = format!(" {title} ");
+ let desired = unicode_column_width(&label, None)
+ .min(u16::MAX as usize)
+ .min(PANE_NAV_TAB_MAX_COLUMNS as usize) as u16
+ + button;
+ (entry, label, desired)
+ })
+ .collect::<Vec<_>>();
+ let widths = candidates
+ .iter()
+ .map(|(_, _, width)| *width)
+ .collect::<Vec<_>>();
+ let outer_width = edge.saturating_sub(bar.x);
+ let overflowing = widths.iter().map(|width| *width as u32).sum::<u32>() > outer_width as u32;
+ let overflow_width =
+ (overflowing && outer_width >= 3).then(|| overflow_button_width(outer_width));
+ let tab_budget = outer_width.saturating_sub(overflow_width.unwrap_or(0).saturating_mul(2));
+ let active = stack.iter().position(|entry| entry.is_active).unwrap_or(0);
+ let requested_start = if overflowing { requested_start } else { 0 };
+ let (start, end) = visible_item_window(&widths, requested_start, active, tab_budget);
+ let mut overflow = Vec::new();
let mut x = bar.x;
- for entry in stack {
- if x >= edge {
- break;
+ if let Some(width) = overflow_width {
+ let rect = Rect::new(x, bar.y, width, bar.height);
+ let hidden = start;
+ if hidden > 0 {
+ view.hits.push(HitRegion {
+ rect,
+ target: HitTarget::PaneNavScroll(pane_id, -1),
+ });
}
- let title = if entry.title.trim().is_empty() {
- "shell"
- } else {
- entry.title.trim()
- };
- // No icon before the name. `▯` was there to mark a terminal, and on a
- // phone whose font does not carry U+25AF it drew a tofu box that read
- // as a bug. The name is doing the naming already.
- let label = format!(" {title} ");
- let desired = unicode_column_width(&label, None)
- .min(u16::MAX as usize)
- .min(PANE_NAV_TAB_MAX_COLUMNS as usize) as u16;
- let want_close = edge.saturating_sub(x) >= desired + button;
- let width = (desired + if want_close { button } else { 0 }).min(edge - x);
+ overflow.push(TabOverflowButton {
+ rect,
+ direction: -1,
+ hidden,
+ });
+ x += width;
+ }
+ let visible_right = edge.saturating_sub(overflow_width.unwrap_or(0));
+ let mut tabs = Vec::new();
+ for (entry, label, desired) in &candidates[start..end] {
+ let width = (*desired).min(visible_right.saturating_sub(x));
if width == 0 {
break;
}
@@ -1089,7 +1245,7 @@ fn compute_pane_nav(
});
// Pushed after the tab so the narrower target wins the hit test —
// `hit` searches from the back.
- let close = want_close.then(|| {
+ let close = (width >= button.saturating_add(3)).then(|| {
let rect = Rect::new(rect.right() - button, rect.y, button, rect.height);
view.hits.push(HitRegion {
rect,
@@ -1100,16 +1256,33 @@ fn compute_pane_nav(
tabs.push(PaneNavTab {
rect,
pane_id: entry.pane_id,
- label,
+ label: label.clone(),
active: entry.is_active,
close,
});
x = x.saturating_add(width);
}
+ if let Some(width) = overflow_width {
+ let rect = Rect::new(visible_right, bar.y, width, bar.height);
+ let hidden = candidates.len().saturating_sub(end);
+ if hidden > 0 {
+ view.hits.push(HitRegion {
+ rect,
+ target: HitTarget::PaneNavScroll(pane_id, 1),
+ });
+ }
+ overflow.push(TabOverflowButton {
+ rect,
+ direction: 1,
+ hidden,
+ });
+ }
Some(PaneNav {
rect: bar,
+ scroll_start: start,
tabs,
+ overflow,
tools,
})
}
@@ -1194,7 +1367,13 @@ fn compute_overlays(ui: &UiState, view: &mut ViewLayout) {
}
} else if ui.mode == crate::state::AppMode::Settings {
let width = view.screen.width.saturating_sub(4).clamp(1, 64);
- let height = 10.min(view.screen.height.saturating_sub(2).max(1));
+ let section_rows = crate::SETTINGS
+ .windows(2)
+ .filter(|rows| rows[0].0 != rows[1].0)
+ .count() as u16
+ + 1;
+ let height = (crate::SETTINGS.len() as u16 + section_rows + 2)
+ .min(view.screen.height.saturating_sub(2).max(1));
let rect = Rect::new(
view.screen.x + view.screen.width.saturating_sub(width) / 2,
view.screen.y + view.screen.height.saturating_sub(height) / 2,
@@ -1202,14 +1381,20 @@ fn compute_overlays(ui: &UiState, view: &mut ViewLayout) {
height,
);
view.dialog = Some(rect);
- for index in 0..5 {
- let row = rect.y.saturating_add(2 + index as u16);
+ let mut row = rect.y.saturating_add(1);
+ let mut section = "";
+ for (index, (row_section, _)) in crate::SETTINGS.iter().enumerate() {
+ if *row_section != section {
+ section = row_section;
+ row = row.saturating_add(1);
+ }
if row < rect.bottom().saturating_sub(1) {
view.hits.push(HitRegion {
rect: Rect::new(rect.x + 1, row, rect.width.saturating_sub(2), 1),
target: HitTarget::Setting(index),
});
}
+ row = row.saturating_add(1);
}
} else if ui.prompt.is_some() || ui.confirmation.is_some() {
let width = view.screen.width.saturating_sub(4).clamp(1, 64);
@@ -1257,7 +1442,7 @@ mod tests {
fn nav(rect: Rect, stack: &[PaneStackTab], zoomed: bool, touch: bool) -> (PaneNav, ViewLayout) {
let mut view = ViewLayout::default();
- let nav = compute_pane_nav(1, stack, zoomed, true, touch, rect, &mut view)
+ let nav = compute_pane_nav(1, stack, zoomed, true, touch, 0, rect, &mut view)
.expect("a pane this size has room for its own bar");
(nav, view)
}
@@ -1370,6 +1555,7 @@ mod tests {
false,
true,
false,
+ 0,
Rect::new(0, 0, 60, 2),
&mut view
)
@@ -1384,6 +1570,7 @@ mod tests {
false,
true,
false,
+ 0,
Rect::new(0, 0, 11, 20),
&mut view
)
@@ -1397,6 +1584,7 @@ mod tests {
false,
false,
false,
+ 0,
Rect::new(0, 0, 60, 20),
&mut view
)
@@ -1415,6 +1603,7 @@ mod tests {
false,
true,
false,
+ 0,
Rect::new(0, 0, 60, 7),
&mut short
)
@@ -1456,6 +1645,49 @@ mod tests {
assert_eq!(touch.tools[0].0.width, 3);
}
+ #[test]
+ fn level_two_overflow_keeps_the_active_tab_visible_and_uses_complete_buttons() {
+ let entries = stack(
+ &[
+ "shell", "vim", "logs", "server", "tests", "build", "watch", "notes",
+ ],
+ 6,
+ );
+ let mut view = ViewLayout::default();
+ let bar = compute_pane_nav(
+ 1,
+ &entries,
+ false,
+ true,
+ false,
+ 0,
+ Rect::new(0, 0, 42, 20),
+ &mut view,
+ )
+ .unwrap();
+ assert_eq!(bar.overflow.len(), 2);
+ assert!(bar.overflow[0].hidden > 0);
+ assert!(bar.tabs.iter().any(|tab| tab.active));
+ assert!(bar
+ .tabs
+ .windows(2)
+ .all(|tabs| tabs[0].rect.right() <= tabs[1].rect.x));
+ assert!(bar.tabs.last().unwrap().rect.right() <= bar.overflow[1].rect.x);
+ assert!(bar.overflow[1].rect.right() <= bar.tools[0].0.x);
+ }
+
+ #[test]
+ fn pane_frame_starts_below_the_level_two_layer_and_keeps_all_four_edges() {
+ let outer = Rect::new(4, 7, 40, 12);
+ let (border, grid) = pane_frame_and_grid(outer, 1, true);
+ assert_eq!(border, Some(Rect::new(4, 8, 40, 11)));
+ assert_eq!(grid, Rect::new(5, 9, 38, 9));
+ let border = border.unwrap();
+ assert_eq!(border.bottom(), outer.bottom());
+ assert_eq!(grid.y, border.y + 1);
+ assert_eq!(grid.bottom(), border.bottom() - 1);
+ }
+
fn model_with_threads() -> AppModel {
let mut model = AppModel::default();
model.apply_snapshot(
@@ -1490,6 +1722,45 @@ mod tests {
model
}
+ fn model_with_many_tabs() -> AppModel {
+ let mut model = AppModel::default();
+ model.apply_snapshot(
+ "server",
+ ThinkTermSessionState {
+ server_id: "runtime".into(),
+ generation: 1,
+ spaces: vec![ThinkTermSessionSpace {
+ id: "space".into(),
+ name: "Space".into(),
+ ..Default::default()
+ }],
+ projects: vec![ThinkTermSessionProject {
+ id: "project".into(),
+ space_id: "space".into(),
+ name: "Project".into(),
+ threads: vec![codec::ThinkTermSessionThread {
+ id: "thread".into(),
+ project_id: "project".into(),
+ name: "Thread".into(),
+ tabs: (0..9)
+ .map(|index| codec::ThinkTermSessionTab {
+ window_id: 1,
+ tab_id: index + 1,
+ pane_ids: vec![index + 1],
+ title: format!("command-{index}"),
+ is_active: index == 7,
+ })
+ .collect(),
+ ..Default::default()
+ }],
+ ..Default::default()
+ }],
+ ..Default::default()
+ },
+ );
+ model
+ }
+
#[test]
fn view_classes_are_deterministic() {
assert_eq!(classify(64, 64), ViewClass::Narrow);
@@ -1524,6 +1795,22 @@ mod tests {
assert_eq!(view.hit(1, 0), Some(&HitTarget::SidebarToggle));
}
+ #[test]
+ fn level_one_overflow_keeps_the_selected_tab_and_exposes_both_directions() {
+ let model = model_with_many_tabs();
+ let mut ui = UiState::new(String::new());
+ ui.sidebar_visible = false;
+ let view = compute_view(Rect::new(0, 0, 64, 20), &model, &ui, None);
+ assert_eq!(view.tab_overflow.len(), 2);
+ assert!(view.tab_overflow[0].hidden > 0);
+ assert!(view.tabs.iter().any(|tab| tab.selected));
+ assert!(view
+ .tabs
+ .windows(2)
+ .all(|tabs| tabs[0].rect.right() <= tabs[1].rect.x));
+ assert!(view.tabs.last().unwrap().rect.right() <= view.tab_overflow[1].rect.x);
+ }
+
#[test]
fn every_settings_row_has_an_exact_modal_hit() {
let model = model_with_threads();
@@ -1531,11 +1818,18 @@ mod tests {
ui.mode = crate::state::AppMode::Settings;
let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);
let dialog = view.dialog.unwrap();
- for index in 0..5 {
+ let mut row = dialog.y + 1;
+ let mut section = "";
+ for (index, (row_section, _)) in crate::SETTINGS.iter().enumerate() {
+ if *row_section != section {
+ section = row_section;
+ row += 1;
+ }
assert_eq!(
- view.hit(dialog.x + 2, dialog.y + 2 + index as u16),
+ view.hit(dialog.x + 2, row),
Some(&HitTarget::Setting(index))
);
+ row += 1;
}
}
@@ -1787,10 +2081,10 @@ mod tests {
assert_eq!(narrow.tab_bar.height, 1);
}
- /// A message still needs somewhere to go; it just does not get to keep a
- /// row of the terminal when there is nothing to report.
+ /// Messages float over the terminal and never resize it. The optional
+ /// persistent status bar is the only setting that spends a row.
#[test]
- fn narrow_view_reclaims_the_footer_row_only_while_it_is_empty() {
+ fn narrow_view_messages_never_change_the_footer_geometry() {
let model = model_with_threads();
let mut ui = UiState::new(String::new());
ui.sidebar_visible = false;
@@ -1799,8 +2093,13 @@ mod tests {
ui.status = "Viewport: something went wrong".to_string();
let noisy = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);
- assert_eq!(noisy.status.height, 1);
- assert_eq!(noisy.content.height, quiet.content.height - 1);
+ assert_eq!(noisy.status.height, 0);
+ assert_eq!(noisy.content.height, quiet.content.height);
+
+ ui.show_status_bar = true;
+ let with_bar = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);
+ assert_eq!(with_bar.status.height, 1);
+ assert_eq!(with_bar.content.height, quiet.content.height - 1);
}
/// The toggle used to sit on a narrow screen with nothing to toggle: the
@@ -1854,7 +2153,7 @@ mod tests {
ui.sidebar_visible = false;
let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);
assert!(view.sidebar.is_none());
- assert_eq!(view.content, Rect::new(0, 1, 100, 28));
+ assert_eq!(view.content, Rect::new(0, 1, 100, 29));
assert_eq!(view.hit(1, 0), Some(&HitTarget::SidebarToggle));
assert!(view.tabs.iter().all(|tab| tab.rect.x >= 4));
}
diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index a24744cb..929bfed9 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -1,6 +1,8 @@
use crate::domain::ClientInner;
use crate::pane::mousestate::MouseState;
-use crate::pane::renderable::{RenderableInner, RenderableState, hydrate_lines};
+use crate::pane::renderable::{
+ hydrate_lines, FrontendPreviewPolicy, RenderableInner, RenderableState,
+};
use anyhow::bail;
use async_trait::async_trait;
use codec::*;
@@ -9,8 +11,8 @@ use config::keyassignment::ScrollbackEraseMode;
use futures::lock::Mutex as AsyncMutex;
use mux::domain::DomainId;
use mux::pane::{
- CachePolicy, CloseReason, ForEachPaneLogicalLine, LogicalLine, Pane, PaneId, Pattern,
- SearchResult, WithPaneLines, alloc_pane_id,
+ alloc_pane_id, CachePolicy, CloseReason, ForEachPaneLogicalLine, LogicalLine, Pane, PaneId,
+ Pattern, SearchResult, WithPaneLines,
};
use mux::renderable::{RenderableDimensions, StableCursorPosition};
use mux::tab::TabId;
@@ -21,8 +23,8 @@ use ratelim::RateLimiter;
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::ops::Range;
-use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
use termwiz::input::KeyEvent;
use termwiz::surface::SequenceNo;
use url::Url;
@@ -644,10 +646,26 @@ impl ClientPane {
/// normal adoption this deliberately preserves cached rows and ignores
/// older server dimensions until the final full viewport is confirmed.
pub fn preview_frontend_geometry(&self, epoch: u64, size: TerminalSize) -> bool {
+ self.preview_frontend_geometry_with_policy(epoch, size, FrontendPreviewPolicy::PreserveRows)
+ }
+
+ /// Preview a divider that remains visible while it is moving. Retained
+ /// rows are normalized to the new width and refetched rather than being
+ /// interpreted as though their old cell storage already matched it.
+ pub fn preview_live_frontend_geometry(&self, epoch: u64, size: TerminalSize) -> bool {
+ self.preview_frontend_geometry_with_policy(epoch, size, FrontendPreviewPolicy::LiveResize)
+ }
+
+ fn preview_frontend_geometry_with_policy(
+ &self,
+ epoch: u64,
+ size: TerminalSize,
+ policy: FrontendPreviewPolicy,
+ ) -> bool {
*self.requested_size.lock() = Some(size);
let render = self.renderable.lock();
let mut inner = render.inner.borrow_mut();
- let changed = inner.begin_frontend_preview(epoch, size);
+ let changed = inner.begin_frontend_preview(epoch, size, policy);
if changed {
inner.update_last_send();
}
@@ -1433,7 +1451,7 @@ mod test {
#[cfg(test)]
mod palette_delivery_tests {
- use super::{PaletteDelivery, application_palette_transition};
+ use super::{application_palette_transition, PaletteDelivery};
use wezterm_term::color::ColorPalette;
fn palette(fg: f32) -> ColorPalette {
diff --git a/wezterm-client/src/pane/renderable.rs b/wezterm-client/src/pane/renderable.rs
index f2121e46..b32e94d1 100644
--- a/wezterm-client/src/pane/renderable.rs
+++ b/wezterm-client/src/pane/renderable.rs
@@ -37,6 +37,17 @@ struct FetchToken {
struct FrontendPreviewGeometry {
epoch: u64,
size: wezterm_term::TerminalSize,
+ policy: FrontendPreviewPolicy,
+}
+
+/// How an optimistic frontend geometry should treat rows that were fetched for
+/// the preceding grid. Takeover previews are hidden by an opaque frontend
+/// surface, while a live divider resize is visible and must never expose a row
+/// whose cell storage still has the old width.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum FrontendPreviewPolicy {
+ PreserveRows,
+ LiveResize,
}
#[derive(Debug)]
@@ -85,6 +96,28 @@ fn invalidate_line_entries(lines: &mut LruCache<StableRowIndex, LineEntry>, pres
*lines = stale;
}
+/// Keep a stable visual fallback while a visible divider is moving, but make
+/// every retained row structurally valid for the new grid before it can be
+/// painted. Cropping/padding a prior complete row is preferable to either a
+/// blank flash or mixing old-width storage with newly fetched cells.
+fn resize_stale_line_entries(lines: &mut LruCache<StableRowIndex, LineEntry>, cols: usize) {
+ let mut stale = LruCache::unbounded();
+ while let Some((stable_row, entry)) = lines.pop_lru() {
+ let line = match entry {
+ LineEntry::Stale(line)
+ | LineEntry::Line(line)
+ | LineEntry::LineAndFetching(line, _) => line,
+ LineEntry::Fetching(_) => continue,
+ };
+ let seqno = line.current_seqno();
+ let mut line = line;
+ line.resize(cols, seqno);
+ line.set_last_cell_was_wrapped(false, seqno);
+ stale.put(stable_row, LineEntry::Stale(line));
+ }
+ *lines = stale;
+}
+
fn render_geometry_changed(current: RenderableDimensions, next: RenderableDimensions) -> bool {
current.cols != next.cols
|| current.viewport_rows != next.viewport_rows
@@ -104,6 +137,42 @@ fn render_dimensions_match_terminal_size(
&& dimensions.dpi == size.dpi
}
+fn confirmed_frontend_visible_range(
+ dimensions: RenderableDimensions,
+ size: wezterm_term::TerminalSize,
+) -> Option<Range<StableRowIndex>> {
+ if !render_dimensions_match_terminal_size(dimensions, size) {
+ return None;
+ }
+ let top = dimensions.physical_top;
+ Some(top..top.saturating_add(size.rows as StableRowIndex))
+}
+
+fn release_unreturned_fetches(
+ lines: &mut LruCache<StableRowIndex, LineEntry>,
+ requested: &RangeSet<StableRowIndex>,
+ returned: &RangeSet<StableRowIndex>,
+ fetch_token: FetchToken,
+) {
+ for range in requested.iter() {
+ for row in range.clone() {
+ if returned.contains(row) {
+ continue;
+ }
+ match lines.pop(&row) {
+ Some(LineEntry::Fetching(token)) if token == fetch_token => {}
+ Some(LineEntry::LineAndFetching(line, token)) if token == fetch_token => {
+ lines.put(row, LineEntry::Stale(line));
+ }
+ Some(entry) => {
+ lines.put(row, entry);
+ }
+ None => {}
+ }
+ }
+ }
+}
+
fn resolve_server_geometry(
visible: RenderableDimensions,
previous_server: RenderableDimensions,
@@ -401,6 +470,11 @@ impl RenderableInner {
self.poll_interval = BASE_POLL_INTERVAL;
self.last_recv_time = now;
+ let live_preview_accepts_snapshot = self.frontend_preview.is_none_or(|preview| {
+ preview.policy != FrontendPreviewPolicy::LiveResize
+ || render_dimensions_match_terminal_size(delta.dimensions, preview.size)
+ });
+
let mut dirty = RangeSet::new();
for r in delta.dirty_lines {
dirty.add_range(r.clone());
@@ -429,8 +503,9 @@ impl RenderableInner {
// finally right one in quick succession.
// If the delta was not from an input event then we trust it; this is most
// like due to a unilateral movement by the application on the other end.
- if delta.input_serial.is_none()
- || delta.input_serial.unwrap_or(InputSerial::empty()) >= self.input_serial
+ if live_preview_accepts_snapshot
+ && (delta.input_serial.is_none()
+ || delta.input_serial.unwrap_or(InputSerial::empty()) >= self.input_serial)
{
self.cursor_position = delta.cursor_position;
}
@@ -460,6 +535,14 @@ impl RenderableInner {
let config = configuration();
for (stable_row, line) in bonus_lines {
+ // A live preview can have several acknowledged server grids in
+ // flight over its lifetime. Rows bundled with an intermediate
+ // grid are authoritative for that grid only; accepting them into
+ // the final-width cache is exactly how old-width fragments survive
+ // after the divider stops.
+ if !live_preview_accepts_snapshot {
+ continue;
+ }
log::trace!("bonus line {} seqno={}", stable_row, line.current_seqno());
self.put_line(stable_row, line, &config, None);
dirty.remove(stable_row);
@@ -565,6 +648,7 @@ impl RenderableInner {
&mut self,
epoch: u64,
size: wezterm_term::TerminalSize,
+ policy: FrontendPreviewPolicy,
) -> bool {
if self
.frontend_preview
@@ -572,15 +656,28 @@ impl RenderableInner {
{
return false;
}
- self.frontend_preview = Some(FrontendPreviewGeometry { epoch, size });
+ self.frontend_preview = Some(FrontendPreviewGeometry {
+ epoch,
+ size,
+ policy,
+ });
if render_dimensions_match_terminal_size(self.dimensions, size) {
return false;
}
+ let width_changed = self.dimensions.cols != size.cols;
self.dimensions.cols = size.cols;
self.dimensions.viewport_rows = size.rows;
self.dimensions.pixel_width = size.pixel_width;
self.dimensions.pixel_height = size.pixel_height;
self.dimensions.dpi = size.dpi;
+ if policy == FrontendPreviewPolicy::LiveResize {
+ self.line_cache_epoch = self.line_cache_epoch.wrapping_add(1);
+ if width_changed {
+ resize_stale_line_entries(&mut self.lines, size.cols);
+ } else {
+ invalidate_line_entries(&mut self.lines, true);
+ }
+ }
true
}
@@ -735,11 +832,20 @@ impl RenderableInner {
match result {
Ok(lines) => {
let config = configuration();
+ let mut returned = RangeSet::new();
log::trace!("fetch complete for {:?} with {:?}", to_fetch, fetch_token);
for (stable_row, line) in lines.into_iter() {
+ returned.add(stable_row);
inner.put_line(stable_row, line, &config, Some(fetch_token));
}
+ // The terminal can scroll or resize while GetLines is in
+ // flight, so a successful response is allowed to omit a
+ // row that no longer exists in its stable range. Leaving
+ // that row tagged Fetching would suppress every future
+ // request for it and can hold an opaque takeover mask up
+ // forever.
+ release_unreturned_fetches(&mut inner.lines, &to_fetch, &returned, fetch_token);
}
Err(err) => {
log::error!("get_lines failed: {}", err);
@@ -1049,40 +1155,59 @@ impl RenderableState {
self.inner.borrow().dimensions
}
- /// What the server last advertised. This, not `get_dimensions`, is what
- /// `prime_frontend_geometry` compares a takeover against, and the two can
- /// disagree — so a takeover that never completes is only explainable from
- /// this value.
- pub(crate) fn server_dimensions(&self) -> RenderableDimensions {
- self.inner.borrow().server_dimensions
- }
-
- /// Which fields block a takeover from settling on `size`, for zoomtrace.
+ /// Which fields or render rows block a takeover from settling on `size`.
pub(crate) fn frontend_geometry_mismatch(
&self,
size: wezterm_term::TerminalSize,
) -> Option<String> {
- let dims = self.inner.borrow().server_dimensions;
- if render_dimensions_match_terminal_size(dims, size) {
- return None;
- }
- let mut fields = Vec::new();
- if dims.cols != size.cols {
- fields.push(format!("cols {}!={}", dims.cols, size.cols));
- }
- if dims.viewport_rows != size.rows {
- fields.push(format!("rows {}!={}", dims.viewport_rows, size.rows));
- }
- if dims.pixel_width != size.pixel_width {
- fields.push(format!("px_w {}!={}", dims.pixel_width, size.pixel_width));
- }
- if dims.pixel_height != size.pixel_height {
- fields.push(format!("px_h {}!={}", dims.pixel_height, size.pixel_height));
+ let mut inner = self.inner.borrow_mut();
+ let dims = inner.server_dimensions;
+ if !render_dimensions_match_terminal_size(dims, size) {
+ let mut fields = Vec::new();
+ if dims.cols != size.cols {
+ fields.push(format!("cols {}!={}", dims.cols, size.cols));
+ }
+ if dims.viewport_rows != size.rows {
+ fields.push(format!("rows {}!={}", dims.viewport_rows, size.rows));
+ }
+ if dims.pixel_width != size.pixel_width {
+ fields.push(format!("px_w {}!={}", dims.pixel_width, size.pixel_width));
+ }
+ if dims.pixel_height != size.pixel_height {
+ fields.push(format!("px_h {}!={}", dims.pixel_height, size.pixel_height));
+ }
+ if dims.dpi != size.dpi {
+ fields.push(format!("dpi {}!={}", dims.dpi, size.dpi));
+ }
+ return Some(fields.join(","));
}
- if dims.dpi != size.dpi {
- fields.push(format!("dpi {}!={}", dims.dpi, size.dpi));
+
+ let top = inner.server_dimensions.physical_top;
+ let end = top.saturating_add(size.rows as StableRowIndex);
+ let mut total = 0usize;
+ let mut sample = Vec::new();
+ for row in top..end {
+ let kind = match inner.lines.get(&row) {
+ Some(LineEntry::Line(_)) => continue,
+ Some(LineEntry::Fetching(token)) => format!("Fetching/e{}", token.epoch),
+ Some(LineEntry::LineAndFetching(_, token)) => {
+ format!("LineAndFetching/e{}", token.epoch)
+ }
+ Some(LineEntry::Stale(_)) => "Stale".to_string(),
+ None => "Missing".to_string(),
+ };
+ total += 1;
+ if sample.len() < 8 {
+ sample.push(format!("{row}:{kind}"));
+ }
}
- Some(fields.join(","))
+ (total > 0).then(|| {
+ format!(
+ "render rows {top}..{end} pending {total} [{}], cache_epoch={}",
+ sample.join(" "),
+ inner.line_cache_epoch
+ )
+ })
}
/// Drive a render poll and populate every currently visible line while a
@@ -1102,8 +1227,11 @@ impl RenderableState {
if let Err(err) = inner.poll() {
log::trace!("polling takeover geometry: {err:#}");
}
- let top = inner.dimensions.physical_top;
- top..top.saturating_add(size.rows as StableRowIndex)
+ let Some(visible) = confirmed_frontend_visible_range(inner.server_dimensions, size)
+ else {
+ return false;
+ };
+ visible
};
// This both returns any retained rows and schedules missing/stale
@@ -1112,7 +1240,9 @@ impl RenderableState {
let _ = self.get_lines(visible.clone());
let mut inner = self.inner.borrow_mut();
- if !render_dimensions_match_terminal_size(inner.server_dimensions, size) {
+ if confirmed_frontend_visible_range(inner.server_dimensions, size).as_ref()
+ != Some(&visible)
+ {
return false;
}
visible.all(|row| matches!(inner.lines.get(&row), Some(LineEntry::Line(_))))
@@ -1171,6 +1301,25 @@ mod test {
assert!(lines.is_empty());
}
+ #[test]
+ fn live_resize_normalizes_retained_rows_to_the_preview_width() {
+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());
+ let mut wrapped = line(80);
+ wrapped.set_last_cell_was_wrapped(true, SEQ_ZERO);
+ lines.put(1, LineEntry::Line(wrapped));
+ lines.put(2, LineEntry::Stale(line(80)));
+
+ resize_stale_line_entries(&mut lines, 37);
+
+ for row in [1, 2] {
+ let Some(LineEntry::Stale(line)) = lines.get(&row) else {
+ panic!("row {} was not retained as stale", row);
+ };
+ assert_eq!(line.len(), 37);
+ assert!(!line.last_cell_was_wrapped());
+ }
+ }
+
#[test]
fn geometry_epoch_ignores_scrollback_motion_but_detects_render_size() {
let current = dimensions(80, 24, 96);
@@ -1227,6 +1376,46 @@ mod test {
));
}
+ #[test]
+ fn takeover_fetches_the_authoritative_server_rows_after_bottom_anchored_resize() {
+ let size = wezterm_term::TerminalSize {
+ rows: 27,
+ cols: 120,
+ pixel_width: 1200,
+ pixel_height: 540,
+ dpi: 96,
+ };
+ let mut server = dimensions(120, 27, 96);
+ server.pixel_width = size.pixel_width;
+ server.pixel_height = size.pixel_height;
+ server.physical_top = 69;
+
+ assert_eq!(
+ confirmed_frontend_visible_range(server, size),
+ Some(69..96),
+ "a preview's stale top row must not shift the request to 70..97"
+ );
+ }
+
+ #[test]
+ fn a_partial_fetch_response_does_not_leave_an_unreturned_row_in_flight_forever() {
+ let token = FetchToken {
+ epoch: 9,
+ started_at: Instant::now(),
+ };
+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());
+ lines.put(70, LineEntry::Fetching(token));
+ lines.put(71, LineEntry::LineAndFetching(line(80), token));
+ let mut requested = RangeSet::new();
+ requested.add_range(70..72);
+ let returned = RangeSet::new();
+
+ release_unreturned_fetches(&mut lines, &requested, &returned, token);
+
+ assert!(lines.get(&70).is_none());
+ assert!(matches!(lines.get(&71), Some(LineEntry::Stale(_))));
+ }
+
#[test]
fn fetch_token_from_prior_epoch_is_not_current() {
let token = FetchToken {