Skip to main content

hexicon_host/
pane.rs

1//! Panes: the panes a program can divide the screen into, such as
2//! a status line across the top.
3//!
4//! A host that displays panes keeps a [`Screen`], which does what the
5//! reference interpreter's character-mode display layer does (`osgen3.c`):
6//! it keeps the tree of panes, lays them out in character cells, holds
7//! the text each one shows, and works out how big a pane's contents
8//! are. The host only draws what the screen says is where.
9//!
10//! The VM formats the text for a pane before handing it over, broken
11//! into lines that fit the pane's width, so a pane receives plain
12//! text with newlines.
13
14use std::collections::{BTreeMap, BTreeSet};
15
16/// Where a pane goes in its parent's list of panes. Panes earlier in
17/// the list take their space first.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Placement {
20    /// At the start of the list.
21    First,
22    /// At the end of the list.
23    Last,
24    /// Just before another pane, or at the end if it is not there.
25    Before(u32),
26    /// Just after another pane, or at the end if it is not there.
27    After(u32),
28}
29
30/// The kinds of pane.
31pub mod kind {
32    /// Text that flows from line to line, as in the main window.
33    pub const TEXT: i32 = 1;
34    /// A grid of character cells, written at a position.
35    pub const GRID: i32 = 2;
36}
37
38/// Which side of its parent a pane is attached to.
39pub mod align {
40    /// The top, across the full width.
41    pub const TOP: i32 = 0;
42    /// The bottom, across the full width.
43    pub const BOTTOM: i32 = 1;
44    /// The left, the full height.
45    pub const LEFT: i32 = 2;
46    /// The right, the full height.
47    pub const RIGHT: i32 = 3;
48}
49
50/// How a pane's size is given.
51pub mod units {
52    /// A percentage of the parent's size.
53    pub const PERCENT: i32 = 1;
54    /// Character cells: lines for a top or bottom pane, columns for a
55    /// left or right one.
56    pub const CELLS: i32 = 2;
57}
58
59/// Pane style flags. The values are the ones programs see.
60pub mod style {
61    /// A border between the pane and the rest of the screen.
62    pub const BORDER: u32 = 0x01;
63    /// A vertical scroll bar.
64    pub const VSCROLL: u32 = 0x02;
65    /// A horizontal scroll bar.
66    pub const HSCROLL: u32 = 0x04;
67    /// Keep the last line in view as text is added.
68    pub const AUTO_VSCROLL: u32 = 0x08;
69    /// Keep the end of the line in view as text is added.
70    pub const AUTO_HSCROLL: u32 = 0x10;
71    /// `<tab>` alignment works, as it does on a fixed-pitch display.
72    pub const TAB_ALIGN: u32 = 0x20;
73    /// Pause when a screenful has gone by.
74    pub const MORE_MODE: u32 = 0x40;
75    /// Sizing the parent to its contents makes room for this pane's
76    /// width.
77    pub const HSTRUT: u32 = 0x80;
78    /// Sizing the parent to its contents makes room for this pane's
79    /// height.
80    pub const VSTRUT: u32 = 0x100;
81}
82
83/// Colors the host chooses, as programs name them. Any other color is an
84/// RGB value, `0xrrggbb`.
85pub mod color {
86    /// The color of ordinary text.
87    pub const TEXT: u32 = 0x0200_0000;
88    /// The background of ordinary text.
89    pub const TEXT_BG: u32 = 0x0300_0000;
90    /// The color of the status line's text.
91    pub const STATUS_TEXT: u32 = 0x0400_0000;
92    /// The status line's background.
93    pub const STATUS_BG: u32 = 0x0500_0000;
94}
95
96/// What a program asks for when it creates a pane.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct PaneSpec {
99    /// A [`kind`] value.
100    pub kind: i32,
101    /// An [`align`] value.
102    pub align: i32,
103    /// The size, in `units`.
104    pub size: i32,
105    /// A [`units`] value.
106    pub units: i32,
107    /// A combination of [`style`] flags.
108    pub style: u32,
109}
110
111/// What a program can learn about a pane.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub struct PaneInfo {
114    /// An [`align`] value.
115    pub align: i32,
116    /// The [`style`] flags in effect.
117    pub style: u32,
118    /// The height in lines.
119    pub rows: usize,
120    /// The width in columns.
121    pub columns: usize,
122}
123
124/// An area of the screen, in character cells.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
126pub struct Rect {
127    /// The leftmost column.
128    pub x: usize,
129    /// The top line.
130    pub y: usize,
131    /// The width in columns.
132    pub width: usize,
133    /// The height in lines.
134    pub height: usize,
135}
136
137/// How a pane is placed, as the program asked: for a display that lays
138/// the panes out in its own measures, as a rich one does, and not in
139/// character cells.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub struct PaneLayout {
142    /// The pane it is part of, or `None` for the main window.
143    pub parent: Option<u32>,
144    /// A [`kind`] value.
145    pub kind: i32,
146    /// An [`align`] value.
147    pub align: i32,
148    /// The size, in `units`.
149    pub size: i32,
150    /// A [`units`] value.
151    pub units: i32,
152    /// Whether the program last asked for it to be sized to what it
153    /// holds, rather than given a size.
154    pub fitted: bool,
155}
156
157/// The most lines of text a pane keeps. A pane shows no more than a
158/// screenful, so more would only be kept to be thrown away.
159const MAX_LINES: usize = 500;
160
161#[derive(Debug)]
162struct Window {
163    /// The pane it is part of, or `None` for the main window.
164    parent: Option<u32>,
165    /// Whether it is in its parent's list, and so on the screen if its
166    /// parent is. A pane whose parent is deleted stays, but is shown
167    /// nowhere.
168    attached: bool,
169    children: Vec<u32>,
170    kind: i32,
171    align: i32,
172    size: i32,
173    units: i32,
174    flags: u32,
175    /// The text, a line at a time.
176    lines: Vec<Vec<char>>,
177    /// Where the next character goes.
178    x: usize,
179    y: usize,
180    /// The furthest column and line written to, for sizing to contents.
181    xmax: usize,
182    ymax: usize,
183    /// Where the pane is on the screen.
184    rect: Rect,
185    /// The background color asked for.
186    screen_color: Option<u32>,
187    /// Whether it was last sized to its contents.
188    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            // Forget the oldest line. What is in view, and the size of
227            // the contents, are measured from the end.
228            self.lines.remove(0);
229            self.y -= 1;
230            self.ymax = self.ymax.saturating_sub(1);
231        }
232    }
233}
234
235/// The panes on a screen, and where everything goes.
236#[derive(Debug)]
237pub struct Screen {
238    rows: usize,
239    columns: usize,
240    /// Whether a pane can be at the left or right of the main window.
241    /// A terminal cannot keep the main window's text to part of its width,
242    /// so it says no.
243    side_panes: bool,
244    windows: BTreeMap<u32, Window>,
245    /// The panes in the main window, in order.
246    main_children: Vec<u32>,
247    next_id: u32,
248    main: Rect,
249    /// The old-style status line, kept as a pane of its own.
250    status: Option<u32>,
251    layout_changed: bool,
252    changed: BTreeSet<u32>,
253}
254
255impl Screen {
256    /// A screen of the given size, with no panes.
257    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    /// The screen has a new size.
278    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    /// The screen's size, as lines and columns.
287    pub fn size(&self) -> (usize, usize) {
288        (self.rows, self.columns)
289    }
290
291    /// What is left for the main window.
292    pub fn main(&self) -> Rect {
293        self.main
294    }
295
296    /// Create a pane, or `None` if it cannot be.
297    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        // A parent that is not a pane means the main window.
307        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        // A pane starts with no size in the dimension it can be sized
317        // in, and the main window's in the other.
318        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    /// Delete a pane. Its own panes stay, but are no longer shown.
373    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    /// Remove a pane's text.
394    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    /// Add text to a pane. A newline goes to the start of the next line.
402    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    /// Move where the next character goes in a grid, counting from zero.
417    /// Text panes have no positions, and ignore this.
418    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    /// Change a pane's size. An advisory size is only a guess for hosts
428    /// that cannot size a pane to its contents, so it is ignored.
429    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    /// Make a pane just big enough for what it holds, in the dimension
446    /// it can be sized in.
447    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    /// Give a pane a background color.
503    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    /// The background color a pane was given, if any. The old-style
513    /// status line has the status line's.
514    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    /// What a program can learn about a pane.
522    pub fn info(&self, id: u32) -> Option<PaneInfo> {
523        let window = self.windows.get(&id)?;
524        Some(PaneInfo {
525            align: window.align,
526            // A fixed-pitch display lines text up at tab stops.
527            style: window.flags | style::TAB_ALIGN,
528            rows: window.rect.height,
529            columns: window.rect.width,
530        })
531    }
532
533    /// How a pane is placed, as the program asked.
534    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    /// Whether a pane can be at the left or right of the main window: a
547    /// display that can keep the main window's text to part of its width
548    /// says yes.
549    pub fn set_side_panes(&mut self, side_panes: bool) {
550        self.side_panes = side_panes;
551    }
552
553    /// Show the old-style status line, the program's location at the left
554    /// and its score at the right, in a line of its own at the top.
555    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    /// The old-style status line, if there is one.
594    pub fn status(&self) -> Option<u32> {
595        self.status
596    }
597
598    /// The panes on the screen, outermost first, with where each is.
599    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    /// The area a pane shows its own text in: what is left once its own
614    /// panes have taken their space.
615    pub fn rect(&self, id: u32) -> Option<Rect> {
616        self.windows.get(&id).map(|window| window.rect)
617    }
618
619    /// What a pane shows, a line for each line of its area, each as wide
620    /// as the area.
621    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        // A text pane that keeps its last line in view shows the end of
627        // its text; anything else shows the start.
628        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    /// Whether the layout has changed since this was last asked, and
649    /// everything needs drawing again.
650    pub fn take_layout_changed(&mut self) -> bool {
651        std::mem::take(&mut self.layout_changed)
652    }
653
654    /// The panes whose text has changed since this was last asked.
655    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    /// Work out where everything goes: the main window starts with the
667    /// whole screen, and each pane in turn takes its space from what its
668    /// parent has left.
669    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        // A quarter of the 22 lines the top pane left.
766        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        // Placed first, a pane takes its space before the others.
795        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        // An advisory size leaves it fitted; a size it is given does not.
859        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        // Advisory sizes are for hosts that cannot do this.
907        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}