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.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
use crate::domain::DomainId;
use crate::renderable::*;
use crate::ExitBehavior;
use async_trait::async_trait;
use config::keyassignment::{KeyAssignment, ScrollbackEraseMode};
use downcast_rs::{impl_downcast, Downcast};
use parking_lot::MappedMutexGuard;
use rangeset::RangeSet;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;
use termwiz::hyperlink::Rule;
use termwiz::input::KeyboardEncoding;
use termwiz::surface::{Line, SequenceNo};
use url::Url;
use wezterm_dynamic::Value;
use wezterm_term::color::ColorPalette;
use wezterm_term::{
Clipboard, DownloadHandler, KeyCode, KeyModifiers, MouseEvent, Progress, SemanticZone,
StableRowIndex, TerminalConfiguration, TerminalSize,
};
static PANE_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0);
pub use thinkterm_proto::{PaneId, Pattern, SearchResult};
/// Keeps optional frame metadata flowing while a downstream viewer needs it.
/// Dropping the last subscription releases the upstream subscription and cache.
pub trait KittyFrameSubscription: std::fmt::Debug + Send + Sync {}
/// See `Pane::read_after_batch`. Passed the pane rather than holding it, as
/// a pane keeps these and must not end up owning itself.
pub type BatchRead = Box<dyn FnOnce(&dyn Pane) + Send>;
pub type KittyImageFuture = std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<thinkterm_proto::image::GetImageCellResponse>> + Send>>;
pub fn alloc_pane_id() -> PaneId {
PANE_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)
}
/// Keep `alloc_pane_id` away from every id below `next`: a server that
/// adopts panes from its predecessor keeps their ids and must not hand
/// them out again.
pub fn reserve_pane_ids_below(next: PaneId) {
PANE_ID.fetch_max(next, ::std::sync::atomic::Ordering::Relaxed);
}
/// The id the next pane would get; what a successor has to reserve.
pub fn next_pane_id() -> PaneId {
PANE_ID.load(::std::sync::atomic::Ordering::Relaxed)
}
/// The cell geometry a frontend sizes this pane's PTY with.
///
/// The split tree thinks in root-font cells and knows nothing of per-pane
/// font scale or per-pane chrome (the pane nav bar), while the GUI sizes
/// PTYs through both. With two writers using different arithmetic, every
/// split-tree resize and every GUI sync would set a *different* size on the
/// same PTY — during a divider drag that alternates the TUI between two
/// widths at frame rate. A GUI therefore registers, per pane, the metrics
/// it sizes with, and `PaneStack::resize` converts the tree's pixel rect
/// through them so both writers land on the identical size. Headless mux
/// has no entries and keeps the raw cell behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrontendCellMetrics {
pub cell_width: usize,
pub cell_height: usize,
/// Vertical chrome drawn inside the pane's rect (the pane nav bar), px.
pub chrome_height: usize,
/// Room under the tree the frontend lets a pane along its bottom edge
/// run its terminal on into, px: what is left of the window under the
/// tree's last row. The tree knows which panes those are.
pub extra_height: usize,
pub dpi: u32,
}
lazy_static::lazy_static! {
static ref FRONTEND_CELL_METRICS: parking_lot::RwLock<HashMap<PaneId, FrontendCellMetrics>> =
parking_lot::RwLock::new(HashMap::new());
}
pub fn set_frontend_cell_metrics(pane_id: PaneId, metrics: Option<FrontendCellMetrics>) {
let mut map = FRONTEND_CELL_METRICS.write();
match metrics {
Some(m) => {
map.insert(pane_id, m);
}
None => {
map.remove(&pane_id);
}
}
}
pub fn frontend_cell_metrics(pane_id: PaneId) -> Option<FrontendCellMetrics> {
FRONTEND_CELL_METRICS.read().get(&pane_id).copied()
}
/// Convert a split-tree pixel rect into the size the registered frontend
/// would compute for it. Mirrors the GUI's `terminal_size_for_positioned_pane`
/// exactly: chrome is clamped so one terminal row always survives, the room
/// under the tree is added for a pane `along_bottom` of it, and the pixel
/// size is re-derived from whole cells.
pub fn apply_frontend_cell_metrics(
pane_id: PaneId,
size: TerminalSize,
along_bottom: bool,
) -> TerminalSize {
let Some(m) = frontend_cell_metrics(pane_id) else {
return size;
};
let cell_width = m.cell_width.max(1);
let cell_height = m.cell_height.max(1);
let chrome = m
.chrome_height
.min(size.pixel_height.saturating_sub(cell_height));
let pixel_width = size.pixel_width.max(cell_width);
let room_below = if along_bottom { m.extra_height } else { 0 };
let pixel_height = (size.pixel_height + room_below)
.saturating_sub(chrome)
.max(cell_height);
let cols = (pixel_width / cell_width).max(1);
let rows = (pixel_height / cell_height).max(1);
TerminalSize {
rows,
cols,
pixel_width: cols * cell_width,
pixel_height: rows * cell_height,
dpi: m.dpi,
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PerformAssignmentResult {
/// Continue search for handler
Unhandled,
/// Found handler and acted upon the action
Handled,
/// Do not perform assignment, but instead treat the key event
/// as though there was no assignment and run it as a key_down
/// event.
BlockAssignmentAndRouteToKeyDown,
}
// SearchResult and Pattern moved to thinkterm-proto; re-exported at the top
// of this module. PatternType stays: it is not a wire type.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum PatternType {
CaseSensitiveString,
CaseInSensitiveString,
Regex,
}
impl From<&Pattern> for PatternType {
fn from(value: &Pattern) -> Self {
match value {
Pattern::CaseSensitiveString(_) => PatternType::CaseSensitiveString,
Pattern::CaseInSensitiveString(_) => PatternType::CaseInSensitiveString,
Pattern::Regex(_) => PatternType::Regex,
}
}
}
/// Why a close request is being made
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum CloseReason {
/// The containing window is being closed
Window,
/// The containing tab is being close
Tab,
/// Just this tab is being closed
Pane,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LogicalLine {
pub physical_lines: Vec<Line>,
pub logical: Line,
pub first_row: StableRowIndex,
}
impl LogicalLine {
pub fn contains_y(&self, y: StableRowIndex) -> bool {
y >= self.first_row && y < self.first_row + self.physical_lines.len() as StableRowIndex
}
pub fn xy_to_logical_x(&self, x: usize, y: StableRowIndex) -> usize {
let mut offset = 0;
for (idx, line) in self.physical_lines.iter().enumerate() {
let phys_y = self.first_row + idx as StableRowIndex;
if y < phys_y {
// Eg: trying to drag off the top of the viewport.
// Their y coordinate precedes our first line, so
// the only logical x we can return is 0
return 0;
}
if phys_y == y {
return offset + x;
}
offset += line.len();
}
// Allow selecting off the end of the line
offset + x
}
pub fn logical_x_to_physical_coord(&self, x: usize) -> (StableRowIndex, usize) {
let mut y = self.first_row;
let mut idx = 0;
for line in &self.physical_lines {
let x_off = x - idx;
let line_len = line.len();
if x_off < line_len {
return (y, x_off);
}
y += 1;
idx += line_len;
}
(y - 1, x - idx + self.physical_lines.last().unwrap().len())
}
}
/// The facts about a pane that a listing shows: what `Tab` reads for its
/// pane tree and a mux server answers `ListPanes` with. Gathered under one
/// guard where the pane has one, and kept where it can be handed out even
/// while the pane's parser holds that guard. Always one coherent snapshot
/// of the terminal; a size the terminal has yet to take rides alongside.
#[derive(Debug, Clone)]
pub struct PaneSummary {
pub title: String,
pub dimensions: RenderableDimensions,
pub cursor_position: StableCursorPosition,
pub working_dir: Option<Url>,
pub alt_screen: bool,
/// A size the pane's pty already has but its terminal does not yet,
/// because the parser held the terminal when the resize came. The
/// size the pane *has*; `dimensions` is what its screen still shows.
pub resize_pending: Option<TerminalSize>,
}
impl PaneSummary {
/// The snapshot straight from a terminal, under the guard the caller
/// holds. `tmux` hides the cursor and the alternate screen, as the
/// individual readers do for a pane fronting a tmux control mode.
pub fn from_terminal(term: &mut wezterm_term::Terminal, tmux: bool) -> Self {
Self {
title: term.get_title().to_string(),
dimensions: terminal_get_dimensions(term),
cursor_position: Self::cursor_position_of(term, tmux),
working_dir: term.get_current_dir().cloned(),
alt_screen: Self::alt_screen_of(term, tmux),
resize_pending: None,
}
}
pub fn cursor_position_of(
term: &mut wezterm_term::Terminal,
tmux: bool,
) -> StableCursorPosition {
let mut cursor = terminal_get_cursor_position(term);
if tmux {
cursor.visibility = termwiz::surface::CursorVisibility::Hidden;
}
cursor
}
pub fn alt_screen_of(term: &wezterm_term::Terminal, tmux: bool) -> bool {
!tmux && term.is_alt_screen_active()
}
/// The size the pane has: the pending one when a resize is waiting
/// on the parser, otherwise the one its screen shows.
pub fn terminal_size(&self) -> TerminalSize {
self.resize_pending.unwrap_or(TerminalSize {
cols: self.dimensions.cols,
rows: self.dimensions.viewport_rows,
pixel_width: self.dimensions.pixel_width,
pixel_height: self.dimensions.pixel_height,
dpi: self.dimensions.dpi,
})
}
}
/// A Pane represents a view on a terminal
#[async_trait(?Send)]
pub trait Pane: Downcast + Send + Sync {
fn pane_id(&self) -> PaneId;
/// Returns the 0-based cursor position relative to the top left of
/// the visible screen
fn get_cursor_position(&self) -> StableCursorPosition;
fn get_current_seqno(&self) -> SequenceNo;
/// Returns misc metadata that is pane-specific
fn get_metadata(&self) -> Value {
Value::Null
}
/// Given a range of lines, return the subset of those lines that
/// have changed since the supplied sequence no.
fn get_changed_since(
&self,
lines: Range<StableRowIndex>,
seqno: SequenceNo,
) -> RangeSet<StableRowIndex>;
/// Returns a set of lines from the scrollback or visible portion of
/// the display. The lines are indexed using StableRowIndex, which
/// can be invalidated if the scrollback is busy, or when switching
/// to the alternate screen.
/// To deal with this, this function will adjust the input so that
/// a range that has been scrolled off the top will return the top
/// n rows of the scrollback (where n is the size of the input range),
/// or the bottom n rows of the scrollback when switching to the alt
/// screen and the index would go off the bottom.
/// Because of this, we also return the adjusted StableRowIndex for
/// the first row in the range.
fn get_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>);
/// `get_lines`, held to the rows on the screen as they are read. The
/// screen's bounds and its rows are read together: the two screens
/// number their rows apart, so bounds read before a switch from one
/// to the other would name rows of the other one, as like as not its
/// oldest history. A pane that cannot read both at once reads them one
/// after the other.
fn get_screen_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>) {
let lines = on_screen(&self.get_dimensions(), lines);
// Not asked: a screen can answer an empty range with a row.
if lines.is_empty() {
return (lines.start, vec![]);
}
self.get_lines(lines)
}
fn with_lines_mut(&self, lines: Range<StableRowIndex>, with_lines: &mut dyn WithPaneLines);
fn for_each_logical_line_in_stable_range_mut(
&self,
lines: Range<StableRowIndex>,
for_line: &mut dyn ForEachPaneLogicalLine,
);
fn get_logical_lines(&self, lines: Range<StableRowIndex>) -> Vec<LogicalLine>;
fn apply_hyperlinks(&self, lines: Range<StableRowIndex>, rules: &[Rule]) {
struct ApplyHyperLinks<'a> {
rules: &'a [Rule],
}
impl<'a> ForEachPaneLogicalLine for ApplyHyperLinks<'a> {
fn with_logical_line_mut(
&mut self,
_: Range<StableRowIndex>,
lines: &mut [&mut Line],
) -> bool {
Line::apply_hyperlink_rules(self.rules, lines);
true
}
}
self.for_each_logical_line_in_stable_range_mut(lines, &mut ApplyHyperLinks { rules });
}
/// Returns render related dimensions
fn get_dimensions(&self) -> RenderableDimensions;
fn get_title(&self) -> String;
fn get_progress(&self) -> Progress {
Progress::None
}
fn send_paste(&self, text: &str) -> anyhow::Result<()>;
/// Whether the program in the pane takes pastes bracketed (DECSET
/// 2004), so that a newline pasted to it runs nothing by itself. `None`
/// when this side cannot tell.
fn bracketed_paste(&self) -> Option<bool> {
None
}
fn reader(&self) -> anyhow::Result<Option<Box<dyn std::io::Read + Send>>>;
/// The pty behind `reader`, when there is one: the reader thread waits
/// for it with poll, which is what lets it be parked (see
/// `crate::pause_pane_reader`), and can read a flood from it directly.
#[cfg(unix)]
fn pty_raw_fd(&self) -> Option<std::os::unix::io::RawFd> {
None
}
fn writer(&self) -> MappedMutexGuard<'_, dyn std::io::Write>;
fn resize(&self, size: TerminalSize) -> anyhow::Result<()>;
/// Called as a hint that the pane is being resized as part of
/// a zoom-to-fill-all-the-tab-space operation.
fn set_zoomed(&self, _zoomed: bool) {}
fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()>;
fn key_up(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()>;
fn perform_assignment(&self, _assignment: &KeyAssignment) -> PerformAssignmentResult {
PerformAssignmentResult::Unhandled
}
fn mouse_event(&self, event: MouseEvent) -> anyhow::Result<()>;
fn perform_actions(&self, _actions: Vec<termwiz::escape::Action>) {}
/// Apply every action in `actions` exactly like `perform_actions`,
/// leaving the vector empty. This default hands the allocation on with
/// the actions; implementations that keep it for reuse override it.
/// `may_hold_external_kitty` is false when the caller knows that no
/// action carries an external Kitty payload, so it need not be scanned.
fn perform_actions_in_place(
&self,
actions: &mut Vec<termwiz::escape::Action>,
_may_hold_external_kitty: bool,
) {
self.perform_actions(std::mem::take(actions));
}
fn is_dead(&self) -> bool;
fn kill(&self) {}
/// One tick of the idle image sweep (`crate::spawn_idle_image_sweeper`):
/// drop the pictures nothing refers to any more once the pane has seen
/// no image traffic for `ticks_until_release` ticks. Returns the bytes
/// released; a pane without pictures of its own has nothing to do.
fn idle_image_tick(&self, _ticks_until_release: u32) -> usize {
0
}
/// (images, placements, bytes) of pictures this pane holds, for logs.
fn image_stats(&self) -> (usize, usize, usize) {
(0, 0, 0)
}
fn kitty_frame_selections(&self, known: Option<u64>) -> Option<(u64, u64, Vec<wezterm_term::KittyFrameSelection>)> {
(known != Some(0)).then(|| (0, 0, Vec::new()))
}
fn get_kitty_image(&self, _request: thinkterm_proto::image::GetKittyImage) -> KittyImageFuture {
Box::pin(async { anyhow::bail!("pane does not provide canonical Kitty images") })
}
fn subscribe_kitty_frames(&self) -> Option<Box<dyn KittyFrameSubscription>> {
None
}
fn palette(&self) -> ColorPalette;
/// Palette state explicitly established by the application. `None`
/// means that consumers should use their configured palette.
fn palette_override(&self) -> Option<ColorPalette> {
None
}
fn domain_id(&self) -> DomainId;
fn get_keyboard_encoding(&self) -> KeyboardEncoding {
KeyboardEncoding::Xterm
}
/// Would reading render state (lines, cursor, dimensions) have to wait
/// for this pane's parser right now? A mux server asks before it reads
/// on behalf of a client, so its one thread is never stuck behind a
/// pane digesting a huge frame. A pane with nothing to wait for says
/// no.
fn render_state_is_contended(&self) -> bool {
false
}
/// Have the thread applying this pane's output run `read` once the
/// batch it is on is done, for a reader `render_state_is_contended`
/// turned away. Between two batches that thread is the only one that
/// will not miss: a probe from anywhere else has to land in a gap of
/// about 0.1 ms, and under a flood can go on missing it for a second.
/// The read never happens if no batch follows, so the caller keeps
/// another way of finding out. Whatever it does comes off the pane's
/// throughput, so nothing that looks at the pane's processes belongs
/// here. Handed back by a pane with no such thread.
fn read_after_batch(&self, read: BatchRead) -> Result<(), BatchRead> {
Err(read)
}
/// Take whatever `render_state_is_contended` reports on and hold it
/// for `hold`, sleeping. Only the wedge hook in `send_actions_to_mux`
/// uses it; a pane with nothing to hold does nothing.
fn hold_render_state_for_the_test(&self, hold: std::time::Duration) {
let _ = hold;
}
/// The terminal's own facts about this pane, without waiting for its
/// parser: as they are if they can be read now, otherwise as they were
/// last read. Nothing here consults the process behind the pane. A
/// pane with nothing to wait for reads them now.
fn summary_without_waiting(&self) -> PaneSummary {
PaneSummary {
title: self.get_title(),
dimensions: self.get_dimensions(),
cursor_position: self.get_cursor_position(),
working_dir: self.get_current_working_dir(CachePolicy::AllowStale),
alt_screen: self.is_alt_screen_active(),
resize_pending: None,
}
}
/// `summary_without_waiting` with what a listing wants on top: the
/// title and working directory the way `get_title` and
/// `get_current_working_dir` would give them, process lookups
/// included. Costlier than the summary; not for a per-frame path.
fn listing_summary(&self) -> PaneSummary {
self.summary_without_waiting()
}
/// `get_title`, without waiting for the parser. For paths that paint
/// every frame and want nothing else.
fn title_without_waiting(&self) -> String {
self.summary_without_waiting().title
}
/// `get_current_working_dir`, without waiting for the parser; the
/// policy still governs how fresh a divined directory has to be.
fn working_dir_without_waiting(&self, policy: CachePolicy) -> Option<Url> {
self.get_current_working_dir(policy)
}
fn copy_user_vars(&self) -> HashMap<String, String> {
HashMap::new()
}
/// True for panes that mirror a pane owned by another mux (a mux
/// client's local proxy for a server-side pane). The terminal size of
/// such a pane is driven by the GUI layer, which reserves per-pane
/// chrome (the pane nav bar) out of the cell size; resizing it to the
/// raw cell size from split layout code would undo that reservation
/// and ping-pong sizes across the wire.
fn is_remote_mirror(&self) -> bool {
false
}
fn erase_scrollback(&self, _erase_mode: ScrollbackEraseMode) {}
/// Called to advise on whether this tab has focus
fn focus_changed(&self, _focused: bool) {}
/// Called to advise remote mux that this is the active tab
/// for the current identity
fn advise_focus(&self) {}
fn has_unseen_output(&self) -> bool {
false
}
/// Certain panes are OK to be closed with impunity (no prompts)
fn can_close_without_prompting(&self, _reason: CloseReason) -> bool {
false
}
/// Performs a search bounded to the specified range.
/// If the result is empty then there are no matches.
/// Otherwise, if limit.is_none(), the result shall contain all possible
/// matches.
/// If limit.is_some(), then the maximum number of results that will be
/// returned is limited to the specified number, and the
/// SearchResult::start_y of the last item
/// in the result can be used as the start of the next region to search.
/// You can tell that you have reached the end of the results if the number
/// of results is smaller than the limit you set.
async fn search(
&self,
_pattern: Pattern,
_range: Range<StableRowIndex>,
_limit: Option<u32>,
) -> anyhow::Result<Vec<SearchResult>> {
Ok(vec![])
}
/// How far the pane's programs have got: whether the program it
/// started is still running, and what its shell has reported about
/// its commands. A mirror asks the mux that owns the pane.
async fn run_state(&self) -> anyhow::Result<thinkterm_proto::PaneRunState> {
Ok(thinkterm_proto::PaneRunState::unknown())
}
/// Retrieve the set of semantic zones
fn get_semantic_zones(&self) -> anyhow::Result<Vec<SemanticZone>> {
Ok(vec![])
}
/// Returns true if the terminal has grabbed the mouse and wants to
/// give the embedded application a chance to process events.
/// In practice this controls whether the gui will perform local
/// handling of clicks.
fn is_mouse_grabbed(&self) -> bool;
fn is_alt_screen_active(&self) -> bool;
fn set_clipboard(&self, _clipboard: &Arc<dyn Clipboard>) {}
fn set_download_handler(&self, _handler: &Arc<dyn DownloadHandler>) {}
fn set_config(&self, _config: Arc<dyn TerminalConfiguration>) {}
fn get_config(&self) -> Option<Arc<dyn TerminalConfiguration>> {
None
}
fn get_current_working_dir(&self, policy: CachePolicy) -> Option<Url>;
/// The agent (if any) this pane is running, as classified by the mux
/// that owns it. Locally-owned panes answer from this process's
/// detector; ClientPane overrides with what the owning server pushed.
fn agent_status(&self) -> Option<thinkterm_proto::AgentStatus> {
crate::agent_status::status_for_pane(self.pane_id())
}
/// [`agent_status`](Self::agent_status) without its report's text: what
/// a painter asking every frame needs, without copying the rest.
fn agent_status_summary(&self) -> Option<crate::agent_status::AgentStatusSummary> {
crate::agent_status::summary_for_pane(self.pane_id())
}
/// The program leading this pane's terminal, as observed by the mux
/// that owns it. Same shape as `agent_status`: locally-owned panes
/// answer from this process's observer, ClientPane from its server.
fn foreground_program(&self) -> Option<thinkterm_proto::ForegroundProgram> {
crate::foreground_program::program_for_pane(self.pane_id())
}
/// OSC title/progress the application actually emitted, retained for
/// agent detection. Deliberately not `get_title`/`get_progress`, which
/// exist for display and substitute defaults (process basename, "4;0")
/// that would make idle screen rules match unconditionally. The default
/// is empty: remote mirrors are never detected locally.
fn agent_osc_evidence(&self) -> wezterm_term::AgentOscEvidence {
Default::default()
}
/// Drop retained agent OSC evidence so a pane's next occupant does not
/// inherit the previous agent's signals. No-op by default.
fn clear_agent_osc_evidence(&self) {}
/// What programs in this pane have reported about themselves with
/// OSC 7501. Empty by default: remote mirrors are never classified
/// locally.
fn program_status(&self) -> wezterm_term::program_status::ProgramStatusSnapshot {
Default::default()
}
/// The program behind the pane's OSC 7501 records has gone: drop all
/// but the results nobody has seen yet, among the records received up
/// to serial `through` -- a snapshot's `latest_serial`. No-op by default.
fn end_program_status(&self, _through: u64) {}
/// Someone has looked at the pane: retire the finished or failed
/// results its programs reported. No-op by default.
fn program_status_seen(&self) {}
/// Whether the pane's own shell holds the foreground without child
/// processes. This does not establish that it is at a prompt: builtins
/// and functions can run in the shell itself. `None` where the platform
/// cannot tell.
fn shell_is_foreground(&self) -> Option<bool> {
None
}
/// The process group holding the pane's foreground, asked fresh. `None`
/// where the platform has no such thing or cannot tell.
fn foreground_process_group(&self) -> Option<u32> {
None
}
fn get_foreground_process_name(&self, _policy: CachePolicy) -> Option<String> {
None
}
/// The argument vector of the foreground process-group leader, when
/// the platform can read it. Agent identification asks for this only
/// when the leader executable is a generic interpreter (node, python,
/// a shell), so implementations may fetch it on demand rather than
/// caching it alongside the leader path.
fn get_foreground_process_argv(&self, _policy: CachePolicy) -> Option<Vec<String>> {
None
}
/// The pane's root (pty child) process id, when the platform tracks
/// one. Windows agent identification walks the process tree from
/// here — there is no foreground-group concept to ask instead.
fn root_process_id(&self) -> Option<u32> {
None
}
fn get_foreground_process_info(
&self,
_policy: CachePolicy,
) -> Option<procinfo::LocalProcessInfo> {
None
}
fn tty_name(&self) -> Option<String> {
None
}
fn exit_behavior(&self) -> Option<ExitBehavior> {
None
}
}
impl_downcast!(Pane);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CachePolicy {
FetchImmediate,
AllowStale,
}
/// This trait is used to implement/provide a callback that is used together
/// with the Pane::with_lines_mut method.
/// Ideally we'd simply pass an FnMut with the same signature as the trait
/// method defined here, but doing so results in Pane not being object-safe.
pub trait WithPaneLines {
/// The `first_row` parameter is set to the StableRowIndex of the resolved
/// first row from the Pane::with_lines_mut method. It will usually be
/// the start of the lines range, but in case that row is no longer in
/// a valid range (scrolled out of scrollback), it may be revised.
///
/// `lines` is a mutable slice of the mutable lines in the requested
/// stable range.
fn with_lines_mut(&mut self, first_row: StableRowIndex, lines: &mut [&mut Line]);
}
/// This trait is used to implement/provide a callback that is used together
/// with the Pane::for_each_logical_line_in_stable_range_mut method.
/// Ideally we'd simply pass an FnMut with the same signature as the trait
/// method defined here, but doing so results in Pane not being object-safe.
pub trait ForEachPaneLogicalLine {
/// The `stable_range` parameter is set to the range of physical lines
/// that comprise the current logical line.
///
/// `lines` is a mutable slice of the mutable physical lines that comprise
/// the current logical line.
///
/// Return `true` to continue with the next logical line in the requested
/// range, or `false` to cease iteration.
fn with_logical_line_mut(
&mut self,
stable_range: Range<StableRowIndex>,
lines: &mut [&mut Line],
) -> bool;
}
/// A helper that allows you to implement Pane::with_lines_mut in terms
/// of your existing Pane::get_lines method.
///
/// The mutability is really a lie: while `with_lines` is passed something
/// that is mutable, it is operating on a copy the lines that won't persist
/// beyond the call to Pane::with_lines_mut.
pub fn impl_with_lines_via_get_lines<P: Pane + ?Sized>(
pane: &P,
lines: Range<StableRowIndex>,
with_lines: &mut dyn WithPaneLines,
) {
let (first, mut lines) = pane.get_lines(lines);
let mut line_refs = vec![];
for line in lines.iter_mut() {
line_refs.push(line);
}
with_lines.with_lines_mut(first, &mut line_refs);
}
/// A helper that allows you to implement Pane::for_each_logical_line_in_stable_range_mut
/// in terms of your existing Pane::get_logical_lines method.
///
/// The mutability is really a lie: while `with_lines` is passed something
/// that is mutable, it is operating on a copy the lines that won't persist
/// beyond the call to Pane::with_lines_mut.
pub fn impl_for_each_logical_line_via_get_logical_lines<P: Pane + ?Sized>(
pane: &P,
lines: Range<StableRowIndex>,
for_line: &mut dyn ForEachPaneLogicalLine,
) {
let mut logical = pane.get_logical_lines(lines);
for line in &mut logical {
let num_lines = line.physical_lines.len() as StableRowIndex;
let mut line_refs = vec![];
for phys in line.physical_lines.iter_mut() {
line_refs.push(phys);
}
let should_continue = for_line
.with_logical_line_mut(line.first_row..line.first_row + num_lines, &mut line_refs);
if !should_continue {
break;
}
}
}
/// A helper that allows you to implement Pane::get_logical_lines in terms of
/// your Pane::get_lines method.
pub fn impl_get_logical_lines_via_get_lines<P: Pane + ?Sized>(
pane: &P,
lines: Range<StableRowIndex>,
) -> Vec<LogicalLine> {
let (mut first, mut phys) = pane.get_lines(lines);
// Avoid pathological cases where we have eg: a really long logical line
// (such as 1.5MB of json) that we previously wrapped. We don't want to
// un-wrap, scan, and re-wrap that thing.
// This is an imperfect length constraint to partially manage the cost.
const MAX_LOGICAL_LINE_LEN: usize = 1024;
let mut back_len = 0;
// Look backwards to find the start of the first logical line
while first > 0 {
let (prior, back) = pane.get_lines(first - 1..first);
if prior == first {
break;
}
if !back[0].last_cell_was_wrapped() {
break;
}
if back[0].len() + back_len > MAX_LOGICAL_LINE_LEN {
break;
}
back_len += back[0].len();
first = prior;
for (idx, line) in back.into_iter().enumerate() {
phys.insert(idx, line);
}
}
// Look forwards to find the end of the last logical line
while let Some(last) = phys.last() {
if !last.last_cell_was_wrapped() {
break;
}
if last.len() > MAX_LOGICAL_LINE_LEN {
break;
}
let next_row = first + phys.len() as StableRowIndex;
let (last_row, mut ahead) = pane.get_lines(next_row..next_row + 1);
if last_row != next_row {
break;
}
phys.append(&mut ahead);
}
// Now process this stuff into logical lines
let mut lines = vec![];
for (idx, line) in phys.into_iter().enumerate() {
match lines.last_mut() {
None => {
let logical = line.clone();
lines.push(LogicalLine {
physical_lines: vec![line],
logical,
first_row: first + idx as StableRowIndex,
});
}
Some(prior) => {
if prior.logical.last_cell_was_wrapped()
&& prior.logical.len() <= MAX_LOGICAL_LINE_LEN
{
let seqno = prior.logical.current_seqno().max(line.current_seqno());
prior.logical.set_last_cell_was_wrapped(false, seqno);
prior.logical.append_line(line.clone(), seqno);
prior.physical_lines.push(line);
} else {
let logical = line.clone();
lines.push(LogicalLine {
physical_lines: vec![line],
logical,
first_row: first + idx as StableRowIndex,
});
}
}
}
}
lines
}
/// The rows of `lines` on the screen `dims` describe.
pub fn on_screen(
dims: &RenderableDimensions,
lines: Range<StableRowIndex>,
) -> Range<StableRowIndex> {
let top = dims.physical_top;
let start = lines.start.max(top);
start..lines.end.min(top + dims.viewport_rows as StableRowIndex).max(start)
}
/// A helper that allows you to implement Pane::get_lines in terms
/// of your Pane::with_lines_mut method.
pub fn impl_get_lines_via_with_lines<P: Pane + ?Sized>(
pane: &P,
lines: Range<StableRowIndex>,
) -> (StableRowIndex, Vec<Line>) {
struct LineCollector {
first: StableRowIndex,
lines: Vec<Line>,
}
let mut collector = LineCollector {
first: 0,
lines: vec![],
};
impl WithPaneLines for LineCollector {
fn with_lines_mut(&mut self, first_row: StableRowIndex, lines: &mut [&mut Line]) {
self.first = first_row;
for line in lines.iter_mut() {
self.lines.push(line.clone());
}
}
}
pane.with_lines_mut(lines, &mut collector);
(collector.first, collector.lines)
}
#[cfg(test)]
mod test {
use super::*;
use k9::snapshot;
use parking_lot::{MappedMutexGuard, Mutex};
use std::borrow::Cow;
use termwiz::surface::SEQ_ZERO;
struct FakePane {
lines: Mutex<Vec<Line>>,
}
impl Pane for FakePane {
fn pane_id(&self) -> PaneId {
unimplemented!()
}
fn get_cursor_position(&self) -> StableCursorPosition {
unimplemented!()
}
fn get_current_seqno(&self) -> SequenceNo {
unimplemented!()
}
fn get_changed_since(
&self,
_: Range<StableRowIndex>,
_: SequenceNo,
) -> RangeSet<StableRowIndex> {
unimplemented!()
}
fn with_lines_mut(
&self,
stable_range: Range<StableRowIndex>,
with_lines: &mut dyn WithPaneLines,
) {
let mut line_refs = vec![];
let mut lines = self.lines.lock();
for line in lines
.iter_mut()
.skip(stable_range.start as usize)
.take((stable_range.end - stable_range.start) as usize)
{
line_refs.push(line);
}
with_lines.with_lines_mut(stable_range.start, &mut line_refs);
}
fn for_each_logical_line_in_stable_range_mut(
&self,
lines: Range<StableRowIndex>,
for_line: &mut dyn ForEachPaneLogicalLine,
) {
crate::pane::impl_for_each_logical_line_via_get_logical_lines(self, lines, for_line)
}
fn get_logical_lines(&self, lines: Range<StableRowIndex>) -> Vec<LogicalLine> {
crate::pane::impl_get_logical_lines_via_get_lines(self, lines)
}
fn get_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>) {
let first = lines.start;
(
first,
self.lines
.lock()
.iter()
.skip(lines.start as usize)
.take((lines.end - lines.start) as usize)
.cloned()
.collect(),
)
}
fn get_dimensions(&self) -> RenderableDimensions {
unimplemented!()
}
fn get_title(&self) -> String {
unimplemented!()
}
fn send_paste(&self, _: &str) -> anyhow::Result<()> {
unimplemented!()
}
fn reader(&self) -> anyhow::Result<Option<Box<dyn std::io::Read + Send>>> {
Ok(None)
}
fn writer(&self) -> MappedMutexGuard<'_, dyn std::io::Write> {
unimplemented!()
}
fn resize(&self, _: TerminalSize) -> anyhow::Result<()> {
unimplemented!()
}
fn mouse_event(&self, _: MouseEvent) -> anyhow::Result<()> {
unimplemented!()
}
fn is_dead(&self) -> bool {
unimplemented!()
}
fn palette(&self) -> ColorPalette {
unimplemented!()
}
fn domain_id(&self) -> DomainId {
unimplemented!()
}
fn is_mouse_grabbed(&self) -> bool {
false
}
fn is_alt_screen_active(&self) -> bool {
false
}
fn get_current_working_dir(&self, _policy: CachePolicy) -> Option<Url> {
None
}
fn key_down(&self, _: KeyCode, _: KeyModifiers) -> anyhow::Result<()> {
unimplemented!()
}
fn key_up(&self, _: KeyCode, _: KeyModifiers) -> anyhow::Result<()> {
unimplemented!()
}
}
fn physical_lines_from_text(text: &str, width: usize) -> Vec<Line> {
let mut physical_lines = vec![];
for logical in text.split('\n') {
let chunks = logical
.chars()
.collect::<Vec<char>>()
.chunks(width)
.map(|c| c.into_iter().collect::<String>())
.collect::<Vec<String>>();
let n_chunks = chunks.len();
for (idx, chunk) in chunks.into_iter().enumerate() {
let mut line = Line::from_text(&chunk, &Default::default(), 1, None);
if idx < n_chunks - 1 {
line.set_last_cell_was_wrapped(true, 1);
}
physical_lines.push(line);
}
}
physical_lines
}
fn summarize_logical_lines(lines: &[LogicalLine]) -> Vec<(StableRowIndex, Cow<'_, str>)> {
lines
.iter()
.map(|l| (l.first_row, l.logical.as_str()))
.collect::<Vec<_>>()
}
// A range that ends before it starts is one of those asked about.
#[allow(clippy::reversed_empty_ranges)]
#[test]
fn only_rows_on_the_screen_are_on_it() {
let dims = RenderableDimensions {
viewport_rows: 24,
physical_top: 100,
..RenderableDimensions::default()
};
assert_eq!(on_screen(&dims, 90..110), 100..110);
assert_eq!(on_screen(&dims, 120..200), 120..124);
assert!(on_screen(&dims, 0..100).is_empty());
assert!(on_screen(&dims, 124..130).is_empty());
assert!(on_screen(&dims, 110..105).is_empty());
// The alternate screen numbers its rows from nought.
let alt = RenderableDimensions {
viewport_rows: 24,
..RenderableDimensions::default()
};
assert_eq!(on_screen(&alt, 0..5000), 0..24);
}
#[test]
fn logical_lines() {
let text = "Hello there this is a long line.\nlogical line two\nanother long line here\nlogical line four\nlogical line five\ncap it off with another long line";
let width = 20;
let physical_lines = physical_lines_from_text(text, width);
fn text_from_lines(lines: &[Line]) -> Vec<Cow<'_, str>> {
lines.iter().map(|l| l.as_str()).collect::<Vec<_>>()
}
let line_text = text_from_lines(&physical_lines);
snapshot!(
line_text,
r#"
[
"Hello there this is ",
"a long line.",
"logical line two",
"another long line he",
"re",
"logical line four",
"logical line five",
"cap it off with anot",
"her long line",
]
"#
);
let pane = FakePane {
lines: Mutex::new(physical_lines),
};
let logical = pane.get_logical_lines(0..30);
snapshot!(
summarize_logical_lines(&logical),
r#"
[
(
0,
"Hello there this is a long line.",
),
(
2,
"logical line two",
),
(
3,
"another long line here",
),
(
5,
"logical line four",
),
(
6,
"logical line five",
),
(
7,
"cap it off with another long line",
),
]
"#
);
// Now try with offset bounds
let offset = pane.get_logical_lines(1..3);
snapshot!(
summarize_logical_lines(&offset),
r#"
[
(
0,
"Hello there this is a long line.",
),
(
2,
"logical line two",
),
]
"#
);
let offset = pane.get_logical_lines(1..4);
snapshot!(
summarize_logical_lines(&offset),
r#"
[
(
0,
"Hello there this is a long line.",
),
(
2,
"logical line two",
),
(
3,
"another long line here",
),
]
"#
);
let offset = pane.get_logical_lines(1..5);
snapshot!(
summarize_logical_lines(&offset),
r#"
[
(
0,
"Hello there this is a long line.",
),
(
2,
"logical line two",
),
(
3,
"another long line here",
),
]
"#
);
let offset = pane.get_logical_lines(1..6);
snapshot!(
summarize_logical_lines(&offset),
r#"
[
(
0,
"Hello there this is a long line.",
),
(
2,
"logical line two",
),
(
3,
"another long line here",
),
(
5,
"logical line four",
),
]
"#
);
let offset = pane.get_logical_lines(1..7);
snapshot!(
summarize_logical_lines(&offset),
r#"
[
(
0,
"Hello there this is a long line.",
),
(
2,
"logical line two",
),
(
3,
"another long line here",
),
(
5,
"logical line four",
),
(
6,
"logical line five",
),
]
"#
);
let offset = pane.get_logical_lines(1..8);
snapshot!(
summarize_logical_lines(&offset),
r#"
[
(
0,
"Hello there this is a long line.",
),
(
2,
"logical line two",
),
(
3,
"another long line here",
),
(
5,
"logical line four",
),
(
6,
"logical line five",
),
(
7,
"cap it off with another long line",
),
]
"#
);
let line = &offset[0];
let coords = (0..line.logical.len())
.map(|idx| line.logical_x_to_physical_coord(idx))
.collect::<Vec<_>>();
snapshot!(
coords,
"
[
(
0,
0,
),
(
0,
1,
),
(
0,
2,
),
(
0,
3,
),
(
0,
4,
),
(
0,
5,
),
(
0,
6,
),
(
0,
7,
),
(
0,
8,
),
(
0,
9,
),
(
0,
10,
),
(
0,
11,
),
(
0,
12,
),
(
0,
13,
),
(
0,
14,
),
(
0,
15,
),
(
0,
16,
),
(
0,
17,
),
(
0,
18,
),
(
0,
19,
),
(
1,
0,
),
(
1,
1,
),
(
1,
2,
),
(
1,
3,
),
(
1,
4,
),
(
1,
5,
),
(
1,
6,
),
(
1,
7,
),
(
1,
8,
),
(
1,
9,
),
(
1,
10,
),
(
1,
11,
),
]
"
);
}
fn is_double_click_word(s: &str) -> bool {
match s.chars().count() {
1 => !" \t\n{[}]()\"'`".contains(s),
0 => false,
_ => true,
}
}
#[test]
fn double_click() {
let attr = Default::default();
let logical = LogicalLine {
physical_lines: vec![
Line::from_text("hello", &attr, SEQ_ZERO, None),
Line::from_text("yo", &attr, SEQ_ZERO, None),
],
logical: Line::from_text("helloyo", &attr, SEQ_ZERO, None),
first_row: 0,
};
assert_eq!(logical.xy_to_logical_x(2, -1), 0);
assert_eq!(logical.xy_to_logical_x(20, 1), 25);
let start_idx = logical.xy_to_logical_x(2, 1);
use termwiz::surface::line::DoubleClickRange;
assert_eq!(start_idx, 7);
match logical
.logical
.compute_double_click_range(start_idx, is_double_click_word)
{
DoubleClickRange::Range(click_range) => {
assert_eq!(click_range, 7..7);
}
_ => unreachable!(),
}
}
#[test]
fn the_room_under_a_pane_adds_up_with_its_own_remainder_to_another_row() {
let pane_id = PaneId::MAX - 7;
let metrics = FrontendCellMetrics {
cell_width: 10,
cell_height: 32,
chrome_height: 78,
extra_height: 0,
dpi: 96,
};
let rect = TerminalSize {
rows: 39,
cols: 80,
pixel_width: 800,
pixel_height: 39 * 32,
dpi: 96,
};
set_frontend_cell_metrics(pane_id, Some(metrics));
// The nav bar takes 78 of the rect's 1248: 36 rows and 18 over.
assert_eq!(apply_frontend_cell_metrics(pane_id, rect, true).rows, 36);
set_frontend_cell_metrics(
pane_id,
Some(FrontendCellMetrics {
extra_height: 16,
..metrics
}),
);
// With the 16 under the tree, 37 -- for a pane along its bottom.
assert_eq!(apply_frontend_cell_metrics(pane_id, rect, true).rows, 37);
assert_eq!(apply_frontend_cell_metrics(pane_id, rect, false).rows, 36);
set_frontend_cell_metrics(pane_id, None);
}
}