Skip to main content

tvui/
desktop.rs

1//! The window manager as plain data: the windows in z-order with their rects and zoom flags.
2//! No events and no app types; the app owns the window state and asks the desktop where each goes.
3
4use ratatui::buffer::Buffer;
5use ratatui::layout::Rect;
6use std::slice::Iter;
7
8use crate::{Caps, Role, Theme};
9
10mod arrange;
11mod drag;
12mod fit;
13mod place;
14
15pub use drag::{Change, changed};
16pub use place::{Place, copy_visible};
17
18/// TV's `minWinSize`: the least columns and rows a window is sized to.
19pub(crate) const MIN_SIZE: (u16, u16) = (16, 6);
20
21/// The desktop background pattern, TV's `defaultBkgrnd` (CP437 0xB0).
22const BACKGROUND: &str = "\u{2591}";
23
24/// One window of the desktop. The place is where it sits when not zoomed, in screen-absolute
25/// cells (TV stores it relative to the desktop): the app draws the desktop at a fixed offset,
26/// and `place_of` limits it against whatever area it is handed.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct Window<Id> {
29    pub id: Id,
30    pub place: Place,
31    pub zoomed: bool,
32    pub caps: Caps,
33}
34
35impl<Id> Window<Id> {
36    /// Stores `to`, keeping the size when the window cannot grow.
37    fn set_place(&mut self, to: Place) {
38        self.place = match self.caps.grow {
39            true => to,
40            false => Place {
41                x: to.x,
42                y: to.y,
43                ..self.place
44            },
45        };
46    }
47}
48
49/// The windows back to front: the last is the front (current) one.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Desktop<Id> {
52    windows: Vec<Window<Id>>,
53}
54
55impl<Id> Default for Desktop<Id> {
56    fn default() -> Self {
57        Self {
58            windows: Vec::new(),
59        }
60    }
61}
62
63impl<Id: Copy + Eq> Desktop<Id> {
64    /// Opens `id` on top; ids are never reused, so `id` is not already open.
65    pub fn open(&mut self, id: Id, rect: Rect, caps: Caps) {
66        self.windows.push(Window {
67            id,
68            place: Place::from(rect),
69            zoomed: false,
70            caps,
71        });
72    }
73
74    /// Brings `id` to the front; false when it is not open.
75    pub fn raise(&mut self, id: Id) -> bool {
76        let Some(index) = self.position(id) else {
77            return false;
78        };
79        let window = self.windows.remove(index);
80        self.windows.push(window);
81        true
82    }
83
84    /// Sends `id` behind every other window; false when it is not open.
85    pub fn lower(&mut self, id: Id) -> bool {
86        let Some(index) = self.position(id) else {
87            return false;
88        };
89        let window = self.windows.remove(index);
90        self.windows.insert(0, window);
91        true
92    }
93
94    /// Removes `id`; false when it is not open.
95    pub fn close(&mut self, id: Id) -> bool {
96        let Some(index) = self.position(id) else {
97            return false;
98        };
99        self.windows.remove(index);
100        true
101    }
102
103    pub fn front(&self) -> Option<Id> {
104        self.windows.last().map(|window| window.id)
105    }
106
107    pub fn rearmost(&self) -> Option<Id> {
108        self.windows.first().map(|window| window.id)
109    }
110
111    /// Flips the zoom flag of `id`; false when it is not open or cannot zoom.
112    pub fn toggle_zoom(&mut self, id: Id) -> bool {
113        let Some(index) = self.position(id) else {
114            return false;
115        };
116        let window = &mut self.windows[index];
117        window.zoomed ^= window.caps.zoom;
118        window.caps.zoom
119    }
120
121    /// Lays every tileable window out in TV's tile grid over `area`, unzoomed; false, with nothing
122    /// moved, when the tileable windows do not fit.
123    pub fn tile(&mut self, area: Rect) -> bool {
124        match arrange::tile(self.tileable(), area) {
125            Some(rects) => self.place(&rects),
126            None => false,
127        }
128    }
129
130    /// Lays every tileable window out in TV's cascade over `area`, unzoomed; false, with nothing
131    /// moved, when the tileable windows do not fit.
132    pub fn cascade(&mut self, area: Rect) -> bool {
133        match arrange::cascade(self.tileable(), area) {
134            Some(rects) => self.place(&rects),
135            None => false,
136        }
137    }
138
139    fn tileable(&self) -> usize {
140        self.windows
141            .iter()
142            .filter(|window| window.caps.tile)
143            .count()
144    }
145
146    /// Gives the tileable windows back to front the stored `rects`, unzoomed.
147    fn place(&mut self, rects: &[Rect]) -> bool {
148        let tileable = self.windows.iter_mut().filter(|window| window.caps.tile);
149        for (window, rect) in tileable.zip(rects) {
150            window.place = Place::from(*rect);
151            window.zoomed = false;
152        }
153        true
154    }
155
156    /// Fits every window to the desktop going from `old` to `new`, as TV does when its owner
157    /// changes size: see `Place::scaled`.
158    pub fn resize(&mut self, old: Rect, new: Rect) {
159        for window in &mut self.windows {
160            window.set_place(window.place.scaled(old, new));
161        }
162    }
163
164    /// Where `id` is placed in `area`: all of it when zoomed, else its place as TV keeps it
165    /// (see `restored_place`). The place may reach beyond `area`; `Place::visible_in` says which
166    /// cells show.
167    pub fn place_of(&self, id: Id, area: Rect) -> Option<Place> {
168        let window = self.windows.get(self.position(id)?)?;
169        match window.zoomed {
170            true => Some(Place::from(area)),
171            false => self.restored_place(id, area),
172        }
173    }
174
175    /// Where `id` sits once unzoomed, whether it is zoomed now or not: the size limited to
176    /// `area`'s, the origin to TV's limits.
177    pub fn restored_place(&self, id: Id, area: Rect) -> Option<Place> {
178        let window = self.windows.get(self.position(id)?)?;
179        Some(window.place.limited(area))
180    }
181
182    /// True when the windows in front of `id` cover all the cells that show it.
183    pub fn occluded(&self, id: Id, area: Rect) -> bool {
184        let Some(index) = self.position(id) else {
185            return false;
186        };
187        let Some(place) = self.place_of(id, area) else {
188            return false;
189        };
190        let in_front: Vec<Rect> = self.windows[index + 1..]
191            .iter()
192            .filter_map(|window| self.place_of(window.id, area))
193            .map(|front| front.visible_in(area))
194            .collect();
195        place
196            .visible_in(area)
197            .positions()
198            .all(|position| in_front.iter().any(|front| front.contains(position)))
199    }
200
201    /// The slot of `id` as it is now, to hand back to `restore`.
202    pub fn window(&self, id: Id) -> Option<Window<Id>> {
203        self.windows.get(self.position(id)?).copied()
204    }
205
206    /// Puts a window saved by `window` back in its slot, rect and zoom as they were; false when
207    /// it is not open.
208    pub fn restore(&mut self, saved: Window<Id>) -> bool {
209        let Some(index) = self.position(saved.id) else {
210            return false;
211        };
212        self.windows[index] = saved;
213        true
214    }
215
216    /// The windows in drawing order: the front one last.
217    pub fn iter_back_to_front(&self) -> Iter<'_, Window<Id>> {
218        self.windows.iter()
219    }
220
221    fn window_mut(&mut self, id: Id) -> Option<&mut Window<Id>> {
222        let index = self.position(id)?;
223        self.windows.get_mut(index)
224    }
225
226    fn position(&self, id: Id) -> Option<usize> {
227        self.windows.iter().position(|window| window.id == id)
228    }
229}
230
231/// Fills `area` with the desktop background pattern; the windows draw over it.
232pub fn render_background(area: Rect, buf: &mut Buffer, theme: &Theme) {
233    let style = theme.style(Role::Desktop);
234    for position in area.intersection(buf.area).positions() {
235        if let Some(cell) = buf.cell_mut(position) {
236            cell.set_symbol(BACKGROUND).set_style(style);
237        }
238    }
239}
240
241#[cfg(test)]
242mod caps_tests;
243#[cfg(test)]
244mod fit_tests;
245#[cfg(test)]
246mod tests;