envision 0.16.0

A ratatui framework for collaborative TUI development with headless testing support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! CaptureBackend implementation - the core of Envision.
//!
//! This module provides a ratatui `Backend` implementation that captures
//! all rendering operations for inspection, testing, and headless operation.

use std::collections::VecDeque;
use std::fmt;
use std::io;
use std::sync::Arc;

use ratatui::backend::{Backend, ClearType, WindowSize};
use ratatui::buffer::Cell;
use ratatui::layout::{Position, Size};

use super::cell::EnhancedCell;
use super::output::OutputFormat;

/// A backend that captures rendered frames for inspection and testing.
///
/// `CaptureBackend` implements ratatui's `Backend` trait, storing all rendering
/// operations in an internal buffer that can be inspected, serialized, or
/// converted to various output formats.
///
/// # Features
///
/// - **Frame capture**: All rendering is captured in an inspectable buffer
/// - **History tracking**: Optionally track multiple frames for diff analysis
/// - **Multiple output formats**: Plain text, ANSI colored, JSON, annotated
/// - **Full serialization**: State can be serialized for snapshots
///
/// # Example
///
/// ```rust
/// use envision::backend::CaptureBackend;
/// use ratatui::Terminal;
/// use ratatui::widgets::Paragraph;
///
/// let backend = CaptureBackend::new(80, 24);
/// let mut terminal = Terminal::new(backend).unwrap();
///
/// terminal.draw(|frame| {
///     frame.render_widget(Paragraph::new("Hello!"), frame.area());
/// }).unwrap();
///
/// // Get plain text output
/// println!("{}", terminal.backend());
///
/// // Get with colors (ANSI)
/// println!("{}", terminal.backend().to_ansi());
/// ```
#[derive(Clone, Debug)]
pub struct CaptureBackend {
    /// The captured cells
    cells: Vec<EnhancedCell>,

    /// Width of the terminal
    width: u16,

    /// Height of the terminal
    height: u16,

    /// Current cursor position
    cursor_position: Position,

    /// Whether the cursor is visible
    cursor_visible: bool,

    /// Current frame number (incremented on each flush)
    current_frame: u64,

    /// History of frame snapshots (if enabled)
    history: VecDeque<FrameSnapshot>,

    /// Maximum history size (0 = disabled)
    history_capacity: usize,
}

/// A snapshot of a single frame's state.
///
/// This captures the complete state of the backend at a point in time,
/// useful for comparing frames or serializing for testing.
///
/// Uses `Arc<[EnhancedCell]>` for copy-on-write semantics - snapshots
/// share cell data until mutation is needed, avoiding expensive clones.
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct FrameSnapshot {
    /// The frame number
    pub frame: u64,

    /// Terminal dimensions
    pub size: (u16, u16),

    /// Cursor state
    pub cursor: CursorSnapshot,

    /// All cells in the buffer (shared via Arc for efficient cloning)
    #[cfg_attr(
        feature = "serialization",
        serde(serialize_with = "serialize_arc_cells")
    )]
    #[cfg_attr(
        feature = "serialization",
        serde(deserialize_with = "deserialize_arc_cells")
    )]
    cells: Arc<[EnhancedCell]>,
}

/// Serialize Arc<[EnhancedCell]> as a regular slice
#[cfg(feature = "serialization")]
fn serialize_arc_cells<S>(cells: &Arc<[EnhancedCell]>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    use serde::ser::SerializeSeq;
    let mut seq = serializer.serialize_seq(Some(cells.len()))?;
    for cell in cells.iter() {
        seq.serialize_element(cell)?;
    }
    seq.end()
}

/// Deserialize into Arc<[EnhancedCell]>
#[cfg(feature = "serialization")]
fn deserialize_arc_cells<'de, D>(deserializer: D) -> Result<Arc<[EnhancedCell]>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    let vec = Vec::<EnhancedCell>::deserialize(deserializer)?;
    Ok(Arc::from(vec))
}

/// Snapshot of cursor state
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct CursorSnapshot {
    pub position: (u16, u16),
    pub visible: bool,
}

