Skip to main content

hyprstream_compositor/
layout.rs

1//! Pane layout — per-pane buffer state.
2
3use std::collections::HashMap;
4
5pub type PaneId = u32;
6
7// ============================================================================
8// Frame update types (decoded TuiFrame, passed from shell_handlers → compositor)
9// ============================================================================
10
11/// Cursor state for a server-buffered pane.
12#[derive(Clone, Debug, Default)]
13pub struct CursorState {
14    pub x: u16,
15    pub y: u16,
16    pub visible: bool,
17}
18
19/// A decoded cell from a TuiFrame.
20#[derive(Debug, Clone)]
21pub struct CellUpdate {
22    pub x: u16,
23    pub y: u16,
24    pub symbol: String,
25    pub fg: ratatui::style::Color,
26    pub bg: ratatui::style::Color,
27    pub modifiers: ratatui::style::Modifier,
28}
29
30/// A decoded scroll operation from a TuiFrame.
31#[derive(Debug, Clone)]
32pub struct ScrollUpdate {
33    pub top: u16,
34    pub bottom: u16,
35    /// Positive = scroll up (content moves up, new rows at bottom).
36    /// Negative = scroll down.
37    pub amount: i16,
38}
39
40/// Decoded frame content (full or incremental).
41#[derive(Debug)]
42pub enum FrameContent {
43    Full {
44        cols: u16,
45        rows: u16,
46        cells: Vec<CellUpdate>,
47    },
48    Incremental {
49        scrolls: Vec<ScrollUpdate>,
50        deltas: Vec<CellUpdate>,
51    },
52}
53
54/// A fully decoded TuiFrame ready for the compositor to apply.
55///
56/// Produced by `shell_handlers::decode_tui_frame` and delivered via
57/// `CompositorInput::ServerFrameCapnp`.
58#[derive(Debug)]
59pub struct FrameUpdate {
60    pub pane_id: u32,
61    pub generation: u64,
62    pub cursor: CursorState,
63    pub content: FrameContent,
64}
65
66// ============================================================================
67// Pane storage variants
68// ============================================================================
69
70/// Source of a pane's content.
71pub enum PaneSource {
72    /// Frame received from TuiService.
73    Server { pane_id: u32 },
74    /// Rendered ANSI bytes from a client-owned ChatApp (Phase 4+).
75    Private { app_id: u32 },
76}
77
78/// How a pane's content is stored client-side.
79pub enum PaneStorage {
80    /// Server pane fed by decoded TuiFrame diffs (native CLI / Capnp path).
81    ServerBuf {
82        buf: ratatui::buffer::Buffer,
83        cursor: CursorState,
84    },
85    /// Server pane fed by ANSI bytes via avt::Vt (WASM/browser/ANSI path).
86    ServerVt(avt::Vt),
87    /// Private (client-owned) pane fed by ANSI from ChatApp.render().
88    PrivateVt(avt::Vt),
89}
90
91// ============================================================================
92// PaneState
93// ============================================================================
94
95/// Per-pane state: storage buffer + source.
96pub struct PaneState {
97    pub storage: PaneStorage,
98    pub source: PaneSource,
99}
100
101impl PaneState {
102    /// Create a server pane backed by an ANSI VT emulator (legacy / WASM path).
103    pub fn server(pane_id: u32, cols: u16, rows: u16) -> Self {
104        Self {
105            storage: PaneStorage::ServerVt(
106                avt::Vt::builder()
107                    .size(cols as usize, rows as usize)
108                    .build(),
109            ),
110            source: PaneSource::Server { pane_id },
111        }
112    }
113
114    /// Create a server pane backed by a ratatui Buffer (native Capnp path).
115    pub fn server_buf(pane_id: u32, cols: u16, rows: u16) -> Self {
116        Self {
117            storage: PaneStorage::ServerBuf {
118                buf: ratatui::buffer::Buffer::empty(ratatui::layout::Rect::new(0, 0, cols, rows)),
119                cursor: CursorState::default(),
120            },
121            source: PaneSource::Server { pane_id },
122        }
123    }
124
125    /// Create a private client-owned pane backed by an ANSI VT emulator.
126    pub fn private(app_id: u32, cols: u16, rows: u16) -> Self {
127        Self {
128            storage: PaneStorage::PrivateVt(
129                avt::Vt::builder()
130                    .size(cols as usize, rows as usize)
131                    .build(),
132            ),
133            source: PaneSource::Private { app_id },
134        }
135    }
136
137    /// Feed ANSI bytes into the VTE emulator (VT-backed panes only).
138    /// No-op for `ServerBuf` panes.
139    pub fn feed(&mut self, ansi: &[u8]) {
140        match &mut self.storage {
141            PaneStorage::ServerVt(vt) | PaneStorage::PrivateVt(vt) => {
142                vt.feed_str(&String::from_utf8_lossy(ansi));
143            }
144            PaneStorage::ServerBuf { .. } => {}
145        }
146    }
147}
148
149// ============================================================================
150// LayoutTree
151// ============================================================================
152
153/// Tracks per-pane buffer state keyed by pane_id (or app_id for private panes).
154pub struct LayoutTree {
155    panes: HashMap<PaneId, PaneState>,
156    cols: u16,
157    rows: u16,
158}
159
160impl LayoutTree {
161    pub fn new(cols: u16, rows: u16) -> Self {
162        Self {
163            panes: HashMap::new(),
164            cols,
165            rows,
166        }
167    }
168
169    /// Get or create a server pane backed by ANSI VT (WASM / ANSI mode).
170    pub fn get_or_create_server(&mut self, pane_id: u32) -> &mut PaneState {
171        let cols = self.cols;
172        let rows = self.rows;
173        self.panes
174            .entry(pane_id)
175            .or_insert_with(|| PaneState::server(pane_id, cols, rows))
176    }
177
178    /// Get or create a private client-owned pane.
179    pub fn get_or_create_private(&mut self, app_id: u32) -> &mut PaneState {
180        let cols = self.cols;
181        let rows = self.rows;
182        self.panes
183            .entry(app_id)
184            .or_insert_with(|| PaneState::private(app_id, cols, rows))
185    }
186
187    pub fn get_pane(&self, pane_id: u32) -> Option<&PaneState> {
188        self.panes.get(&pane_id)
189    }
190
191    pub fn get_pane_mut(&mut self, pane_id: u32) -> Option<&mut PaneState> {
192        self.panes.get_mut(&pane_id)
193    }
194
195    pub fn remove_pane(&mut self, pane_id: u32) {
196        self.panes.remove(&pane_id);
197    }
198
199    /// Apply a decoded TuiFrame to a server pane buffer (native Capnp path).
200    ///
201    /// Creates the pane as `ServerBuf` if it doesn't exist yet.
202    /// Upgrades a `ServerVt` pane to `ServerBuf` on first Capnp frame.
203    pub fn apply_server_frame(&mut self, frame: &FrameUpdate) {
204        let cols = self.cols;
205        let rows = self.rows;
206        let pane_id = frame.pane_id;
207
208        let pane = self
209            .panes
210            .entry(pane_id)
211            .or_insert_with(|| PaneState::server_buf(pane_id, cols, rows));
212
213        // Upgrade ServerVt → ServerBuf if this pane was previously ANSI-fed.
214        if matches!(pane.storage, PaneStorage::ServerVt(_)) {
215            pane.storage = PaneStorage::ServerBuf {
216                buf: ratatui::buffer::Buffer::empty(ratatui::layout::Rect::new(0, 0, cols, rows)),
217                cursor: CursorState::default(),
218            };
219        }
220
221        if let PaneStorage::ServerBuf { buf, cursor } = &mut pane.storage {
222            apply_frame_to_buffer(buf, &frame.content);
223            cursor.x = frame.cursor.x;
224            cursor.y = frame.cursor.y;
225            cursor.visible = frame.cursor.visible;
226        }
227    }
228
229    pub fn resize(&mut self, cols: u16, rows: u16) {
230        self.cols = cols;
231        self.rows = rows;
232        // Rebuild all pane buffers at the new size.
233        // Content is discarded — the server sends a full frame after its own resize.
234        for pane in self.panes.values_mut() {
235            match &mut pane.storage {
236                PaneStorage::ServerVt(vt) | PaneStorage::PrivateVt(vt) => {
237                    *vt = avt::Vt::builder()
238                        .size(cols as usize, rows as usize)
239                        .build();
240                }
241                PaneStorage::ServerBuf { buf, .. } => {
242                    *buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect::new(
243                        0, 0, cols, rows,
244                    ));
245                }
246            }
247        }
248    }
249}
250
251// ============================================================================
252// Buffer helpers
253// ============================================================================
254
255/// Apply decoded frame content to a ratatui Buffer.
256fn apply_frame_to_buffer(buf: &mut ratatui::buffer::Buffer, content: &FrameContent) {
257    match content {
258        FrameContent::Full { cols, rows, cells } => {
259            // Replace the buffer entirely.
260            *buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect::new(0, 0, *cols, *rows));
261            let width = *cols as usize;
262            for cell in cells {
263                let idx = cell.y as usize * width + cell.x as usize;
264                if idx < buf.content.len() {
265                    buf.content[idx].set_symbol(&cell.symbol);
266                    buf.content[idx].fg = cell.fg;
267                    buf.content[idx].bg = cell.bg;
268                    buf.content[idx].modifier = cell.modifiers;
269                }
270            }
271        }
272        FrameContent::Incremental { scrolls, deltas } => {
273            for scroll in scrolls {
274                apply_scroll(buf, scroll);
275            }
276            let width = buf.area.width as usize;
277            for cell in deltas {
278                let idx = cell.y as usize * width + cell.x as usize;
279                if idx < buf.content.len() {
280                    buf.content[idx].set_symbol(&cell.symbol);
281                    buf.content[idx].fg = cell.fg;
282                    buf.content[idx].bg = cell.bg;
283                    buf.content[idx].modifier = cell.modifiers;
284                }
285            }
286        }
287    }
288}
289
290/// Apply a scroll operation to a ratatui Buffer in-place.
291fn apply_scroll(buf: &mut ratatui::buffer::Buffer, scroll: &ScrollUpdate) {
292    let width = buf.area.width as usize;
293    let height = buf.area.height as usize;
294    let top = scroll.top as usize;
295    let bottom = (scroll.bottom as usize).min(height.saturating_sub(1));
296
297    if scroll.amount > 0 {
298        // Scroll up: copy row (top + n..=bottom) → (top..=bottom - n), clear tail.
299        let n = scroll.amount as usize;
300        for dst_y in top..=bottom {
301            let src_y = dst_y + n;
302            if src_y <= bottom {
303                let src = src_y * width;
304                let dst = dst_y * width;
305                // Can't do copy_within because Cell is not Copy; clone row.
306                let row: Vec<_> = buf.content[src..src + width].to_vec();
307                buf.content[dst..dst + width].clone_from_slice(&row);
308            } else {
309                let dst = dst_y * width;
310                for x in 0..width {
311                    buf.content[dst + x] = ratatui::buffer::Cell::default();
312                }
313            }
314        }
315    } else if scroll.amount < 0 {
316        // Scroll down: copy row (top..=bottom - n) → (top + n..=bottom), clear head.
317        let n = (-scroll.amount) as usize;
318        let mut dst_y = bottom;
319        loop {
320            if dst_y >= top + n {
321                let src_y = dst_y - n;
322                let src = src_y * width;
323                let dst = dst_y * width;
324                let row: Vec<_> = buf.content[src..src + width].to_vec();
325                buf.content[dst..dst + width].clone_from_slice(&row);
326            } else {
327                let dst = dst_y * width;
328                for x in 0..width {
329                    buf.content[dst + x] = ratatui::buffer::Cell::default();
330                }
331            }
332            if dst_y == top {
333                break;
334            }
335            dst_y -= 1;
336        }
337    }
338}