Skip to main content

hyprstream_core/tui/
state.rs

1//! Core types for the TUI display server state.
2//!
3//! The state hierarchy is: `TuiState` → `TuiSession` → `TuiWindow` → `TuiPane`.
4//! Each pane owns a ratatui `Buffer` for cell storage and tracks damage via bitmask.
5
6use std::collections::VecDeque;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use ratatui::buffer::{Buffer, Cell};
10use tokio::sync::broadcast;
11
12// ============================================================================
13// Cursor
14// ============================================================================
15
16/// Cursor shape (matches DEC private mode sequences).
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum CursorShape {
19    #[default]
20    Block,
21    Underline,
22    Bar,
23    BlinkingBlock,
24    BlinkingUnderline,
25    BlinkingBar,
26}
27
28/// Cursor state for a pane.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct CursorState {
31    pub x: u16,
32    pub y: u16,
33    pub visible: bool,
34    pub shape: CursorShape,
35}
36
37impl Default for CursorState {
38    fn default() -> Self {
39        Self {
40            x: 0,
41            y: 0,
42            visible: true,
43            shape: CursorShape::default(),
44        }
45    }
46}
47
48// ============================================================================
49// Scroll Operations
50// ============================================================================
51
52/// A scroll operation recorded for incremental diff encoding.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct ScrollOp {
55    /// Top row of scroll region (inclusive, 0-indexed).
56    pub top: u16,
57    /// Bottom row of scroll region (inclusive, 0-indexed).
58    pub bottom: u16,
59    /// Positive = scroll up, negative = scroll down.
60    pub amount: i16,
61}
62
63// ============================================================================
64// Pane Buffer
65// ============================================================================
66
67/// A pane's cell buffer with damage tracking.
68///
69/// Wraps a ratatui `Buffer` and tracks which rows have been modified since
70/// the last frame was sent. Uses a `u128` bitmask for rows 0–127; if the
71/// pane has more than 128 rows, `force_full_frame` is set instead.
72pub struct PaneBuffer {
73    /// The cell buffer.
74    pub buffer: Buffer,
75    /// Bitmask of dirty rows (bit N = row N is dirty). Rows ≥128 set `force_full_frame`.
76    pub damage_rows: u128,
77    /// Scroll operations since last frame (capped at 256).
78    pub scroll_log: Vec<ScrollOp>,
79    /// If true, next frame must be a full frame (resize, alt screen switch, etc.).
80    pub force_full_frame: bool,
81}
82
83impl PaneBuffer {
84    /// Create a new buffer with the given dimensions.
85    pub fn new(cols: u16, rows: u16) -> Self {
86        Self {
87            buffer: Buffer::empty(ratatui::layout::Rect::new(0, 0, cols, rows)),
88            damage_rows: 0,
89            scroll_log: Vec::new(),
90            force_full_frame: true, // First frame is always full
91        }
92    }
93
94    /// Mark a row as dirty.
95    #[inline]
96    pub fn mark_dirty(&mut self, row: u16) {
97        if row < 128 {
98            self.damage_rows |= 1u128 << row;
99        } else {
100            self.force_full_frame = true;
101        }
102    }
103
104    /// Mark all rows as dirty.
105    pub fn mark_all_dirty(&mut self) {
106        self.damage_rows = u128::MAX;
107    }
108
109    /// Check if a row is dirty.
110    #[inline]
111    pub fn is_row_dirty(&self, row: u16) -> bool {
112        if row < 128 {
113            (self.damage_rows >> row) & 1 != 0
114        } else {
115            self.force_full_frame
116        }
117    }
118
119    /// Count dirty rows.
120    pub fn dirty_count(&self) -> u32 {
121        self.damage_rows.count_ones()
122    }
123
124    /// Clear damage tracking (called after frame is sent).
125    pub fn clear_damage(&mut self) {
126        self.damage_rows = 0;
127        self.scroll_log.clear();
128        self.force_full_frame = false;
129    }
130
131    /// Record a scroll operation.
132    pub fn record_scroll(&mut self, op: ScrollOp) {
133        if self.scroll_log.len() < 256 {
134            self.scroll_log.push(op);
135        } else {
136            // Too many scrolls — force full frame
137            self.force_full_frame = true;
138        }
139    }
140
141    /// Resize the buffer. Sets `force_full_frame`.
142    pub fn resize(&mut self, cols: u16, rows: u16) {
143        self.buffer
144            .resize(ratatui::layout::Rect::new(0, 0, cols, rows));
145        self.force_full_frame = true;
146        self.damage_rows = 0;
147        self.scroll_log.clear();
148    }
149
150    /// Get a cell by position.
151    pub fn cell(&self, x: u16, y: u16) -> Option<&Cell> {
152        let area = self.buffer.area();
153        if x < area.width && y < area.height {
154            Some(&self.buffer[(x, y)])
155        } else {
156            None
157        }
158    }
159}
160
161// ============================================================================
162// Ingestion Mode
163// ============================================================================
164
165/// How a pane receives content.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
167pub enum IngestionMode {
168    /// Direct ratatui Backend writes (TuiPaneBackend).
169    #[default]
170    Direct,
171    /// ANSI escape sequences parsed by VTE.
172    Ansi,
173    /// Packed binary cells from StructuredBackend.
174    Structured,
175}
176
177// ============================================================================
178// Pane Backend
179// ============================================================================
180
181/// How the server manages a pane's content.
182///
183/// Separate from [`PaneSource`](hyprstream_compositor::PaneSource) in the
184/// compositor crate — that type describes the *client-side* source, while this
185/// describes the *server-side* backend.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
187pub enum PaneBackend {
188    /// Server owns the PTY / process (default).
189    #[default]
190    Managed,
191    /// Content is owned by the client; server publishes a `[PRIVATE]`
192    /// placeholder frame to other viewers instead of real cell data.
193    Private,
194}
195
196// ============================================================================
197// TUI Pane
198// ============================================================================
199
200/// A single terminal pane with primary and alternate screen buffers.
201pub struct TuiPane {
202    /// Pane identifier (unique within a window).
203    pub id: u32,
204    /// Primary screen buffer.
205    pub primary: PaneBuffer,
206    /// Alternate screen buffer (lazy-allocated on `?1049h`).
207    pub alternate: Option<PaneBuffer>,
208    /// Which buffer is currently active (false = primary, true = alternate).
209    pub using_alternate: bool,
210    /// Scrollback history (lines that scrolled off the top of primary).
211    pub scrollback: VecDeque<Vec<Cell>>,
212    /// Maximum scrollback lines.
213    pub max_scrollback: usize,
214    /// Cursor state.
215    pub cursor: CursorState,
216    /// How this pane receives content.
217    pub ingestion_mode: IngestionMode,
218    /// Pane title (set via OSC 0/2).
219    pub title: String,
220    /// Server-side backend classification (managed vs. private).
221    pub backend: PaneBackend,
222}
223
224impl TuiPane {
225    /// Create a new pane.
226    pub fn new(id: u32, cols: u16, rows: u16, max_scrollback: usize) -> Self {
227        Self {
228            id,
229            primary: PaneBuffer::new(cols, rows),
230            alternate: None,
231            using_alternate: false,
232            scrollback: VecDeque::new(),
233            max_scrollback,
234            cursor: CursorState::default(),
235            ingestion_mode: IngestionMode::default(),
236            title: String::new(),
237            backend: PaneBackend::default(),
238        }
239    }
240
241    /// Get the active buffer.
242    pub fn active_buffer(&self) -> &PaneBuffer {
243        if self.using_alternate {
244            self.alternate.as_ref().unwrap_or(&self.primary)
245        } else {
246            &self.primary
247        }
248    }
249
250    /// Get the active buffer mutably.
251    pub fn active_buffer_mut(&mut self) -> &mut PaneBuffer {
252        if self.using_alternate {
253            self.alternate.as_mut().unwrap_or(&mut self.primary)
254        } else {
255            &mut self.primary
256        }
257    }
258
259    /// Get terminal dimensions (from active buffer).
260    pub fn size(&self) -> (u16, u16) {
261        let area = self.active_buffer().buffer.area();
262        (area.width, area.height)
263    }
264
265    /// Switch to alternate screen buffer (`\x1b[?1049h`).
266    pub fn enter_alternate_screen(&mut self) {
267        if !self.using_alternate {
268            let (cols, rows) = self.size();
269            self.alternate
270                .get_or_insert_with(|| PaneBuffer::new(cols, rows));
271            self.using_alternate = true;
272            // Force full frame on screen switch
273            if let Some(alt) = &mut self.alternate {
274                alt.force_full_frame = true;
275            }
276        }
277    }
278
279    /// Switch back to primary screen buffer (`\x1b[?1049l`).
280    pub fn leave_alternate_screen(&mut self) {
281        if self.using_alternate {
282            self.using_alternate = false;
283            self.primary.force_full_frame = true;
284        }
285    }
286
287    /// Resize this pane.
288    pub fn resize(&mut self, cols: u16, rows: u16) {
289        self.primary.resize(cols, rows);
290        if let Some(alt) = &mut self.alternate {
291            alt.resize(cols, rows);
292        }
293    }
294
295    /// Push a line to scrollback (when content scrolls off the top).
296    pub fn push_scrollback(&mut self, line: Vec<Cell>) {
297        if self.scrollback.len() >= self.max_scrollback {
298            self.scrollback.pop_front();
299        }
300        self.scrollback.push_back(line);
301    }
302}
303
304// ============================================================================
305// Layout
306// ============================================================================
307
308/// Layout tree node for window pane arrangement.
309#[derive(Debug, Clone)]
310pub enum LayoutNode {
311    /// A leaf pane.
312    Leaf { pane_id: u32 },
313    /// Horizontal split (top/bottom).
314    HSplit {
315        ratio: f32,
316        first: Box<LayoutNode>,
317        second: Box<LayoutNode>,
318    },
319    /// Vertical split (left/right).
320    VSplit {
321        ratio: f32,
322        first: Box<LayoutNode>,
323        second: Box<LayoutNode>,
324    },
325}
326
327impl LayoutNode {
328    /// Collect all pane IDs in this layout tree.
329    pub fn pane_ids(&self) -> Vec<u32> {
330        match self {
331            LayoutNode::Leaf { pane_id } => vec![*pane_id],
332            LayoutNode::HSplit { first, second, .. } | LayoutNode::VSplit { first, second, .. } => {
333                let mut ids = first.pane_ids();
334                ids.extend(second.pane_ids());
335                ids
336            }
337        }
338    }
339
340    /// Remove a pane from the layout tree, collapsing its parent split.
341    /// Returns the pruned tree, or None if the tree is now empty.
342    pub fn prune(&self, target_pane_id: u32) -> Option<LayoutNode> {
343        match self {
344            LayoutNode::Leaf { pane_id } => {
345                if *pane_id == target_pane_id {
346                    None
347                } else {
348                    Some(self.clone())
349                }
350            }
351            LayoutNode::HSplit {
352                ratio,
353                first,
354                second,
355            } => {
356                let f = first.prune(target_pane_id);
357                let s = second.prune(target_pane_id);
358                match (f, s) {
359                    (Some(f), Some(s)) => Some(LayoutNode::HSplit {
360                        ratio: *ratio,
361                        first: Box::new(f),
362                        second: Box::new(s),
363                    }),
364                    (Some(node), None) | (None, Some(node)) => Some(node),
365                    (None, None) => None,
366                }
367            }
368            LayoutNode::VSplit {
369                ratio,
370                first,
371                second,
372            } => {
373                let f = first.prune(target_pane_id);
374                let s = second.prune(target_pane_id);
375                match (f, s) {
376                    (Some(f), Some(s)) => Some(LayoutNode::VSplit {
377                        ratio: *ratio,
378                        first: Box::new(f),
379                        second: Box::new(s),
380                    }),
381                    (Some(node), None) | (None, Some(node)) => Some(node),
382                    (None, None) => None,
383                }
384            }
385        }
386    }
387}
388
389// ============================================================================
390// Window
391// ============================================================================
392
393/// A window containing one or more panes in a layout tree.
394pub struct TuiWindow {
395    /// Window identifier.
396    pub id: u32,
397    /// Window name/title.
398    pub name: String,
399    /// Layout tree.
400    pub layout: LayoutNode,
401    /// All panes in this window.
402    pub panes: Vec<TuiPane>,
403    /// Currently focused pane ID.
404    pub active_pane_id: u32,
405}
406
407impl TuiWindow {
408    /// Create a new window with a single pane.
409    pub fn new(id: u32, pane_id: u32, cols: u16, rows: u16, max_scrollback: usize) -> Self {
410        let pane = TuiPane::new(pane_id, cols, rows, max_scrollback);
411        Self {
412            id,
413            name: format!("window-{}", id),
414            layout: LayoutNode::Leaf { pane_id },
415            panes: vec![pane],
416            active_pane_id: pane_id,
417        }
418    }
419
420    /// Find a pane by ID.
421    pub fn pane(&self, pane_id: u32) -> Option<&TuiPane> {
422        self.panes.iter().find(|p| p.id == pane_id)
423    }
424
425    /// Find a pane by ID mutably.
426    pub fn pane_mut(&mut self, pane_id: u32) -> Option<&mut TuiPane> {
427        self.panes.iter_mut().find(|p| p.id == pane_id)
428    }
429
430    /// Get the active pane.
431    pub fn active_pane(&self) -> Option<&TuiPane> {
432        self.pane(self.active_pane_id)
433    }
434
435    /// Get the active pane mutably.
436    pub fn active_pane_mut(&mut self) -> Option<&mut TuiPane> {
437        self.pane_mut(self.active_pane_id)
438    }
439}
440
441// ============================================================================
442// Session
443// ============================================================================
444
445/// A TUI session containing one or more windows.
446pub struct TuiSession {
447    /// Session identifier.
448    pub id: u32,
449    /// Subject (user identity) that created this session.
450    /// Empty string for local/anonymous sessions.
451    pub owner: String,
452    /// All windows in this session.
453    pub windows: Vec<TuiWindow>,
454    /// Currently active window ID.
455    pub active_window_id: u32,
456}
457
458impl TuiSession {
459    /// Create a new session with one window containing one pane.
460    pub fn new(
461        id: u32,
462        window_id: u32,
463        pane_id: u32,
464        cols: u16,
465        rows: u16,
466        max_scrollback: usize,
467    ) -> Self {
468        let window = TuiWindow::new(window_id, pane_id, cols, rows, max_scrollback);
469        Self {
470            id,
471            owner: String::new(),
472            windows: vec![window],
473            active_window_id: window_id,
474        }
475    }
476
477    /// Find a window by ID.
478    pub fn window(&self, window_id: u32) -> Option<&TuiWindow> {
479        self.windows.iter().find(|w| w.id == window_id)
480    }
481
482    /// Find a window by ID mutably.
483    pub fn window_mut(&mut self, window_id: u32) -> Option<&mut TuiWindow> {
484        self.windows.iter_mut().find(|w| w.id == window_id)
485    }
486
487    /// Get the active window.
488    pub fn active_window(&self) -> Option<&TuiWindow> {
489        self.window(self.active_window_id)
490    }
491
492    /// Get the active window mutably.
493    pub fn active_window_mut(&mut self) -> Option<&mut TuiWindow> {
494        self.window_mut(self.active_window_id)
495    }
496}
497
498// ============================================================================
499// Events
500// ============================================================================
501
502/// Events broadcast from the TUI state to viewers and the 9P filesystem.
503#[derive(Debug, Clone)]
504pub enum TuiEvent {
505    /// A pane's buffer was modified.
506    Damage {
507        session_id: u32,
508        window_id: u32,
509        pane_id: u32,
510    },
511    /// A window was created.
512    WindowCreated { session_id: u32, window_id: u32 },
513    /// A window was closed.
514    WindowClosed { session_id: u32, window_id: u32 },
515    /// The active window changed (focus switched).
516    WindowFocused { session_id: u32, window_id: u32 },
517    /// A pane was created.
518    PaneCreated {
519        session_id: u32,
520        window_id: u32,
521        pane_id: u32,
522    },
523    /// A pane was closed.
524    PaneClosed {
525        session_id: u32,
526        window_id: u32,
527        pane_id: u32,
528    },
529    /// A session was created.
530    SessionCreated { session_id: u32 },
531    /// A session was destroyed.
532    SessionDestroyed { session_id: u32 },
533    /// Terminal resized.
534    Resized { cols: u16, rows: u16 },
535}
536
537// ============================================================================
538// TuiState (top-level)
539// ============================================================================
540
541/// Top-level TUI multiplexer state.
542///
543/// Owns all sessions and provides a broadcast channel for state change events.
544/// The composite buffer and generation counter are used by the frame loop
545/// to detect changes and encode diffs.
546pub struct TuiState {
547    /// All sessions.
548    pub sessions: Vec<TuiSession>,
549    /// Monotonically increasing generation counter.
550    generation: AtomicU64,
551    /// Event broadcast sender.
552    pub event_tx: broadcast::Sender<TuiEvent>,
553    /// Next ID counters.
554    next_session_id: u32,
555    next_window_id: u32,
556    next_pane_id: u32,
557    /// Default terminal dimensions.
558    pub default_cols: u16,
559    pub default_rows: u16,
560    /// Default scrollback lines per pane.
561    pub default_scrollback: usize,
562}
563
564impl TuiState {
565    /// Create a new TUI state.
566    pub fn new(cols: u16, rows: u16, scrollback: usize) -> Self {
567        let (event_tx, _) = broadcast::channel(256);
568        Self {
569            sessions: Vec::new(),
570            generation: AtomicU64::new(0),
571            event_tx,
572            next_session_id: 1,
573            next_window_id: 1,
574            next_pane_id: 1,
575            default_cols: cols,
576            default_rows: rows,
577            default_scrollback: scrollback,
578        }
579    }
580
581    /// Get the current generation.
582    pub fn generation(&self) -> u64 {
583        self.generation.load(Ordering::Relaxed)
584    }
585
586    /// Increment and return the new generation.
587    pub fn next_generation(&self) -> u64 {
588        self.generation.fetch_add(1, Ordering::Relaxed) + 1
589    }
590
591    /// Create a new session.
592    pub fn create_session(&mut self) -> u32 {
593        let session_id = self.next_session_id;
594        self.next_session_id = self.next_session_id.saturating_add(1);
595        let window_id = self.next_window_id;
596        self.next_window_id = self.next_window_id.saturating_add(1);
597        let pane_id = self.next_pane_id;
598        self.next_pane_id = self.next_pane_id.saturating_add(1);
599
600        let session = TuiSession::new(
601            session_id,
602            window_id,
603            pane_id,
604            self.default_cols,
605            self.default_rows,
606            self.default_scrollback,
607        );
608        self.sessions.push(session);
609
610        let _ = self.event_tx.send(TuiEvent::SessionCreated { session_id });
611        session_id
612    }
613
614    /// Find a session by ID.
615    pub fn session(&self, session_id: u32) -> Option<&TuiSession> {
616        self.sessions.iter().find(|s| s.id == session_id)
617    }
618
619    /// Find a session by ID mutably.
620    pub fn session_mut(&mut self, session_id: u32) -> Option<&mut TuiSession> {
621        self.sessions.iter_mut().find(|s| s.id == session_id)
622    }
623
624    /// Create a new window in a session.
625    pub fn create_window(&mut self, session_id: u32) -> Option<u32> {
626        let window_id = self.next_window_id;
627        self.next_window_id = self.next_window_id.saturating_add(1);
628        let pane_id = self.next_pane_id;
629        self.next_pane_id = self.next_pane_id.saturating_add(1);
630
631        let session = self.sessions.iter_mut().find(|s| s.id == session_id)?;
632        let window = TuiWindow::new(
633            window_id,
634            pane_id,
635            self.default_cols,
636            self.default_rows,
637            self.default_scrollback,
638        );
639        session.windows.push(window);
640        session.active_window_id = window_id;
641
642        let _ = self.event_tx.send(TuiEvent::WindowCreated {
643            session_id,
644            window_id,
645        });
646        let _ = self.event_tx.send(TuiEvent::WindowFocused {
647            session_id,
648            window_id,
649        });
650        Some(window_id)
651    }
652
653    /// Allocate a new pane ID.
654    pub fn next_pane_id(&mut self) -> u32 {
655        let id = self.next_pane_id;
656        self.next_pane_id = self.next_pane_id.saturating_add(1);
657        id
658    }
659
660    /// Close a window in a session. Returns true if the window was found and removed.
661    pub fn close_window(&mut self, session_id: u32, window_id: u32) -> bool {
662        let session = match self.session_mut(session_id) {
663            Some(s) => s,
664            None => return false,
665        };
666        let pos = match session.windows.iter().position(|w| w.id == window_id) {
667            Some(p) => p,
668            None => return false,
669        };
670        session.windows.remove(pos);
671        if session.active_window_id == window_id {
672            session.active_window_id = session.windows.first().map(|w| w.id).unwrap_or(0);
673        }
674        let _ = self.event_tx.send(TuiEvent::WindowClosed {
675            session_id,
676            window_id,
677        });
678        true
679    }
680
681    /// Focus a window in a session. Returns true if the window exists.
682    pub fn focus_window(&mut self, session_id: u32, window_id: u32) -> bool {
683        let session = match self.session_mut(session_id) {
684            Some(s) => s,
685            None => return false,
686        };
687        if session.window(window_id).is_none() {
688            return false;
689        }
690        session.active_window_id = window_id;
691        let _ = self.event_tx.send(TuiEvent::WindowFocused {
692            session_id,
693            window_id,
694        });
695        true
696    }
697
698    /// Split the active pane in the active window. Returns (new_pane_id, cols, rows) on success.
699    pub fn split_pane(
700        &mut self,
701        session_id: u32,
702        horizontal: bool,
703        ratio: f32,
704    ) -> Option<(u32, u16, u16)> {
705        let new_pane_id = self.next_pane_id();
706        let cols = self.default_cols;
707        let rows = self.default_rows;
708        let scrollback = self.default_scrollback;
709
710        let session = self.session_mut(session_id)?;
711        let window = session.active_window_mut()?;
712        let _active_id = window.active_pane_id;
713
714        let new_pane = TuiPane::new(new_pane_id, cols, rows, scrollback);
715        window.panes.push(new_pane);
716
717        let old_layout = window.layout.clone();
718        let new_leaf = LayoutNode::Leaf {
719            pane_id: new_pane_id,
720        };
721        window.layout = if horizontal {
722            LayoutNode::HSplit {
723                ratio,
724                first: Box::new(old_layout),
725                second: Box::new(new_leaf),
726            }
727        } else {
728            LayoutNode::VSplit {
729                ratio,
730                first: Box::new(old_layout),
731                second: Box::new(new_leaf),
732            }
733        };
734
735        let window_id = window.id;
736        let _ = self.event_tx.send(TuiEvent::PaneCreated {
737            session_id,
738            window_id,
739            pane_id: new_pane_id,
740        });
741        Some((new_pane_id, cols, rows))
742    }
743
744    /// Close a pane in the active window. Returns true if found and removed.
745    pub fn close_pane(&mut self, session_id: u32, pane_id: u32) -> bool {
746        let session = match self.session_mut(session_id) {
747            Some(s) => s,
748            None => return false,
749        };
750        let window = match session.active_window_mut() {
751            Some(w) => w,
752            None => return false,
753        };
754
755        // Don't close the last pane
756        if window.panes.len() <= 1 {
757            return false;
758        }
759
760        let pos = match window.panes.iter().position(|p| p.id == pane_id) {
761            Some(p) => p,
762            None => return false,
763        };
764        window.panes.remove(pos);
765
766        // Prune from layout tree
767        if let Some(pruned) = window.layout.prune(pane_id) {
768            window.layout = pruned;
769        }
770
771        if window.active_pane_id == pane_id {
772            window.active_pane_id = window.panes.first().map(|p| p.id).unwrap_or(0);
773        }
774
775        let window_id = window.id;
776        let _ = self.event_tx.send(TuiEvent::PaneClosed {
777            session_id,
778            window_id,
779            pane_id,
780        });
781        true
782    }
783
784    /// Focus a pane in the active window. Returns true if the pane exists.
785    pub fn focus_pane(&mut self, session_id: u32, pane_id: u32) -> bool {
786        let session = match self.session_mut(session_id) {
787            Some(s) => s,
788            None => return false,
789        };
790        let window = match session.active_window_mut() {
791            Some(w) => w,
792            None => return false,
793        };
794        if window.pane(pane_id).is_none() {
795            return false;
796        }
797        window.active_pane_id = pane_id;
798        true
799    }
800
801    /// Subscribe to TUI events.
802    pub fn subscribe(&self) -> broadcast::Receiver<TuiEvent> {
803        self.event_tx.subscribe()
804    }
805
806    /// Notify that a pane has been damaged (content changed).
807    pub fn notify_damage(&self, session_id: u32, window_id: u32, pane_id: u32) {
808        self.next_generation();
809        let _ = self.event_tx.send(TuiEvent::Damage {
810            session_id,
811            window_id,
812            pane_id,
813        });
814    }
815}
816
817impl Default for TuiState {
818    fn default() -> Self {
819        Self::new(80, 24, 2000)
820    }
821}
822
823// ============================================================================
824// Tests
825// ============================================================================
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830
831    #[test]
832    fn test_damage_bitmask_boundaries() {
833        let mut buf = PaneBuffer::new(80, 24);
834        buf.clear_damage();
835
836        // Row 0
837        buf.mark_dirty(0);
838        assert!(buf.is_row_dirty(0));
839        assert!(!buf.is_row_dirty(1));
840
841        // Row 63
842        buf.mark_dirty(63);
843        assert!(buf.is_row_dirty(63));
844
845        // Row 127
846        buf.mark_dirty(127);
847        assert!(buf.is_row_dirty(127));
848        assert!(!buf.force_full_frame);
849
850        // Row 128+ triggers force_full_frame
851        buf.mark_dirty(128);
852        assert!(buf.force_full_frame);
853    }
854
855    #[test]
856    fn test_scroll_log_overflow() {
857        let mut buf = PaneBuffer::new(80, 24);
858        buf.clear_damage();
859
860        for i in 0..256 {
861            buf.record_scroll(ScrollOp {
862                top: 0,
863                bottom: 23,
864                amount: 1,
865            });
866            assert!(
867                !buf.force_full_frame,
868                "should not force full frame at scroll {}",
869                i
870            );
871        }
872
873        // 257th scroll should trigger force_full_frame
874        buf.record_scroll(ScrollOp {
875            top: 0,
876            bottom: 23,
877            amount: 1,
878        });
879        assert!(buf.force_full_frame);
880    }
881
882    #[test]
883    fn test_resize_triggers_full_frame() {
884        let mut buf = PaneBuffer::new(80, 24);
885        buf.clear_damage();
886        assert!(!buf.force_full_frame);
887
888        buf.resize(120, 40);
889        assert!(buf.force_full_frame);
890    }
891
892    #[test]
893    fn test_session_creation() -> Result<(), Box<dyn std::error::Error>> {
894        let mut state = TuiState::default();
895        let sid = state.create_session();
896        assert_eq!(sid, 1);
897
898        let session = state.session(sid).ok_or("session missing")?;
899        assert_eq!(session.windows.len(), 1);
900        assert_eq!(session.windows[0].panes.len(), 1);
901        Ok(())
902    }
903
904    #[test]
905    fn test_window_creation() -> Result<(), Box<dyn std::error::Error>> {
906        let mut state = TuiState::default();
907        let sid = state.create_session();
908        let wid = state.create_window(sid).ok_or("create_window failed")?;
909
910        let session = state.session(sid).ok_or("session missing")?;
911        assert_eq!(session.windows.len(), 2);
912        assert!(session.window(wid).is_some());
913        Ok(())
914    }
915
916    #[test]
917    fn test_alternate_screen() {
918        let mut pane = TuiPane::new(1, 80, 24, 2000);
919        assert!(!pane.using_alternate);
920        assert!(pane.alternate.is_none());
921
922        pane.enter_alternate_screen();
923        assert!(pane.using_alternate);
924        assert!(pane.alternate.is_some());
925        if let Some(alt) = pane.alternate.as_ref() {
926            assert!(alt.force_full_frame);
927        }
928
929        pane.leave_alternate_screen();
930        assert!(!pane.using_alternate);
931        assert!(pane.primary.force_full_frame);
932    }
933
934    #[test]
935    fn test_generation_counter() {
936        let state = TuiState::default();
937        assert_eq!(state.generation(), 0);
938        assert_eq!(state.next_generation(), 1);
939        assert_eq!(state.next_generation(), 2);
940        assert_eq!(state.generation(), 2);
941    }
942}