impl FrameSnapshot {
    /// Returns the cells as a slice.
    pub fn cells(&self) -> &[EnhancedCell] {
        &self.cells
    }

    /// Returns the content of a specific row as a string.
    pub fn row_content(&self, y: u16) -> String {
        if y >= self.size.1 {
            return String::new();
        }

        let start = (y as usize) * (self.size.0 as usize);
        let end = start + self.size.0 as usize;
        if end <= self.cells.len() {
            self.cells[start..end].iter().map(|c| c.symbol()).collect()
        } else {
            String::new()
        }
    }

    /// Renders the snapshot as plain text.
    pub fn to_plain(&self) -> String {
        let mut lines = Vec::with_capacity(self.size.1 as usize);
        for y in 0..self.size.1 {
            lines.push(self.row_content(y));
        }
        lines.join("\n")
    }

    /// Renders the snapshot with ANSI color codes.
    pub fn to_ansi(&self) -> String {
        use crate::backend::cell::SerializableColor;

        let mut output = String::new();

        for y in 0..self.size.1 {
            let start = (y as usize) * (self.size.0 as usize);
            let end = start + self.size.0 as usize;

            if end <= self.cells.len() {
                for cell in &self.cells[start..end] {
                    // Apply foreground color
                    if cell.fg != SerializableColor::Reset {
                        output.push_str(&cell.fg.to_ansi_fg());
                    }

                    // Apply background color
                    if cell.bg != SerializableColor::Reset {
                        output.push_str(&cell.bg.to_ansi_bg());
                    }

                    // Apply modifiers
                    output.push_str(&cell.modifiers.to_ansi());

                    // Write the symbol
                    output.push_str(cell.symbol());

                    // Reset if we had any styling
                    if cell.fg != SerializableColor::Reset
                        || cell.bg != SerializableColor::Reset
                        || !cell.modifiers.is_empty()
                    {
                        output.push_str("\x1b[0m");
                    }
                }
            }

            if y + 1 < self.size.1 {
                output.push('\n');
            }
        }

        output
    }

    /// Returns true if the snapshot contains the given text.
    pub fn contains_text(&self, needle: &str) -> bool {
        for y in 0..self.size.1 {
            if self.row_content(y).contains(needle) {
                return true;
            }
        }
        false
    }
}

impl CaptureBackend {
    /// Creates a new CaptureBackend with the specified dimensions.
    pub fn new(width: u16, height: u16) -> Self {
        let size = (width as usize) * (height as usize);
        Self {
            cells: vec![EnhancedCell::new(); size],
            width,
            height,
            cursor_position: Position::new(0, 0),
            cursor_visible: true,
            current_frame: 0,
            history: VecDeque::new(),
            history_capacity: 0,
        }
    }

    /// Creates a new CaptureBackend with history tracking enabled.
    ///
    /// # Arguments
    ///
    /// * `width` - Terminal width in columns
    /// * `height` - Terminal height in rows
    /// * `history_capacity` - Maximum number of frames to keep in history
    pub fn with_history(width: u16, height: u16, history_capacity: usize) -> Self {
        let mut backend = Self::new(width, height);
        backend.history_capacity = history_capacity;
        backend.history = VecDeque::with_capacity(history_capacity);
        backend
    }

    /// Returns the current frame number.
    pub fn current_frame(&self) -> u64 {
        self.current_frame
    }

    /// Returns the cell at the given position, if valid.
    pub fn cell(&self, x: u16, y: u16) -> Option<&EnhancedCell> {
        if x < self.width && y < self.height {
            Some(&self.cells[self.index_of(x, y)])
        } else {
            None
        }
    }

    /// Returns a mutable reference to the cell at the given position.
    pub fn cell_mut(&mut self, x: u16, y: u16) -> Option<&mut EnhancedCell> {
        if x < self.width && y < self.height {
            let idx = self.index_of(x, y);
            Some(&mut self.cells[idx])
        } else {
            None
        }
    }

    /// Returns all cells as a slice.
    pub fn cells(&self) -> &[EnhancedCell] {
        &self.cells
    }

