1#![forbid(unsafe_code)]
2
3#[cfg(feature = "input-parser")]
15pub mod input_parser;
16pub mod pane_keyboard;
17pub mod pane_pointer_capture;
18pub mod release_readiness;
19pub mod runtime_options;
20pub mod sdk_adapter;
21pub mod sdk_event_model;
22pub mod session_record;
23pub mod step_program;
24
25pub mod pane {
37 pub mod pointer {
39 pub use crate::pane_pointer_capture::{
40 PanePointerCaptureAdapter, PanePointerCaptureCommand, PanePointerCaptureConfig,
41 PanePointerDispatch, PanePointerIgnoredReason, PanePointerLifecyclePhase,
42 PanePointerLogEntry, PanePointerLogOutcome,
43 };
44 }
45
46 pub mod keyboard {
48 pub use crate::pane_keyboard::{
49 PaneAriaNode, PaneAriaOrientation, PaneAriaRole, PaneWebKeyOutcome,
50 PaneWebKeyboardController, key_to_pane_command, pane_accessibility_tree,
51 };
52 }
53}
54
55use core::time::Duration;
56use std::collections::VecDeque;
57
58use ftui_backend::{
59 Backend, BackendClock, BackendEventSource, BackendFeatures, BackendPresenter, ScreenMode,
60};
61use ftui_core::event::Event;
62use ftui_core::terminal_capabilities::TerminalCapabilities;
63use ftui_render::buffer::Buffer;
64use ftui_render::cell::{Cell, CellAttrs, CellContent};
65use ftui_render::diff::BufferDiff;
66use ftui_render::grapheme_pool::GraphemePool;
67use ftui_render::link_registry::LinkRegistry;
68
69const GRAPHEME_FALLBACK_CODEPOINT: u32 = '□' as u32;
70const ATTR_STYLE_MASK: u32 = 0xFF;
71const ATTR_LINK_ID_MAX: u32 = CellAttrs::LINK_ID_MAX;
72const WEB_PATCH_CELL_BYTES: u64 = 16;
73const PATCH_HASH_ALGO: &str = "fnv1a64";
74const FNV64_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
75const FNV64_PRIME: u64 = 0x100000001b3;
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum WebBackendError {
80 Unsupported(&'static str),
82 InputQueueFull {
85 limit: WebInputLimit,
87 event: Event,
89 },
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum WebInputLimit {
95 Events,
97 PayloadBytes,
99}
100
101impl core::fmt::Display for WebBackendError {
102 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
103 match self {
104 Self::Unsupported(msg) => write!(f, "unsupported: {msg}"),
105 Self::InputQueueFull { limit, .. } => {
106 write!(f, "input queue full ({limit:?}); drain before retrying")
107 }
108 }
109 }
110}
111
112impl std::error::Error for WebBackendError {}
113
114#[derive(Debug, Default, Clone)]
116pub struct DeterministicClock {
117 now: Duration,
118}
119
120impl DeterministicClock {
121 #[must_use]
123 pub const fn new() -> Self {
124 Self {
125 now: Duration::ZERO,
126 }
127 }
128
129 pub fn set(&mut self, now: Duration) {
131 self.now = now;
132 }
133
134 pub fn advance(&mut self, dt: Duration) {
136 self.now = self.now.saturating_add(dt);
137 }
138}
139
140impl BackendClock for DeterministicClock {
141 fn now_mono(&self) -> Duration {
142 self.now
143 }
144}
145
146#[derive(Debug)]
150pub struct WebEventSource {
151 size: (u16, u16),
152 features: BackendFeatures,
153 queue: VecDeque<Event>,
154 queued_payload_bytes: usize,
155}
156
157impl Clone for WebEventSource {
158 fn clone(&self) -> Self {
159 let queue = self.queue.clone();
160 let queued_payload_bytes = queue.iter().map(event_payload_bytes).sum();
163 Self {
164 size: self.size,
165 features: self.features,
166 queue,
167 queued_payload_bytes,
168 }
169 }
170}
171
172fn event_payload_bytes(event: &Event) -> usize {
173 match event {
174 Event::Paste(paste) => paste.text.capacity(),
175 Event::Ime(ime) => ime.text.capacity(),
176 Event::Clipboard(clipboard) => clipboard.content.capacity(),
177 Event::TerminalResponse(resp) => match resp {
178 ftui_core::event::TerminalResponse::Dcs { payload, .. }
179 | ftui_core::event::TerminalResponse::Apc { payload, .. } => payload.capacity(),
180 ftui_core::event::TerminalResponse::CellSize { .. } => 0,
181 },
182 Event::Key(_) | Event::Mouse(_) | Event::Resize { .. } | Event::Focus(_) | Event::Tick => 0,
183 }
184}
185
186impl WebEventSource {
187 pub const MAX_EVENTS: usize = 4096;
189 pub const MAX_PAYLOAD_BYTES: usize = 1024 * 1024;
191
192 #[must_use]
194 pub fn new(width: u16, height: u16) -> Self {
195 Self {
196 size: (width, height),
197 features: BackendFeatures::default(),
198 queue: VecDeque::new(),
199 queued_payload_bytes: 0,
200 }
201 }
202
203 pub fn set_size(&mut self, width: u16, height: u16) {
205 self.size = (width, height);
206 }
207
208 #[must_use]
210 pub const fn features(&self) -> BackendFeatures {
211 self.features
212 }
213
214 pub fn push_event(&mut self, event: Event) -> Result<(), WebBackendError> {
219 if self.queue.len() >= Self::MAX_EVENTS {
220 return Err(WebBackendError::InputQueueFull {
221 limit: WebInputLimit::Events,
222 event,
223 });
224 }
225 let payload_bytes = event_payload_bytes(&event);
226 if payload_bytes > Self::MAX_PAYLOAD_BYTES - self.queued_payload_bytes {
227 return Err(WebBackendError::InputQueueFull {
228 limit: WebInputLimit::PayloadBytes,
229 event,
230 });
231 }
232 self.queued_payload_bytes += payload_bytes;
233 self.queue.push_back(event);
234 Ok(())
235 }
236
237 #[must_use]
239 pub fn queued_events(&self) -> usize {
240 self.queue.len()
241 }
242
243 #[must_use]
245 pub const fn queued_payload_bytes(&self) -> usize {
246 self.queued_payload_bytes
247 }
248
249 fn pop_event(&mut self) -> Option<Event> {
250 let event = self.queue.pop_front()?;
251 self.queued_payload_bytes -= event_payload_bytes(&event);
252 Some(event)
253 }
254
255 pub fn drain_events(&mut self) -> impl Iterator<Item = Event> + '_ {
258 std::iter::from_fn(|| self.pop_event())
259 }
260}
261
262impl BackendEventSource for WebEventSource {
263 type Error = WebBackendError;
264
265 fn size(&self) -> Result<(u16, u16), Self::Error> {
266 Ok(self.size)
267 }
268
269 fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error> {
270 self.features = features;
271 Ok(())
272 }
273
274 fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error> {
275 let _ = timeout;
277 Ok(!self.queue.is_empty())
278 }
279
280 fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
281 Ok(self.pop_event())
282 }
283}
284
285#[derive(Debug, Default, Clone)]
287pub struct WebOutputs {
288 pub logs: Vec<String>,
290 pub last_buffer: Option<Buffer>,
292 pub last_patches: Vec<WebPatchRun>,
294 pub last_patch_stats: Option<WebPatchStats>,
296 pub last_patch_hash: Option<String>,
298 pub last_full_repaint_hint: bool,
300 hash_computed: bool,
302}
303
304impl WebOutputs {
305 pub fn compute_patch_hash(&mut self) -> Option<&str> {
309 if !self.hash_computed && !self.last_patches.is_empty() {
310 self.last_patch_hash = Some(patch_batch_hash(&self.last_patches));
311 self.hash_computed = true;
312 }
313 self.last_patch_hash.as_deref()
314 }
315}
316
317impl WebOutputs {
318 #[must_use]
324 pub fn flatten_patches_u32(&self) -> WebFlatPatchBatch {
325 let total_cells = self
326 .last_patches
327 .iter()
328 .map(|patch| patch.cells.len())
329 .sum::<usize>();
330 let mut cells = Vec::with_capacity(total_cells.saturating_mul(4));
331 let mut spans = Vec::with_capacity(self.last_patches.len().saturating_mul(2));
332
333 for patch in &self.last_patches {
334 spans.push(patch.offset);
335 let len = patch.cells.len().min(u32::MAX as usize) as u32;
336 spans.push(len);
337
338 for cell in &patch.cells {
339 cells.push(cell.bg);
340 cells.push(cell.fg);
341 cells.push(cell.glyph);
342 cells.push(cell.attrs);
343 }
344 }
345
346 WebFlatPatchBatch { cells, spans }
347 }
348}
349
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
353pub struct WebPatchCell {
354 pub bg: u32,
355 pub fg: u32,
356 pub glyph: u32,
357 pub attrs: u32,
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct WebPatchRun {
363 pub offset: u32,
364 pub cells: Vec<WebPatchCell>,
365}
366
367#[derive(Debug, Default, Clone, PartialEq, Eq)]
369pub struct WebFlatPatchBatch {
370 pub cells: Vec<u32>,
372 pub spans: Vec<u32>,
374}
375
376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378pub struct WebPatchStats {
379 pub dirty_cells: u32,
380 pub patch_count: u32,
381 pub bytes_uploaded: u64,
382}
383
384#[derive(Debug, Clone)]
386pub struct WebPresenter {
387 caps: TerminalCapabilities,
388 outputs: WebOutputs,
389 pool: GraphemePool,
390 links: LinkRegistry,
391 screen_mode: ScreenMode,
392 width: u16,
393 height: u16,
394}
395
396impl WebPresenter {
397 #[must_use]
399 pub fn new() -> Self {
400 Self {
401 caps: TerminalCapabilities::modern(),
402 outputs: WebOutputs::default(),
403 pool: GraphemePool::new(),
404 links: LinkRegistry::new(),
405 screen_mode: ScreenMode::default(),
406 width: 80,
407 height: 24,
408 }
409 }
410
411 #[must_use]
413 pub fn with_size(width: u16, height: u16) -> Self {
414 Self {
415 caps: TerminalCapabilities::modern(),
416 outputs: WebOutputs::default(),
417 pool: GraphemePool::new(),
418 links: LinkRegistry::new(),
419 screen_mode: ScreenMode::default(),
420 width,
421 height,
422 }
423 }
424
425 #[must_use]
427 pub const fn outputs(&self) -> &WebOutputs {
428 &self.outputs
429 }
430
431 pub fn outputs_mut(&mut self) -> &mut WebOutputs {
433 &mut self.outputs
434 }
435
436 pub fn take_outputs(&mut self) -> WebOutputs {
438 std::mem::take(&mut self.outputs)
439 }
440
441 #[must_use]
443 pub const fn pool(&self) -> &GraphemePool {
444 &self.pool
445 }
446
447 pub fn pool_mut(&mut self) -> &mut GraphemePool {
449 &mut self.pool
450 }
451
452 #[must_use]
454 pub const fn links(&self) -> &LinkRegistry {
455 &self.links
456 }
457
458 pub fn links_mut(&mut self) -> &mut LinkRegistry {
460 &mut self.links
461 }
462
463 #[must_use]
465 pub const fn width(&self) -> u16 {
466 self.width
467 }
468
469 #[must_use]
471 pub const fn height(&self) -> u16 {
472 self.height
473 }
474
475 pub fn flatten_patches_into(&self, cells: &mut Vec<u32>, spans: &mut Vec<u32>) {
480 cells.clear();
481 spans.clear();
482
483 let total_cells = self
484 .outputs
485 .last_patches
486 .iter()
487 .map(|p| p.cells.len())
488 .sum::<usize>();
489 cells.reserve(total_cells.saturating_mul(4));
490 spans.reserve(self.outputs.last_patches.len().saturating_mul(2));
491
492 for patch in &self.outputs.last_patches {
493 spans.push(patch.offset);
494 let len = patch.cells.len().min(u32::MAX as usize) as u32;
495 spans.push(len);
496
497 for cell in &patch.cells {
498 cells.push(cell.bg);
499 cells.push(cell.fg);
500 cells.push(cell.glyph);
501 cells.push(cell.attrs);
502 }
503 }
504 }
505
506 pub fn present_ui_owned(
512 &mut self,
513 buf: Buffer,
514 diff: Option<&BufferDiff>,
515 full_repaint_hint: bool,
516 ) {
517 let patches = build_patch_runs(&buf, diff, full_repaint_hint);
518 let stats = patch_batch_stats(&patches);
519 self.outputs.last_buffer = Some(buf);
520 self.outputs.last_patches = patches;
521 self.outputs.last_patch_stats = Some(stats);
522 self.outputs.last_patch_hash = None;
523 self.outputs.hash_computed = false;
524 self.outputs.last_full_repaint_hint = full_repaint_hint;
525 }
526}
527
528impl Default for WebPresenter {
529 fn default() -> Self {
530 Self::new()
531 }
532}
533
534impl BackendPresenter for WebPresenter {
535 type Error = WebBackendError;
536
537 fn capabilities(&self) -> &TerminalCapabilities {
538 &self.caps
539 }
540
541 fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
542 self.outputs.logs.push(text.to_owned());
543 Ok(())
544 }
545
546 fn resize(&mut self, cols: u16, rows: u16) {
547 self.width = cols;
548 self.height = rows;
549 }
550
551 fn screen_mode(&self) -> ScreenMode {
552 self.screen_mode
553 }
554
555 fn set_screen_mode(&mut self, mode: ScreenMode) {
556 self.screen_mode = mode;
557 }
558
559 fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry) {
560 (&mut self.pool, &mut self.links)
561 }
562
563 fn pool_mut(&mut self) -> &mut GraphemePool {
564 &mut self.pool
565 }
566
567 fn present_ui(
568 &mut self,
569 buf: &Buffer,
570 diff: Option<&BufferDiff>,
571 full_repaint_hint: bool,
572 ) -> Result<(), Self::Error> {
573 let patches = build_patch_runs(buf, diff, full_repaint_hint);
574 let stats = patch_batch_stats(&patches);
575 self.outputs.last_buffer = Some(buf.clone());
576 self.outputs.last_patches = patches;
577 self.outputs.last_patch_stats = Some(stats);
578 self.outputs.last_patch_hash = None;
579 self.outputs.hash_computed = false;
580 self.outputs.last_full_repaint_hint = full_repaint_hint;
581 Ok(())
582 }
583
584 fn present_ui_owned(
585 &mut self,
586 buf: Buffer,
587 cursor: Option<(u16, u16)>,
588 cursor_visible: bool,
589 ) -> Result<(), Self::Error> {
590 let _ = (cursor, cursor_visible);
591 self.present_ui_owned(buf, None, false);
592 Ok(())
593 }
594}
595
596#[must_use]
597fn fnv1a64_extend(mut hash: u64, bytes: &[u8]) -> u64 {
598 for &byte in bytes {
599 hash ^= u64::from(byte);
600 hash = hash.wrapping_mul(FNV64_PRIME);
601 }
602 hash
603}
604
605#[must_use]
606fn cell_to_patch(cell: &Cell) -> WebPatchCell {
607 let glyph = match cell.content {
608 CellContent::EMPTY | CellContent::CONTINUATION => 0,
609 other if other.is_grapheme() => GRAPHEME_FALLBACK_CODEPOINT,
610 other => other.as_char().map_or(0, |c| c as u32),
611 };
612 let style_bits = u32::from(cell.attrs.flags().bits()) & ATTR_STYLE_MASK;
613 let link_id = cell.attrs.link_id().min(ATTR_LINK_ID_MAX);
614 WebPatchCell {
615 bg: cell.bg.0,
616 fg: cell.fg.0,
617 glyph,
618 attrs: style_bits | (link_id << 8),
619 }
620}
621
622#[must_use]
623fn full_buffer_patch(buffer: &Buffer) -> WebPatchRun {
624 let cols = buffer.width();
625 let rows = buffer.height();
626 let total = usize::from(cols) * usize::from(rows);
627 let mut cells = Vec::with_capacity(total);
628 for y in 0..rows {
629 for x in 0..cols {
630 cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
631 }
632 }
633 WebPatchRun { offset: 0, cells }
634}
635
636#[must_use]
637fn diff_to_patches(buffer: &Buffer, diff: &BufferDiff) -> Vec<WebPatchRun> {
638 if diff.is_empty() {
639 return Vec::new();
640 }
641 let width = buffer.width();
642 let height = buffer.height();
643 let cols = u32::from(width);
644 let est_patches = diff.len().div_ceil(8).max(1);
646 let mut patches = Vec::with_capacity(est_patches);
647 let mut span_start: u32 = 0;
648 let mut span_cells: Vec<WebPatchCell> = Vec::with_capacity(diff.len());
649 let mut prev_offset: u32 = 0;
650 let mut has_span = false;
651
652 for &(x, y) in diff.changes() {
653 if x >= width || y >= height {
655 return vec![full_buffer_patch(buffer)];
656 }
657 let offset = u32::from(y) * cols + u32::from(x);
658 if !has_span {
659 span_start = offset;
660 prev_offset = offset;
661 has_span = true;
662 span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
663 continue;
664 }
665 if offset == prev_offset {
666 continue;
667 }
668 if offset == prev_offset + 1 {
669 span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
670 } else {
671 patches.push(WebPatchRun {
672 offset: span_start,
673 cells: std::mem::take(&mut span_cells),
674 });
675 span_start = offset;
676 span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
677 }
678 prev_offset = offset;
679 }
680 if !span_cells.is_empty() {
681 patches.push(WebPatchRun {
682 offset: span_start,
683 cells: span_cells,
684 });
685 }
686 patches
687}
688
689#[must_use]
690fn build_patch_runs(
691 buffer: &Buffer,
692 diff: Option<&BufferDiff>,
693 full_repaint_hint: bool,
694) -> Vec<WebPatchRun> {
695 if full_repaint_hint {
696 return vec![full_buffer_patch(buffer)];
697 }
698 match diff {
699 Some(dirty) => diff_to_patches(buffer, dirty),
700 None => vec![full_buffer_patch(buffer)],
701 }
702}
703
704#[must_use]
705fn patch_batch_stats(patches: &[WebPatchRun]) -> WebPatchStats {
706 let dirty_cells_u64 = patches
707 .iter()
708 .map(|patch| patch.cells.len() as u64)
709 .sum::<u64>();
710 let dirty_cells = dirty_cells_u64.min(u64::from(u32::MAX)) as u32;
711 let patch_count = patches.len().min(u32::MAX as usize) as u32;
712 let bytes_uploaded = dirty_cells_u64.saturating_mul(WEB_PATCH_CELL_BYTES);
713 WebPatchStats {
714 dirty_cells,
715 patch_count,
716 bytes_uploaded,
717 }
718}
719
720#[must_use]
721fn patch_batch_hash(patches: &[WebPatchRun]) -> String {
722 let mut hash = FNV64_OFFSET_BASIS;
723 let patch_count = u64::try_from(patches.len()).unwrap_or(u64::MAX);
724 hash = fnv1a64_extend(hash, &patch_count.to_le_bytes());
725
726 let mut cell_bytes = [0u8; 16];
729 for patch in patches {
730 let cell_count = u64::try_from(patch.cells.len()).unwrap_or(u64::MAX);
731 hash = fnv1a64_extend(hash, &patch.offset.to_le_bytes());
732 hash = fnv1a64_extend(hash, &cell_count.to_le_bytes());
733 for cell in &patch.cells {
734 cell_bytes[0..4].copy_from_slice(&cell.bg.to_le_bytes());
735 cell_bytes[4..8].copy_from_slice(&cell.fg.to_le_bytes());
736 cell_bytes[8..12].copy_from_slice(&cell.glyph.to_le_bytes());
737 cell_bytes[12..16].copy_from_slice(&cell.attrs.to_le_bytes());
738 hash = fnv1a64_extend(hash, &cell_bytes);
739 }
740 }
741
742 format!("{PATCH_HASH_ALGO}:{hash:016x}")
743}
744
745#[derive(Debug, Clone)]
752pub struct WebBackend {
753 clock: DeterministicClock,
754 events: WebEventSource,
755 presenter: WebPresenter,
756}
757
758impl WebBackend {
759 #[must_use]
761 pub fn new(width: u16, height: u16) -> Self {
762 Self {
763 clock: DeterministicClock::new(),
764 events: WebEventSource::new(width, height),
765 presenter: WebPresenter::with_size(width, height),
766 }
767 }
768
769 pub fn clock_mut(&mut self) -> &mut DeterministicClock {
771 &mut self.clock
772 }
773
774 pub fn events_mut(&mut self) -> &mut WebEventSource {
776 &mut self.events
777 }
778
779 #[must_use]
781 pub const fn presenter(&self) -> &WebPresenter {
782 &self.presenter
783 }
784
785 pub fn presenter_mut(&mut self) -> &mut WebPresenter {
787 &mut self.presenter
788 }
789}
790
791impl Backend for WebBackend {
792 type Error = WebBackendError;
793
794 type Clock = DeterministicClock;
795 type Events = WebEventSource;
796
797 fn clock(&self) -> &Self::Clock {
798 &self.clock
799 }
800
801 fn events(&mut self) -> &mut Self::Events {
802 &mut self.events
803 }
804}
805
806#[cfg(test)]
807mod tests {
808 use super::*;
809 use ftui_core::event::{
810 ClipboardEvent, ClipboardSource, ImeEvent, KeyCode, KeyEvent, PasteEvent,
811 };
812 use ftui_render::cell::Cell;
813
814 use pretty_assertions::assert_eq;
815
816 #[test]
817 fn deterministic_clock_advances_monotonically() {
818 let mut c = DeterministicClock::new();
819 assert_eq!(c.now_mono(), Duration::ZERO);
820
821 c.advance(Duration::from_millis(10));
822 assert_eq!(c.now_mono(), Duration::from_millis(10));
823
824 c.advance(Duration::from_millis(5));
825 assert_eq!(c.now_mono(), Duration::from_millis(15));
826
827 c.set(Duration::MAX);
829 c.advance(Duration::from_secs(1));
830 assert_eq!(c.now_mono(), Duration::MAX);
831 }
832
833 #[test]
834 fn web_event_source_fifo_queue() {
835 let mut ev = WebEventSource::new(80, 24);
836 assert_eq!(ev.size().unwrap(), (80, 24));
837 assert_eq!(ev.poll_event(Duration::from_millis(0)).unwrap(), false);
838
839 ev.push_event(Event::Tick).unwrap();
840 ev.push_event(Event::Resize {
841 width: 100,
842 height: 40,
843 })
844 .unwrap();
845
846 assert_eq!(ev.poll_event(Duration::from_millis(0)).unwrap(), true);
847 assert_eq!(ev.read_event().unwrap(), Some(Event::Tick));
848 assert_eq!(
849 ev.read_event().unwrap(),
850 Some(Event::Resize {
851 width: 100,
852 height: 40,
853 })
854 );
855 assert_eq!(ev.read_event().unwrap(), None);
856 }
857
858 #[test]
859 fn presenter_captures_logs_and_last_buffer() {
860 let mut p = WebPresenter::new();
861 p.write_log("hello").unwrap();
862 p.write_log("world").unwrap();
863
864 let buf = Buffer::new(2, 2);
865 p.present_ui(&buf, None, true).unwrap();
866
867 let mut outputs = p.take_outputs();
868 assert_eq!(outputs.logs, vec!["hello", "world"]);
869 assert_eq!(outputs.last_full_repaint_hint, true);
870 assert_eq!(outputs.last_buffer.as_ref().unwrap().width(), 2);
871 assert_eq!(outputs.last_patches.len(), 1);
872 let stats = outputs.last_patch_stats.expect("stats should be present");
873 assert_eq!(stats.patch_count, 1);
874 assert_eq!(stats.dirty_cells, 4);
875 assert_eq!(stats.bytes_uploaded, 64);
876 let hash = outputs
877 .compute_patch_hash()
878 .expect("hash should be present");
879 assert!(hash.starts_with("fnv1a64:"));
880 }
881
882 #[test]
883 fn presenter_emits_incremental_patch_runs_from_diff() {
884 let mut presenter = WebPresenter::new();
885 let old = Buffer::new(6, 2);
886 presenter.present_ui(&old, None, true).unwrap();
887
888 let mut next = Buffer::new(6, 2);
889 next.set_raw(2, 0, Cell::from_char('A'));
890 next.set_raw(3, 0, Cell::from_char('B'));
891 next.set_raw(0, 1, Cell::from_char('C'));
892 let diff = BufferDiff::compute(&old, &next);
893 presenter.present_ui(&next, Some(&diff), false).unwrap();
894
895 let mut outputs = presenter.take_outputs();
896 assert_eq!(outputs.last_full_repaint_hint, false);
897 assert_eq!(outputs.last_patches.len(), 2);
898 assert_eq!(outputs.last_patches[0].offset, 2);
899 assert_eq!(outputs.last_patches[0].cells.len(), 2);
900 assert_eq!(outputs.last_patches[1].offset, 6);
901 assert_eq!(outputs.last_patches[1].cells.len(), 1);
902 let stats = outputs.last_patch_stats.expect("stats should be present");
903 assert_eq!(stats.patch_count, 2);
904 assert_eq!(stats.dirty_cells, 3);
905 assert_eq!(stats.bytes_uploaded, 48);
906 let hash = outputs
907 .compute_patch_hash()
908 .expect("hash should be present");
909 assert!(hash.starts_with("fnv1a64:"));
910 }
911
912 #[test]
913 fn stale_diff_falls_back_to_full_patch() {
914 let old = Buffer::new(4, 2);
915 let mut next = Buffer::new(4, 2);
916 next.set_raw(3, 1, Cell::from_char('X'));
917 let stale_diff = BufferDiff::compute(&old, &next);
918
919 let resized = Buffer::new(2, 1);
920 let patches = build_patch_runs(&resized, Some(&stale_diff), false);
921
922 assert_eq!(patches.len(), 1);
923 assert_eq!(patches[0].offset, 0);
924 assert_eq!(patches[0].cells.len(), 2);
925 }
926
927 #[test]
928 fn patch_batch_hash_is_deterministic() {
929 let patches = vec![
930 WebPatchRun {
931 offset: 2,
932 cells: vec![
933 WebPatchCell {
934 bg: 0x1122_3344,
935 fg: 0x5566_7788,
936 glyph: 'A' as u32,
937 attrs: 0x0000_0001,
938 },
939 WebPatchCell {
940 bg: 0x1122_3344,
941 fg: 0x5566_7788,
942 glyph: 'B' as u32,
943 attrs: 0x0000_0002,
944 },
945 ],
946 },
947 WebPatchRun {
948 offset: 10,
949 cells: vec![WebPatchCell {
950 bg: 0xAABB_CCDD,
951 fg: 0xDDEE_FF00,
952 glyph: '中' as u32,
953 attrs: 0x0000_0010,
954 }],
955 },
956 ];
957
958 let hash_a = patch_batch_hash(&patches);
959 let hash_b = patch_batch_hash(&patches);
960 assert_eq!(hash_a, hash_b);
961 assert!(hash_a.starts_with("fnv1a64:"));
962 }
963
964 #[test]
965 fn patch_batch_hash_changes_with_patch_payload() {
966 let baseline = vec![WebPatchRun {
967 offset: 4,
968 cells: vec![WebPatchCell {
969 bg: 0x0000_00FF,
970 fg: 0xFFFF_FFFF,
971 glyph: 'x' as u32,
972 attrs: 0x0000_0001,
973 }],
974 }];
975 let mut changed = baseline.clone();
976 changed[0].offset = 5;
977
978 let base_hash = patch_batch_hash(&baseline);
979 let changed_hash = patch_batch_hash(&changed);
980 assert_ne!(base_hash, changed_hash);
981
982 changed[0].offset = 4;
983 changed[0].cells[0].glyph = 'y' as u32;
984 let changed_glyph_hash = patch_batch_hash(&changed);
985 assert_ne!(base_hash, changed_glyph_hash);
986 }
987
988 #[test]
989 fn flatten_patches_u32_emits_row_major_cells_and_spans() {
990 let outputs = WebOutputs {
991 last_patches: vec![
992 WebPatchRun {
993 offset: 2,
994 cells: vec![
995 WebPatchCell {
996 bg: 10,
997 fg: 11,
998 glyph: 12,
999 attrs: 13,
1000 },
1001 WebPatchCell {
1002 bg: 20,
1003 fg: 21,
1004 glyph: 22,
1005 attrs: 23,
1006 },
1007 ],
1008 },
1009 WebPatchRun {
1010 offset: 9,
1011 cells: vec![WebPatchCell {
1012 bg: 30,
1013 fg: 31,
1014 glyph: 32,
1015 attrs: 33,
1016 }],
1017 },
1018 ],
1019 ..WebOutputs::default()
1020 };
1021
1022 let flat = outputs.flatten_patches_u32();
1023 assert_eq!(flat.spans, vec![2, 2, 9, 1]);
1024 assert_eq!(
1025 flat.cells,
1026 vec![
1027 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33
1030 ]
1031 );
1032 }
1033
1034 #[test]
1035 fn flatten_patches_u32_handles_empty_payload() {
1036 let outputs = WebOutputs::default();
1037 let flat = outputs.flatten_patches_u32();
1038 assert!(flat.cells.is_empty());
1039 assert!(flat.spans.is_empty());
1040 }
1041
1042 #[test]
1045 fn web_backend_error_display() {
1046 let err = WebBackendError::Unsupported("test op");
1047 assert_eq!(format!("{err}"), "unsupported: test op");
1048 }
1049
1050 #[test]
1051 fn web_backend_error_is_std_error() {
1052 let err = WebBackendError::Unsupported("foo");
1053 let _: &dyn std::error::Error = &err;
1054 }
1055
1056 #[test]
1057 fn web_backend_error_eq() {
1058 assert_eq!(
1059 WebBackendError::Unsupported("a"),
1060 WebBackendError::Unsupported("a")
1061 );
1062 assert_ne!(
1063 WebBackendError::Unsupported("a"),
1064 WebBackendError::Unsupported("b")
1065 );
1066 }
1067
1068 #[test]
1071 fn clock_set_overrides_current() {
1072 let mut c = DeterministicClock::new();
1073 c.set(Duration::from_secs(42));
1074 assert_eq!(c.now_mono(), Duration::from_secs(42));
1075 }
1076
1077 #[test]
1078 fn clock_default_is_zero() {
1079 let c = DeterministicClock::default();
1080 assert_eq!(c.now_mono(), Duration::ZERO);
1081 }
1082
1083 #[test]
1084 fn clock_clone() {
1085 let mut c = DeterministicClock::new();
1086 c.advance(Duration::from_millis(100));
1087 let c2 = c.clone();
1088 assert_eq!(c2.now_mono(), Duration::from_millis(100));
1089 }
1090
1091 #[test]
1094 fn event_source_set_size() {
1095 let mut ev = WebEventSource::new(80, 24);
1096 ev.set_size(120, 50);
1097 assert_eq!(ev.size().unwrap(), (120, 50));
1098 }
1099
1100 #[test]
1101 fn event_source_drain_events() {
1102 let mut ev = WebEventSource::new(80, 24);
1103 ev.push_event(Event::Tick).unwrap();
1104 ev.push_event(Event::Tick).unwrap();
1105
1106 let drained: Vec<_> = ev.drain_events().collect();
1107 assert_eq!(drained.len(), 2);
1108 assert_eq!(ev.poll_event(Duration::ZERO).unwrap(), false);
1109 }
1110
1111 #[test]
1112 fn event_source_count_limit_preserves_every_accepted_event_and_retry_order() {
1113 let mut source = WebEventSource::new(80, 24);
1114 let accepted: Vec<_> = (0..WebEventSource::MAX_EVENTS)
1115 .map(|index| {
1116 Event::Key(KeyEvent::new(KeyCode::Char(
1117 char::from_u32(0x1000 + index as u32).unwrap(),
1118 )))
1119 })
1120 .collect();
1121 for event in &accepted {
1122 source.push_event(event.clone()).unwrap();
1123 }
1124 let tail = Event::Paste(PasteEvent::bracketed("rejected tail: 日本語 👩💻"));
1125 let error = source.push_event(tail.clone()).unwrap_err();
1126 assert_eq!(
1127 error,
1128 WebBackendError::InputQueueFull {
1129 limit: WebInputLimit::Events,
1130 event: tail.clone(),
1131 }
1132 );
1133 assert_eq!(source.queued_events(), WebEventSource::MAX_EVENTS);
1134 assert_eq!(source.queued_payload_bytes(), 0);
1135 assert_eq!(source.read_event().unwrap(), Some(accepted[0].clone()));
1136 let WebBackendError::InputQueueFull { event, .. } = error else {
1137 unreachable!();
1138 };
1139 source.push_event(event).unwrap();
1140 let delivered: Vec<_> = source.drain_events().collect();
1141 assert_eq!(&delivered[..delivered.len() - 1], &accepted[1..]);
1142 assert_eq!(delivered.last(), Some(&tail));
1143 assert_eq!(source.queued_events(), 0);
1144 assert_eq!(source.queued_payload_bytes(), 0);
1145 }
1146
1147 #[test]
1148 fn event_source_bounds_cumulative_paste_ime_and_clipboard_allocations() {
1149 let half = "x".repeat(WebEventSource::MAX_PAYLOAD_BYTES / 2);
1150 let events = [
1151 Event::Paste(PasteEvent::bracketed(half.clone())),
1152 Event::Ime(ImeEvent::commit(half.clone())),
1153 Event::Clipboard(ClipboardEvent::new(half, ClipboardSource::Osc52)),
1154 ];
1155 for event in events {
1156 let mut source = WebEventSource::new(80, 24);
1157 source.push_event(event.clone()).unwrap();
1158 source.push_event(event.clone()).unwrap();
1159 assert_eq!(
1160 source.queued_payload_bytes(),
1161 WebEventSource::MAX_PAYLOAD_BYTES
1162 );
1163 let error = source.push_event(event.clone()).unwrap_err();
1164 assert_eq!(
1165 error,
1166 WebBackendError::InputQueueFull {
1167 limit: WebInputLimit::PayloadBytes,
1168 event: event.clone(),
1169 }
1170 );
1171 source.push_event(Event::Focus(false)).unwrap();
1173 assert_eq!(source.read_event().unwrap(), Some(event.clone()));
1174 let WebBackendError::InputQueueFull { event: retry, .. } = error else {
1175 unreachable!();
1176 };
1177 source.push_event(retry).unwrap();
1178 assert_eq!(
1179 source.drain_events().collect::<Vec<_>>(),
1180 vec![event.clone(), Event::Focus(false), event]
1181 );
1182 assert_eq!(source.queued_payload_bytes(), 0);
1183 }
1184 }
1185
1186 #[test]
1187 fn event_source_rejects_oversized_allocation_without_retaining_or_logging_text() {
1188 let mut text = String::with_capacity(WebEventSource::MAX_PAYLOAD_BYTES + 1);
1189 text.push_str("private clipboard text");
1190 let event = Event::Clipboard(ClipboardEvent::new(text, ClipboardSource::Unknown));
1191 let allocation = event_payload_bytes(&event);
1192 let mut source = WebEventSource::new(80, 24);
1193 let error = source.push_event(event).unwrap_err();
1194 assert_eq!(
1195 error.to_string(),
1196 "input queue full (PayloadBytes); drain before retrying"
1197 );
1198 let WebBackendError::InputQueueFull { limit, event } = error else {
1199 unreachable!();
1200 };
1201 assert_eq!(limit, WebInputLimit::PayloadBytes);
1202 assert_eq!(event_payload_bytes(&event), allocation);
1203 assert_eq!(source.queued_events(), 0);
1204 assert_eq!(source.queued_payload_bytes(), 0);
1205 source.push_event(Event::Ime(ImeEvent::cancel())).unwrap();
1206 assert_eq!(
1207 source.read_event().unwrap(),
1208 Some(Event::Ime(ImeEvent::cancel()))
1209 );
1210 }
1211
1212 #[test]
1213 fn event_source_partial_drain_and_clone_account_for_actual_allocations() {
1214 let mut text = String::with_capacity(4096);
1215 text.push('中');
1216 let allocation = text.capacity();
1217 let mut source = WebEventSource::new(80, 24);
1218 source.push_event(Event::Tick).unwrap();
1219 source
1220 .push_event(Event::Paste(PasteEvent::bracketed(text)))
1221 .unwrap();
1222 {
1223 let mut drain = source.drain_events();
1224 assert_eq!(drain.next(), Some(Event::Tick));
1225 }
1226 assert_eq!(source.queued_events(), 1);
1227 assert_eq!(source.queued_payload_bytes(), allocation);
1228 let mut cloned = source.clone();
1229 let clone_bytes = cloned.queued_payload_bytes();
1230 let delivered = cloned.read_event().unwrap().unwrap();
1231 assert_eq!(clone_bytes, event_payload_bytes(&delivered));
1232 assert_eq!(delivered, Event::Paste(PasteEvent::bracketed("中")));
1233 assert_eq!(cloned.queued_payload_bytes(), 0);
1234 assert_eq!(source.queued_payload_bytes(), allocation);
1235 assert_eq!(source.read_event().unwrap(), Some(delivered));
1236 assert_eq!(source.queued_payload_bytes(), 0);
1237 }
1238
1239 #[test]
1240 fn event_source_features() {
1241 let mut ev = WebEventSource::new(80, 24);
1242 let f = BackendFeatures::default();
1243 ev.set_features(f).unwrap();
1244 let _ = ev.features(); }
1246
1247 #[test]
1248 fn event_source_empty_read_returns_none() {
1249 let mut ev = WebEventSource::new(80, 24);
1250 assert_eq!(ev.read_event().unwrap(), None);
1251 }
1252
1253 #[test]
1256 fn presenter_default_is_new() {
1257 let a = WebPresenter::new();
1258 let b = WebPresenter::default();
1259 assert!(a.outputs().logs.is_empty());
1260 assert!(b.outputs().logs.is_empty());
1261 }
1262
1263 #[test]
1264 fn presenter_outputs_accessor() {
1265 let mut p = WebPresenter::new();
1266 p.write_log("test").unwrap();
1267 assert_eq!(p.outputs().logs.len(), 1);
1268 }
1269
1270 #[test]
1271 fn presenter_outputs_mut() {
1272 let mut p = WebPresenter::new();
1273 p.outputs_mut().logs.push("manual".to_string());
1274 assert_eq!(p.outputs().logs, vec!["manual"]);
1275 }
1276
1277 #[test]
1278 fn presenter_take_outputs_clears() {
1279 let mut p = WebPresenter::new();
1280 p.write_log("a").unwrap();
1281 let taken = p.take_outputs();
1282 assert_eq!(taken.logs, vec!["a"]);
1283 assert!(p.outputs().logs.is_empty());
1284 }
1285
1286 #[test]
1287 fn presenter_capabilities_are_modern() {
1288 let p = WebPresenter::new();
1289 let caps = p.capabilities();
1290 assert!(caps.supports_true_color());
1291 }
1292
1293 #[test]
1294 fn presenter_present_ui_owned() {
1295 let mut p = WebPresenter::new();
1296 let buf = Buffer::new(3, 2);
1297 p.present_ui_owned(buf, None, true);
1298
1299 let mut out = p.take_outputs();
1300 assert!(out.last_full_repaint_hint);
1301 assert_eq!(out.last_buffer.as_ref().unwrap().width(), 3);
1302 assert_eq!(out.last_patches.len(), 1);
1303 assert!(out.last_patch_stats.is_some());
1304 assert!(out.compute_patch_hash().is_some());
1305 }
1306
1307 #[test]
1308 fn presenter_resize_and_screen_mode() {
1309 let mut p = WebPresenter::new();
1310 assert_eq!(p.screen_mode(), ScreenMode::default());
1311 p.set_screen_mode(ScreenMode::AltScreen);
1312 assert_eq!(p.screen_mode(), ScreenMode::AltScreen);
1313
1314 p.resize(100, 50);
1315 assert_eq!(p.width(), 100);
1316 assert_eq!(p.height(), 50);
1317 }
1318
1319 #[test]
1320 fn presenter_pool_and_links() {
1321 let mut p = WebPresenter::new();
1322 let (pool, links) = p.pool_and_links_mut();
1323 let id = pool.intern("hello", 1);
1324 let _link = links.register("https://example.com");
1325 assert_eq!(p.pool_mut().get(id), Some("hello"));
1326 }
1327
1328 #[test]
1331 fn web_backend_construction() {
1332 let mut wb = WebBackend::new(80, 24);
1333 assert_eq!(wb.events_mut().size().unwrap(), (80, 24));
1334 assert_eq!(wb.clock_mut().now_mono(), Duration::ZERO);
1335 }
1336
1337 #[test]
1338 fn web_backend_implements_backend_trait() {
1339 let mut wb = WebBackend::new(80, 24);
1340 let _ = wb.clock();
1342 let _ = wb.events();
1343 let _ = wb.presenter();
1344 }
1345
1346 #[test]
1349 fn patch_batch_stats_empty() {
1350 let stats = patch_batch_stats(&[]);
1351 assert_eq!(stats.dirty_cells, 0);
1352 assert_eq!(stats.patch_count, 0);
1353 assert_eq!(stats.bytes_uploaded, 0);
1354 }
1355
1356 #[test]
1357 fn patch_batch_stats_counts_cells() {
1358 let patches = vec![
1359 WebPatchRun {
1360 offset: 0,
1361 cells: vec![
1362 WebPatchCell {
1363 bg: 0,
1364 fg: 0,
1365 glyph: 0,
1366 attrs: 0,
1367 };
1368 3
1369 ],
1370 },
1371 WebPatchRun {
1372 offset: 10,
1373 cells: vec![WebPatchCell {
1374 bg: 0,
1375 fg: 0,
1376 glyph: 0,
1377 attrs: 0,
1378 }],
1379 },
1380 ];
1381 let stats = patch_batch_stats(&patches);
1382 assert_eq!(stats.dirty_cells, 4);
1383 assert_eq!(stats.patch_count, 2);
1384 assert_eq!(stats.bytes_uploaded, 64); }
1386
1387 #[test]
1390 fn patch_hash_empty_is_deterministic() {
1391 let a = patch_batch_hash(&[]);
1392 let b = patch_batch_hash(&[]);
1393 assert_eq!(a, b);
1394 assert!(a.starts_with("fnv1a64:"));
1395 }
1396
1397 #[test]
1400 fn build_patch_runs_full_repaint_hint() {
1401 let buf = Buffer::new(2, 2);
1402 let patches = build_patch_runs(&buf, None, true);
1403 assert_eq!(patches.len(), 1);
1404 assert_eq!(patches[0].offset, 0);
1405 assert_eq!(patches[0].cells.len(), 4);
1406 }
1407
1408 #[test]
1409 fn build_patch_runs_no_diff_triggers_full() {
1410 let buf = Buffer::new(3, 1);
1411 let patches = build_patch_runs(&buf, None, false);
1412 assert_eq!(patches.len(), 1);
1414 assert_eq!(patches[0].cells.len(), 3);
1415 }
1416
1417 #[test]
1420 fn web_outputs_default_is_empty() {
1421 let out = WebOutputs::default();
1422 assert!(out.logs.is_empty());
1423 assert!(out.last_buffer.is_none());
1424 assert!(out.last_patches.is_empty());
1425 assert!(out.last_patch_stats.is_none());
1426 assert!(out.last_patch_hash.is_none());
1427 assert!(!out.last_full_repaint_hint);
1428 }
1429
1430 #[test]
1433 fn cell_to_patch_empty_cell() {
1434 let cell = Cell::default();
1435 let patch = cell_to_patch(&cell);
1436 assert_eq!(patch.glyph, 0);
1438 }
1439
1440 #[test]
1441 fn cell_to_patch_ascii_char() {
1442 let cell = Cell::from_char('A');
1443 let patch = cell_to_patch(&cell);
1444 assert_eq!(patch.glyph, 'A' as u32);
1445 }
1446
1447 #[test]
1448 fn cell_to_patch_preserves_max_link_id() {
1449 use ftui_render::cell::{CellAttrs, StyleFlags};
1450
1451 let cell = Cell::from_char('L').with_attrs(CellAttrs::new(
1452 StyleFlags::UNDERLINE,
1453 CellAttrs::LINK_ID_MAX,
1454 ));
1455 let patch = cell_to_patch(&cell);
1456
1457 assert_eq!(patch.attrs >> 8, CellAttrs::LINK_ID_MAX);
1458 }
1459
1460 #[test]
1461 fn web_presenter_default_trait_methods_are_neutral() {
1462 let mut presenter = WebPresenter::default();
1463 BackendPresenter::resize(&mut presenter, 120, 40);
1464 assert_eq!(presenter.width, 120);
1465 assert_eq!(presenter.height, 40);
1466
1467 let mode = ScreenMode::Inline { ui_height: 8 };
1468 BackendPresenter::set_screen_mode(&mut presenter, mode);
1469 assert_eq!(BackendPresenter::screen_mode(&presenter), mode);
1470
1471 BackendPresenter::write_log(&mut presenter, "hello").unwrap();
1472 assert_eq!(presenter.outputs().logs, vec!["hello".to_string()]);
1473 }
1474}