1use std::collections::{BTreeMap, BTreeSet};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Placement {
20 First,
22 Last,
24 Before(u32),
26 After(u32),
28}
29
30pub mod kind {
32 pub const TEXT: i32 = 1;
34 pub const GRID: i32 = 2;
36}
37
38pub mod align {
40 pub const TOP: i32 = 0;
42 pub const BOTTOM: i32 = 1;
44 pub const LEFT: i32 = 2;
46 pub const RIGHT: i32 = 3;
48}
49
50pub mod units {
52 pub const PERCENT: i32 = 1;
54 pub const CELLS: i32 = 2;
57}
58
59pub mod style {
61 pub const BORDER: u32 = 0x01;
63 pub const VSCROLL: u32 = 0x02;
65 pub const HSCROLL: u32 = 0x04;
67 pub const AUTO_VSCROLL: u32 = 0x08;
69 pub const AUTO_HSCROLL: u32 = 0x10;
71 pub const TAB_ALIGN: u32 = 0x20;
73 pub const MORE_MODE: u32 = 0x40;
75 pub const HSTRUT: u32 = 0x80;
78 pub const VSTRUT: u32 = 0x100;
81}
82
83pub mod color {
86 pub const TEXT: u32 = 0x0200_0000;
88 pub const TEXT_BG: u32 = 0x0300_0000;
90 pub const STATUS_TEXT: u32 = 0x0400_0000;
92 pub const STATUS_BG: u32 = 0x0500_0000;
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct PaneSpec {
99 pub kind: i32,
101 pub align: i32,
103 pub size: i32,
105 pub units: i32,
107 pub style: u32,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub struct PaneInfo {
114 pub align: i32,
116 pub style: u32,
118 pub rows: usize,
120 pub columns: usize,
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
126pub struct Rect {
127 pub x: usize,
129 pub y: usize,
131 pub width: usize,
133 pub height: usize,
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub struct PaneLayout {
142 pub parent: Option<u32>,
144 pub kind: i32,
146 pub align: i32,
148 pub size: i32,
150 pub units: i32,
152 pub fitted: bool,
155}
156
157const MAX_LINES: usize = 500;
160
161#[derive(Debug)]
162struct Window {
163 parent: Option<u32>,
165 attached: bool,
169 children: Vec<u32>,
170 kind: i32,
171 align: i32,
172 size: i32,
173 units: i32,
174 flags: u32,
175 lines: Vec<Vec<char>>,
177 x: usize,
179 y: usize,
180 xmax: usize,
182 ymax: usize,
183 rect: Rect,
185 screen_color: Option<u32>,
187 fitted: bool,
189}
190
191impl Window {
192 fn clear(&mut self) {
193 self.lines.clear();
194 self.x = 0;
195 self.y = 0;
196 self.xmax = 0;
197 self.ymax = 0;
198 }
199
200 fn horizontal(&self) -> bool {
201 self.align == align::TOP || self.align == align::BOTTOM
202 }
203
204 fn put(&mut self, c: char) {
205 while self.lines.len() <= self.y {
206 self.lines.push(Vec::new());
207 }
208 let line = &mut self.lines[self.y];
209 while line.len() < self.x {
210 line.push(' ');
211 }
212 if self.x < line.len() {
213 line[self.x] = c;
214 } else {
215 line.push(c);
216 }
217 self.xmax = self.xmax.max(self.x);
218 self.x += 1;
219 }
220
221 fn newline(&mut self) {
222 self.ymax = self.ymax.max(self.y);
223 self.y += 1;
224 self.x = 0;
225 if self.kind == kind::TEXT && self.y >= MAX_LINES {
226 self.lines.remove(0);
229 self.y -= 1;
230 self.ymax = self.ymax.saturating_sub(1);
231 }
232 }
233}
234
235#[derive(Debug)]
237pub struct Screen {
238 rows: usize,
239 columns: usize,
240 side_panes: bool,
244 windows: BTreeMap<u32, Window>,
245 main_children: Vec<u32>,
247 next_id: u32,
248 main: Rect,
249 status: Option<u32>,
251 layout_changed: bool,
252 changed: BTreeSet<u32>,
253}
254
255impl Screen {
256 pub fn new(rows: usize, columns: usize, side_panes: bool) -> Self {
258 Self {
259 rows,
260 columns,
261 side_panes,
262 windows: BTreeMap::new(),
263 main_children: Vec::new(),
264 next_id: 1,
265 main: Rect {
266 x: 0,
267 y: 0,
268 width: columns,
269 height: rows,
270 },
271 status: None,
272 layout_changed: false,
273 changed: BTreeSet::new(),
274 }
275 }
276
277 pub fn resize(&mut self, rows: usize, columns: usize) {
279 if (rows, columns) != (self.rows, self.columns) {
280 self.rows = rows;
281 self.columns = columns;
282 self.lay_out();
283 }
284 }
285
286 pub fn size(&self) -> (usize, usize) {
288 (self.rows, self.columns)
289 }
290
291 pub fn main(&self) -> Rect {
293 self.main
294 }
295
296 pub fn create(
298 &mut self,
299 parent: Option<u32>,
300 placement: Placement,
301 spec: PaneSpec,
302 ) -> Option<u32> {
303 if spec.kind != kind::TEXT && spec.kind != kind::GRID {
304 return None;
305 }
306 let parent = parent.filter(|id| self.windows.contains_key(id));
308 if parent.is_none()
309 && !self.side_panes
310 && (spec.align == align::LEFT || spec.align == align::RIGHT)
311 {
312 return None;
313 }
314 let id = self.next_id;
315 self.next_id += 1;
316 let rect = if spec.align == align::LEFT || spec.align == align::RIGHT {
319 Rect {
320 height: self.main.height,
321 ..Rect::default()
322 }
323 } else {
324 Rect {
325 width: self.main.width,
326 ..Rect::default()
327 }
328 };
329 let mut flags =
330 spec.style & (style::AUTO_VSCROLL | style::MORE_MODE | style::HSTRUT | style::VSTRUT);
331 if flags & style::MORE_MODE != 0 {
332 flags |= style::AUTO_VSCROLL;
333 }
334 self.windows.insert(
335 id,
336 Window {
337 parent,
338 attached: true,
339 children: Vec::new(),
340 kind: spec.kind,
341 align: spec.align,
342 size: spec.size,
343 units: spec.units,
344 flags,
345 lines: Vec::new(),
346 x: 0,
347 y: 0,
348 xmax: 0,
349 ymax: 0,
350 rect,
351 screen_color: None,
352 fitted: false,
353 },
354 );
355 let list = self.children_mut(parent);
356 let at = match placement {
357 Placement::First => 0,
358 Placement::Last => list.len(),
359 Placement::Before(other) => list.iter().position(|&c| c == other).unwrap_or(list.len()),
360 Placement::After(other) => list
361 .iter()
362 .position(|&c| c == other)
363 .map_or(list.len(), |at| at + 1),
364 };
365 list.insert(at, id);
366 if spec.size != 0 {
367 self.lay_out();
368 }
369 Some(id)
370 }
371
372 pub fn delete(&mut self, id: u32) {
374 let Some(window) = self.windows.remove(&id) else {
375 return;
376 };
377 if window.attached {
378 self.children_mut(window.parent).retain(|&c| c != id);
379 }
380 for child in window.children {
381 if let Some(child) = self.windows.get_mut(&child) {
382 child.parent = None;
383 child.attached = false;
384 }
385 }
386 if self.status == Some(id) {
387 self.status = None;
388 }
389 self.changed.remove(&id);
390 self.lay_out();
391 }
392
393 pub fn clear(&mut self, id: u32) {
395 if let Some(window) = self.windows.get_mut(&id) {
396 window.clear();
397 self.changed.insert(id);
398 }
399 }
400
401 pub fn write(&mut self, id: u32, text: &str) {
403 let Some(window) = self.windows.get_mut(&id) else {
404 return;
405 };
406 for c in text.chars() {
407 match c {
408 '\n' => window.newline(),
409 '\r' => window.x = 0,
410 _ => window.put(c),
411 }
412 }
413 self.changed.insert(id);
414 }
415
416 pub fn go_to(&mut self, id: u32, row: usize, column: usize) {
419 if let Some(window) = self.windows.get_mut(&id)
420 && window.kind == kind::GRID
421 {
422 window.y = row;
423 window.x = column;
424 }
425 }
426
427 pub fn set_size(&mut self, id: u32, size: i32, units: i32, advisory: bool) {
430 let Some(window) = self.windows.get_mut(&id) else {
431 return;
432 };
433 if advisory {
434 return;
435 }
436 window.fitted = false;
437 if (window.size, window.units) == (size, units) {
438 return;
439 }
440 window.size = size;
441 window.units = units;
442 self.lay_out();
443 }
444
445 pub fn size_to_contents(&mut self, id: u32) {
448 let Some(window) = self.windows.get_mut(&id) else {
449 return;
450 };
451 window.fitted = true;
452 let window = &self.windows[&id];
453 let (size, current) = if window.horizontal() {
454 (self.content_height(id), window.rect.height)
455 } else {
456 (self.content_width(id), window.rect.width)
457 };
458 if size == current {
459 return;
460 }
461 if let Some(window) = self.windows.get_mut(&id) {
462 window.size = i32::try_from(size).unwrap_or(i32::MAX);
463 window.units = units::CELLS;
464 }
465 self.lay_out();
466 }
467
468 fn content_height(&self, id: u32) -> usize {
469 let window = &self.windows[&id];
470 let mut height = window.ymax + 1;
471 for &child in &window.children {
472 let chi = &self.windows[&child];
473 if chi.flags & style::VSTRUT != 0 {
474 let child_height = self.content_height(child);
475 if chi.horizontal() {
476 height += child_height;
477 } else {
478 height = height.max(child_height);
479 }
480 }
481 }
482 height
483 }
484
485 fn content_width(&self, id: u32) -> usize {
486 let window = &self.windows[&id];
487 let mut width = window.xmax + 1;
488 for &child in &window.children {
489 let chi = &self.windows[&child];
490 if chi.flags & style::HSTRUT != 0 {
491 let child_width = self.content_width(child);
492 if chi.horizontal() {
493 width = width.max(child_width);
494 } else {
495 width += child_width;
496 }
497 }
498 }
499 width
500 }
501
502 pub fn set_screen_color(&mut self, id: u32, color: u32) {
504 if let Some(window) = self.windows.get_mut(&id)
505 && window.screen_color != Some(color)
506 {
507 window.screen_color = Some(color);
508 self.changed.insert(id);
509 }
510 }
511
512 pub fn screen_color(&self, id: u32) -> Option<u32> {
515 if self.status == Some(id) {
516 return Some(color::STATUS_BG);
517 }
518 self.windows.get(&id).and_then(|window| window.screen_color)
519 }
520
521 pub fn info(&self, id: u32) -> Option<PaneInfo> {
523 let window = self.windows.get(&id)?;
524 Some(PaneInfo {
525 align: window.align,
526 style: window.flags | style::TAB_ALIGN,
528 rows: window.rect.height,
529 columns: window.rect.width,
530 })
531 }
532
533 pub fn layout(&self, id: u32) -> Option<PaneLayout> {
535 let window = self.windows.get(&id)?;
536 Some(PaneLayout {
537 parent: window.parent,
538 kind: window.kind,
539 align: window.align,
540 size: window.size,
541 units: window.units,
542 fitted: window.fitted,
543 })
544 }
545
546 pub fn set_side_panes(&mut self, side_panes: bool) {
550 self.side_panes = side_panes;
551 }
552
553 pub fn set_status(&mut self, left: &str, right: &str) {
556 let id = match self.status {
557 Some(id) => id,
558 None => {
559 let spec = PaneSpec {
560 kind: kind::GRID,
561 align: align::TOP,
562 size: 1,
563 units: units::CELLS,
564 style: 0,
565 };
566 let Some(id) = self.create(None, Placement::First, spec) else {
567 return;
568 };
569 self.status = Some(id);
570 id
571 }
572 };
573 let width = self.windows[&id].rect.width;
574 let left: Vec<char> = left.chars().collect();
575 let right: Vec<char> = right.chars().collect();
576 let mut line = vec![' '; width];
577 for (i, &c) in left.iter().take(width.saturating_sub(1)).enumerate() {
578 line[i + 1] = c;
579 }
580 let start = width.saturating_sub(right.len() + 1);
581 for (i, &c) in right.iter().enumerate() {
582 if let Some(cell) = line.get_mut(start + i) {
583 *cell = c;
584 }
585 }
586 if let Some(window) = self.windows.get_mut(&id) {
587 window.clear();
588 window.lines.push(line);
589 self.changed.insert(id);
590 }
591 }
592
593 pub fn status(&self) -> Option<u32> {
595 self.status
596 }
597
598 pub fn panes(&self) -> Vec<(u32, Rect)> {
600 let mut out = Vec::new();
601 self.collect(&self.main_children, &mut out);
602 out
603 }
604
605 fn collect(&self, list: &[u32], out: &mut Vec<(u32, Rect)>) {
606 for &id in list {
607 let window = &self.windows[&id];
608 out.push((id, window.rect));
609 self.collect(&window.children, out);
610 }
611 }
612
613 pub fn rect(&self, id: u32) -> Option<Rect> {
616 self.windows.get(&id).map(|window| window.rect)
617 }
618
619 pub fn view(&self, id: u32) -> Vec<String> {
622 let Some(window) = self.windows.get(&id) else {
623 return Vec::new();
624 };
625 let Rect { width, height, .. } = window.rect;
626 let last = window.lines.len().min(window.y + 1);
629 let first = if window.kind == kind::TEXT && window.flags & style::AUTO_VSCROLL != 0 {
630 last.saturating_sub(height)
631 } else {
632 0
633 };
634 (first..first + height)
635 .map(|row| {
636 let mut line: String = window
637 .lines
638 .get(row)
639 .map(|chars| chars.iter().take(width).collect())
640 .unwrap_or_default();
641 let len = line.chars().count();
642 line.extend(std::iter::repeat_n(' ', width - len));
643 line
644 })
645 .collect()
646 }
647
648 pub fn take_layout_changed(&mut self) -> bool {
651 std::mem::take(&mut self.layout_changed)
652 }
653
654 pub fn take_changed(&mut self) -> Vec<u32> {
656 std::mem::take(&mut self.changed).into_iter().collect()
657 }
658
659 fn children_mut(&mut self, parent: Option<u32>) -> &mut Vec<u32> {
660 match parent {
661 Some(id) => &mut self.windows.get_mut(&id).expect("parent pane").children,
662 None => &mut self.main_children,
663 }
664 }
665
666 fn lay_out(&mut self) {
670 let mut area = Rect {
671 x: 0,
672 y: 0,
673 width: self.columns,
674 height: self.rows,
675 };
676 let children = self.main_children.clone();
677 for id in children {
678 self.lay_out_window(id, &mut area);
679 }
680 self.main = area;
681 self.layout_changed = true;
682 }
683
684 fn lay_out_window(&mut self, id: u32, parent: &mut Rect) {
685 let window = &self.windows[&id];
686 let base = if window.horizontal() {
687 parent.height
688 } else {
689 parent.width
690 };
691 let size = match window.units {
692 units::PERCENT => usize::try_from(window.size).unwrap_or(0) * base / 100,
693 _ => usize::try_from(window.size).unwrap_or(0),
694 };
695 let mut rect = *parent;
696 match window.align {
697 align::TOP => {
698 rect.height = size.min(parent.height);
699 parent.y += rect.height;
700 parent.height -= rect.height;
701 }
702 align::BOTTOM => {
703 rect.height = size.min(parent.height);
704 rect.y = parent.y + parent.height - rect.height;
705 parent.height -= rect.height;
706 }
707 align::LEFT => {
708 rect.width = size.min(parent.width);
709 parent.x += rect.width;
710 parent.width -= rect.width;
711 }
712 _ => {
713 rect.width = size.min(parent.width);
714 rect.x = parent.x + parent.width - rect.width;
715 parent.width -= rect.width;
716 }
717 }
718 let children = window.children.clone();
719 for child in children {
720 self.lay_out_window(child, &mut rect);
721 }
722 self.windows.get_mut(&id).expect("pane").rect = rect;
723 }
724}
725
726#[cfg(test)]
727mod tests {
728 use super::*;
729
730 fn spec(align: i32, size: i32, units: i32) -> PaneSpec {
731 PaneSpec {
732 kind: kind::TEXT,
733 align,
734 size,
735 units,
736 style: 0,
737 }
738 }
739
740 #[test]
741 fn panes_take_their_space_in_order() {
742 let mut screen = Screen::new(24, 80, true);
743 let top = screen
744 .create(None, Placement::Last, spec(align::TOP, 2, units::CELLS))
745 .unwrap();
746 let bottom = screen
747 .create(
748 None,
749 Placement::Last,
750 spec(align::BOTTOM, 25, units::PERCENT),
751 )
752 .unwrap();
753 let left = screen
754 .create(None, Placement::Last, spec(align::LEFT, 10, units::CELLS))
755 .unwrap();
756 assert_eq!(
757 screen.rect(top).unwrap(),
758 Rect {
759 x: 0,
760 y: 0,
761 width: 80,
762 height: 2
763 }
764 );
765 assert_eq!(
767 screen.rect(bottom).unwrap(),
768 Rect {
769 x: 0,
770 y: 19,
771 width: 80,
772 height: 5
773 }
774 );
775 assert_eq!(
776 screen.rect(left).unwrap(),
777 Rect {
778 x: 0,
779 y: 2,
780 width: 10,
781 height: 17
782 }
783 );
784 assert_eq!(
785 screen.main(),
786 Rect {
787 x: 10,
788 y: 2,
789 width: 70,
790 height: 17
791 }
792 );
793
794 let first = screen
796 .create(None, Placement::First, spec(align::TOP, 1, units::CELLS))
797 .unwrap();
798 assert_eq!(screen.rect(first).unwrap().y, 0);
799 assert_eq!(screen.rect(top).unwrap().y, 1);
800 }
801
802 #[test]
803 fn a_pane_within_a_pane_takes_from_its_parent() {
804 let mut screen = Screen::new(24, 80, true);
805 let outer = screen
806 .create(None, Placement::Last, spec(align::TOP, 6, units::CELLS))
807 .unwrap();
808 let inner = screen
809 .create(
810 Some(outer),
811 Placement::Last,
812 spec(align::RIGHT, 20, units::CELLS),
813 )
814 .unwrap();
815 assert_eq!(
816 screen.rect(inner).unwrap(),
817 Rect {
818 x: 60,
819 y: 0,
820 width: 20,
821 height: 6
822 }
823 );
824 assert_eq!(
825 screen.rect(outer).unwrap(),
826 Rect {
827 x: 0,
828 y: 0,
829 width: 60,
830 height: 6
831 }
832 );
833 screen.delete(outer);
834 assert_eq!(screen.panes(), []);
835 assert_eq!(screen.main().height, 24);
836 }
837
838 #[test]
839 fn a_panes_layout_is_as_the_program_asked() {
840 let mut screen = Screen::new(24, 80, false);
841 screen.set_side_panes(true);
842 let side = screen
843 .create(None, Placement::Last, spec(align::LEFT, 30, units::PERCENT))
844 .unwrap();
845 let layout = screen.layout(side).unwrap();
846 assert_eq!(
847 (
848 layout.parent,
849 layout.align,
850 layout.size,
851 layout.units,
852 layout.fitted
853 ),
854 (None, align::LEFT, 30, units::PERCENT, false)
855 );
856 screen.size_to_contents(side);
857 assert!(screen.layout(side).unwrap().fitted);
858 screen.set_size(side, 10, units::CELLS, true);
860 assert!(screen.layout(side).unwrap().fitted);
861 screen.set_size(side, 10, units::CELLS, false);
862 assert!(!screen.layout(side).unwrap().fitted);
863 assert_eq!(screen.layout(side + 1), None);
864 }
865
866 #[test]
867 fn a_terminal_has_no_panes_at_the_sides() {
868 let mut screen = Screen::new(24, 80, false);
869 assert_eq!(
870 screen.create(None, Placement::Last, spec(align::LEFT, 10, units::CELLS)),
871 None
872 );
873 let top = screen
874 .create(None, Placement::Last, spec(align::TOP, 3, units::CELLS))
875 .unwrap();
876 assert!(
877 screen
878 .create(
879 Some(top),
880 Placement::Last,
881 spec(align::LEFT, 10, units::CELLS)
882 )
883 .is_some()
884 );
885 }
886
887 #[test]
888 fn sizing_to_contents_counts_the_lines_ended() {
889 let mut screen = Screen::new(24, 80, true);
890 let id = screen
891 .create(None, Placement::Last, spec(align::TOP, 0, units::CELLS))
892 .unwrap();
893 assert_eq!(screen.info(id).unwrap().rows, 0);
894 screen.write(id, "Kitchen Score: 5\n");
895 screen.size_to_contents(id);
896 assert_eq!(screen.info(id).unwrap().rows, 1);
897 screen.write(id, "Exits: north\n");
898 screen.size_to_contents(id);
899 assert_eq!(
900 screen.view(id),
901 [
902 format!("{:<80}", "Kitchen Score: 5"),
903 format!("{:<80}", "Exits: north")
904 ]
905 );
906 screen.set_size(id, 5, units::CELLS, true);
908 assert_eq!(screen.info(id).unwrap().rows, 2);
909 screen.clear(id);
910 screen.size_to_contents(id);
911 assert_eq!(screen.info(id).unwrap().rows, 1);
912 }
913
914 #[test]
915 fn a_grid_is_written_at_a_position() {
916 let mut screen = Screen::new(24, 20, true);
917 let id = screen
918 .create(
919 None,
920 Placement::Last,
921 PaneSpec {
922 kind: kind::GRID,
923 align: align::TOP,
924 size: 2,
925 units: units::CELLS,
926 style: 0,
927 },
928 )
929 .unwrap();
930 screen.go_to(id, 1, 3);
931 screen.write(id, "abc");
932 screen.go_to(id, 1, 4);
933 screen.write(id, "X");
934 assert_eq!(
935 screen.view(id),
936 [" ".repeat(20), format!("{:<20}", " aXc")]
937 );
938 }
939
940 #[test]
941 fn a_scrolling_pane_shows_its_last_lines() {
942 let mut screen = Screen::new(24, 10, true);
943 let id = screen
944 .create(
945 None,
946 Placement::Last,
947 PaneSpec {
948 style: style::AUTO_VSCROLL,
949 ..spec(align::TOP, 2, units::CELLS)
950 },
951 )
952 .unwrap();
953 screen.write(id, "one\ntwo\nthree");
954 assert_eq!(
955 screen.view(id),
956 [format!("{:<10}", "two"), format!("{:<10}", "three")]
957 );
958 assert_eq!(
959 screen.info(id).unwrap().style,
960 style::AUTO_VSCROLL | style::TAB_ALIGN
961 );
962 }
963
964 #[test]
965 fn the_status_line_is_a_line_at_the_top() {
966 let mut screen = Screen::new(24, 30, false);
967 screen.set_status("Kitchen", "5/12");
968 let id = screen.status().unwrap();
969 assert_eq!(screen.view(id), [format!(" {:<24}5/12 ", "Kitchen")]);
970 assert_eq!(screen.main().y, 1);
971 }
972}