    /// Returns the content of a specific row as a string.
    pub fn row_content(&self, y: u16) -> String {
        if y >= self.height {
            return String::new();
        }

        let start = self.index_of(0, y);
        let end = start + self.width as usize;
        self.cells[start..end].iter().map(|c| c.symbol()).collect()
    }

    /// Returns all content as a vector of row strings.
    pub fn content_lines(&self) -> Vec<String> {
        (0..self.height).map(|y| self.row_content(y)).collect()
    }

    /// Searches for text in the buffer and returns positions where it appears.
    pub fn find_text(&self, needle: &str) -> Vec<Position> {
        let mut positions = Vec::new();
        for y in 0..self.height {
            let row = self.row_content(y);
            for (x, _) in row.match_indices(needle) {
                positions.push(Position::new(x as u16, y));
            }
        }
        positions
    }

    /// Returns true if the buffer contains the given text.
    pub fn contains_text(&self, needle: &str) -> bool {
        !self.find_text(needle).is_empty()
    }

    /// Creates a snapshot of the current state.
    pub fn snapshot(&self) -> FrameSnapshot {
        FrameSnapshot {
            frame: self.current_frame,
            size: (self.width, self.height),
            cursor: CursorSnapshot {
                position: (self.cursor_position.x, self.cursor_position.y),
                visible: self.cursor_visible,
            },
            cells: Arc::from(self.cells.as_slice()),
        }
    }

    /// Returns the frame history (if history tracking is enabled).
    pub fn history(&self) -> &VecDeque<FrameSnapshot> {
        &self.history
    }

    /// Computes the diff between the current frame and the previous one.
    pub fn diff_from_previous(&self) -> Option<FrameDiff> {
        self.history.back().map(|prev| self.diff_from(prev))
    }

    /// Computes the diff between the current state and a snapshot.
    pub fn diff_from(&self, previous: &FrameSnapshot) -> FrameDiff {
        let mut changed_cells = Vec::new();

        for y in 0..self.height.min(previous.size.1) {
            for x in 0..self.width.min(previous.size.0) {
                let idx = self.index_of(x, y);
                let prev_idx = (y as usize) * (previous.size.0 as usize) + (x as usize);

                if idx < self.cells.len() && prev_idx < previous.cells.len() {
                    let current = &self.cells[idx];
                    let prev = &previous.cells[prev_idx];

                    if current != prev {
                        changed_cells.push(CellChange {
                            position: (x, y),
                            old: prev.clone(),
                            new: current.clone(),
                        });
                    }
                }
            }
        }

        FrameDiff {
            from_frame: previous.frame,
            to_frame: self.current_frame,
            changed_cells,
            size_changed: (self.width, self.height) != previous.size,
            cursor_moved: (self.cursor_position.x, self.cursor_position.y)
                != previous.cursor.position,
        }
    }

    /// Renders the buffer to a string using the specified format.
    pub fn render(&self, format: OutputFormat) -> String {
        format.render(self)
    }

    /// Renders the buffer with ANSI color codes.
    pub fn to_ansi(&self) -> String {
        self.render(OutputFormat::Ansi)
    }

    /// Creates an [`AnnotatedOutput`] combining the visual text and structured annotations.
    ///
    /// This pairs the plain text representation of the current buffer with
    /// the annotation data collected during rendering.
    ///
    /// # Arguments
    ///
    /// * `registry` - The annotation registry populated during rendering
    ///   (typically obtained via [`with_annotations`]).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::annotation::{Annotate, Annotation, with_annotations};
    /// use envision::backend::CaptureBackend;
    /// use ratatui::Terminal;
    /// use ratatui::widgets::Paragraph;
    ///
    /// let backend = CaptureBackend::new(80, 24);
    /// let mut terminal = Terminal::new(backend).unwrap();
    ///
    /// let registry = with_annotations(|| {
    ///     terminal.draw(|frame| {
    ///         let widget = Annotate::new(
    ///             Paragraph::new("Submit"),
    ///             Annotation::button("submit").with_label("Submit Order"),
    ///         );
    ///         frame.render_widget(widget, frame.area());
    ///     }).unwrap();
    /// });
    ///
    /// let output = terminal.backend().to_annotated_output(&registry);
    /// assert!(output.visual.contains("Submit"));
    /// assert_eq!(output.annotation_count(), 1);
    /// assert_eq!(output.find_by_id("submit").unwrap().widget_type, "Button");
    /// ```
    ///
    /// [`AnnotatedOutput`]: crate::annotation::AnnotatedOutput
    /// [`with_annotations`]: crate::annotation::with_annotations
    pub fn to_annotated_output(
        &self,
        registry: &crate::annotation::AnnotationRegistry,
    ) -> crate::annotation::AnnotatedOutput {
        crate::annotation::AnnotatedOutput::from_backend_and_registry(self, registry)
    }

