Skip to main content

hyprstream_core/tui/
backend.rs

1//! TuiPaneBackend — native ratatui Backend writing directly to TuiPane.
2//!
3//! Double-buffer pattern: writes to a private staging buffer (no lock, ~8ns/cell),
4//! then takes a brief write lock to swap into the pane buffer, sets damage,
5//! and sends a damage notification.
6
7use std::io;
8use std::sync::Arc;
9
10use ratatui::{
11    backend::{Backend, ClearType, WindowSize},
12    buffer::{Buffer, Cell},
13    layout::{Position, Rect, Size},
14};
15use tokio::sync::RwLock;
16
17use super::state::{TuiPane, TuiState};
18
19/// A ratatui Backend that writes directly to a TuiPane's cell buffer.
20///
21/// Uses double-buffering: `draw()` writes to a private staging buffer,
22/// then briefly locks the pane to swap the staging buffer in.
23pub struct TuiPaneBackend {
24    /// Staging buffer (private, no contention during writes).
25    staging: Buffer,
26    /// Shared TUI state for damage notification.
27    state: Arc<RwLock<TuiState>>,
28    /// Target session/window/pane IDs.
29    session_id: u32,
30    window_id: u32,
31    pane_id: u32,
32    /// Terminal dimensions.
33    cols: u16,
34    rows: u16,
35}
36
37impl TuiPaneBackend {
38    /// Create a new TuiPaneBackend.
39    pub fn new(
40        state: Arc<RwLock<TuiState>>,
41        session_id: u32,
42        window_id: u32,
43        pane_id: u32,
44        cols: u16,
45        rows: u16,
46    ) -> Self {
47        Self {
48            staging: Buffer::empty(Rect::new(0, 0, cols, rows)),
49            state,
50            session_id,
51            window_id,
52            pane_id,
53            cols,
54            rows,
55        }
56    }
57
58    /// Swap staging buffer into the pane (blocking, takes write lock).
59    ///
60    /// This is called after `draw()` completes. The brief write lock
61    /// duration is proportional to a memcpy, not cell-by-cell iteration.
62    pub fn flush_to_pane(&mut self) {
63        let state = self.state.clone();
64        let staging = std::mem::replace(
65            &mut self.staging,
66            Buffer::empty(Rect::new(0, 0, self.cols, self.rows)),
67        );
68        let session_id = self.session_id;
69        let window_id = self.window_id;
70        let pane_id = self.pane_id;
71
72        // Use try_write to avoid blocking the current thread if possible.
73        // In the Thread spawner context, this always succeeds.
74        tokio::task::block_in_place(move || {
75            let rt = tokio::runtime::Handle::current();
76            rt.block_on(async {
77                let mut state = state.write().await;
78                if let Some(session) = state.session_mut(session_id) {
79                    if let Some(window) = session.window_mut(window_id) {
80                        if let Some(pane) = window.pane_mut(pane_id) {
81                            let buf = pane.active_buffer_mut();
82                            buf.buffer = staging;
83                            buf.mark_all_dirty();
84                        }
85                    }
86                }
87                state.notify_damage(session_id, window_id, pane_id);
88            });
89        });
90    }
91}
92
93impl Backend for TuiPaneBackend {
94    type Error = io::Error;
95
96    fn draw<'a, I>(&mut self, content: I) -> Result<(), Self::Error>
97    where
98        I: Iterator<Item = (u16, u16, &'a Cell)>,
99    {
100        for (x, y, cell) in content {
101            if x < self.cols && y < self.rows {
102                self.staging[(x, y)] = cell.clone();
103            }
104        }
105        // Flush staging to pane
106        self.flush_to_pane();
107        Ok(())
108    }
109
110    fn hide_cursor(&mut self) -> Result<(), Self::Error> {
111        Ok(())
112    }
113
114    fn show_cursor(&mut self) -> Result<(), Self::Error> {
115        Ok(())
116    }
117
118    fn get_cursor_position(&mut self) -> Result<Position, Self::Error> {
119        Ok(Position::new(0, 0))
120    }
121
122    fn set_cursor_position<P: Into<Position>>(&mut self, _position: P) -> Result<(), Self::Error> {
123        Ok(())
124    }
125
126    fn clear(&mut self) -> Result<(), Self::Error> {
127        self.staging.reset();
128        Ok(())
129    }
130
131    fn clear_region(&mut self, _clear_type: ClearType) -> Result<(), Self::Error> {
132        Ok(())
133    }
134
135    fn size(&self) -> Result<Size, Self::Error> {
136        Ok(Size::new(self.cols, self.rows))
137    }
138
139    fn window_size(&mut self) -> Result<WindowSize, Self::Error> {
140        Ok(WindowSize {
141            columns_rows: Size::new(self.cols, self.rows),
142            pixels: Size::new(0, 0),
143        })
144    }
145
146    fn flush(&mut self) -> Result<(), Self::Error> {
147        Ok(())
148    }
149}
150
151/// Ingest structured binary data (from StructuredBackend) into a pane buffer.
152///
153/// Deserializes the packed cell tuples and writes them directly to the pane's buffer.
154pub fn ingest_structured(pane: &mut TuiPane, data: &[u8]) -> io::Result<()> {
155    let (_cols, _rows, cells) = waxterm::structured::decode_structured(data)?;
156
157    let buf = pane.active_buffer_mut();
158    for cell in cells {
159        let area = buf.buffer.area();
160        if cell.x < area.width && cell.y < area.height {
161            let target = &mut buf.buffer[(cell.x, cell.y)];
162            target.set_symbol(&cell.symbol);
163            target.set_style(
164                ratatui::style::Style::new()
165                    .fg(cell.fg)
166                    .bg(cell.bg)
167                    .add_modifier(cell.modifiers),
168            );
169            buf.mark_dirty(cell.y);
170        }
171    }
172
173    Ok(())
174}
175
176// ============================================================================
177// Tests
178// ============================================================================
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[tokio::test]
185    async fn test_backend_size() -> Result<(), Box<dyn std::error::Error>> {
186        let state = Arc::new(RwLock::new(TuiState::default()));
187        let backend = TuiPaneBackend::new(state, 1, 1, 1, 80, 24);
188        assert_eq!(backend.size()?, Size::new(80, 24));
189        Ok(())
190    }
191}