1use std::collections::VecDeque;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use ratatui::buffer::{Buffer, Cell};
10use tokio::sync::broadcast;
11
12#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct ScrollOp {
55 pub top: u16,
57 pub bottom: u16,
59 pub amount: i16,
61}
62
63pub struct PaneBuffer {
73 pub buffer: Buffer,
75 pub damage_rows: u128,
77 pub scroll_log: Vec<ScrollOp>,
79 pub force_full_frame: bool,
81}
82
83impl PaneBuffer {
84 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, }
92 }
93
94 #[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 pub fn mark_all_dirty(&mut self) {
106 self.damage_rows = u128::MAX;
107 }
108
109 #[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 pub fn dirty_count(&self) -> u32 {
121 self.damage_rows.count_ones()
122 }
123
124 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 pub fn record_scroll(&mut self, op: ScrollOp) {
133 if self.scroll_log.len() < 256 {
134 self.scroll_log.push(op);
135 } else {
136 self.force_full_frame = true;
138 }
139 }
140
141 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
167pub enum IngestionMode {
168 #[default]
170 Direct,
171 Ansi,
173 Structured,
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
187pub enum PaneBackend {
188 #[default]
190 Managed,
191 Private,
194}
195
196pub struct TuiPane {
202 pub id: u32,
204 pub primary: PaneBuffer,
206 pub alternate: Option<PaneBuffer>,
208 pub using_alternate: bool,
210 pub scrollback: VecDeque<Vec<Cell>>,
212 pub max_scrollback: usize,
214 pub cursor: CursorState,
216 pub ingestion_mode: IngestionMode,
218 pub title: String,
220 pub backend: PaneBackend,
222}
223
224impl TuiPane {
225 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 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 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 pub fn size(&self) -> (u16, u16) {
261 let area = self.active_buffer().buffer.area();
262 (area.width, area.height)
263 }
264
265 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 if let Some(alt) = &mut self.alternate {
274 alt.force_full_frame = true;
275 }
276 }
277 }
278
279 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 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 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#[derive(Debug, Clone)]
310pub enum LayoutNode {
311 Leaf { pane_id: u32 },
313 HSplit {
315 ratio: f32,
316 first: Box<LayoutNode>,
317 second: Box<LayoutNode>,
318 },
319 VSplit {
321 ratio: f32,
322 first: Box<LayoutNode>,
323 second: Box<LayoutNode>,
324 },
325}
326
327impl LayoutNode {
328 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 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
389pub struct TuiWindow {
395 pub id: u32,
397 pub name: String,
399 pub layout: LayoutNode,
401 pub panes: Vec<TuiPane>,
403 pub active_pane_id: u32,
405}
406
407impl TuiWindow {
408 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 pub fn pane(&self, pane_id: u32) -> Option<&TuiPane> {
422 self.panes.iter().find(|p| p.id == pane_id)
423 }
424
425 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 pub fn active_pane(&self) -> Option<&TuiPane> {
432 self.pane(self.active_pane_id)
433 }
434
435 pub fn active_pane_mut(&mut self) -> Option<&mut TuiPane> {
437 self.pane_mut(self.active_pane_id)
438 }
439}
440
441pub struct TuiSession {
447 pub id: u32,
449 pub owner: String,
452 pub windows: Vec<TuiWindow>,
454 pub active_window_id: u32,
456}
457
458impl TuiSession {
459 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 pub fn window(&self, window_id: u32) -> Option<&TuiWindow> {
479 self.windows.iter().find(|w| w.id == window_id)
480 }
481
482 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 pub fn active_window(&self) -> Option<&TuiWindow> {
489 self.window(self.active_window_id)
490 }
491
492 pub fn active_window_mut(&mut self) -> Option<&mut TuiWindow> {
494 self.window_mut(self.active_window_id)
495 }
496}
497
498#[derive(Debug, Clone)]
504pub enum TuiEvent {
505 Damage {
507 session_id: u32,
508 window_id: u32,
509 pane_id: u32,
510 },
511 WindowCreated { session_id: u32, window_id: u32 },
513 WindowClosed { session_id: u32, window_id: u32 },
515 WindowFocused { session_id: u32, window_id: u32 },
517 PaneCreated {
519 session_id: u32,
520 window_id: u32,
521 pane_id: u32,
522 },
523 PaneClosed {
525 session_id: u32,
526 window_id: u32,
527 pane_id: u32,
528 },
529 SessionCreated { session_id: u32 },
531 SessionDestroyed { session_id: u32 },
533 Resized { cols: u16, rows: u16 },
535}
536
537pub struct TuiState {
547 pub sessions: Vec<TuiSession>,
549 generation: AtomicU64,
551 pub event_tx: broadcast::Sender<TuiEvent>,
553 next_session_id: u32,
555 next_window_id: u32,
556 next_pane_id: u32,
557 pub default_cols: u16,
559 pub default_rows: u16,
560 pub default_scrollback: usize,
562}
563
564impl TuiState {
565 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 pub fn generation(&self) -> u64 {
583 self.generation.load(Ordering::Relaxed)
584 }
585
586 pub fn next_generation(&self) -> u64 {
588 self.generation.fetch_add(1, Ordering::Relaxed) + 1
589 }
590
591 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 pub fn session(&self, session_id: u32) -> Option<&TuiSession> {
616 self.sessions.iter().find(|s| s.id == session_id)
617 }
618
619 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 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 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 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 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 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 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 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 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 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 pub fn subscribe(&self) -> broadcast::Receiver<TuiEvent> {
803 self.event_tx.subscribe()
804 }
805
806 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#[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 buf.mark_dirty(0);
838 assert!(buf.is_row_dirty(0));
839 assert!(!buf.is_row_dirty(1));
840
841 buf.mark_dirty(63);
843 assert!(buf.is_row_dirty(63));
844
845 buf.mark_dirty(127);
847 assert!(buf.is_row_dirty(127));
848 assert!(!buf.force_full_frame);
849
850 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 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}