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::cellcluster::CellCluster;
use crate::hyperlink::Rule;
use crate::line::cellref::CellRef;
use crate::line::clusterline::{runs_into, ClusteredLine};
use crate::line::linebits::LineBits;
use crate::line::storage::{CellStorage, VisibleCellIter};
use crate::line::vecstorage::{VecStorage, VecStorageIter};
use crate::{Change, SequenceNo, SEQ_ZERO};
use alloc::borrow::Cow;
#[cfg(feature = "appdata")]
use alloc::sync::{Arc, Weak};
#[cfg(feature = "appdata")]
use core::any::Any;
use core::hash::Hash;
use core::ops::Range;
use finl_unicode::grapheme_clusters::Graphemes;
#[cfg(feature = "use_serde")]
use serde::{Deserialize, Serialize};
use siphasher::sip128::{Hasher128, SipHasher};
#[cfg(feature = "appdata")]
use std::sync::Mutex;
use wezterm_bidi::{Direction, ParagraphDirectionHint};
use wezterm_cell::{Cell, CellAttributes, SemanticType, UnicodeVersion};
extern crate alloc;
use crate::alloc::string::ToString;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZoneRange {
pub semantic_type: SemanticType,
pub range: Range<u16>,
}
/// Semantic zones, computed on demand: absent until then, after any change
/// and whenever there are none, so that a row holds just a pointer. Shown
/// and sent as the plain list they were before being boxed.
#[derive(Clone, Default, PartialEq)]
struct Zones(Option<Box<Vec<ZoneRange>>>);
impl Zones {
fn as_slice(&self) -> &[ZoneRange] {
self.0.as_deref().map_or(&[], |zones| zones.as_slice())
}
fn set(&mut self, zones: Vec<ZoneRange>) {
self.0 = if zones.is_empty() {
None
} else {
Some(Box::new(zones))
};
}
}
impl core::fmt::Debug for Zones {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
fmt.debug_list().entries(self.as_slice()).finish()
}
}
#[cfg(feature = "use_serde")]
impl Serialize for Zones {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.as_slice().serialize(serializer)
}
}
#[cfg(feature = "use_serde")]
impl<'de> Deserialize<'de> for Zones {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let mut zones = Zones::default();
zones.set(Vec::deserialize(deserializer)?);
Ok(zones)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum DoubleClickRange {
Range(Range<usize>),
RangeWithWrap(Range<usize>),
}
#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub struct Line {
pub(crate) cells: CellStorage,
zones: Zones,
seqno: SequenceNo,
bits: LineBits,
#[cfg(feature = "appdata")]
#[cfg_attr(feature = "use_serde", serde(skip))]
appdata: Mutex<Option<Weak<dyn Any + Send + Sync>>>,
}
impl Clone for Line {
fn clone(&self) -> Self {
Self {
cells: self.cells.clone(),
zones: self.zones.clone(),
seqno: self.seqno,
bits: self.bits,
#[cfg(feature = "appdata")]
appdata: Mutex::new(self.appdata.lock().unwrap().clone()),
}
}
}
/// The character of a cell of one printable ASCII character.
fn printable_ascii(cell: &Cell) -> Option<char> {
match *cell.str().as_bytes() {
[byte @ b' '..=b'~'] => Some(byte as char),
_ => None,
}
}
impl PartialEq for Line {
fn eq(&self, other: &Self) -> bool {
self.seqno == other.seqno && self.bits == other.bits && self.cells == other.cells
}
}
impl Line {
pub fn with_width_and_cell(width: usize, cell: Cell, seqno: SequenceNo) -> Self {
let mut cells = Vec::with_capacity(width);
cells.resize(width, cell.clone());
let bits = LineBits::NONE;
Self {
bits,
cells: CellStorage::V(VecStorage::new(cells)),
seqno,
zones: Zones::default(),
#[cfg(feature = "appdata")]
appdata: Mutex::new(None),
}
}
pub fn from_cells(cells: Vec<Cell>, seqno: SequenceNo) -> Self {
let bits = LineBits::NONE;
Self {
bits,
cells: CellStorage::V(VecStorage::new(cells)),
seqno,
zones: Zones::default(),
#[cfg(feature = "appdata")]
appdata: Mutex::new(None),
}
}
/// Create a new line using cluster storage, optimized for appending
/// and lower memory utilization.
/// The line will automatically switch to cell storage when necessary
/// to apply edits.
pub fn new(seqno: SequenceNo) -> Self {
Self {
bits: LineBits::NONE,
cells: CellStorage::C(ClusteredLine::new()),
seqno,
zones: Zones::default(),
#[cfg(feature = "appdata")]
appdata: Mutex::new(None),
}
}
/// Replace a discarded row with the equivalent of `Line::new`, retaining
/// only bounded compact buffers. Never retain a vector of cells or a large
/// historical allocation merely because the row has scrolled off screen.
pub fn reset_for_scrolling(&mut self, seqno: SequenceNo, columns: usize) {
self.reset_for_scrolling_within(seqno, columns.max(80).saturating_mul(2));
}
/// `reset_for_scrolling`, keeping a text buffer no larger than a new
/// row's, for rows that may go on into the scrollback.
pub fn reset_for_scrolling_as_new(&mut self, seqno: SequenceNo) {
self.reset_for_scrolling_within(seqno, ClusteredLine::NEW_TEXT_CAPACITY);
}
fn reset_for_scrolling_within(&mut self, seqno: SequenceNo, max_text_capacity: usize) {
if let CellStorage::C(cl) = &mut self.cells {
if cl.clear_for_scrolling(max_text_capacity) {
self.bits = LineBits::NONE;
self.seqno = seqno;
self.zones = Zones::default();
#[cfg(feature = "appdata")]
{
// Keep the lock itself, which some platforms allocate on
// first use; a poisoned one is replaced, as a new row's.
if self.appdata.is_poisoned() {
self.appdata = Mutex::new(None);
} else if let Ok(appdata) = self.appdata.get_mut() {
*appdata = None;
}
}
return;
}
}
*self = Self::new(seqno);
}
/// Computes a hash over the line that will change if the way that
/// the line contents are shaped would change.
/// This is independent of the seqno and is based purely on the
/// content of the line.
///
/// Line doesn't implement Hash in terms of this function as compute_shape_hash
/// doesn't every possible bit of internal state, and we don't want to
/// encourage using Line directly as a hash key.
pub fn compute_shape_hash(&self) -> [u8; 16] {
let mut hasher = SipHasher::new();
self.bits.bits().hash(&mut hasher);
for cell in self.visible_cells() {
cell.compute_shape_hash(&mut hasher);
}
hasher.finish128().as_bytes()
}
pub fn with_width(width: usize, seqno: SequenceNo) -> Self {
let mut cells = Vec::with_capacity(width);
cells.resize_with(width, Cell::blank);
let bits = LineBits::NONE;
Self {
bits,
cells: CellStorage::V(VecStorage::new(cells)),
seqno,
zones: Zones::default(),
#[cfg(feature = "appdata")]
appdata: Mutex::new(None),
}
}
pub fn from_text(
s: &str,
attrs: &CellAttributes,
seqno: SequenceNo,
unicode_version: Option<&UnicodeVersion>,
) -> Line {
let mut cells = Vec::new();
for sub in Graphemes::new(s) {
let cell = Cell::new_grapheme(sub, attrs.clone(), unicode_version);
let width = cell.width();
cells.push(cell);
for _ in 1..width {
cells.push(Cell::new(' ', attrs.clone()));
}
}
Line {
cells: CellStorage::V(VecStorage::new(cells)),
bits: LineBits::NONE,
seqno,
zones: Zones::default(),
#[cfg(feature = "appdata")]
appdata: Mutex::new(None),
}
}
pub fn from_text_with_wrapped_last_col(
s: &str,
attrs: &CellAttributes,
seqno: SequenceNo,
) -> Line {
let mut line = Self::from_text(s, attrs, seqno, None);
line.cells_mut()
.last_mut()
.map(|cell| cell.attrs_mut().set_wrapped(true));
line
}
pub fn resize_and_clear(
&mut self,
width: usize,
seqno: SequenceNo,
blank_attr: CellAttributes,
) {
// All old cells are being discarded. Expanding a compact scrollback
// row first would decode its text and clone its styles only to erase
// them below. Drop that storage before allocating the replacement.
if matches!(&self.cells, CellStorage::C(_)) {
self.cells = CellStorage::V(VecStorage::new(Vec::new()));
}
self.coerce_vec_storage()
.resize_and_clear(width, blank_attr);
self.update_last_change_seqno(seqno);
self.invalidate_zones();
self.bits = LineBits::NONE;
}
pub fn resize(&mut self, width: usize, seqno: SequenceNo) {
self.coerce_vec_storage().resize_with(width, Cell::blank);
self.update_last_change_seqno(seqno);
self.invalidate_zones();
}
/// Wrap the line so that it fits within the provided width.
/// Returns the list of resultant line(s)
pub fn wrap(self, width: usize, seqno: SequenceNo) -> Vec<Self> {
let mut cells: Vec<CellRef> = self.visible_cells().collect();
if let Some(end_idx) = cells.iter().rposition(|c| c.str() != " ") {
cells.truncate(end_idx + 1);
let mut lines: Vec<Self> = vec![];
let mut delta = 0;
for cell in cells {
let need_new_line = lines
.last_mut()
.map(|line| line.len() + cell.width() > width)
.unwrap_or(true);
if need_new_line {
lines
.last_mut()
.map(|line| line.set_last_cell_was_wrapped(true, seqno));
lines.push(Line::new(seqno));
delta = cell.cell_index();
}
let line = lines.last_mut().unwrap();
line.set_cell_grapheme(
cell.cell_index() - delta,
cell.str(),
cell.width(),
(*cell.attrs()).clone(),
seqno,
);
}
lines
} else {
vec![self]
}
}
/// Set arbitrary application specific data for the line.
/// Only one piece of appdata can be tracked per line,
/// so this is only suitable for the overall application
/// and not for use by "middleware" crates.
/// A Weak reference is stored.
/// `get_appdata` is used to retrieve a previously stored reference.
#[cfg(feature = "appdata")]
pub fn set_appdata<T: Any + Send + Sync>(&self, appdata: Arc<T>) {
let appdata: Arc<dyn Any + Send + Sync> = appdata;
self.appdata
.lock()
.unwrap()
.replace(Arc::downgrade(&appdata));
}
#[cfg(feature = "appdata")]
pub fn clear_appdata(&self) {
self.appdata.lock().unwrap().take();
}
/// Retrieve the appdata for the line, if any.
/// This may return None in the case where the underlying data has
/// been released: Line only stores a Weak reference to it.
#[cfg(feature = "appdata")]
pub fn get_appdata(&self) -> Option<Arc<dyn Any + Send + Sync>> {
self.appdata
.lock()
.unwrap()
.as_ref()
.and_then(|data| data.upgrade())
}
/// Returns true if the line's last changed seqno is more recent
/// than the provided seqno parameter
pub fn changed_since(&self, seqno: SequenceNo) -> bool {
self.seqno == SEQ_ZERO || self.seqno > seqno
}
pub fn current_seqno(&self) -> SequenceNo {
self.seqno
}
/// Annotate the line with the sequence number of a change.
/// This can be used together with Line::changed_since to
/// manage caching and rendering
#[inline]
pub fn update_last_change_seqno(&mut self, seqno: SequenceNo) {
self.seqno = self.seqno.max(seqno);
}
/// Check whether the line is single-width.
#[inline]
pub fn is_single_width(&self) -> bool {
(self.bits
& (LineBits::DOUBLE_WIDTH
| LineBits::DOUBLE_HEIGHT_TOP
| LineBits::DOUBLE_HEIGHT_BOTTOM))
== LineBits::NONE
}
/// Force single-width. This also implicitly sets
/// double-height-(top/bottom) and dirty.
#[inline]
pub fn set_single_width(&mut self, seqno: SequenceNo) {
self.bits.remove(LineBits::DOUBLE_WIDTH_HEIGHT_MASK);
self.update_last_change_seqno(seqno);
}
/// Check whether the line is double-width and not double-height.
#[inline]
pub fn is_double_width(&self) -> bool {
(self.bits & LineBits::DOUBLE_WIDTH_HEIGHT_MASK) == LineBits::DOUBLE_WIDTH
}
/// Force double-width. This also implicitly sets
/// double-height-(top/bottom) and dirty.
#[inline]
pub fn set_double_width(&mut self, seqno: SequenceNo) {
self.bits
.remove(LineBits::DOUBLE_HEIGHT_TOP | LineBits::DOUBLE_HEIGHT_BOTTOM);
self.bits.insert(LineBits::DOUBLE_WIDTH);
self.update_last_change_seqno(seqno);
}
/// Check whether the line is double-height-top.
#[inline]
pub fn is_double_height_top(&self) -> bool {
(self.bits & LineBits::DOUBLE_WIDTH_HEIGHT_MASK)
== LineBits::DOUBLE_WIDTH | LineBits::DOUBLE_HEIGHT_TOP
}
/// Force double-height top-half. This also implicitly sets
/// double-width and dirty.
#[inline]
pub fn set_double_height_top(&mut self, seqno: SequenceNo) {
self.bits.remove(LineBits::DOUBLE_HEIGHT_BOTTOM);
self.bits
.insert(LineBits::DOUBLE_WIDTH | LineBits::DOUBLE_HEIGHT_TOP);
self.update_last_change_seqno(seqno);
}
/// Check whether the line is double-height-bottom.
#[inline]
pub fn is_double_height_bottom(&self) -> bool {
(self.bits & LineBits::DOUBLE_WIDTH_HEIGHT_MASK)
== LineBits::DOUBLE_WIDTH | LineBits::DOUBLE_HEIGHT_BOTTOM
}
/// Force double-height bottom-half. This also implicitly sets
/// double-width and dirty.
#[inline]
pub fn set_double_height_bottom(&mut self, seqno: SequenceNo) {
self.bits.remove(LineBits::DOUBLE_HEIGHT_TOP);
self.bits
.insert(LineBits::DOUBLE_WIDTH | LineBits::DOUBLE_HEIGHT_BOTTOM);
self.update_last_change_seqno(seqno);
}
/// Set a flag the indicate whether the line should have the bidi
/// algorithm applied during rendering
pub fn set_bidi_enabled(&mut self, enabled: bool, seqno: SequenceNo) {
self.bits.set(LineBits::BIDI_ENABLED, enabled);
self.update_last_change_seqno(seqno);
}
/// Set the bidi direction for the line.
/// This affects both the bidi algorithm (if enabled via set_bidi_enabled)
/// and the layout direction of the line.
/// `auto_detect` specifies whether the direction should be auto-detected
/// before falling back to the specified direction.
pub fn set_direction(&mut self, direction: Direction, auto_detect: bool, seqno: SequenceNo) {
self.bits
.set(LineBits::RTL, direction == Direction::LeftToRight);
self.bits.set(LineBits::AUTO_DETECT_DIRECTION, auto_detect);
self.update_last_change_seqno(seqno);
}
pub fn set_bidi_info(
&mut self,
enabled: bool,
direction: ParagraphDirectionHint,
seqno: SequenceNo,
) {
self.bits.set(LineBits::BIDI_ENABLED, enabled);
let (auto, rtl) = match direction {
ParagraphDirectionHint::AutoRightToLeft => (true, true),
ParagraphDirectionHint::AutoLeftToRight => (true, false),
ParagraphDirectionHint::LeftToRight => (false, false),
ParagraphDirectionHint::RightToLeft => (false, true),
};
self.bits.set(LineBits::AUTO_DETECT_DIRECTION, auto);
self.bits.set(LineBits::RTL, rtl);
self.update_last_change_seqno(seqno);
}
/// Returns a tuple of (BIDI_ENABLED, Direction), indicating whether
/// the line should have the bidi algorithm applied and its base
/// direction, respectively.
pub fn bidi_info(&self) -> (bool, ParagraphDirectionHint) {
(
self.bits.contains(LineBits::BIDI_ENABLED),
match (
self.bits.contains(LineBits::AUTO_DETECT_DIRECTION),
self.bits.contains(LineBits::RTL),
) {
(true, true) => ParagraphDirectionHint::AutoRightToLeft,
(false, true) => ParagraphDirectionHint::RightToLeft,
(true, false) => ParagraphDirectionHint::AutoLeftToRight,
(false, false) => ParagraphDirectionHint::LeftToRight,
},
)
}
fn invalidate_zones(&mut self) {
self.zones = Zones::default();
}
fn compute_zones(&mut self) {
let blank_cell = Cell::blank();
let mut last_cell: Option<CellRef> = None;
let mut current_zone: Option<ZoneRange> = None;
let mut zones = vec![];
// Rows may have trailing space+Output cells interleaved
// with other zones as a result of clear-to-eol and
// clear-to-end-of-screen sequences. We don't want
// those to affect the zones that we compute here
let mut last_non_blank = self.len();
for cell in self.visible_cells() {
if cell.str() != blank_cell.str() || cell.attrs() != blank_cell.attrs() {
last_non_blank = cell.cell_index();
}
}
for cell in self.visible_cells() {
if cell.cell_index() > last_non_blank {
break;
}
let grapheme_idx = cell.cell_index() as u16;
let semantic_type = cell.attrs().semantic_type();
let new_zone = match last_cell {
None => true,
Some(ref c) => c.attrs().semantic_type() != semantic_type,
};
if new_zone {
if let Some(zone) = current_zone.take() {
zones.push(zone);
}
current_zone.replace(ZoneRange {
range: grapheme_idx..grapheme_idx + 1,
semantic_type,
});
}
if let Some(zone) = current_zone.as_mut() {
zone.range.end = grapheme_idx;
}
last_cell.replace(cell);
}
if let Some(zone) = current_zone.take() {
zones.push(zone);
}
self.zones.set(zones);
}
pub fn semantic_zone_ranges(&mut self) -> &[ZoneRange] {
if self.zones.0.is_none() {
self.compute_zones();
}
self.zones.as_slice()
}
/// If we have any cells with an implicit hyperlink, remove the hyperlink
/// from the cell attributes but leave the remainder of the attributes alone.
#[inline]
pub fn invalidate_implicit_hyperlinks(&mut self, seqno: SequenceNo) {
if (self.bits & (LineBits::SCANNED_IMPLICIT_HYPERLINKS | LineBits::HAS_IMPLICIT_HYPERLINKS))
== LineBits::NONE
{
return;
}
self.bits &= !LineBits::SCANNED_IMPLICIT_HYPERLINKS;
if (self.bits & LineBits::HAS_IMPLICIT_HYPERLINKS) == LineBits::NONE {
return;
}
self.invalidate_implicit_hyperlinks_impl(seqno);
}
fn invalidate_implicit_hyperlinks_impl(&mut self, seqno: SequenceNo) {
let cells = self.coerce_vec_storage();
for cell in cells.iter_mut() {
let replace = match cell.attrs().hyperlink() {
Some(ref link) if link.is_implicit() => Some(Cell::new_grapheme(
cell.str(),
cell.attrs().clone().set_hyperlink(None).clone(),
None,
)),
_ => None,
};
if let Some(replace) = replace {
*cell = replace;
}
}
self.bits &= !LineBits::HAS_IMPLICIT_HYPERLINKS;
self.update_last_change_seqno(seqno);
}
/// Scan through the line and look for sequences that match the provided
/// rules. Matching sequences are considered to be implicit hyperlinks
/// and will have a hyperlink attribute associated with them.
/// This function will only make changes if the line has been invalidated
/// since the last time this function was called.
/// This function does not remember the values of the `rules` slice, so it
/// is the responsibility of the caller to call `invalidate_implicit_hyperlinks`
/// if it wishes to call this function with different `rules`.
pub fn scan_and_create_hyperlinks(&mut self, rules: &[Rule]) {
if (self.bits & LineBits::SCANNED_IMPLICIT_HYPERLINKS)
== LineBits::SCANNED_IMPLICIT_HYPERLINKS
{
// Has not changed since last time we scanned
return;
}
// FIXME: let's build a string and a byte-to-cell map here, and
// use this as an opportunity to rebuild HAS_HYPERLINK, skip matching
// cells with existing non-implicit hyperlinks, and avoid matching
// text with zero-width cells.
self.bits |= LineBits::SCANNED_IMPLICIT_HYPERLINKS;
self.bits &= !LineBits::HAS_IMPLICIT_HYPERLINKS;
let line = self.as_str();
let matches = Rule::match_hyperlinks(&line, rules);
if matches.is_empty() {
return;
}
let line = line.into_owned();
let cells = self.coerce_vec_storage();
if cells.scan_and_create_hyperlinks(&line, matches) {
self.bits |= LineBits::HAS_IMPLICIT_HYPERLINKS;
}
}
/// Scan through a logical line that is comprised of an array of
/// physical lines and look for sequences that match the provided
/// rules. Matching sequences are considered to be implicit hyperlinks
/// and will have a hyperlink attribute associated with them.
/// This function will only make changes if the line has been invalidated
/// since the last time this function was called.
/// This function does not remember the values of the `rules` slice, so it
/// is the responsibility of the caller to call `invalidate_implicit_hyperlinks`
/// if it wishes to call this function with different `rules`.
///
/// This function will call Line::clear_appdata on lines where
/// hyperlinks are adjusted.
pub fn apply_hyperlink_rules(rules: &[Rule], logical_line: &mut [&mut Line]) {
if rules.is_empty() || logical_line.is_empty() {
return;
}
let mut need_scan = false;
for line in logical_line.iter() {
if !line.bits.contains(LineBits::SCANNED_IMPLICIT_HYPERLINKS) {
need_scan = true;
break;
}
}
if !need_scan {
return;
}
let mut logical = logical_line[0].clone();
for line in &logical_line[1..] {
let seqno = logical.current_seqno().max(line.current_seqno());
logical.append_line((**line).clone(), seqno);
}
let seq = logical.current_seqno();
logical.invalidate_implicit_hyperlinks(seq);
logical.scan_and_create_hyperlinks(rules);
if !logical.has_hyperlink() {
for line in logical_line.iter_mut() {
line.bits.set(LineBits::SCANNED_IMPLICIT_HYPERLINKS, true);
#[cfg(feature = "appdata")]
line.clear_appdata();
}
return;
}
// Re-compute the physical lines that comprise this logical line
for phys in logical_line.iter_mut() {
let wrapped = phys.last_cell_was_wrapped();
let is_cluster = matches!(&phys.cells, CellStorage::C(_));
let len = phys.len();
let remainder = logical.split_off(len, seq);
**phys = logical;
logical = remainder;
phys.set_last_cell_was_wrapped(wrapped, seq);
#[cfg(feature = "appdata")]
phys.clear_appdata();
if is_cluster {
phys.compress_for_scrollback();
}
}
}
/// Returns true if the line contains a hyperlink
#[inline]
pub fn has_hyperlink(&self) -> bool {
(self.bits & (LineBits::HAS_HYPERLINK | LineBits::HAS_IMPLICIT_HYPERLINKS))
!= LineBits::NONE
}
/// Recompose line into the corresponding utf8 string.
pub fn as_str(&self) -> Cow<'_, str> {
match &self.cells {
CellStorage::V(_) => {
let mut s = String::new();
for cell in self.visible_cells() {
s.push_str(cell.str());
}
Cow::Owned(s)
}
CellStorage::C(cl) => Cow::Borrowed(cl.text()),
}
}
pub fn split_off(&mut self, idx: usize, seqno: SequenceNo) -> Self {
let my_cells = self.coerce_vec_storage();
// Clamp to avoid out of bounds panic if the line is shorter
// than the requested split point
// <https://github.com/wezterm/wezterm/issues/2355>
let idx = idx.min(my_cells.len());
let cells = my_cells.split_off(idx);
Self {
bits: self.bits,
cells: CellStorage::V(VecStorage::new(cells)),
seqno,
zones: Zones::default(),
#[cfg(feature = "appdata")]
appdata: Mutex::new(None),
}
}
pub fn compute_double_click_range<F: Fn(&str) -> bool>(
&self,
click_col: usize,
is_word: F,
) -> DoubleClickRange {
let len = self.len();
if click_col >= len {
return DoubleClickRange::Range(click_col..click_col);
}
let mut lower = click_col;
let mut upper = click_col;
// TODO: look back and look ahead for cells that are hidden by
// a preceding multi-wide cell
let cells = self.visible_cells().collect::<Vec<_>>();
for cell in &cells {
if cell.cell_index() < click_col {
continue;
}
if !is_word(cell.str()) {
break;
}
upper = cell.cell_index() + 1;
}
for cell in cells.iter().rev() {
if cell.cell_index() > click_col {
continue;
}
if !is_word(cell.str()) {
break;
}
lower = cell.cell_index();
}
if upper > lower
&& upper >= len
&& cells
.last()
.map(|cell| cell.attrs().wrapped())
.unwrap_or(false)
{
DoubleClickRange::RangeWithWrap(lower..upper)
} else {
DoubleClickRange::Range(lower..upper)
}
}
/// Returns a substring from the line.
pub fn columns_as_str(&self, range: Range<usize>) -> String {
let mut s = String::new();
for c in self.visible_cells() {
if c.cell_index() < range.start {
continue;
}
if c.cell_index() >= range.end {
break;
}
s.push_str(c.str());
}
s
}
pub fn columns_as_line(&self, range: Range<usize>) -> Self {
let mut cells = vec![];
for c in self.visible_cells() {
if c.cell_index() < range.start {
continue;
}
if c.cell_index() >= range.end {
break;
}
cells.push(c.as_cell());
}
Self {
bits: LineBits::NONE,
cells: CellStorage::V(VecStorage::new(cells)),
seqno: self.current_seqno(),
zones: Zones::default(),
#[cfg(feature = "appdata")]
appdata: Mutex::new(None),
}
}
/// If we're about to modify a cell obscured by a double-width
/// character ahead of that cell, we need to nerf that sequence
/// of cells to avoid partial rendering concerns.
/// Similarly, when we assign a cell, we need to blank out those
/// occluded successor cells.
pub fn set_cell(&mut self, idx: usize, cell: Cell, seqno: SequenceNo) {
self.set_cell_impl(idx, cell, false, seqno);
}
/// Assign a cell using grapheme text with a known width and attributes.
/// This is a micro-optimization over first constructing a Cell from
/// the grapheme info. If assigning this particular cell can be optimized
/// to an append to the interal clustered storage then the cost of
/// constructing and dropping the Cell can be avoided.
pub fn set_cell_grapheme(
&mut self,
idx: usize,
text: &str,
width: usize,
attr: CellAttributes,
seqno: SequenceNo,
) {
self.set_cell_grapheme_after(idx, text, width, attr, false, seqno);
}
/// `set_cell_grapheme`, where `follows` says that `text` is known to be
/// separate from what is before it.
pub fn set_cell_grapheme_after(
&mut self,
idx: usize,
text: &str,
width: usize,
attr: CellAttributes,
follows: bool,
seqno: SequenceNo,
) {
if attr.hyperlink().is_some() {
self.bits |= LineBits::HAS_HYPERLINK;
}
if let CellStorage::C(cl) = &mut self.cells {
if idx == cl.len() && (follows || !cl.joins(text)) {
cl.append_grapheme(text, width, attr);
self.invalidate_implicit_hyperlinks(seqno);
self.invalidate_zones();
self.update_last_change_seqno(seqno);
return;
}
}
self.set_cell_grapheme_nonappend(idx, text, width, attr, seqno);
}
/// Whether `append_grapheme_run` can take graphemes starting at `idx`:
/// the end of clustered storage, or where only blanks are left of it,
/// without implicit hyperlinks, which the first write would otherwise
/// expand to cells.
pub fn can_append_grapheme_run(&self, idx: usize) -> bool {
match &self.cells {
CellStorage::C(cl) => {
(idx == cl.len() || cl.is_blank_from(idx))
&& (self.bits & LineBits::HAS_IMPLICIT_HYPERLINKS) == LineBits::NONE
}
_ => false,
}
}
/// `set_cell_grapheme` for each grapheme of a run written one after
/// another from `idx`, all with `attr`; see `ClusteredLine::append_run`
/// for the arguments. `follows` says that `text` is known to be separate
/// from what is before it. Returns false, changing nothing, unless
/// `can_append_grapheme_run(idx)` and `append_run` takes the run; the
/// caller then writes the graphemes one at a time.
pub fn append_grapheme_run(
&mut self,
idx: usize,
text: &str,
max_len: usize,
cells: usize,
wide: &[u16],
last_width: u8,
attr: &CellAttributes,
follows: bool,
seqno: SequenceNo,
) -> bool {
if !self.can_append_grapheme_run(idx) {
return false;
}
let CellStorage::C(cl) = &mut self.cells else {
return false;
};
if !follows && cl.joins_at(idx, text) {
return false;
}
// Blanks make way for the run, and those it does not reach stay.
let len = cl.len();
if idx < len && runs_into(text.as_bytes(), " ") {
return false;
}
cl.truncate_blanks(idx);
let appended = cl.append_run(text, max_len, cells, wide, last_width, attr);
if cl.len() < len {
cl.append_ascii_repeated(' ', len - cl.len(), &CellAttributes::blank());
}
if !appended {
return false;
}
// What each set_cell_grapheme would do; repeating it changes nothing.
if attr.hyperlink().is_some() {
self.bits |= LineBits::HAS_HYPERLINK;
}
self.invalidate_implicit_hyperlinks(seqno);
self.invalidate_zones();
self.update_last_change_seqno(seqno);
true
}
// Keep padding and overwrites out of the common sequential append path.
#[inline(never)]
fn set_cell_grapheme_nonappend(
&mut self,
idx: usize,
text: &str,
width: usize,
attr: CellAttributes,
seqno: SequenceNo,
) {
if let CellStorage::C(cl) = &mut self.cells {
if idx > cl.len() {
if text == " " && attr == CellAttributes::blank() {
// Appending blank beyond end of line; is already
// implicitly blank
return;
}
Self::pad_clustered_line(cl, idx);
}
if idx == cl.len() && !cl.joins(text) {
cl.append_grapheme(text, width, attr);
self.invalidate_implicit_hyperlinks(seqno);
self.invalidate_zones();
self.update_last_change_seqno(seqno);
return;
}
}
self.set_cell(idx, Cell::new_grapheme_with_width(text, width, attr), seqno);
}
// Keep gap filling off the overwrite path, which never needs padding.
#[inline(never)]
fn pad_clustered_line(cl: &mut ClusteredLine, idx: usize) {
// Tabs, cursor movement and LF without CR leave gaps.
let count = idx.saturating_sub(cl.len());
cl.append_ascii_repeated(' ', count, &CellAttributes::blank());
}
/// Write ASCII over `range` of the cells without expanding compact storage;
/// see `ClusteredLine::overwrite_ascii`. What each write of a cell would
/// do to the rest of the line is done here if that went ahead.
fn overwrite_ascii(
&mut self,
range: Range<usize>,
attr: &CellAttributes,
seqno: SequenceNo,
write: impl FnOnce(&mut [u8]),
) -> bool {
if (self.bits & LineBits::HAS_IMPLICIT_HYPERLINKS) != LineBits::NONE {
return false;
}
let CellStorage::C(cl) = &mut self.cells else {
return false;
};
if !cl.overwrite_ascii(range, attr, write) {
return false;
}
if attr.hyperlink().is_some() {
self.bits |= LineBits::HAS_HYPERLINK;
}
self.invalidate_implicit_hyperlinks(seqno);
self.invalidate_zones();
self.update_last_change_seqno(seqno);
true
}
/// Write a run of printable ASCII with the same semantics as individual
/// `set_cell_grapheme` calls. Appending keeps compact storage; overwriting
/// preserves image placements.
pub fn set_printable_ascii_cells(
&mut self,
idx: usize,
text: &str,
attr: &CellAttributes,
seqno: SequenceNo,
) {
debug_assert!(text.bytes().all(|b| (b' '..=b'~').contains(&b)));
if text.is_empty() {
return;
}
// Over cells of the same sort, a row can stay as it is.
let over = text.len().min(self.len().saturating_sub(idx));
if over > 0
&& self.overwrite_ascii(idx..idx + over, attr, seqno, |cells| {
cells.copy_from_slice(&text.as_bytes()[..over])
})
{
if over == text.len() {
return;
}
if let CellStorage::C(cl) = &mut self.cells {
cl.append_ascii(&text[over..], attr);
}
return;
}
// An append cannot overlap a wide cell. Write the whole run without
// allocating attributes for a scalar first cell, unless hyperlink
// invalidation can change the storage before the rest of the write.
// Single-character writes use the cheaper scalar append below.
if text.len() > 1
&& (self.bits
& (LineBits::SCANNED_IMPLICIT_HYPERLINKS | LineBits::HAS_IMPLICIT_HYPERLINKS))
== LineBits::NONE
{
if let CellStorage::C(cl) = &mut self.cells {
if idx == cl.len() && !cl.joins(text) {
cl.append_ascii(text, attr);
if attr.hyperlink().is_some() {
self.bits |= LineBits::HAS_HYPERLINK;
}
self.invalidate_zones();
self.update_last_change_seqno(seqno);
return;
}
}
}
// Establish the same wide-cell boundary and line metadata as a scalar
// write before taking either storage-specific path.
self.set_cell_grapheme(idx, &text[..1], 1, attr.clone(), seqno);
match &mut self.cells {
CellStorage::C(cl) if cl.len() == idx + 1 => {
cl.append_ascii(&text[1..], attr);
}
CellStorage::V(cells) => {
let end = idx + text.len();
if end > cells.len() {
cells.resize_with(end, Cell::blank);
}
// Printable ASCII (checked above) is one column wide in every
// Unicode version; don't look the width up per character.
for offset in 1..text.len() {
let cell =
Cell::new_grapheme_with_width(&text[offset..offset + 1], 1, attr.clone());
cells.set_cell(idx + offset, cell, false);
}
}
_ => {
// A default blank beyond the end of compact storage is elided.
// Retain that behavior if the first write did not append.
for offset in 1..text.len() {
self.set_cell_grapheme(
idx + offset,
&text[offset..offset + 1],
1,
attr.clone(),
seqno,
);
}
}
}
}
pub fn set_cell_clearing_image_placements(
&mut self,
idx: usize,
cell: Cell,
seqno: SequenceNo,
) {
self.set_cell_impl(idx, cell, true, seqno)
}
fn raw_set_cell(&mut self, idx: usize, cell: Cell, clear: bool) {
let cells = self.coerce_vec_storage();
cells.set_cell(idx, cell, clear);
}
fn set_cell_impl(&mut self, idx: usize, cell: Cell, clear: bool, seqno: SequenceNo) {
// The .max(1) stuff is here in case we get called with a
// zero-width cell. That shouldn't happen: those sequences
// should get filtered out in the terminal parsing layer,
// but in case one does sneak through, we need to ensure that
// we grow the cells array to hold this bogus entry.
// https://github.com/wezterm/wezterm/issues/768
let width = cell.width().max(1);
self.invalidate_implicit_hyperlinks(seqno);
self.invalidate_zones();
self.update_last_change_seqno(seqno);
if cell.attrs().hyperlink().is_some() {
self.bits |= LineBits::HAS_HYPERLINK;
}
if let CellStorage::C(cl) = &mut self.cells {
if idx > cl.len() && cell == Cell::blank() {
// Appending blank beyond end of line; is already
// implicitly blank
return;
}
while cl.len() < idx {
// Fill out any implied blanks until we can append
// their intended cell content
cl.append_grapheme(" ", 1, CellAttributes::blank());
}
if idx == cl.len() && !cl.joins(cell.str()) {
cl.append(cell);
return;
}
/*
log::info!(
"cannot append {cell:?} to {:?} as idx={idx} and cl.len is {}",
cl,
cl.len
);
*/
}
// if the line isn't wide enough, pad it out with the default attributes.
{
let cells = self.coerce_vec_storage();
if idx + width > cells.len() {
cells.resize_with(idx + width, Cell::blank);
}
}
self.invalidate_grapheme_at_or_before(idx);
// For double-wide or wider chars, ensure that the cells that
// are overlapped by this one are blanked out.
for i in 1..=width.saturating_sub(1) {
self.raw_set_cell(idx + i, Cell::blank_with_attrs(cell.attrs().clone()), clear);
}
self.raw_set_cell(idx, cell, clear);
}
/// Place text starting at the specified column index.
/// Each grapheme of the text run has the same attributes.
pub fn overlay_text_with_attribute(
&mut self,
mut start_idx: usize,
text: &str,
attr: CellAttributes,
seqno: SequenceNo,
) {
for (i, c) in Graphemes::new(text).enumerate() {
let cell = Cell::new_grapheme(c, attr.clone(), None);
let width = cell.width();
self.set_cell(i + start_idx, cell, seqno);
// Compensate for required spacing/placement of
// double width characters
start_idx += width.saturating_sub(1);
}
}
fn invalidate_grapheme_at_or_before(&mut self, idx: usize) {
// Assumption: that the width of a grapheme is never > 2.
// This constrains the amount of look-back that we need to do here.
if idx > 0 {
let prior = idx - 1;
let cells = self.coerce_vec_storage();
let width = cells[prior].width();
if width > 1 {
let attrs = cells[prior].attrs().clone();
for nerf in prior..prior + width {
cells[nerf] = Cell::blank_with_attrs(attrs.clone());
}
}
}
}
pub fn insert_cell(&mut self, x: usize, cell: Cell, right_margin: usize, seqno: SequenceNo) {
self.invalidate_implicit_hyperlinks(seqno);
let cells = self.coerce_vec_storage();
if right_margin <= cells.len() {
cells.remove(right_margin - 1);
}
if x >= cells.len() {
cells.resize_with(x, Cell::blank);
}
// If we're inserting a wide cell, we should also insert the overlapped cells.
// We insert them first so that the grapheme winds up left-most.
let width = cell.width();
for _ in 1..=width.saturating_sub(1) {
cells.insert(x, Cell::blank_with_attrs(cell.attrs().clone()));
}
cells.insert(x, cell);
self.update_last_change_seqno(seqno);
self.invalidate_zones();
}
pub fn erase_cell(&mut self, x: usize, seqno: SequenceNo) {
if x >= self.len() {
// Already implicitly erased
return;
}
self.invalidate_implicit_hyperlinks(seqno);
self.invalidate_grapheme_at_or_before(x);
{
let cells = self.coerce_vec_storage();
cells.remove(x);
cells.push(Cell::default());
}
self.update_last_change_seqno(seqno);
self.invalidate_zones();
}
pub fn remove_cell(&mut self, x: usize, seqno: SequenceNo) {
if x >= self.len() {
// Already implicitly removed
return;
}
self.invalidate_implicit_hyperlinks(seqno);
self.invalidate_grapheme_at_or_before(x);
self.coerce_vec_storage().remove(x);
self.update_last_change_seqno(seqno);
self.invalidate_zones();
}
pub fn erase_cell_with_margin(
&mut self,
x: usize,
right_margin: usize,
seqno: SequenceNo,
blank_attr: CellAttributes,
) {
self.invalidate_implicit_hyperlinks(seqno);
if x < self.len() {
self.invalidate_grapheme_at_or_before(x);
self.coerce_vec_storage().remove(x);
}
if right_margin <= self.len() + 1
/* we just removed one */
{
self.coerce_vec_storage()
.insert(right_margin - 1, Cell::blank_with_attrs(blank_attr));
}
self.update_last_change_seqno(seqno);
self.invalidate_zones();
}
pub fn prune_trailing_blanks(&mut self, seqno: SequenceNo) {
if let CellStorage::C(cl) = &mut self.cells {
if cl.prune_trailing_blanks() {
self.update_last_change_seqno(seqno);
self.invalidate_zones();
}
return;
}
let def_attr = CellAttributes::blank();
let cells = self.coerce_vec_storage();
if let Some(end_idx) = cells
.iter()
.rposition(|c| c.str() != " " || c.attrs() != &def_attr)
{
cells.resize_with(end_idx + 1, Cell::blank);
self.update_last_change_seqno(seqno);
self.invalidate_zones();
}
}
pub fn fill_range(&mut self, mut cols: Range<usize>, cell: &Cell, seqno: SequenceNo) {
if self.len() == 0 && *cell == Cell::blank() {
// We would be filling it with blanks only to prune
// them all away again before we return; NOP
return;
}
if cols.start == 0
&& cols.end >= self.len()
&& cols.end <= u16::MAX as usize
&& matches!(&self.cells, CellStorage::C(_))
&& (self.bits & LineBits::HAS_IMPLICIT_HYPERLINKS) == LineBits::NONE
&& *cell == Cell::blank()
{
// The whole row: no cell of it survives to need looking at, and
// blanks need no more than a run of spaces. A row of cells stays
// one, or a row that has to be would go back and forth. Taking
// links back out of a row turns it into cells, so not one of those.
self.invalidate_implicit_hyperlinks(seqno);
self.invalidate_zones();
self.update_last_change_seqno(seqno);
if let CellStorage::C(cl) = &mut self.cells {
if !cl.clear_for_scrolling(cols.end.max(80).saturating_mul(2)) {
*cl = ClusteredLine::new();
}
cl.append_ascii_repeated(' ', cols.end, cell.attrs());
}
return;
}
if !cols.is_empty()
&& cols.start < self.len()
&& cols.end >= self.len()
&& *cell == Cell::blank()
&& matches!(&self.cells, CellStorage::V(_))
{
// Resolve a wide grapheme crossing the start and invalidate links
// before deciding which prefix can remain. The erased tail will
// be pruned, so don't first construct a blank Cell for every column.
let start = cols.start;
self.set_cell_impl(start, cell.clone(), true, seqno);
if let CellStorage::V(cells) = &mut self.cells {
if let Some(last) = cells[..start]
.iter()
.rposition(|c| c.str() != " " || c.attrs() != cell.attrs())
{
cells.truncate(last + 1);
return;
}
// The whole row ends up blank. Vec storage historically
// retains the length of all-blank lines, so write the tail
// in one go; the trailing-blank scan could prune nothing.
cells.truncate(start + 1);
cells.resize(cols.end, cell.clone());
return;
}
// Vec storage historically retains the length of all-blank lines.
// Preserve that behavior, including styled wide-cell padding.
cols.start += 1;
}
// Compact storage only keeps a row of blanks it was overwriting: one
// that got this far by appending blanks has always lost them again.
let overwriting = cols.start < self.len() && !cols.is_empty();
self.set_cell_range_impl(cols, cell, true, seqno);
if let CellStorage::C(cl) = &self.cells {
if overwriting && *cell == Cell::blank() && cl.is_all_blank() {
return;
}
}
self.prune_trailing_blanks(seqno);
}
/// Equivalent to calling `set_cell` at each column, including preservation
/// of Kitty image placements. Unlike `fill_range`, this does not prune
/// trailing blanks or erase image placements.
pub fn set_cell_range(&mut self, cols: Range<usize>, cell: &Cell, seqno: SequenceNo) {
self.set_cell_range_impl(cols, cell, false, seqno);
}
fn set_cell_range_impl(
&mut self,
mut cols: Range<usize>,
cell: &Cell,
clear_image_placements: bool,
seqno: SequenceNo,
) {
if cols.is_empty() {
return;
}
if let Some(c) = printable_ascii(cell) {
let over = cols.end.min(self.len());
if cols.start < over
&& self.overwrite_ascii(cols.start..over, cell.attrs(), seqno, |cells| {
cells.fill(c as u8)
})
{
cols.start = over;
if cols.is_empty() {
return;
}
if let CellStorage::C(cl) = &mut self.cells {
cl.append_ascii_repeated(c, cols.len(), cell.attrs());
return;
}
}
}
let Some(first) = cols.next() else {
return;
};
// The first write handles an overlapping wide cell, invalidates links
// and zones, and updates the sequence number exactly as a scalar write.
self.set_cell_impl(first, cell.clone(), clear_image_placements, seqno);
if cell.width() == 1 && !cols.is_empty() {
if let CellStorage::V(cells) = &mut self.cells {
if cols.end > cells.len() {
cells.resize_with(cols.end, Cell::blank);
}
// Every preceding cell in this run has just been written with
// width one, so subsequent writes cannot overlap a wide cell
// on their left. Keep VecStorage's image-placement semantics.
if clear_image_placements {
cells[cols].fill(cell.clone());
} else {
for x in cols {
cells.set_cell_from(x, cell);
}
}
return;
}
if let (CellStorage::C(cl), Some(c)) = (&mut self.cells, printable_ascii(cell)) {
if cols.start == cl.len() {
cl.append_ascii_repeated(c, cols.len(), cell.attrs());
return;
}
}
}
// Preserve compact append storage and the scalar semantics of wide or
// zero-width cells. Never expand a compact line just for this fast path.
for x in cols {
self.set_cell_impl(x, cell.clone(), clear_image_placements, seqno);
}
}
pub fn len(&self) -> usize {
match &self.cells {
CellStorage::V(cells) => cells.len(),
CellStorage::C(cl) => cl.len(),
}
}
/// Whether the line currently sits in compact cluster storage.
pub fn is_compressed_for_scrollback(&self) -> bool {
matches!(&self.cells, CellStorage::C(_))
}
/// Check image attachments without walking the text or cloning image
/// references when the line is in compact cluster storage.
#[cfg(feature = "use_image")]
pub fn has_images(&self) -> bool {
match &self.cells {
CellStorage::V(cells) => cells.iter().any(|cell| cell.attrs().has_images()),
CellStorage::C(cl) => cl.any_cluster_attrs(CellAttributes::has_images),
}
}
/// Whether any cell carries a hyperlink or attached image, answered
/// without decompressing cluster storage. Serialization uses this to
/// leave the great majority of lines, which carry neither, in their
/// compact form.
pub fn has_hyperlinks_or_images(&self) -> bool {
fn wants_extraction(attrs: &CellAttributes) -> bool {
if attrs.hyperlink().is_some() {
return true;
}
#[cfg(feature = "use_image")]
if attrs.has_images() {
return true;
}
false
}
match &self.cells {
CellStorage::V(cells) => cells.iter().any(|cell| wants_extraction(cell.attrs())),
CellStorage::C(cl) => cl.any_cluster_attrs(wants_extraction),
}
}
/// Iterates the visible cells, respecting the width of the cell.
/// For instance, a double-width cell overlaps the following (blank)
/// cell, so that blank cell is omitted from the iterator results.
/// The iterator yields (column_index, Cell). Column index is the
/// index into Self::cells, and due to the possibility of skipping
/// the characters that follow wide characters, the column index may
/// skip some positions. It is returned as a convenience to the consumer
/// as using .enumerate() on this iterator wouldn't be as useful.
pub fn visible_cells<'a>(&'a self) -> impl Iterator<Item = CellRef<'a>> {
match &self.cells {
CellStorage::V(cells) => VisibleCellIter::V(VecStorageIter {
cells: cells.iter(),
idx: 0,
skip_width: 0,
}),
CellStorage::C(cl) => VisibleCellIter::C(cl.iter()),
}
}
pub fn get_cell(&self, cell_index: usize) -> Option<CellRef<'_>> {
self.visible_cells()
.find(|cell| cell.cell_index() == cell_index)
}
/// The cell at `cell_index` of a row of nothing but one-byte cells in
/// compact storage, where it can be had without expanding the row.
pub fn ascii_cell(&self, cell_index: usize) -> Option<Cell> {
match &self.cells {
CellStorage::C(cl) => cl.get_byte_cell(cell_index).map(|cell| cell.as_cell()),
CellStorage::V(_) => None,
}
}
pub fn cluster(&self, bidi_hint: Option<ParagraphDirectionHint>) -> Vec<CellCluster> {
CellCluster::make_cluster(self.len(), self.visible_cells(), bidi_hint)
}
fn make_cells(&mut self) {
let cells = match &self.cells {
CellStorage::V(_) => return,
CellStorage::C(cl) => cl.to_cell_vec(),
};
// log::info!("make_cells\n{:?}", backtrace::Backtrace::new());
self.cells = CellStorage::V(VecStorage::new(cells));
}
pub(crate) fn coerce_vec_storage(&mut self) -> &mut VecStorage {
self.make_cells();
match &mut self.cells {
CellStorage::V(c) => return c,
CellStorage::C(_) => unreachable!(),
}
}
/// Adjusts the internal storage so that it occupies less
/// space. Subsequent mutations will incur some overhead to
/// re-materialize the storage in a form that is suitable
/// for mutation.
pub fn compress_for_scrollback(&mut self) {
let cv = match &self.cells {
CellStorage::V(v) => ClusteredLine::from_cell_vec(v.len(), self.visible_cells()),
CellStorage::C(_) => return,
};
if cv.reads_back_as(self.visible_cells()) {
self.cells = CellStorage::C(cv);
}
}
/// Make a compact line as long as `len` cells, where blanks written
/// beyond its end have been left implicit. They matter once what follows
/// on the next row is to be read as following them.
pub fn keep_blanks_to(&mut self, len: usize) {
if let CellStorage::C(cl) = &mut self.cells {
if cl.len() < len {
Self::pad_clustered_line(cl, len);
self.invalidate_zones();
}
}
}
pub fn cells_mut(&mut self) -> &mut [Cell] {
self.coerce_vec_storage().as_mut_slice()
}
/// Return true if the line consists solely of whitespace cells
pub fn is_whitespace(&self) -> bool {
self.visible_cells().all(|c| c.str() == " ")
}
/// Return true if the last cell in the line has the wrapped attribute,
/// indicating that the following line is logically a part of this one.
pub fn last_cell_was_wrapped(&self) -> bool {
self.visible_cells()
.last()
.map(|c| c.attrs().wrapped())
.unwrap_or(false)
}
/// Adjust the value of the wrapped attribute on the last cell of this
/// line.
pub fn set_last_cell_was_wrapped(&mut self, wrapped: bool, seqno: SequenceNo) {
self.update_last_change_seqno(seqno);
if let CellStorage::C(cl) = &mut self.cells {
if cl.len() == 0 {
// Need to mark that implicit space as wrapped, so
// explicitly add it
cl.append(Cell::blank());
}
cl.set_last_cell_was_wrapped(wrapped);
return;
}
let cells = self.coerce_vec_storage();
if let Some(cell) = cells.last_mut() {
cell.attrs_mut().set_wrapped(wrapped);
}
}
/// Concatenate the cells from other with this line, appending them
/// to this line.
/// This function is used by rewrapping logic when joining wrapped
/// lines back together.
pub fn append_line(&mut self, other: Line, seqno: SequenceNo) {
match &mut self.cells {
CellStorage::V(cells) => {
for cell in other.visible_cells() {
cells.push(cell.as_cell());
for _ in 1..cell.width() {
cells.push(Cell::new(' ', cell.attrs().clone()));
}
}
}
CellStorage::C(cl) => {
for cell in other.visible_cells() {
cl.append(cell.as_cell());
}
}
}
self.update_last_change_seqno(seqno);
self.invalidate_zones();
}
/// mutable access the cell data, but the caller must take care
/// to only mutate attributes rather than the cell textual content.
/// Use set_cell if you need to modify the textual content of the
/// cell, so that important invariants are upheld.
pub fn cells_mut_for_attr_changes_only(&mut self) -> &mut [Cell] {
self.coerce_vec_storage().as_mut_slice()
}
/// Given a starting attribute value, produce a series of Change
/// entries to recreate the current line
pub fn changes(&self, start_attr: &CellAttributes) -> Vec<Change> {
let mut result = Vec::new();
let mut attr = start_attr.clone();
let mut text_run = String::new();
for cell in self.visible_cells() {
if *cell.attrs() == attr {
text_run.push_str(cell.str());
} else {
// flush out the current text run
if !text_run.is_empty() {
result.push(Change::Text(text_run.clone()));
text_run.clear();
}
attr = cell.attrs().clone();
result.push(Change::AllAttributes(attr.clone()));
text_run.push_str(cell.str());
}
}
// flush out any remaining text run
if !text_run.is_empty() {
// if this is just spaces then it is likely cheaper
// to emit ClearToEndOfLine instead.
if attr
== CellAttributes::default()
.set_background(attr.background())
.clone()
{
let left = text_run.trim_end_matches(' ').to_string();
let num_trailing_spaces = text_run.len() - left.len();
if num_trailing_spaces > 0 {
if !left.is_empty() {
result.push(Change::Text(left));
} else if result.len() == 1 {
// if the only queued result prior to clearing
// to the end of the line is an attribute change,
// we can prune it out and return just the line
// clearing operation
if let Change::AllAttributes(_) = result[0] {
result.clear()
}
}
// Since this function is only called in the full repaint
// case, and we always emit a clear screen with the default
// background color, we don't need to emit an instruction
// to clear the remainder of the line unless it has a different
// background color.
if attr.background() != Default::default() {
result.push(Change::ClearToEndOfLine(attr.background()));
}
} else {
result.push(Change::Text(text_run));
}
} else {
result.push(Change::Text(text_run));
}
}
result
}
}
impl<'a> From<&'a str> for Line {
fn from(s: &str) -> Line {
Line::from_text(s, &CellAttributes::default(), SEQ_ZERO, None)
}
}
#[cfg(test)]
#[path = "resize_clear_tests.rs"]
mod resize_clear_tests;