use std::collections::VecDeque;
use std::fmt::{Display, Formatter};
use base64::Engine as _;
use crate::presentation::{
BrowserFrame, CaptureScale, FrameCleanupReason, FrameOwnershipEvent, FrameOwnershipRecord,
FrameStoragePolicy, LatestFrameMailbox, PaneGeometry, PixelSize, PresentationContractError,
TargetResourceIdentity, ViewportGeometry,
};
mod ansi;
pub use ansi::{AnsiCanvas, AnsiCell, AnsiUpdate, FrameFit, Rgb};
pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
pub const MAX_OUTPUT_BYTES: usize = 6 * 1024 * 1024;
pub const MAX_SEMANTIC_BYTES: usize = 16 * 1024;
pub const MAX_OWNERSHIP_RECORDS: usize = 32;
const KITTY_INTRO: &[u8] = b"\x1b_G";
const KITTY_END: &[u8] = b"\x1b\\";
const KITTY_CHUNK_BYTES: usize = 4096;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GraphicsMode {
Kitty,
#[default]
Semantic,
}
impl GraphicsMode {
pub const fn label(self) -> &'static str {
match self {
Self::Kitty => "Kitty graphics",
Self::Semantic => "semantic fallback",
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TerminalEnvironment<'a> {
pub term: Option<&'a str>,
pub term_program: Option<&'a str>,
pub kitty_window_id: Option<&'a str>,
}
impl<'a> TerminalEnvironment<'a> {
pub const fn new(
term: Option<&'a str>,
term_program: Option<&'a str>,
kitty_window_id: Option<&'a str>,
) -> Self {
Self {
term,
term_program,
kitty_window_id,
}
}
pub fn from_process() -> TerminalEnvironmentOwned {
TerminalEnvironmentOwned {
term: std::env::var("TERM").ok(),
term_program: std::env::var("TERM_PROGRAM").ok(),
kitty_window_id: std::env::var("KITTY_WINDOW_ID").ok(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TerminalEnvironmentOwned {
pub term: Option<String>,
pub term_program: Option<String>,
pub kitty_window_id: Option<String>,
}
impl TerminalEnvironmentOwned {
pub fn as_borrowed(&self) -> TerminalEnvironment<'_> {
TerminalEnvironment::new(
self.term.as_deref(),
self.term_program.as_deref(),
self.kitty_window_id.as_deref(),
)
}
}
pub fn negotiate(env: TerminalEnvironment<'_>) -> GraphicsMode {
let term = env.term.unwrap_or_default().to_ascii_lowercase();
if matches!(term.as_str(), "dumb" | "unknown") {
return GraphicsMode::Semantic;
}
if term == "xterm-kitty" {
return GraphicsMode::Kitty;
}
if env.kitty_window_id.is_some_and(|value| !value.is_empty()) {
return GraphicsMode::Kitty;
}
let program = env.term_program.unwrap_or_default().to_ascii_lowercase();
if matches!(program.as_str(), "kitty" | "wezterm" | "ghostty") {
return GraphicsMode::Kitty;
}
GraphicsMode::Semantic
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PaneArea {
pub x: u16,
pub y: u16,
pub width: u16,
pub height: u16,
}
impl PaneArea {
pub const fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
Self {
x,
y,
width,
height,
}
}
pub const fn is_empty(self) -> bool {
self.width == 0 || self.height == 0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GraphicsError {
Invalid(String),
Presentation(PresentationContractError),
PayloadTooLarge { actual: usize, maximum: usize },
OutputTooLarge { actual: usize, maximum: usize },
}
impl Display for GraphicsError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Invalid(message) => {
write!(formatter, "invalid terminal graphics state: {message}")
}
Self::Presentation(error) => Display::fmt(error, formatter),
Self::PayloadTooLarge { actual, maximum } => {
write!(
formatter,
"frame payload is {actual} bytes; maximum is {maximum}"
)
}
Self::OutputTooLarge { actual, maximum } => {
write!(
formatter,
"terminal output is {actual} bytes; maximum is {maximum}"
)
}
}
}
}
impl std::error::Error for GraphicsError {}
impl From<PresentationContractError> for GraphicsError {
fn from(error: PresentationContractError) -> Self {
Self::Presentation(error)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedFrame {
pub mode: GraphicsMode,
pub generation: Option<u64>,
pub pane: PaneArea,
pub bytes: Vec<u8>,
}
impl RenderedFrame {
pub fn as_text(&self) -> Option<&str> {
(self.mode == GraphicsMode::Semantic)
.then(|| std::str::from_utf8(&self.bytes).ok())
.flatten()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphicsFallbackReason {
UnsupportedEncoding,
InvalidRawRgbaPayload,
}
impl GraphicsFallbackReason {
pub const fn label(self) -> &'static str {
match self {
Self::UnsupportedEncoding => "unsupported-encoding",
Self::InvalidRawRgbaPayload => "invalid-rgba-payload",
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GraphicsDiagnostics {
pub mode: GraphicsMode,
pub accepted_frames: u64,
pub presented_frames: u64,
pub replaced_frames: u64,
pub dropped_frames: u64,
pub stale_frames: u64,
pub current_bytes: usize,
pub pending_bytes: usize,
pub geometry_revision: u64,
pub cleanup_count: u64,
pub fallback_count: u64,
pub last_fallback: Option<GraphicsFallbackReason>,
}
#[derive(Debug, Clone)]
struct PayloadFrame {
frame: BrowserFrame,
bytes: Vec<u8>,
fallback: Option<GraphicsFallbackReason>,
}
pub struct TerminalGraphics {
mode: GraphicsMode,
mailbox: LatestFrameMailbox,
current_payload: Option<PayloadFrame>,
pending_payload: Option<PayloadFrame>,
pane: PaneArea,
geometry: Option<ViewportGeometry>,
geometry_revision: u64,
browser_revision: u64,
cleanup_count: u64,
fallback_count: u64,
last_fallback: Option<GraphicsFallbackReason>,
cleaned: bool,
ownership: VecDeque<FrameOwnershipRecord>,
}
impl TerminalGraphics {
pub fn new(
mode: GraphicsMode,
identity: TargetResourceIdentity,
) -> Result<Self, GraphicsError> {
Ok(Self {
mode,
mailbox: LatestFrameMailbox::new(identity)?,
current_payload: None,
pending_payload: None,
pane: PaneArea::default(),
geometry: None,
geometry_revision: 0,
browser_revision: 0,
cleanup_count: 0,
fallback_count: 0,
last_fallback: None,
cleaned: false,
ownership: VecDeque::new(),
})
}
pub fn for_environment(
environment: TerminalEnvironment<'_>,
identity: TargetResourceIdentity,
) -> Result<Self, GraphicsError> {
Self::new(negotiate(environment), identity)
}
pub const fn mode(&self) -> GraphicsMode {
self.mode
}
pub const fn pane(&self) -> PaneArea {
self.pane
}
pub const fn geometry_revision(&self) -> u64 {
self.geometry_revision
}
pub fn geometry(&self) -> Option<&ViewportGeometry> {
self.geometry.as_ref()
}
pub const fn browser_revision(&self) -> u64 {
self.browser_revision
}
pub fn resize(
&mut self,
pane: PaneArea,
viewport: PixelSize,
content: PixelSize,
capture_scale: CaptureScale,
browser_revision: u64,
) -> Result<bool, GraphicsError> {
if browser_revision < self.browser_revision {
return Err(GraphicsError::Presentation(
PresentationContractError::StaleRevision {
expected: self.browser_revision,
actual: browser_revision,
},
));
}
if pane.is_empty() {
return Err(GraphicsError::Invalid("pane must be non-empty".into()));
}
let changed = self.pane != pane
|| self.geometry.as_ref().is_none_or(|geometry| {
geometry.viewport != viewport
|| geometry.content != content
|| geometry.capture_scale.get() != capture_scale.get()
|| geometry.browser_revision != browser_revision
});
if !changed {
return Ok(false);
}
self.clear_payloads(FrameCleanupReason::Resize);
self.geometry_revision = self.geometry_revision.saturating_add(1).max(1);
self.browser_revision = browser_revision;
self.pane = pane;
self.geometry = Some(ViewportGeometry::new(
PaneGeometry {
origin: crate::presentation::PixelPoint {
x: pane.x as u32,
y: pane.y as u32,
},
size: PixelSize::new(pane.width as u32, pane.height as u32),
},
viewport,
content,
capture_scale,
browser_revision,
self.geometry_revision,
)?);
self.cleaned = false;
Ok(true)
}
pub fn clear_pane(&mut self) -> Result<bool, GraphicsError> {
let changed = self.geometry.is_some() || !self.mailbox.is_empty() || !self.pane.is_empty();
if !changed {
return Ok(false);
}
self.clear_payloads(FrameCleanupReason::Resize);
let identity = self
.mailbox
.identity()
.cloned()
.ok_or_else(|| GraphicsError::Invalid("graphics mailbox has no identity".into()))?;
self.mailbox.rebind(identity)?;
self.geometry = None;
self.pane = PaneArea::default();
self.cleaned = false;
Ok(true)
}
pub fn bind_browser_revision(&mut self, browser_revision: u64) -> Result<bool, GraphicsError> {
if browser_revision < self.browser_revision {
return Err(GraphicsError::Presentation(
PresentationContractError::StaleRevision {
expected: self.browser_revision,
actual: browser_revision,
},
));
}
if browser_revision == self.browser_revision {
return Ok(false);
}
self.clear_payloads(FrameCleanupReason::ModeChange);
self.browser_revision = browser_revision;
if let Some(previous) = self.geometry {
self.geometry = Some(ViewportGeometry::new(
previous.pane,
previous.viewport,
previous.content,
previous.capture_scale,
browser_revision,
previous.geometry_revision,
)?);
}
self.cleaned = false;
Ok(true)
}
pub fn submit(
&mut self,
frame: BrowserFrame,
payload: &[u8],
) -> Result<SubmitResult, GraphicsError> {
if payload.len() > MAX_FRAME_BYTES {
return Err(GraphicsError::PayloadTooLarge {
actual: payload.len(),
maximum: MAX_FRAME_BYTES,
});
}
if self.cleaned {
return Err(GraphicsError::Invalid(
"graphics renderer is shut down".into(),
));
}
if let Some(geometry) = self.geometry.as_ref() {
geometry.check_snapshot(frame.browser_revision, frame.geometry_revision)?;
}
let fallback = self.fallback_reason(&frame, payload);
let outcome = self.mailbox.submit(frame.clone())?;
match outcome {
crate::presentation::SubmitOutcome::Current => {
self.current_payload = Some(PayloadFrame {
frame: frame.clone(),
bytes: payload.to_vec(),
fallback,
});
self.note_fallback(fallback);
self.record(frame, FrameOwnershipEvent::Presented);
Ok(SubmitResult::Presented)
}
crate::presentation::SubmitOutcome::Pending => {
self.pending_payload = Some(PayloadFrame {
frame: frame.clone(),
bytes: payload.to_vec(),
fallback,
});
self.note_fallback(fallback);
self.record(frame, FrameOwnershipEvent::Queued);
Ok(SubmitResult::Queued)
}
crate::presentation::SubmitOutcome::ReplacedPending => {
if let Some(previous) = self.pending_payload.take() {
self.record(
previous.frame,
FrameOwnershipEvent::Released {
reason: FrameCleanupReason::Replaced,
},
);
}
self.pending_payload = Some(PayloadFrame {
frame: frame.clone(),
bytes: payload.to_vec(),
fallback,
});
self.note_fallback(fallback);
self.record(frame, FrameOwnershipEvent::Queued);
Ok(SubmitResult::Replaced)
}
crate::presentation::SubmitOutcome::DroppedStale => {
self.record(
frame,
FrameOwnershipEvent::Released {
reason: FrameCleanupReason::Dropped,
},
);
Ok(SubmitResult::Stale)
}
}
}
fn fallback_reason(
&self,
frame: &BrowserFrame,
payload: &[u8],
) -> Option<GraphicsFallbackReason> {
if self.mode != GraphicsMode::Kitty {
return None;
}
match frame.encoding {
crate::presentation::FrameEncoding::Png => None,
crate::presentation::FrameEncoding::RawRgba => {
let expected = frame
.viewport
.width
.checked_mul(frame.viewport.height)
.and_then(|size| size.checked_mul(4));
(expected != Some(payload.len() as u32))
.then_some(GraphicsFallbackReason::InvalidRawRgbaPayload)
}
crate::presentation::FrameEncoding::Jpeg
| crate::presentation::FrameEncoding::Webp
| crate::presentation::FrameEncoding::Av1 => {
Some(GraphicsFallbackReason::UnsupportedEncoding)
}
}
}
fn note_fallback(&mut self, fallback: Option<GraphicsFallbackReason>) {
if let Some(reason) = fallback {
self.fallback_count = self.fallback_count.saturating_add(1);
self.last_fallback = Some(reason);
}
}
pub fn present_pending(&mut self) -> Result<bool, GraphicsError> {
let Some(geometry) = self.geometry.as_ref() else {
return Ok(false);
};
let Some(previous) = self
.mailbox
.promote_pending(self.browser_revision, geometry.geometry_revision)?
else {
return Ok(false);
};
let next = self.pending_payload.take().ok_or_else(|| {
GraphicsError::Invalid("frame metadata and payload mailbox diverged".into())
})?;
let next_frame = next.frame.clone();
self.current_payload = Some(next);
self.record(next_frame, FrameOwnershipEvent::Presented);
self.record(
previous,
FrameOwnershipEvent::Released {
reason: FrameCleanupReason::Presented,
},
);
Ok(true)
}
pub fn render_current(&self, semantic: &str) -> Result<RenderedFrame, GraphicsError> {
let semantic = bounded_text(semantic, MAX_SEMANTIC_BYTES);
let Some(current) = self.current_payload.as_ref() else {
return Ok(RenderedFrame {
mode: GraphicsMode::Semantic,
generation: None,
pane: self.pane,
bytes: semantic.into_bytes(),
});
};
if self.mode == GraphicsMode::Semantic {
return Ok(RenderedFrame {
mode: GraphicsMode::Semantic,
generation: Some(current.frame.generation),
pane: self.pane,
bytes: semantic.into_bytes(),
});
}
if current.fallback.is_some() {
return Ok(RenderedFrame {
mode: GraphicsMode::Semantic,
generation: Some(current.frame.generation),
pane: self.pane,
bytes: semantic.into_bytes(),
});
}
let (format, extra) = match current.frame.encoding {
crate::presentation::FrameEncoding::Png => (100u8, String::new()),
crate::presentation::FrameEncoding::RawRgba => {
let expected = current
.frame
.viewport
.width
.checked_mul(current.frame.viewport.height)
.and_then(|size| size.checked_mul(4));
if expected != Some(current.bytes.len() as u32) {
return Ok(RenderedFrame {
mode: GraphicsMode::Semantic,
generation: Some(current.frame.generation),
pane: self.pane,
bytes: semantic.into_bytes(),
});
}
(
32u8,
format!(
"s={},v={},",
current.frame.viewport.width, current.frame.viewport.height
),
)
}
crate::presentation::FrameEncoding::Jpeg
| crate::presentation::FrameEncoding::Webp
| crate::presentation::FrameEncoding::Av1 => {
return Ok(RenderedFrame {
mode: GraphicsMode::Semantic,
generation: Some(current.frame.generation),
pane: self.pane,
bytes: semantic.into_bytes(),
});
}
};
let (x, y, width, height) = self.kitty_placement();
let encoded = base64::engine::general_purpose::STANDARD.encode(¤t.bytes);
let chunk_count = encoded.len().div_ceil(KITTY_CHUNK_BYTES).max(1);
let mut output = Vec::with_capacity(
KITTY_INTRO
.len()
.saturating_mul(chunk_count)
.saturating_add(encoded.len())
.saturating_add(KITTY_END.len().saturating_mul(chunk_count))
.saturating_add(128),
);
output.extend_from_slice(
format!(
"\x1b[{};{}H",
u32::from(y).saturating_add(1),
u32::from(x).saturating_add(1)
)
.as_bytes(),
);
for index in 0..chunk_count {
let start = index.saturating_mul(KITTY_CHUNK_BYTES);
let end = start.saturating_add(KITTY_CHUNK_BYTES).min(encoded.len());
let final_chunk = index + 1 == chunk_count;
output.extend_from_slice(KITTY_INTRO);
if index == 0 {
let continuation = if final_chunk { "" } else { "m=1" };
output.extend_from_slice(
format!("a=T,q=2,c={width},r={height},C=1,f={format},{extra}{continuation};")
.as_bytes(),
);
} else if final_chunk {
output.extend_from_slice(b";");
} else {
output.extend_from_slice(b"m=1;");
}
output.extend_from_slice(&encoded.as_bytes()[start..end]);
output.extend_from_slice(KITTY_END);
}
if output.len() > MAX_OUTPUT_BYTES {
return Err(GraphicsError::OutputTooLarge {
actual: output.len(),
maximum: MAX_OUTPUT_BYTES,
});
}
Ok(RenderedFrame {
mode: GraphicsMode::Kitty,
generation: Some(current.frame.generation),
pane: self.pane,
bytes: output,
})
}
fn kitty_placement(&self) -> (u16, u16, u16, u16) {
let Some(geometry) = self.geometry.as_ref() else {
return (self.pane.x, self.pane.y, self.pane.width, self.pane.height);
};
let pane = geometry.pane;
let image = geometry.displayed_image;
let local_x = image.x.saturating_sub(pane.origin.x) as u64;
let local_y = image.y.saturating_sub(pane.origin.y) as u64;
let x = self.pane.x as u64
+ local_x.saturating_mul(self.pane.width as u64) / pane.size.width as u64;
let y = self.pane.y as u64
+ local_y.saturating_mul(self.pane.height as u64) / pane.size.height as u64;
let width = (image.width as u64)
.saturating_mul(self.pane.width as u64)
.div_ceil(pane.size.width as u64)
.max(1);
let height = (image.height as u64)
.saturating_mul(self.pane.height as u64)
.div_ceil(pane.size.height as u64)
.max(1);
(
x.min(u16::MAX as u64) as u16,
y.min(u16::MAX as u64) as u16,
width.min(self.pane.width as u64) as u16,
height.min(self.pane.height as u64) as u16,
)
}
pub fn cleanup(&mut self) -> Vec<u8> {
if self.cleaned {
return Vec::new();
}
self.clear_payloads(FrameCleanupReason::Shutdown);
self.cleaned = true;
self.cleanup_count = self.cleanup_count.saturating_add(1);
if self.mode == GraphicsMode::Kitty {
let mut output = Vec::with_capacity(16);
output.extend_from_slice(b"\x1b_Ga=d,d=A\x1b\\");
output
} else {
Vec::new()
}
}
pub fn shutdown(&mut self) -> Vec<u8> {
if self.cleaned {
return Vec::new();
}
self.cleanup()
}
pub fn diagnostics(&self) -> GraphicsDiagnostics {
let counters = self.mailbox.counters();
GraphicsDiagnostics {
mode: self.mode,
accepted_frames: counters.accepted,
presented_frames: counters.presented,
replaced_frames: counters.replaced_pending,
dropped_frames: counters.dropped,
stale_frames: counters.stale_rejected,
current_bytes: self
.current_payload
.as_ref()
.map_or(0, |frame| frame.bytes.len()),
pending_bytes: self
.pending_payload
.as_ref()
.map_or(0, |frame| frame.bytes.len()),
geometry_revision: self.geometry_revision,
cleanup_count: self.cleanup_count,
fallback_count: self.fallback_count,
last_fallback: self.last_fallback,
}
}
pub fn current_fallback(&self) -> Option<GraphicsFallbackReason> {
self.current_payload
.as_ref()
.and_then(|frame| frame.fallback)
}
pub fn diagnostics_label(&self) -> String {
let diagnostics = self.diagnostics();
let fallback = diagnostics
.last_fallback
.map_or("none", GraphicsFallbackReason::label);
format!(
"{} a:{} p:{} q:{} d:{} s:{} fb:{}:{} b:{}/{} g:{}",
diagnostics.mode.label(),
diagnostics.accepted_frames,
diagnostics.presented_frames,
diagnostics.replaced_frames,
diagnostics.dropped_frames,
diagnostics.stale_frames,
diagnostics.fallback_count,
fallback,
diagnostics.current_bytes,
diagnostics.pending_bytes,
diagnostics.geometry_revision,
)
}
pub fn ownership(&self) -> impl Iterator<Item = &FrameOwnershipRecord> {
self.ownership.iter()
}
pub fn storage_policy(&self) -> FrameStoragePolicy {
FrameStoragePolicy::default()
}
fn clear_payloads(&mut self, reason: FrameCleanupReason) {
if let Some(frame) = self.current_payload.take() {
self.record(frame.frame, FrameOwnershipEvent::Released { reason });
}
if let Some(frame) = self.pending_payload.take() {
self.record(frame.frame, FrameOwnershipEvent::Released { reason });
}
self.mailbox.clear();
}
fn record(&mut self, frame: BrowserFrame, event: FrameOwnershipEvent) {
if self.ownership.len() == MAX_OWNERSHIP_RECORDS {
self.ownership.pop_front();
}
self.ownership.push_back(FrameOwnershipRecord {
generation: frame.generation,
browser_revision: frame.browser_revision,
geometry_revision: frame.geometry_revision,
event,
});
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubmitResult {
Presented,
Queued,
Replaced,
Stale,
}
fn bounded_text(value: &str, maximum: usize) -> String {
let mut end = value.len().min(maximum);
while end > 0 && !value.is_char_boundary(end) {
end -= 1;
}
let mut output = value[..end].to_string();
output.retain(|character| !character.is_control() || character == '\n' || character == '\t');
output
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presentation::{
BrowserFrame, FrameDamage, FrameDropCounts, FrameEncoding,
PRESENTATION_CONTRACT_SCHEMA_VERSION,
};
fn identity() -> TargetResourceIdentity {
TargetResourceIdentity::new("tab-1", Some("terminal".into())).unwrap()
}
fn frame(generation: u64, geometry_revision: u64) -> BrowserFrame {
BrowserFrame {
schema_version: PRESENTATION_CONTRACT_SCHEMA_VERSION,
generation,
identity: identity(),
acquired_at_ms: generation,
viewport: PixelSize::new(640, 480),
content: PixelSize::new(640, 480),
capture_scale: CaptureScale::FULL,
encoding: FrameEncoding::Png,
keyframe: true,
damage: FrameDamage::Full,
browser_revision: 1,
geometry_revision,
dropped: FrameDropCounts::default(),
}
}
#[test]
fn capability_prefers_kitty_and_falls_back_semantically() {
assert_eq!(
negotiate(TerminalEnvironment::new(None, Some("kitty"), None)),
GraphicsMode::Kitty
);
assert_eq!(
negotiate(TerminalEnvironment::new(Some("xterm-kitty"), None, None)),
GraphicsMode::Kitty
);
assert_eq!(
negotiate(TerminalEnvironment::new(
Some("xterm"),
Some("unknown"),
None
)),
GraphicsMode::Semantic
);
assert_eq!(
negotiate(TerminalEnvironment::new(
Some("dumb"),
Some("kitty"),
Some("1")
)),
GraphicsMode::Semantic
);
}
#[test]
fn payload_mailbox_replaces_pending_without_growth() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Semantic, identity()).unwrap();
graphics
.resize(
PaneArea::new(1, 1, 40, 20),
PixelSize::new(640, 480),
PixelSize::new(640, 480),
CaptureScale::FULL,
1,
)
.unwrap();
assert_eq!(
graphics.submit(frame(1, 1), b"one").unwrap(),
SubmitResult::Presented
);
assert_eq!(
graphics.submit(frame(2, 1), b"two").unwrap(),
SubmitResult::Queued
);
assert_eq!(
graphics.submit(frame(3, 1), b"three").unwrap(),
SubmitResult::Replaced
);
let diagnostics = graphics.diagnostics();
assert_eq!(diagnostics.pending_bytes, 5);
assert_eq!(diagnostics.replaced_frames, 1);
let records = graphics.ownership().collect::<Vec<_>>();
assert!(records.iter().any(|record| {
record.generation == 2
&& record.event
== FrameOwnershipEvent::Released {
reason: FrameCleanupReason::Replaced,
}
}));
assert!(records.iter().any(|record| {
record.generation == 3 && record.event == FrameOwnershipEvent::Queued
}));
assert!(graphics.present_pending().unwrap());
assert_eq!(graphics.diagnostics().current_bytes, 5);
assert!(graphics.ownership().any(|record| {
record.generation == 3 && record.event == FrameOwnershipEvent::Presented
}));
}
#[test]
fn raw_rgba_render_uses_encoding_and_image_placement() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Kitty, identity()).unwrap();
graphics
.resize(
PaneArea::new(2, 3, 40, 20),
PixelSize::new(2, 1),
PixelSize::new(2, 1),
CaptureScale::FULL,
1,
)
.unwrap();
let mut rgba = frame(1, 1);
rgba.viewport = PixelSize::new(2, 1);
rgba.content = PixelSize::new(2, 1);
rgba.encoding = FrameEncoding::RawRgba;
graphics.submit(rgba, &[0; 8]).unwrap();
let rendered = graphics.render_current("fallback").unwrap();
let command = std::str::from_utf8(&rendered.bytes).unwrap();
assert!(command.contains("f=32"));
assert!(command.contains("s=2,v=1"));
assert!(command.starts_with("\x1b[4;3H\x1b_Ga=T"));
assert!(command.contains("c=40,r=20,C=1,f=32"));
}
#[test]
fn unsupported_encoding_reports_semantic_fallback() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Kitty, identity()).unwrap();
graphics
.resize(
PaneArea::new(0, 0, 40, 20),
PixelSize::new(640, 480),
PixelSize::new(640, 480),
CaptureScale::FULL,
1,
)
.unwrap();
let mut unsupported = frame(1, 1);
unsupported.encoding = FrameEncoding::Webp;
assert_eq!(
graphics.submit(unsupported, b"encoded").unwrap(),
SubmitResult::Presented
);
let rendered = graphics.render_current("semantic fallback").unwrap();
assert_eq!(rendered.mode, GraphicsMode::Semantic);
assert_eq!(rendered.as_text(), Some("semantic fallback"));
assert_eq!(
graphics.current_fallback(),
Some(GraphicsFallbackReason::UnsupportedEncoding)
);
let diagnostics = graphics.diagnostics();
assert_eq!(diagnostics.fallback_count, 1);
assert_eq!(
diagnostics.last_fallback,
Some(GraphicsFallbackReason::UnsupportedEncoding)
);
assert!(
graphics
.diagnostics_label()
.contains("fb:1:unsupported-encoding")
);
}
#[test]
fn invalid_raw_rgba_reports_degraded_output_without_error() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Kitty, identity()).unwrap();
graphics
.resize(
PaneArea::new(0, 0, 40, 20),
PixelSize::new(2, 1),
PixelSize::new(2, 1),
CaptureScale::FULL,
1,
)
.unwrap();
let mut rgba = frame(1, 1);
rgba.viewport = PixelSize::new(2, 1);
rgba.content = PixelSize::new(2, 1);
rgba.encoding = FrameEncoding::RawRgba;
graphics.submit(rgba, &[0; 7]).unwrap();
let rendered = graphics.render_current("invalid rgba").unwrap();
assert_eq!(rendered.mode, GraphicsMode::Semantic);
assert_eq!(rendered.as_text(), Some("invalid rgba"));
assert_eq!(
graphics.current_fallback(),
Some(GraphicsFallbackReason::InvalidRawRgbaPayload)
);
assert_eq!(graphics.diagnostics().fallback_count, 1);
}
#[test]
fn zero_pane_releases_frame_and_preserves_revision_monotonicity() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Kitty, identity()).unwrap();
graphics
.resize(
PaneArea::new(0, 0, 40, 20),
PixelSize::new(640, 480),
PixelSize::new(640, 480),
CaptureScale::FULL,
3,
)
.unwrap();
let mut current = frame(1, 1);
current.browser_revision = 3;
graphics.submit(current, b"frame").unwrap();
assert!(graphics.clear_pane().unwrap());
assert!(graphics.geometry().is_none());
assert_eq!(graphics.diagnostics().current_bytes, 0);
assert_eq!(graphics.diagnostics().accepted_frames, 0);
let error = graphics
.resize(
PaneArea::new(0, 0, 40, 20),
PixelSize::new(640, 480),
PixelSize::new(640, 480),
CaptureScale::FULL,
2,
)
.unwrap_err();
assert!(matches!(
error,
GraphicsError::Presentation(PresentationContractError::StaleRevision {
expected: 3,
actual: 2
})
));
graphics
.resize(
PaneArea::new(0, 0, 50, 20),
PixelSize::new(800, 480),
PixelSize::new(800, 480),
CaptureScale::FULL,
3,
)
.unwrap();
assert!(graphics.geometry_revision() > 1);
}
#[test]
fn stale_frame_is_rejected_and_resize_cleans_payloads() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Kitty, identity()).unwrap();
graphics
.resize(
PaneArea::new(0, 0, 40, 20),
PixelSize::new(640, 480),
PixelSize::new(640, 480),
CaptureScale::FULL,
1,
)
.unwrap();
graphics.submit(frame(2, 1), b"frame").unwrap();
assert_eq!(
graphics.submit(frame(1, 1), b"old").unwrap(),
SubmitResult::Stale
);
graphics
.resize(
PaneArea::new(0, 0, 50, 20),
PixelSize::new(800, 480),
PixelSize::new(800, 480),
CaptureScale::FULL,
1,
)
.unwrap();
assert_eq!(graphics.diagnostics().current_bytes, 0);
assert_eq!(graphics.diagnostics().pending_bytes, 0);
}
#[test]
fn semantic_output_is_plain_and_shutdown_has_no_artifact() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Semantic, identity()).unwrap();
let output = graphics.render_current("hello\x1b[31m").unwrap();
assert_eq!(output.as_text(), Some("hello[31m"));
assert!(graphics.shutdown().is_empty());
assert!(graphics.shutdown().is_empty());
}
#[test]
fn kitty_output_and_cleanup_are_bounded() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Kitty, identity()).unwrap();
graphics
.resize(
PaneArea::new(2, 3, 40, 20),
PixelSize::new(640, 480),
PixelSize::new(640, 480),
CaptureScale::FULL,
1,
)
.unwrap();
graphics.submit(frame(1, 1), b"png").unwrap();
let output = graphics.render_current("ignored").unwrap();
let command = std::str::from_utf8(&output.bytes).unwrap();
assert!(command.starts_with("\x1b[4;10H\x1b_Ga=T"));
assert!(command.contains("c=26,r=20,C=1,f=100"));
assert!(output.bytes.len() <= MAX_OUTPUT_BYTES);
assert!(!graphics.shutdown().is_empty());
}
#[test]
fn kitty_output_chunks_large_payloads() {
let mut graphics = TerminalGraphics::new(GraphicsMode::Kitty, identity()).unwrap();
graphics
.resize(
PaneArea::new(0, 0, 40, 20),
PixelSize::new(640, 480),
PixelSize::new(640, 480),
CaptureScale::FULL,
1,
)
.unwrap();
let payload = vec![0xabu8; 5_000];
graphics.submit(frame(1, 1), &payload).unwrap();
let output = graphics.render_current("ignored").unwrap();
let intro_count = output
.bytes
.windows(KITTY_INTRO.len())
.filter(|window| *window == KITTY_INTRO)
.count();
assert_eq!(intro_count, 2);
assert!(output.bytes.windows(4).any(|window| window == b"m=1;"));
assert!(output.bytes.ends_with(KITTY_END));
}
}