Skip to main content

hyprstream_core/tui/
ninep.rs

1//! Plan 9-style virtual filesystem over TuiState.
2//!
3//! Provides a 9P-inspired namespace for programmatic access to the TUI multiplexer:
4//!
5//! ```text
6//! /tui/ctl           — global control (write "new" to create session)
7//! /tui/new           — walk atomically allocates window (Plan 9 /dev/new pattern)
8//! /tui/event         — blocking event stream (broadcast::Receiver)
9//! /tui/windows/      — directory listing
10//! /tui/windows/0/    — window dir (ctl, cons, screen, winname, layout, panes/)
11//! /tui/windows/0/panes/0/ — pane dir (cons, screen)
12//! ```
13//!
14//! This is NOT the registry's ContainedFs — standalone, ephemeral.
15
16use std::collections::HashMap;
17use std::sync::Arc;
18
19use tokio::sync::Notify;
20
21use super::state::TuiState;
22
23// ============================================================================
24// Node types
25// ============================================================================
26
27/// Virtual file system node identifiers.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum TuiNodeId {
30    Root,
31    Ctl,
32    New,
33    Event,
34    WindowsDir,
35    WindowDir(u32),
36    WindowCtl(u32),
37    WindowCons(u32),
38    WindowScreen(u32),
39    WindowName(u32),
40    WindowLayout(u32),
41    PanesDir(u32),
42    PaneDir(u32, u32),
43    PaneCons(u32, u32),
44    PaneScreen(u32, u32),
45}
46
47impl TuiNodeId {
48    /// Encode as a qid_path: `(type_tag << 56) | (window_id << 32) | pane_id`
49    pub fn qid_path(&self) -> u64 {
50        match self {
51            TuiNodeId::Root => 0,
52            TuiNodeId::Ctl => 1 << 56,
53            TuiNodeId::New => 2 << 56,
54            TuiNodeId::Event => 3 << 56,
55            TuiNodeId::WindowsDir => 4 << 56,
56            TuiNodeId::WindowDir(w) => (5 << 56) | ((*w as u64) << 32),
57            TuiNodeId::WindowCtl(w) => (6 << 56) | ((*w as u64) << 32),
58            TuiNodeId::WindowCons(w) => (7 << 56) | ((*w as u64) << 32),
59            TuiNodeId::WindowScreen(w) => (8 << 56) | ((*w as u64) << 32),
60            TuiNodeId::WindowName(w) => (9 << 56) | ((*w as u64) << 32),
61            TuiNodeId::WindowLayout(w) => (10 << 56) | ((*w as u64) << 32),
62            TuiNodeId::PanesDir(w) => (11 << 56) | ((*w as u64) << 32),
63            TuiNodeId::PaneDir(w, p) => (12 << 56) | ((*w as u64) << 32) | (*p as u64),
64            TuiNodeId::PaneCons(w, p) => (13 << 56) | ((*w as u64) << 32) | (*p as u64),
65            TuiNodeId::PaneScreen(w, p) => (14 << 56) | ((*w as u64) << 32) | (*p as u64),
66        }
67    }
68
69    /// Whether this node is a directory.
70    pub fn is_dir(&self) -> bool {
71        matches!(
72            self,
73            TuiNodeId::Root
74                | TuiNodeId::WindowsDir
75                | TuiNodeId::WindowDir(_)
76                | TuiNodeId::PanesDir(_)
77                | TuiNodeId::PaneDir(_, _)
78        )
79    }
80}
81
82// ============================================================================
83// Fid state
84// ============================================================================
85
86/// State associated with an open fid.
87#[derive(Debug)]
88pub enum TuiFidState {
89    /// Walked to a node but not yet opened.
90    Walked(TuiNodeId),
91    /// Opened for read/write.
92    Opened {
93        node: TuiNodeId,
94        /// Read cursor for cons files (monotonic offset into ring buffer).
95        cons_cursor: u64,
96        /// Whether opened for reading.
97        reading: bool,
98        /// Whether opened for writing.
99        writing: bool,
100    },
101}
102
103// ============================================================================
104// Console ring buffer
105// ============================================================================
106
107/// Ring buffer for console I/O (`cons` files).
108///
109/// 256KB ring with monotonic write_offset. Readers track their own cursor.
110/// If a reader falls too far behind (`write_offset - cursor > capacity`),
111/// a gap marker is emitted.
112pub struct ConsBuffer {
113    /// Ring buffer data.
114    data: Vec<u8>,
115    /// Monotonic write offset (always increases, wraps in ring).
116    write_offset: u64,
117    /// Notify for blocking reads.
118    notify: Arc<Notify>,
119}
120
121impl ConsBuffer {
122    /// Create a new console buffer with the given capacity.
123    pub fn new(capacity: usize) -> Self {
124        Self {
125            data: vec![0u8; capacity],
126            write_offset: 0,
127            notify: Arc::new(Notify::new()),
128        }
129    }
130
131    /// Write data to the ring buffer.
132    pub fn write(&mut self, data: &[u8]) {
133        let cap = self.data.len();
134        for &byte in data {
135            let idx = (self.write_offset as usize) % cap;
136            self.data[idx] = byte;
137            self.write_offset += 1;
138        }
139        self.notify.notify_waiters();
140    }
141
142    /// Read data from the ring buffer starting at the given cursor.
143    ///
144    /// Returns `(bytes_read, new_cursor, gap_detected)`.
145    /// If the cursor is too far behind, returns a gap marker and advances.
146    pub fn read(&self, cursor: u64, buf: &mut [u8]) -> (usize, u64, bool) {
147        let cap = self.data.len() as u64;
148
149        // Gap detection
150        if self.write_offset.saturating_sub(cursor) > cap {
151            // Reader fell behind — data is overwritten
152            let new_cursor = self.write_offset;
153            return (0, new_cursor, true);
154        }
155
156        if cursor >= self.write_offset {
157            return (0, cursor, false);
158        }
159
160        let available = (self.write_offset - cursor) as usize;
161        let to_read = available.min(buf.len());
162
163        for (i, byte) in buf[..to_read].iter_mut().enumerate() {
164            let idx = ((cursor + i as u64) as usize) % cap as usize;
165            *byte = self.data[idx];
166        }
167
168        (to_read, cursor + to_read as u64, false)
169    }
170
171    /// Current write offset.
172    pub fn write_offset(&self) -> u64 {
173        self.write_offset
174    }
175
176    /// Get a notifier for blocking reads.
177    pub fn notifier(&self) -> Arc<Notify> {
178        Arc::clone(&self.notify)
179    }
180}
181
182// ============================================================================
183// Fid table
184// ============================================================================
185
186/// Table mapping fids to their state.
187pub struct TuiFidTable {
188    fids: HashMap<u32, TuiFidState>,
189    next_fid: u32,
190}
191
192impl TuiFidTable {
193    pub fn new() -> Self {
194        Self {
195            fids: HashMap::new(),
196            next_fid: 0,
197        }
198    }
199
200    /// Allocate a new fid walked to the given node.
201    pub fn walk(&mut self, node: TuiNodeId) -> u32 {
202        let fid = self.next_fid;
203        self.next_fid += 1;
204        self.fids.insert(fid, TuiFidState::Walked(node));
205        fid
206    }
207
208    /// Open a walked fid.
209    pub fn open(&mut self, fid: u32, reading: bool, writing: bool, cons_cursor: u64) -> bool {
210        if let Some(state) = self.fids.get_mut(&fid) {
211            if let TuiFidState::Walked(node) = state {
212                let node = *node;
213                *state = TuiFidState::Opened {
214                    node,
215                    cons_cursor,
216                    reading,
217                    writing,
218                };
219                return true;
220            }
221        }
222        false
223    }
224
225    /// Close/remove a fid.
226    pub fn clunk(&mut self, fid: u32) -> Option<TuiFidState> {
227        self.fids.remove(&fid)
228    }
229
230    /// Get a fid's state.
231    pub fn get(&self, fid: u32) -> Option<&TuiFidState> {
232        self.fids.get(&fid)
233    }
234
235    /// Get a fid's state mutably.
236    pub fn get_mut(&mut self, fid: u32) -> Option<&mut TuiFidState> {
237        self.fids.get_mut(&fid)
238    }
239}
240
241impl Default for TuiFidTable {
242    fn default() -> Self {
243        Self::new()
244    }
245}
246
247/// Walk a path from a starting node to resolve a target node.
248pub fn walk_path(state: &TuiState, from: TuiNodeId, name: &str) -> Option<TuiNodeId> {
249    match (from, name) {
250        (TuiNodeId::Root, "ctl") => Some(TuiNodeId::Ctl),
251        (TuiNodeId::Root, "new") => Some(TuiNodeId::New),
252        (TuiNodeId::Root, "event") => Some(TuiNodeId::Event),
253        (TuiNodeId::Root, "windows") => Some(TuiNodeId::WindowsDir),
254        (TuiNodeId::WindowsDir, id_str) => {
255            let w: u32 = id_str.parse().ok()?;
256            // Verify window exists in some session
257            state
258                .sessions
259                .iter()
260                .any(|s| s.window(w).is_some())
261                .then_some(TuiNodeId::WindowDir(w))
262        }
263        (TuiNodeId::WindowDir(w), "ctl") => Some(TuiNodeId::WindowCtl(w)),
264        (TuiNodeId::WindowDir(w), "cons") => Some(TuiNodeId::WindowCons(w)),
265        (TuiNodeId::WindowDir(w), "screen") => Some(TuiNodeId::WindowScreen(w)),
266        (TuiNodeId::WindowDir(w), "winname") => Some(TuiNodeId::WindowName(w)),
267        (TuiNodeId::WindowDir(w), "layout") => Some(TuiNodeId::WindowLayout(w)),
268        (TuiNodeId::WindowDir(w), "panes") => Some(TuiNodeId::PanesDir(w)),
269        (TuiNodeId::PanesDir(w), id_str) => {
270            let p: u32 = id_str.parse().ok()?;
271            // Verify pane exists
272            state
273                .sessions
274                .iter()
275                .flat_map(|s| s.windows.iter())
276                .find(|win| win.id == w)
277                .and_then(|win| win.pane(p))
278                .map(|_| TuiNodeId::PaneDir(w, p))
279        }
280        (TuiNodeId::PaneDir(w, p), "cons") => Some(TuiNodeId::PaneCons(w, p)),
281        (TuiNodeId::PaneDir(w, p), "screen") => Some(TuiNodeId::PaneScreen(w, p)),
282        _ => None,
283    }
284}
285
286// ============================================================================
287// Tests
288// ============================================================================
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn test_walk_paths() -> Result<(), Box<dyn std::error::Error>> {
296        let mut state = TuiState::default();
297        let sid = state.create_session();
298
299        // The first session gets window_id=1, pane_id=1
300        let session = state.session(sid).ok_or("session missing")?;
301        let window = &session.windows[0];
302        let wid = window.id;
303        let pid = window.panes[0].id;
304
305        assert_eq!(
306            walk_path(&state, TuiNodeId::Root, "ctl"),
307            Some(TuiNodeId::Ctl)
308        );
309        assert_eq!(
310            walk_path(&state, TuiNodeId::Root, "new"),
311            Some(TuiNodeId::New)
312        );
313        assert_eq!(
314            walk_path(&state, TuiNodeId::Root, "windows"),
315            Some(TuiNodeId::WindowsDir)
316        );
317        assert_eq!(
318            walk_path(&state, TuiNodeId::WindowsDir, &wid.to_string()),
319            Some(TuiNodeId::WindowDir(wid))
320        );
321        assert_eq!(
322            walk_path(&state, TuiNodeId::WindowDir(wid), "cons"),
323            Some(TuiNodeId::WindowCons(wid))
324        );
325        assert_eq!(
326            walk_path(&state, TuiNodeId::WindowDir(wid), "panes"),
327            Some(TuiNodeId::PanesDir(wid))
328        );
329        assert_eq!(
330            walk_path(&state, TuiNodeId::PanesDir(wid), &pid.to_string()),
331            Some(TuiNodeId::PaneDir(wid, pid))
332        );
333        Ok(())
334    }
335
336    #[test]
337    fn test_cons_buffer_write_read() {
338        let mut buf = ConsBuffer::new(16);
339        buf.write(b"hello");
340
341        let mut out = [0u8; 16];
342        let (n, cursor, gap) = buf.read(0, &mut out);
343        assert_eq!(n, 5);
344        assert_eq!(cursor, 5);
345        assert!(!gap);
346        assert_eq!(&out[..n], b"hello");
347    }
348
349    #[test]
350    fn test_cons_buffer_gap_detection() {
351        let mut buf = ConsBuffer::new(8);
352        // Write 20 bytes into 8-byte ring (overwrites)
353        buf.write(&[b'A'; 20]);
354
355        let mut out = [0u8; 8];
356        let (n, cursor, gap) = buf.read(0, &mut out);
357        assert!(gap);
358        assert_eq!(n, 0);
359        assert_eq!(cursor, 20); // Advanced to write_offset
360    }
361
362    #[test]
363    fn test_qid_path_uniqueness() {
364        use std::collections::HashSet;
365        let nodes = [
366            TuiNodeId::Root,
367            TuiNodeId::Ctl,
368            TuiNodeId::New,
369            TuiNodeId::Event,
370            TuiNodeId::WindowsDir,
371            TuiNodeId::WindowDir(0),
372            TuiNodeId::WindowCtl(0),
373            TuiNodeId::WindowCons(0),
374            TuiNodeId::WindowScreen(0),
375            TuiNodeId::WindowName(0),
376            TuiNodeId::WindowLayout(0),
377            TuiNodeId::PanesDir(0),
378            TuiNodeId::PaneDir(0, 0),
379            TuiNodeId::PaneCons(0, 0),
380            TuiNodeId::PaneScreen(0, 0),
381        ];
382        let paths: HashSet<u64> = nodes.iter().map(super::TuiNodeId::qid_path).collect();
383        assert_eq!(paths.len(), nodes.len(), "qid_path collision detected");
384    }
385
386    #[test]
387    fn test_fid_table() {
388        let mut table = TuiFidTable::new();
389        let fid = table.walk(TuiNodeId::Ctl);
390        assert!(matches!(
391            table.get(fid),
392            Some(TuiFidState::Walked(TuiNodeId::Ctl))
393        ));
394
395        assert!(table.open(fid, true, false, 0));
396        assert!(matches!(table.get(fid), Some(TuiFidState::Opened { .. })));
397
398        assert!(table.clunk(fid).is_some());
399        assert!(table.get(fid).is_none());
400    }
401}