    /// Serializes the annotation registry contents as a pretty-printed JSON string.
    ///
    /// This produces structured semantic data about the widgets rendered
    /// in the current frame, suitable for AI consumption or automated
    /// analysis. The output includes both the visual text and annotation
    /// metadata in a single JSON document.
    ///
    /// # Arguments
    ///
    /// * `registry` - The annotation registry populated during rendering
    ///   (typically obtained via [`with_annotations`]).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::annotation::{Annotate, Annotation, with_annotations};
    /// use envision::backend::CaptureBackend;
    /// use ratatui::Terminal;
    /// use ratatui::widgets::Paragraph;
    ///
    /// let backend = CaptureBackend::new(80, 24);
    /// let mut terminal = Terminal::new(backend).unwrap();
    ///
    /// let registry = with_annotations(|| {
    ///     terminal.draw(|frame| {
    ///         let widget = Annotate::new(
    ///             Paragraph::new("Hello"),
    ///             Annotation::button("btn"),
    ///         );
    ///         frame.render_widget(widget, frame.area());
    ///     }).unwrap();
    /// });
    ///
    /// let json = terminal.backend().to_semantic_json(&registry);
    /// assert!(json.contains("Button"));
    /// assert!(json.contains("btn"));
    /// ```
    ///
    /// [`with_annotations`]: crate::annotation::with_annotations
    #[cfg(feature = "serialization")]
    pub fn to_semantic_json(&self, registry: &crate::annotation::AnnotationRegistry) -> String {
        let output = self.to_annotated_output(registry);
        serde_json::to_string_pretty(&output)
            .unwrap_or_else(|e| format!("{{\"error\": \"serialization failed: {}\"}}", e))
    }

    /// Renders the buffer as JSON.
    #[cfg(feature = "serialization")]
    pub fn to_json(&self) -> String {
        self.render(OutputFormat::Json)
    }

    /// Renders the buffer as JSON (pretty-printed).
    #[cfg(feature = "serialization")]
    pub fn to_json_pretty(&self) -> String {
        self.render(OutputFormat::JsonPretty)
    }

    /// Converts (x, y) coordinates to a linear index.
    fn index_of(&self, x: u16, y: u16) -> usize {
        (y as usize) * (self.width as usize) + (x as usize)
    }

    /// Saves the current state to history (if enabled).
    fn save_to_history(&mut self) {
        if self.history_capacity > 0 {
            if self.history.len() >= self.history_capacity {
                self.history.pop_front();
            }
            self.history.push_back(self.snapshot());
        }
    }

    /// Returns the width of the terminal.
    pub fn width(&self) -> u16 {
        self.width
    }

    /// Returns the height of the terminal.
    pub fn height(&self) -> u16 {
        self.height
    }

    /// Returns whether the cursor is currently visible.
    pub fn is_cursor_visible(&self) -> bool {
        self.cursor_visible
    }

    /// Returns the current cursor position.
    pub fn cursor_position(&self) -> Position {
        self.cursor_position
    }
}

