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.

term: a terminal can be snapshotted and restored

RoversX880e87d58080
diff --git a/Cargo.lock b/Cargo.lock
index e7c2f62f..7e97a985 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8303,6 +8303,7 @@ dependencies = [
"termwiz 0.24.0",
"unicode-normalization",
"url",
+ "varbincode",
"wezterm-bidi 0.2.3",
"wezterm-cell",
"wezterm-dynamic 0.2.1",
diff --git a/term/Cargo.toml b/term/Cargo.toml
index 91fe42a8..5f013a53 100644
--- a/term/Cargo.toml
+++ b/term/Cargo.toml
@@ -41,6 +41,7 @@ wezterm-surface = {workspace = true, features=["std", "appdata", "use_image"]}
[dev-dependencies]
env_logger.workspace = true
k9.workspace = true
+varbincode.workspace = true
[dependencies.termwiz]
workspace = true
diff --git a/term/src/screen.rs b/term/src/screen.rs
index 5fc9b97b..06b45d66 100644
--- a/term/src/screen.rs
+++ b/term/src/screen.rs
@@ -104,6 +104,32 @@ impl Screen {
scrollback_size(&self.config, self.allow_scrollback)
}
+ /// Every line held, scrollback first, visible rows last.
+ pub(crate) fn lines(&self) -> &VecDeque<Line> {
+ &self.lines
+ }
+
+ pub(crate) fn stable_row_index_offset(&self) -> usize {
+ self.stable_row_index_offset
+ }
+
+ /// How many lines this screen may hold before the oldest scroll off:
+ /// the visible rows plus the scrollback the configuration allows.
+ pub(crate) fn line_capacity(&self) -> usize {
+ self.physical_rows + self.scrollback_size()
+ }
+
+ /// Replace the contents wholesale, as a restore from a snapshot does.
+ /// `lines` must hold at least the visible rows and at most
+ /// `line_capacity`; `stable_row_index_offset` says how many lines had
+ /// scrolled off before the first one kept.
+ pub(crate) fn replace_lines(&mut self, lines: VecDeque<Line>, stable_row_index_offset: usize) {
+ debug_assert!(lines.len() >= self.physical_rows);
+ debug_assert!(lines.len() <= self.line_capacity());
+ self.lines = lines;
+ self.stable_row_index_offset = stable_row_index_offset;
+ }
+
fn rewrap_lines(
&mut self,
physical_cols: usize,
diff --git a/term/src/terminalstate/image.rs b/term/src/terminalstate/image.rs
index 873db676..160c76d2 100644
--- a/term/src/terminalstate/image.rs
+++ b/term/src/terminalstate/image.rs
@@ -9,6 +9,10 @@ use wezterm_cell::Cell;
use wezterm_surface::change::ImageData;
use wezterm_surface::TextureCoordinate;
+#[cfg_attr(
+ feature = "use_serde",
+ derive(serde::Serialize, serde::Deserialize)
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PlacementInfo {
pub first_row: StableRowIndex,
diff --git a/term/src/terminalstate/kitty.rs b/term/src/terminalstate/kitty.rs
index 48239787..7f4d17d4 100644
--- a/term/src/terminalstate/kitty.rs
+++ b/term/src/terminalstate/kitty.rs
@@ -66,7 +66,72 @@ pub struct KittyImageState {
used_memory: usize,
}
+impl TerminalState {
+ /// The picture stored under a kitty image id, for tests.
+ #[cfg(test)]
+ pub(crate) fn kitty_image_data_for_id(&self, image_id: u32) -> Option<Arc<ImageData>> {
+ self.kitty_img.image_data_for_id(image_id)
+ }
+}
+
impl KittyImageState {
+ /// The bookkeeping, with each picture replaced by its hash in `images`.
+ #[cfg(feature = "use_serde")]
+ pub(crate) fn snapshot(
+ &self,
+ images: &mut crate::terminalstate::snapshot::ImageTable,
+ ) -> crate::terminalstate::snapshot::KittySnapshot {
+ crate::terminalstate::snapshot::KittySnapshot {
+ max_image_id: self.max_image_id,
+ number_to_id: self.number_to_id.iter().map(|(k, v)| (*k, *v)).collect(),
+ id_to_hash: self
+ .id_to_data
+ .iter()
+ .map(|(id, data)| (*id, images.remember(data)))
+ .collect(),
+ id_seq: self.id_seq.iter().map(|(k, v)| (*k, *v)).collect(),
+ next_seq: self.next_seq,
+ placements: self.placements.iter().map(|(k, v)| (*k, *v)).collect(),
+ transmission_in_progress: !self.accumulator.is_empty(),
+ }
+ }
+
+ /// The bookkeeping from a snapshot, pictures looked up in `images` by
+ /// hash. A transfer that was in flight is not resumed: the accumulator
+ /// starts empty, and the program hears an error for its next fragment.
+ #[cfg(feature = "use_serde")]
+ pub(crate) fn restore(
+ &mut self,
+ snapshot: crate::terminalstate::snapshot::KittySnapshot,
+ images: &std::collections::HashMap<[u8; 32], Arc<ImageData>>,
+ ) -> anyhow::Result<()> {
+ let mut id_to_data = HashMap::new();
+ for (id, hash) in snapshot.id_to_hash {
+ let data = images.get(&hash).ok_or_else(|| {
+ anyhow::anyhow!("kitty image {id} refers to a picture the snapshot does not carry")
+ })?;
+ id_to_data.insert(id, Arc::clone(data));
+ }
+ self.accumulator.clear();
+ self.accumulated_bytes = 0;
+ self.accumulator_overflowed = false;
+ self.max_image_id = snapshot.max_image_id;
+ self.number_to_id = snapshot.number_to_id.into_iter().collect();
+ self.id_to_data = id_to_data;
+ self.id_seq = snapshot.id_seq.into_iter().collect();
+ self.next_seq = snapshot.next_seq;
+ self.placements = snapshot.placements.into_iter().collect();
+ self.recompute_used_memory();
+ Ok(())
+ }
+
+ /// The picture stored under a kitty image id, for tests that check a
+ /// restore shares one `Arc` between the cells and this map.
+ #[cfg(test)]
+ pub(crate) fn image_data_for_id(&self, image_id: u32) -> Option<Arc<ImageData>> {
+ self.id_to_data.get(&image_id).cloned()
+ }
+
/// Bytes actually held: small pictures with identical pixels share one
/// `ImageData` through the content-hash cache, so summing per id would
/// count a logo re-emitted under fresh ids once per prompt, and the
diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rs
index 3c9f9f42..5ebdf1d1 100644
--- a/term/src/terminalstate/mod.rs
+++ b/term/src/terminalstate/mod.rs
@@ -33,8 +33,12 @@ pub(crate) mod kitty;
mod mouse;
pub(crate) mod performer;
mod sixel;
+#[cfg(feature = "use_serde")]
+mod snapshot;
use crate::terminalstate::image::*;
use crate::terminalstate::kitty::*;
+#[cfg(feature = "use_serde")]
+pub use crate::terminalstate::snapshot::*;
lazy_static::lazy_static! {
static ref DB: Database = {
@@ -43,20 +47,33 @@ lazy_static::lazy_static! {
};
}
-pub(crate) struct TabStop {
+#[cfg_attr(
+ feature = "use_serde",
+ derive(serde::Serialize, serde::Deserialize)
+)]
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TabStop {
tabs: Vec<bool>,
tab_width: usize,
}
+#[cfg_attr(
+ feature = "use_serde",
+ derive(serde::Serialize, serde::Deserialize)
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum CharSet {
+pub enum CharSet {
Ascii,
Uk,
DecLineDrawing,
}
+#[cfg_attr(
+ feature = "use_serde",
+ derive(serde::Serialize, serde::Deserialize)
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum MouseEncoding {
+pub enum MouseEncoding {
X10,
Utf8,
SGR,
@@ -131,8 +148,12 @@ impl TabStop {
}
}
-#[derive(Debug, Clone)]
-pub(crate) struct SavedCursor {
+#[cfg_attr(
+ feature = "use_serde",
+ derive(serde::Serialize, serde::Deserialize)
+)]
+#[derive(Debug, Clone, PartialEq)]
+pub struct SavedCursor {
position: CursorPosition,
wrap_next: bool,
pen: CellAttributes,
diff --git a/term/src/terminalstate/snapshot.rs b/term/src/terminalstate/snapshot.rs
new file mode 100644
index 00000000..da92855f
--- /dev/null
+++ b/term/src/terminalstate/snapshot.rs
@@ -0,0 +1,655 @@
+//! Everything a terminal remembers, in a form that can leave the process.
+//!
+//! A mux server that is being replaced hands each pane to the new binary:
+//! the pty goes as a file descriptor, and what the old process had parsed
+//! out of it goes as one of these. The snapshot carries both screens with
+//! their scrollback, the cursor, every mode an application can set, the
+//! titles and variables it announced, and the pictures on screen -- each
+//! picture once, however many cells and kitty ids share it.
+//!
+//! Not carried, on purpose: the configuration and the writer (the new
+//! process has its own), the clipboard and notification handlers (the pane
+//! reinstalls them), the decode cache, mouse buttons held at that instant,
+//! a title still accumulating, the parser's position inside an escape
+//! sequence (the sender drains the pty to a quiet point first), and a
+//! kitty chunked transfer still in flight (flagged, so the sender can say
+//! so).
+
+use super::{
+ CharSet, MouseEncoding, SavedCursor, TabStop, TerminalState, UnicodeVersionStackEntry,
+};
+use crate::color::ColorPalette;
+use crate::screen::Screen;
+use crate::terminalstate::image::PlacementInfo;
+use crate::{CursorPosition, Progress, TerminalSize};
+use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, HashMap};
+use std::sync::Arc;
+use termwiz::input::KeyboardEncoding;
+use url::Url;
+use wezterm_bidi::ParagraphDirectionHint;
+use wezterm_cell::image::{ImageCell, ImageData, ImageDataType, TextureCoordinate};
+use wezterm_cell::{CellAttributes, UnicodeVersion};
+use wezterm_escape_parser::csi::KittyKeyboardFlags;
+use wezterm_surface::{Line, SequenceNo};
+
+/// Bumped whenever the shape of [`TerminalSnapshot`] changes; `restore`
+/// refuses any other number rather than guess at the fields.
+pub const SNAPSHOT_VERSION: u32 = 1;
+
+/// What a terminal remembers. Build one with [`TerminalState::snapshot`]
+/// and unpack it into a fresh terminal of the same size with
+/// [`TerminalState::restore`].
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+pub struct TerminalSnapshot {
+ pub version: u32,
+ pub size: TerminalSize,
+ pub seqno: SequenceNo,
+ pub screen: ScreenSnapshot,
+ pub alt_screen: ScreenSnapshot,
+ pub alt_screen_is_active: bool,
+ /// Every picture a cell or a kitty id refers to, once per content hash,
+ /// sorted by hash.
+ pub images: Vec<SnapshotImage>,
+ pub cursor: CursorSnapshot,
+ pub modes: ModeSnapshot,
+ pub identity: IdentitySnapshot,
+ pub kitty: KittySnapshot,
+}
+
+/// One screen: the primary with its scrollback, or the alternate.
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+pub struct ScreenSnapshot {
+ /// Scrollback first, visible rows last, as the screen keeps them.
+ /// Pictures are detached; `image_cells` says where they were.
+ pub lines: Vec<Line>,
+ pub image_cells: Vec<SnapshotImageCell>,
+ pub stable_row_index_offset: usize,
+ pub physical_rows: usize,
+ pub physical_cols: usize,
+ pub dpi: u32,
+ pub keyboard_stack: Vec<SnapshotKeyboardEncoding>,
+ pub saved_cursor: Option<SavedCursor>,
+}
+
+/// A picture's place in a cell, with the picture itself replaced by its
+/// hash. Keeps the kitty image and placement ids, which the wire format's
+/// image cell drops: a delete-by-id after the restore has to find them.
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+pub struct SnapshotImageCell {
+ /// Index into `ScreenSnapshot::lines`.
+ pub line_idx: usize,
+ pub cell_idx: usize,
+ pub hash: [u8; 32],
+ pub top_left: TextureCoordinate,
+ pub bottom_right: TextureCoordinate,
+ pub z_index: i32,
+ pub padding_left: u16,
+ pub padding_top: u16,
+ pub padding_right: u16,
+ pub padding_bottom: u16,
+ pub image_id: Option<u32>,
+ pub placement_id: Option<u32>,
+}
+
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+pub struct SnapshotImage {
+ pub hash: [u8; 32],
+ pub data: ImageDataType,
+}
+
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+pub struct CursorSnapshot {
+ pub position: CursorPosition,
+ pub pen: CellAttributes,
+ pub wrap_next: bool,
+ pub insert: bool,
+ pub cursor_visible: bool,
+}
+
+/// Every mode an application can set, one field each, named as the
+/// terminal names them so a missing one is easy to spot against
+/// `TerminalState`.
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+pub struct ModeSnapshot {
+ pub dec_auto_wrap: bool,
+ pub reverse_wraparound_mode: bool,
+ pub reverse_video_mode: bool,
+ pub dec_origin_mode: bool,
+ pub top_and_bottom_margins: std::ops::Range<i64>,
+ pub left_and_right_margins: std::ops::Range<usize>,
+ pub left_and_right_margin_mode: bool,
+ pub application_cursor_keys: bool,
+ pub application_keypad: bool,
+ pub modify_other_keys: Option<i64>,
+ pub dec_ansi_mode: bool,
+ pub sixel_display_mode: bool,
+ pub sixel_scrolls_right: bool,
+ pub use_private_color_registers_for_each_graphic: bool,
+ pub bracketed_paste: bool,
+ pub any_event_mouse: bool,
+ pub button_event_mouse: bool,
+ pub mouse_tracking: bool,
+ pub focus_tracking: bool,
+ pub mouse_encoding: MouseEncoding,
+ pub keyboard_encoding: SnapshotKeyboardEncoding,
+ pub g0_charset: CharSet,
+ pub g1_charset: CharSet,
+ pub shift_out: bool,
+ pub newline_mode: bool,
+ pub clear_semantic_attribute_on_newline: bool,
+ pub tabs: TabStop,
+ pub unicode_version: SnapshotUnicodeVersion,
+ pub unicode_version_stack: Vec<SnapshotUnicodeVersionStackEntry>,
+ pub bidi_enabled: Option<bool>,
+ pub bidi_hint: Option<SnapshotBidiHint>,
+ pub focused: bool,
+}
+
+/// What the applications announced about themselves.
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+pub struct IdentitySnapshot {
+ pub title: String,
+ pub icon_title: Option<String>,
+ /// OSC 7, as the URL text.
+ pub current_dir: Option<String>,
+ pub user_vars: BTreeMap<String, String>,
+ pub progress: Progress,
+ pub agent_osc_title: Option<String>,
+ pub agent_osc_progress: Option<String>,
+ pub palette: Option<ColorPalette>,
+ /// The sixel / regis colour registers, as 8-bit RGB.
+ pub color_map: BTreeMap<u16, (u8, u8, u8)>,
+}
+
+/// The kitty graphics bookkeeping: which ids name which pictures (by
+/// hash, see `TerminalSnapshot::images`), their transmission order, and
+/// where each placement sits.
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+pub struct KittySnapshot {
+ pub max_image_id: u32,
+ pub number_to_id: BTreeMap<u32, u32>,
+ pub id_to_hash: BTreeMap<u32, [u8; 32]>,
+ pub id_seq: BTreeMap<u32, u64>,
+ pub next_seq: u64,
+ pub placements: BTreeMap<(u32, Option<u32>), PlacementInfo>,
+ /// A chunked transfer had begun and not finished when the snapshot was
+ /// taken. Its fragments are not carried: the picture is lost, and the
+ /// program will see an error for the rest of it.
+ pub transmission_in_progress: bool,
+}
+
+/// `termwiz::input::KeyboardEncoding` without serde; the kitty flags travel
+/// as their bits.
+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SnapshotKeyboardEncoding {
+ Xterm,
+ CsiU,
+ Win32,
+ Kitty(u16),
+}
+
+impl From<KeyboardEncoding> for SnapshotKeyboardEncoding {
+ fn from(encoding: KeyboardEncoding) -> Self {
+ match encoding {
+ KeyboardEncoding::Xterm => Self::Xterm,
+ KeyboardEncoding::CsiU => Self::CsiU,
+ KeyboardEncoding::Win32 => Self::Win32,
+ KeyboardEncoding::Kitty(flags) => Self::Kitty(flags.bits()),
+ }
+ }
+}
+
+impl From<SnapshotKeyboardEncoding> for KeyboardEncoding {
+ fn from(encoding: SnapshotKeyboardEncoding) -> Self {
+ match encoding {
+ SnapshotKeyboardEncoding::Xterm => Self::Xterm,
+ SnapshotKeyboardEncoding::CsiU => Self::CsiU,
+ SnapshotKeyboardEncoding::Win32 => Self::Win32,
+ SnapshotKeyboardEncoding::Kitty(bits) => {
+ Self::Kitty(KittyKeyboardFlags::from_bits_truncate(bits))
+ }
+ }
+ }
+}
+
+/// `wezterm_cell::UnicodeVersion` without serde.
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
+pub struct SnapshotUnicodeVersion {
+ pub version: u8,
+ pub ambiguous_are_wide: bool,
+ pub cell_widths: Option<BTreeMap<u32, u8>>,
+}
+
+impl From<&UnicodeVersion> for SnapshotUnicodeVersion {
+ fn from(vers: &UnicodeVersion) -> Self {
+ Self {
+ version: vers.version,
+ ambiguous_are_wide: vers.ambiguous_are_wide,
+ cell_widths: vers
+ .cell_widths
+ .as_ref()
+ .map(|widths| widths.iter().map(|(k, v)| (*k, *v)).collect()),
+ }
+ }
+}
+
+impl From<SnapshotUnicodeVersion> for UnicodeVersion {
+ fn from(vers: SnapshotUnicodeVersion) -> Self {
+ Self {
+ version: vers.version,
+ ambiguous_are_wide: vers.ambiguous_are_wide,
+ cell_widths: vers
+ .cell_widths
+ .map(|widths| Arc::new(widths.into_iter().collect::<HashMap<u32, u8>>())),
+ }
+ }
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
+pub struct SnapshotUnicodeVersionStackEntry {
+ pub vers: SnapshotUnicodeVersion,
+ pub label: Option<String>,
+}
+
+/// `wezterm_bidi::ParagraphDirectionHint` without serde.
+#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SnapshotBidiHint {
+ LeftToRight,
+ RightToLeft,
+ AutoLeftToRight,
+ AutoRightToLeft,
+}
+
+impl From<ParagraphDirectionHint> for SnapshotBidiHint {
+ fn from(hint: ParagraphDirectionHint) -> Self {
+ match hint {
+ ParagraphDirectionHint::LeftToRight => Self::LeftToRight,
+ ParagraphDirectionHint::RightToLeft => Self::RightToLeft,
+ ParagraphDirectionHint::AutoLeftToRight => Self::AutoLeftToRight,
+ ParagraphDirectionHint::AutoRightToLeft => Self::AutoRightToLeft,
+ }
+ }
+}
+
+impl From<SnapshotBidiHint> for ParagraphDirectionHint {
+ fn from(hint: SnapshotBidiHint) -> Self {
+ match hint {
+ SnapshotBidiHint::LeftToRight => Self::LeftToRight,
+ SnapshotBidiHint::RightToLeft => Self::RightToLeft,
+ SnapshotBidiHint::AutoLeftToRight => Self::AutoLeftToRight,
+ SnapshotBidiHint::AutoRightToLeft => Self::AutoRightToLeft,
+ }
+ }
+}
+
+/// Pictures met while walking cells and kitty ids, kept once per hash.
+#[derive(Default)]
+pub(crate) struct ImageTable {
+ images: BTreeMap<[u8; 32], ImageDataType>,
+}
+
+impl ImageTable {
+ pub(crate) fn remember(&mut self, data: &Arc<ImageData>) -> [u8; 32] {
+ let hash = data.hash();
+ self.images
+ .entry(hash)
+ .or_insert_with(|| data.data().clone());
+ hash
+ }
+
+ fn into_snapshot(self) -> Vec<SnapshotImage> {
+ self.images
+ .into_iter()
+ .map(|(hash, data)| SnapshotImage { hash, data })
+ .collect()
+ }
+}
+
+impl TerminalState {
+ /// Everything this terminal remembers; see the module documentation
+ /// for what is left behind.
+ pub fn snapshot(&self) -> TerminalSnapshot {
+ let mut images = ImageTable::default();
+ let screen = snapshot_screen(&self.screen.screen, &mut images);
+ let alt_screen = snapshot_screen(&self.screen.alt_screen, &mut images);
+ let kitty = self.kitty_img.snapshot(&mut images);
+ TerminalSnapshot {
+ version: SNAPSHOT_VERSION,
+ size: self.get_size(),
+ seqno: self.seqno,
+ screen,
+ alt_screen,
+ alt_screen_is_active: self.screen.alt_screen_is_active,
+ images: images.into_snapshot(),
+ cursor: CursorSnapshot {
+ position: self.cursor,
+ pen: self.pen.clone(),
+ wrap_next: self.wrap_next,
+ insert: self.insert,
+ cursor_visible: self.cursor_visible,
+ },
+ modes: ModeSnapshot {
+ dec_auto_wrap: self.dec_auto_wrap,
+ reverse_wraparound_mode: self.reverse_wraparound_mode,
+ reverse_video_mode: self.reverse_video_mode,
+ dec_origin_mode: self.dec_origin_mode,
+ top_and_bottom_margins: self.top_and_bottom_margins.clone(),
+ left_and_right_margins: self.left_and_right_margins.clone(),
+ left_and_right_margin_mode: self.left_and_right_margin_mode,
+ application_cursor_keys: self.application_cursor_keys,
+ application_keypad: self.application_keypad,
+ modify_other_keys: self.modify_other_keys,
+ dec_ansi_mode: self.dec_ansi_mode,
+ sixel_display_mode: self.sixel_display_mode,
+ sixel_scrolls_right: self.sixel_scrolls_right,
+ use_private_color_registers_for_each_graphic: self
+ .use_private_color_registers_for_each_graphic,
+ bracketed_paste: self.bracketed_paste,
+ any_event_mouse: self.any_event_mouse,
+ button_event_mouse: self.button_event_mouse,
+ mouse_tracking: self.mouse_tracking,
+ focus_tracking: self.focus_tracking,
+ mouse_encoding: self.mouse_encoding,
+ keyboard_encoding: self.keyboard_encoding.into(),
+ g0_charset: self.g0_charset,
+ g1_charset: self.g1_charset,
+ shift_out: self.shift_out,
+ newline_mode: self.newline_mode,
+ clear_semantic_attribute_on_newline: self.clear_semantic_attribute_on_newline,
+ tabs: self.tabs.clone(),
+ unicode_version: (&self.unicode_version).into(),
+ unicode_version_stack: self
+ .unicode_version_stack
+ .iter()
+ .map(|entry| SnapshotUnicodeVersionStackEntry {
+ vers: (&entry.vers).into(),
+ label: entry.label.clone(),
+ })
+ .collect(),
+ bidi_enabled: self.bidi_enabled,
+ bidi_hint: self.bidi_hint.map(Into::into),
+ focused: self.focused,
+ },
+ identity: IdentitySnapshot {
+ title: self.title.clone(),
+ icon_title: self.icon_title.clone(),
+ current_dir: self.current_dir.as_ref().map(|url| url.to_string()),
+ user_vars: self
+ .user_vars
+ .iter()
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect(),
+ progress: self.progress.clone(),
+ agent_osc_title: self.agent_osc_title.clone(),
+ agent_osc_progress: self.agent_osc_progress.clone(),
+ palette: self.palette.clone(),
+ color_map: self
+ .color_map
+ .iter()
+ .map(|(idx, color)| (*idx, color.to_tuple_rgb8()))
+ .collect(),
+ },
+ kitty,
+ }
+ }
+
+ /// Make this terminal what `snapshot` remembers. Call it on a terminal
+ /// just made by `Terminal::new` with the snapshot's size, the new
+ /// process's configuration and writer, and nothing fed to it yet.
+ /// Scrollback beyond what this configuration allows is dropped from the
+ /// oldest end, with the stable row offset advanced to match, so stable
+ /// row indices keep their meaning.
+ pub fn restore(&mut self, snapshot: TerminalSnapshot) -> anyhow::Result<()> {
+ anyhow::ensure!(
+ snapshot.version == SNAPSHOT_VERSION,
+ "terminal snapshot version {} cannot be restored by a terminal that speaks version {}",
+ snapshot.version,
+ SNAPSHOT_VERSION
+ );
+ let size = self.get_size();
+ anyhow::ensure!(
+ size.rows == snapshot.size.rows && size.cols == snapshot.size.cols,
+ "the snapshot is {}x{} but this terminal is {}x{}: make the terminal with the snapshot's size first",
+ snapshot.size.cols,
+ snapshot.size.rows,
+ size.cols,
+ size.rows
+ );
+
+ let images: HashMap<[u8; 32], Arc<ImageData>> = snapshot
+ .images
+ .into_iter()
+ .map(|image| {
+ (
+ image.hash,
+ Arc::new(ImageData::with_data_and_hash(image.data, image.hash)),
+ )
+ })
+ .collect();
+
+ restore_screen(&mut self.screen.screen, snapshot.screen, &images)?;
+ restore_screen(&mut self.screen.alt_screen, snapshot.alt_screen, &images)?;
+ self.screen.alt_screen_is_active = snapshot.alt_screen_is_active;
+
+ self.pixel_width = snapshot.size.pixel_width;
+ self.pixel_height = snapshot.size.pixel_height;
+ self.dpi = snapshot.size.dpi;
+
+ let cursor = snapshot.cursor;
+ self.cursor = cursor.position;
+ self.pen = cursor.pen;
+ self.wrap_next = cursor.wrap_next;
+ self.insert = cursor.insert;
+ self.cursor_visible = cursor.cursor_visible;
+
+ let modes = snapshot.modes;
+ self.dec_auto_wrap = modes.dec_auto_wrap;
+ self.reverse_wraparound_mode = modes.reverse_wraparound_mode;
+ self.reverse_video_mode = modes.reverse_video_mode;
+ self.dec_origin_mode = modes.dec_origin_mode;
+ self.top_and_bottom_margins = modes.top_and_bottom_margins;
+ self.left_and_right_margins = modes.left_and_right_margins;
+ self.left_and_right_margin_mode = modes.left_and_right_margin_mode;
+ self.application_cursor_keys = modes.application_cursor_keys;
+ self.application_keypad = modes.application_keypad;
+ self.modify_other_keys = modes.modify_other_keys;
+ self.dec_ansi_mode = modes.dec_ansi_mode;
+ self.sixel_display_mode = modes.sixel_display_mode;
+ self.sixel_scrolls_right = modes.sixel_scrolls_right;
+ self.use_private_color_registers_for_each_graphic =
+ modes.use_private_color_registers_for_each_graphic;
+ self.bracketed_paste = modes.bracketed_paste;
+ self.any_event_mouse = modes.any_event_mouse;
+ self.button_event_mouse = modes.button_event_mouse;
+ self.mouse_tracking = modes.mouse_tracking;
+ self.focus_tracking = modes.focus_tracking;
+ self.mouse_encoding = modes.mouse_encoding;
+ self.keyboard_encoding = modes.keyboard_encoding.into();
+ self.g0_charset = modes.g0_charset;
+ self.g1_charset = modes.g1_charset;
+ self.shift_out = modes.shift_out;
+ self.newline_mode = modes.newline_mode;
+ self.clear_semantic_attribute_on_newline = modes.clear_semantic_attribute_on_newline;
+ self.tabs = modes.tabs;
+ self.unicode_version = modes.unicode_version.into();
+ self.unicode_version_stack = modes
+ .unicode_version_stack
+ .into_iter()
+ .map(|entry| UnicodeVersionStackEntry {
+ vers: entry.vers.into(),
+ label: entry.label,
+ })
+ .collect();
+ self.bidi_enabled = modes.bidi_enabled;
+ self.bidi_hint = modes.bidi_hint.map(Into::into);
+ self.focused = modes.focused;
+
+ let identity = snapshot.identity;
+ self.title = identity.title;
+ self.icon_title = identity.icon_title;
+ self.current_dir = match identity.current_dir {
+ Some(url) => Some(Url::parse(&url)?),
+ None => None,
+ };
+ self.user_vars = identity.user_vars.into_iter().collect();
+ self.progress = identity.progress;
+ self.agent_osc_title = identity.agent_osc_title;
+ self.agent_osc_progress = identity.agent_osc_progress;
+ self.palette = identity.palette;
+ self.color_map = identity
+ .color_map
+ .into_iter()
+ .map(|(idx, (r, g, b))| (idx, crate::color::RgbColor::new_8bpc(r, g, b)))
+ .collect();
+
+ self.kitty_img.restore(snapshot.kitty, &images)?;
+
+ self.seqno = snapshot.seqno;
+ self.lost_focus_seqno = snapshot.seqno;
+ self.lost_focus_alerted_seqno = snapshot.seqno;
+ self.current_mouse_buttons.clear();
+ self.last_mouse_move = None;
+ self.accumulating_title = None;
+ Ok(())
+ }
+}
+
+/// Clones the screen's lines with their pictures detached into `images`.
+fn snapshot_screen(screen: &Screen, images: &mut ImageTable) -> ScreenSnapshot {
+ let mut lines = Vec::with_capacity(screen.lines().len());
+ let mut image_cells = vec![];
+ for (line_idx, line) in screen.lines().iter().enumerate() {
+ let mut line = line.clone();
+ // Only a line that carries a picture is walked mutably: that walk
+ // coerces the line to per-cell storage, which for a scrollback line
+ // undoes the compression it just got, and the snapshot should leave
+ // the rest as it found them.
+ let has_images = line.has_hyperlinks_or_images()
+ && (0..line.len())
+ .filter_map(|idx| line.get_cell(idx))
+ .any(|cell| cell.attrs().images().is_some());
+ if has_images {
+ for (cell_idx, cell) in line.cells_mut_for_attr_changes_only().iter_mut().enumerate()
+ {
+ let Some(cell_images) = cell.attrs().images() else {
+ continue;
+ };
+ for image in cell_images {
+ let (padding_left, padding_top, padding_right, padding_bottom) =
+ image.padding();
+ image_cells.push(SnapshotImageCell {
+ line_idx,
+ cell_idx,
+ hash: images.remember(image.image_data()),
+ top_left: image.top_left(),
+ bottom_right: image.bottom_right(),
+ z_index: image.z_index(),
+ padding_left,
+ padding_top,
+ padding_right,
+ padding_bottom,
+ image_id: image.image_id(),
+ placement_id: image.placement_id(),
+ });
+ }
+ cell.attrs_mut().clear_images();
+ }
+ }
+ lines.push(line);
+ }
+ ScreenSnapshot {
+ lines,
+ image_cells,
+ stable_row_index_offset: screen.stable_row_index_offset(),
+ physical_rows: screen.physical_rows,
+ physical_cols: screen.physical_cols,
+ dpi: screen.dpi,
+ keyboard_stack: screen
+ .keyboard_stack
+ .iter()
+ .map(|encoding| (*encoding).into())
+ .collect(),
+ saved_cursor: screen.saved_cursor.clone(),
+ }
+}
+
+fn restore_screen(
+ screen: &mut Screen,
+ snapshot: ScreenSnapshot,
+ images: &HashMap<[u8; 32], Arc<ImageData>>,
+) -> anyhow::Result<()> {
+ anyhow::ensure!(
+ snapshot.physical_rows == screen.physical_rows
+ && snapshot.physical_cols == screen.physical_cols,
+ "the snapshot's screen is {}x{} but this one is {}x{}",
+ snapshot.physical_cols,
+ snapshot.physical_rows,
+ screen.physical_cols,
+ screen.physical_rows
+ );
+ anyhow::ensure!(
+ snapshot.lines.len() >= snapshot.physical_rows,
+ "the snapshot holds {} lines for a {}-row screen",
+ snapshot.lines.len(),
+ snapshot.physical_rows
+ );
+
+ let mut lines = snapshot.lines;
+ for image_cell in snapshot.image_cells {
+ let data = images.get(&image_cell.hash).ok_or_else(|| {
+ anyhow::anyhow!(
+ "line {} cell {} refers to a picture the snapshot does not carry",
+ image_cell.line_idx,
+ image_cell.cell_idx
+ )
+ })?;
+ let line = lines.get_mut(image_cell.line_idx).ok_or_else(|| {
+ anyhow::anyhow!("a picture sits on line {}, past the end", image_cell.line_idx)
+ })?;
+ let cell = line
+ .cells_mut_for_attr_changes_only()
+ .get_mut(image_cell.cell_idx)
+ .ok_or_else(|| {
+ anyhow::anyhow!(
+ "a picture sits on line {} cell {}, past the end",
+ image_cell.line_idx,
+ image_cell.cell_idx
+ )
+ })?;
+ cell.attrs_mut()
+ .attach_image(Box::new(ImageCell::with_z_index(
+ image_cell.top_left,
+ image_cell.bottom_right,
+ Arc::clone(data),
+ image_cell.z_index,
+ image_cell.padding_left,
+ image_cell.padding_top,
+ image_cell.padding_right,
+ image_cell.padding_bottom,
+ image_cell.image_id,
+ image_cell.placement_id,
+ )));
+ }
+
+ // The oldest scrollback goes first when this process allows less of
+ // it; the stable offset advances by as much, so a stable row index
+ // still names the same line.
+ let mut offset = snapshot.stable_row_index_offset;
+ let capacity = screen.line_capacity();
+ let excess = lines.len().saturating_sub(capacity);
+ if excess > 0 {
+ lines.drain(..excess);
+ offset += excess;
+ }
+
+ screen.replace_lines(lines.into(), offset);
+ screen.dpi = snapshot.dpi;
+ screen.keyboard_stack = snapshot
+ .keyboard_stack
+ .into_iter()
+ .map(Into::into)
+ .collect();
+ screen.saved_cursor = snapshot.saved_cursor;
+ Ok(())
+}
diff --git a/term/src/test/mod.rs b/term/src/test/mod.rs
index 600bbb94..adb840f8 100644
--- a/term/src/test/mod.rs
+++ b/term/src/test/mod.rs
@@ -7,6 +7,8 @@ use bitflags::bitflags;
mod c1;
mod csi;
mod graphics;
+#[cfg(feature = "use_serde")]
+mod snapshot;
// mod selection; FIXME: port to render layer
use crate::color::ColorPalette;
use k9::assert_equal as assert_eq;
diff --git a/term/src/test/snapshot.rs b/term/src/test/snapshot.rs
new file mode 100644
index 00000000..0fa3d47b
--- /dev/null
+++ b/term/src/test/snapshot.rs
@@ -0,0 +1,381 @@
+//! A terminal's snapshot restores into a fresh terminal as the same
+//! terminal: same screens, same scrollback, same pictures, same modes, and
+//! the same behaviour for whatever the program sends next.
+
+use crate::color::ColorPalette;
+use crate::terminalstate::{TerminalSnapshot, SNAPSHOT_VERSION};
+use crate::{Terminal, TerminalConfiguration, TerminalSize};
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+
+#[derive(Debug)]
+struct SnapshotConfig {
+ scrollback: usize,
+}
+
+impl TerminalConfiguration for SnapshotConfig {
+ fn scrollback_size(&self) -> usize {
+ self.scrollback
+ }
+
+ fn color_palette(&self) -> ColorPalette {
+ ColorPalette::default()
+ }
+
+ fn enable_kitty_graphics(&self) -> bool {
+ true
+ }
+
+ fn enable_kitty_keyboard(&self) -> bool {
+ true
+ }
+}
+
+/// 80x24 cells of 8x16 pixels, so pictures have a geometry to land in.
+fn terminal(scrollback: usize) -> Terminal {
+ Terminal::new(
+ TerminalSize {
+ rows: 24,
+ cols: 80,
+ pixel_width: 640,
+ pixel_height: 384,
+ dpi: 96,
+ },
+ Arc::new(SnapshotConfig { scrollback }),
+ "ThinkTerm",
+ "O_o",
+ Box::new(Vec::new()),
+ )
+}
+
+/// A 2x2 all-zero RGBA picture.
+const PIXELS_2X2: &str = "AAAAAAAAAAAAAAAAAAAAAA==";
+/// Half of one, for a chunked transfer.
+const HALF_2X2: &str = "AAAAAAAAAAA=";
+/// A 2x2 red sixel.
+const SIXEL_2X2: &str = "\x1bPq\"1;1;2;2#0;2;100;0;0#0~~$-\x1b\\";
+
+/// Touches every field the snapshot carries, on both screens.
+fn everything(term: &mut Terminal) {
+ // Text with attributes and a hyperlink.
+ term.advance_bytes("\x1b[31mred \x1b[1mbold\x1b[0m plain ");
+ term.advance_bytes("\x1b]8;;http://example.com/\x1b\\link\x1b]8;;\x1b\\\r\n");
+ // A line that wraps.
+ term.advance_bytes("x".repeat(100));
+ term.advance_bytes("\r\n");
+ // More lines than rows: scrollback.
+ for i in 0..40 {
+ term.advance_bytes(format!("line {i}\r\n"));
+ }
+ // Pictures: a kitty image placed twice (once by number), and a sixel.
+ term.advance_bytes(format!(
+ "\x1b[3;1H\x1b_Ga=t,i=1,f=32,s=2,v=2;{PIXELS_2X2}\x1b\\\x1b_Ga=p,i=1,p=1\x1b\\"
+ ));
+ term.advance_bytes("\x1b[3;10H\x1b_Ga=p,i=1,p=2,z=3\x1b\\");
+ term.advance_bytes(format!(
+ "\x1b[5;1H\x1b_Ga=T,I=7,f=32,s=2,v=2;{PIXELS_2X2}\x1b\\"
+ ));
+ term.advance_bytes(format!("\x1b[7;1H{SIXEL_2X2}"));
+ // A saved cursor, custom tab stops, margins.
+ term.advance_bytes("\x1b[5;10H\x1b7\x1b[2;3H");
+ term.advance_bytes("\x1b[3g\x1b[1;7H\x1bH\x1b[1;13H\x1bH\x1b[9;2H");
+ term.advance_bytes("\x1b[?69h\x1b[5;70s\x1b[3;20r");
+ // Every mode.
+ term.advance_bytes("\x1b[4h\x1b[?6h\x1b[?5h\x1b[?2004h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h");
+ term.advance_bytes("\x1b[?1004h\x1b[?1h\x1b[?45h\x1b[20h\x1b=\x1b[?80h\x1b[?8452h");
+ term.advance_bytes("\x1b[?1070h\x1b[>4;2m\x1b)0\x0e\x1b[>1u\x1b[?9001h");
+ term.advance_bytes("\x1b]1337;UnicodeVersion=push before\x07\x1b]1337;UnicodeVersion=14\x07");
+ // What the program says about itself.
+ term.advance_bytes("\x1b]0;My Title\x07\x1b]1;icon\x07\x1b]7;file://localhost/tmp/work\x07");
+ term.advance_bytes("\x1b]1337;SetUserVar=foo=YmFy\x07\x1b]4;1;rgb:ff/00/00\x07\x1b]9;4;1;50\x07");
+ term.focus_changed(false);
+ // The alternate screen, with its own saved cursor, content and kitty
+ // keyboard stack (the primary keeps the one pushed above).
+ term.advance_bytes("\x1b[?1049h\x1b[3;4Halt text\x1b7\x1b[10;1H\x1b[>3u");
+}
+
+/// Whether the cell at `x`,`y` of the visible screen carries a picture; a
+/// cell never written to has nothing to ask.
+fn has_image(term: &mut Terminal, x: usize, y: i64) -> bool {
+ term.screen_mut()
+ .get_cell(x, y)
+ .is_some_and(|cell| cell.attrs().images().is_some())
+}
+
+fn restored(snapshot: TerminalSnapshot, scrollback: usize) -> Terminal {
+ let mut term = terminal(scrollback);
+ term.restore(snapshot).expect("restore");
+ term
+}
+
+#[test]
+fn a_restored_terminal_is_the_same_terminal() {
+ let mut original = terminal(100);
+ everything(&mut original);
+ let snapshot = original.snapshot();
+ assert_eq!(snapshot.version, SNAPSHOT_VERSION);
+ assert!(snapshot.alt_screen_is_active);
+ assert!(!snapshot.kitty.transmission_in_progress);
+
+ let mut copy = restored(original.snapshot(), 100);
+ assert_eq!(copy.snapshot(), snapshot, "a snapshot of the restore");
+ for alt in [false, true] {
+ assert_eq!(
+ copy.screen_for_alt(alt).all_lines(),
+ original.screen_for_alt(alt).all_lines(),
+ "lines of the {} screen",
+ if alt { "alternate" } else { "primary" }
+ );
+ }
+ assert_eq!(copy.cursor_pos(), original.cursor_pos());
+ assert_eq!(copy.get_title(), original.get_title());
+ assert_eq!(copy.get_current_dir(), original.get_current_dir());
+ assert_eq!(copy.user_vars(), original.user_vars());
+ assert_eq!(copy.get_keyboard_encoding(), original.get_keyboard_encoding());
+ assert_eq!(copy.get_size(), original.get_size());
+
+ // The same bytes from here on leave both terminals the same: the
+ // modes took effect, the kitty ids resolve, the margins hold.
+ for term in [&mut original, &mut copy] {
+ term.advance_bytes("\x1b[?1049l");
+ term.advance_bytes("\x1b_Ga=d,d=i,i=1\x1b\\");
+ term.advance_bytes("\x1b[4;5Hin the margins\r\n\r\n\r\n");
+ term.advance_bytes("\x1b8restored\t|");
+ term.advance_bytes("\x1b]1337;UnicodeVersion=pop before\x07");
+ }
+ assert_eq!(copy.snapshot(), original.snapshot(), "after more output");
+ assert_eq!(
+ copy.screen().all_lines(),
+ original.screen().all_lines(),
+ "primary lines after more output"
+ );
+}
+
+/// The script is only worth its round trip if it moved every field off
+/// its default; a wrong escape sequence would otherwise leave both sides
+/// at the default and the comparison none the wiser.
+#[test]
+fn the_script_reaches_every_field() {
+ use crate::terminalstate::{CharSet, MouseEncoding, SnapshotKeyboardEncoding};
+ use crate::Progress;
+
+ let mut original = terminal(100);
+ everything(&mut original);
+ let snapshot = original.snapshot();
+
+ let modes = &snapshot.modes;
+ assert!(snapshot.cursor.insert);
+ assert!(modes.dec_origin_mode);
+ assert!(modes.reverse_video_mode);
+ assert!(modes.bracketed_paste);
+ assert!(modes.any_event_mouse);
+ assert!(modes.button_event_mouse);
+ assert!(modes.mouse_tracking);
+ assert_eq!(modes.mouse_encoding, MouseEncoding::SGR);
+ assert!(modes.focus_tracking);
+ assert!(modes.application_cursor_keys);
+ assert!(modes.reverse_wraparound_mode);
+ assert!(modes.newline_mode);
+ assert!(modes.application_keypad);
+ assert!(modes.sixel_display_mode);
+ assert!(modes.sixel_scrolls_right);
+ assert!(modes.use_private_color_registers_for_each_graphic);
+ assert_eq!(modes.modify_other_keys, Some(2));
+ assert_eq!(modes.g1_charset, CharSet::DecLineDrawing);
+ assert!(modes.shift_out);
+ assert_eq!(
+ modes.keyboard_encoding,
+ SnapshotKeyboardEncoding::Win32,
+ "win32-input-mode lives in the terminal, the kitty pushes on the screens"
+ );
+ assert_eq!(
+ snapshot.alt_screen.keyboard_stack,
+ [SnapshotKeyboardEncoding::Kitty(3)]
+ );
+ assert_eq!(modes.unicode_version.version, 14);
+ assert_eq!(modes.unicode_version_stack.len(), 1);
+ assert_eq!(modes.top_and_bottom_margins, 2..20);
+ assert_eq!(modes.left_and_right_margins, 4..70);
+ assert!(modes.left_and_right_margin_mode);
+ assert!(!modes.focused);
+ assert_ne!(
+ modes.tabs,
+ terminal(100).snapshot().modes.tabs,
+ "the tab stops were changed"
+ );
+
+ let identity = &snapshot.identity;
+ assert_eq!(identity.title, "My Title");
+ assert_eq!(identity.icon_title.as_deref(), Some("icon"));
+ assert_eq!(
+ identity.current_dir.as_deref(),
+ Some("file:///tmp/work")
+ );
+ assert_eq!(identity.user_vars.get("foo").map(String::as_str), Some("bar"));
+ assert!(identity.palette.is_some(), "OSC 4 made a palette override");
+ assert_eq!(identity.progress, Progress::Percentage(50));
+ assert!(identity.agent_osc_title.is_some());
+ assert!(identity.agent_osc_progress.is_some());
+
+ assert!(snapshot.screen.saved_cursor.is_some());
+ assert!(snapshot.alt_screen.saved_cursor.is_some());
+ assert!(snapshot.screen.lines.len() > 24, "scrollback");
+ assert_eq!(snapshot.images.len(), 2, "the kitty pixels and the sixel");
+ assert!(!snapshot.screen.image_cells.is_empty());
+ assert_eq!(snapshot.kitty.number_to_id.get(&7).copied(), Some(2));
+ assert_eq!(snapshot.kitty.placements.len(), 3);
+ assert_eq!(
+ snapshot.screen.keyboard_stack,
+ [SnapshotKeyboardEncoding::Kitty(1)],
+ "the primary screen keeps its own stack"
+ );
+}
+
+#[test]
+fn a_snapshot_survives_its_bytes() {
+ let mut original = terminal(100);
+ everything(&mut original);
+ let snapshot = original.snapshot();
+
+ let mut bytes = Vec::new();
+ let mut encode = varbincode::Serializer::new(&mut bytes);
+ snapshot.serialize(&mut encode).expect("serialize");
+ let mut reader = &bytes[..];
+ let mut decode = varbincode::Deserializer::new(&mut reader);
+ let back = TerminalSnapshot::deserialize(&mut decode).expect("deserialize");
+ assert_eq!(back, snapshot);
+
+ let copy = restored(back, 100);
+ assert_eq!(copy.snapshot(), snapshot);
+}
+
+#[test]
+fn a_smaller_scrollback_keeps_the_newest_lines() {
+ let mut original = terminal(100);
+ everything(&mut original);
+ original.advance_bytes("\x1b[?1049l");
+ let snapshot = original.snapshot();
+ let carried = snapshot.screen.lines.len();
+ let offset = snapshot.screen.stable_row_index_offset;
+ assert!(carried > 24 + 4, "the script scrolled {carried} lines");
+
+ let copy = restored(snapshot, 4);
+ let screen = copy.screen();
+ assert_eq!(screen.lines().len(), 24 + 4, "visible rows plus the allowance");
+ assert_eq!(
+ screen.stable_row_index_offset(),
+ offset + (carried - 28),
+ "the dropped lines still count in the stable offset"
+ );
+ assert_eq!(copy.cursor_pos(), original.cursor_pos());
+ assert_eq!(
+ screen.visible_lines(),
+ original.screen().visible_lines(),
+ "the visible rows are untouched"
+ );
+ assert_eq!(
+ screen.visible_row_to_stable_row(0),
+ original.screen().visible_row_to_stable_row(0),
+ "a stable row index names the same line on both sides"
+ );
+}
+
+#[test]
+fn a_picture_travels_once_however_many_cells_and_ids_share_it() {
+ let mut original = terminal(24);
+ original.advance_bytes(format!(
+ "\x1b_Ga=t,i=1,f=32,s=2,v=2;{PIXELS_2X2}\x1b\\\x1b_Ga=p,i=1,p=1\x1b\\"
+ ));
+ original.advance_bytes("\x1b[3;1H\x1b_Ga=p,i=1,p=2\x1b\\");
+ original.advance_bytes(format!(
+ "\x1b[5;1H\x1b_Ga=t,i=2,f=32,s=2,v=2;{PIXELS_2X2}\x1b\\\x1b_Ga=p,i=2\x1b\\"
+ ));
+ let snapshot = original.snapshot();
+ assert_eq!(snapshot.images.len(), 1, "same pixels, one picture");
+ assert_eq!(snapshot.kitty.id_to_hash.len(), 2, "under two ids");
+ assert!(
+ snapshot.screen.image_cells.len() >= 3,
+ "placed three times: {} cells",
+ snapshot.screen.image_cells.len()
+ );
+
+ let mut copy = restored(snapshot, 24);
+ let stored = copy.kitty_image_data_for_id(1).expect("id 1 restored");
+ let same_as_id_2 = copy.kitty_image_data_for_id(2).expect("id 2 restored");
+ assert!(Arc::ptr_eq(&stored, &same_as_id_2), "both ids hold the one Arc");
+ let cell = copy
+ .screen_mut()
+ .get_cell(0, 0)
+ .expect("cell 0,0")
+ .clone();
+ let on_screen = cell.attrs().images().expect("a picture at 0,0");
+ assert!(
+ Arc::ptr_eq(on_screen[0].image_data(), &stored),
+ "the cell shares the Arc with the kitty store"
+ );
+ assert_eq!(on_screen[0].image_id(), Some(1));
+ assert_eq!(on_screen[0].placement_id(), Some(1));
+
+ // A delete by id after the restore finds the placements it names.
+ copy.advance_bytes("\x1b_Ga=d,d=I,i=1\x1b\\");
+ assert!(!has_image(&mut copy, 0, 0), "placement 1 is gone");
+ assert!(!has_image(&mut copy, 0, 2), "placement 2 is gone");
+ assert!(has_image(&mut copy, 0, 4), "the picture under id 2 stays");
+}
+
+#[test]
+fn a_transfer_in_flight_is_flagged_and_not_resumed() {
+ let mut original = terminal(24);
+ original.advance_bytes(format!(
+ "\x1b_Ga=t,i=9,f=32,s=2,v=2,m=1;{HALF_2X2}\x1b\\"
+ ));
+ let snapshot = original.snapshot();
+ assert!(snapshot.kitty.transmission_in_progress);
+ assert!(snapshot.images.is_empty());
+
+ let mut copy = restored(snapshot, 24);
+ copy.advance_bytes(format!("\x1b_Gm=0;{HALF_2X2}\x1b\\"));
+ copy.advance_bytes("\x1b_Ga=p,i=9\x1b\\");
+ assert!(
+ !has_image(&mut copy, 0, 0),
+ "the half-transferred picture never appears"
+ );
+ assert!(copy.kitty_image_data_for_id(9).is_none());
+}
+
+#[test]
+fn a_snapshot_from_another_version_is_refused() {
+ let mut original = terminal(24);
+ original.advance_bytes("hello");
+ let mut snapshot = original.snapshot();
+ snapshot.version += 1;
+ let err = terminal(24).restore(snapshot).expect_err("refused");
+ let message = format!("{err:#}");
+ assert!(
+ message.contains(&format!("version {}", SNAPSHOT_VERSION + 1))
+ && message.contains(&format!("version {}", SNAPSHOT_VERSION)),
+ "{message}"
+ );
+}
+
+#[test]
+fn a_snapshot_needs_a_terminal_of_its_size() {
+ let mut original = terminal(24);
+ original.advance_bytes("hello");
+ let snapshot = original.snapshot();
+ let mut small = Terminal::new(
+ TerminalSize {
+ rows: 10,
+ cols: 40,
+ pixel_width: 320,
+ pixel_height: 160,
+ dpi: 96,
+ },
+ Arc::new(SnapshotConfig { scrollback: 24 }),
+ "ThinkTerm",
+ "O_o",
+ Box::new(Vec::new()),
+ );
+ let err = small.restore(snapshot).expect_err("refused");
+ assert!(format!("{err:#}").contains("80x24"), "{err:#}");
+}