impl Backend for CaptureBackend {
    fn draw<'a, I>(&mut self, content: I) -> io::Result<()>
    where
        I: Iterator<Item = (u16, u16, &'a Cell)>,
    {
        for (x, y, cell) in content {
            if x < self.width && y < self.height {
                let idx = self.index_of(x, y);
                self.cells[idx] = EnhancedCell::from_ratatui_cell(cell, self.current_frame);
            }
        }
        Ok(())
    }

    fn hide_cursor(&mut self) -> io::Result<()> {
        self.cursor_visible = false;
        Ok(())
    }

    fn show_cursor(&mut self) -> io::Result<()> {
        self.cursor_visible = true;
        Ok(())
    }

    fn get_cursor_position(&mut self) -> io::Result<Position> {
        Ok(self.cursor_position)
    }

    fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> io::Result<()> {
        self.cursor_position = position.into();
        Ok(())
    }

    fn clear(&mut self) -> io::Result<()> {
        for cell in &mut self.cells {
            cell.reset();
        }
        Ok(())
    }

    fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {
        let cells_len = self.cells.len();
        let (start, end) = match clear_type {
            ClearType::All => (0, cells_len),
            ClearType::AfterCursor => {
                let start = self.index_of(self.cursor_position.x, self.cursor_position.y);
                (start, cells_len)
            }
            ClearType::BeforeCursor => {
                let end = self.index_of(self.cursor_position.x, self.cursor_position.y);
                (0, end)
            }
            ClearType::CurrentLine => {
                let start = self.index_of(0, self.cursor_position.y);
                let end = start + self.width as usize;
                (start, end)
            }
            ClearType::UntilNewLine => {
                let start = self.index_of(self.cursor_position.x, self.cursor_position.y);
                let end = self.index_of(0, self.cursor_position.y) + self.width as usize;
                (start, end)
            }
        };

        let end = end.min(cells_len);
        for cell in &mut self.cells[start..end] {
            cell.reset();
        }
        Ok(())
    }

    fn size(&self) -> io::Result<Size> {
        Ok(Size::new(self.width, self.height))
    }

    fn window_size(&mut self) -> io::Result<WindowSize> {
        // For a capture backend, we don't have real pixel dimensions
        // Use reasonable defaults (assuming ~8x16 pixels per cell)
        Ok(WindowSize {
            columns_rows: Size::new(self.width, self.height),
            pixels: Size::new(self.width * 8, self.height * 16),
        })
    }

    fn flush(&mut self) -> io::Result<()> {
        self.save_to_history();
        self.current_frame += 1;
        Ok(())
    }
}

impl fmt::Display for CaptureBackend {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.render(OutputFormat::Plain))
    }
}

/// Represents the difference between two frames.
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct FrameDiff {
    /// Frame number of the previous state
    pub from_frame: u64,

    /// Frame number of the current state
    pub to_frame: u64,

    /// Cells that changed between frames
    pub changed_cells: Vec<CellChange>,

    /// Whether the terminal size changed
    pub size_changed: bool,

    /// Whether the cursor moved
    pub cursor_moved: bool,
}

impl FrameDiff {
    /// Returns true if there are any changes.
    pub fn has_changes(&self) -> bool {
        !self.changed_cells.is_empty() || self.size_changed || self.cursor_moved
    }

    /// Returns the number of cells that changed.
    pub fn changed_count(&self) -> usize {
        self.changed_cells.len()
    }
}

impl fmt::Display for FrameDiff {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Frame {}{} changes:", self.from_frame, self.to_frame)?;

        if self.size_changed {
            writeln!(f, "  [Size changed]")?;
        }
        if self.cursor_moved {
            writeln!(f, "  [Cursor moved]")?;
        }

        for change in &self.changed_cells {
            writeln!(
                f,
                "  ({},{}) \"{}\"\"{}\"",
                change.position.0,
                change.position.1,
                change.old.symbol(),
                change.new.symbol()
            )?;
        }

        Ok(())
    }
}

/// A single cell change in a diff.
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct CellChange {
    /// Position of the changed cell
    pub position: (u16, u16),

    /// Previous cell state
    pub old: EnhancedCell,

    /// New cell state
    pub new: EnhancedCell,
}

#[cfg(test)]
mod tests;