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

            
4
use ratatui::buffer::Buffer;
5
use ratatui::layout::Rect;
6
use std::slice::Iter;
7

            
8
use crate::{Caps, Role, Theme};
9

            
10
mod arrange;
11
mod drag;
12
mod fit;
13
mod place;
14

            
15
pub use drag::{Change, changed};
16
pub use place::{Place, copy_visible};
17

            
18
/// TV's `minWinSize`: the least columns and rows a window is sized to.
19
pub(crate) const MIN_SIZE: (u16, u16) = (16, 6);
20

            
21
/// The desktop background pattern, TV's `defaultBkgrnd` (CP437 0xB0).
22
const 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)]
28
pub struct Window<Id> {
29
    pub id: Id,
30
    pub place: Place,
31
    pub zoomed: bool,
32
    pub caps: Caps,
33
}
34

            
35
impl<Id> Window<Id> {
36
    /// Stores `to`, keeping the size when the window cannot grow.
37
228
    fn set_place(&mut self, to: Place) {
38
228
        self.place = match self.caps.grow {
39
222
            true => to,
40
6
            false => Place {
41
6
                x: to.x,
42
6
                y: to.y,
43
6
                ..self.place
44
6
            },
45
        };
46
228
    }
47
}
48

            
49
/// The windows back to front: the last is the front (current) one.
50
#[derive(Debug, Clone, PartialEq, Eq)]
51
pub struct Desktop<Id> {
52
    windows: Vec<Window<Id>>,
53
}
54

            
55
impl<Id> Default for Desktop<Id> {
56
2174
    fn default() -> Self {
57
2174
        Self {
58
2174
            windows: Vec::new(),
59
2174
        }
60
2174
    }
61
}
62

            
63
impl<Id: Copy + Eq> Desktop<Id> {
64
    /// Opens `id` on top; ids are never reused, so `id` is not already open.
65
20790
    pub fn open(&mut self, id: Id, rect: Rect, caps: Caps) {
66
20790
        self.windows.push(Window {
67
20790
            id,
68
20790
            place: Place::from(rect),
69
20790
            zoomed: false,
70
20790
            caps,
71
20790
        });
72
20790
    }
73

            
74
    /// Brings `id` to the front; false when it is not open.
75
2817
    pub fn raise(&mut self, id: Id) -> bool {
76
2817
        let Some(index) = self.position(id) else {
77
1
            return false;
78
        };
79
2816
        let window = self.windows.remove(index);
80
2816
        self.windows.push(window);
81
2816
        true
82
2817
    }
83

            
84
    /// Sends `id` behind every other window; false when it is not open.
85
7
    pub fn lower(&mut self, id: Id) -> bool {
86
7
        let Some(index) = self.position(id) else {
87
1
            return false;
88
        };
89
6
        let window = self.windows.remove(index);
90
6
        self.windows.insert(0, window);
91
6
        true
92
7
    }
93

            
94
    /// Removes `id`; false when it is not open.
95
687
    pub fn close(&mut self, id: Id) -> bool {
96
687
        let Some(index) = self.position(id) else {
97
1
            return false;
98
        };
99
686
        self.windows.remove(index);
100
686
        true
101
687
    }
102

            
103
71789
    pub fn front(&self) -> Option<Id> {
104
71789
        self.windows.last().map(|window| window.id)
105
71789
    }
106

            
107
32
    pub fn rearmost(&self) -> Option<Id> {
108
32
        self.windows.first().map(|window| window.id)
109
32
    }
110

            
111
    /// Flips the zoom flag of `id`; false when it is not open or cannot zoom.
112
20666
    pub fn toggle_zoom(&mut self, id: Id) -> bool {
113
20666
        let Some(index) = self.position(id) else {
114
1
            return false;
115
        };
116
20665
        let window = &mut self.windows[index];
117
20665
        window.zoomed ^= window.caps.zoom;
118
20665
        window.caps.zoom
119
20666
    }
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
8
    pub fn tile(&mut self, area: Rect) -> bool {
124
8
        match arrange::tile(self.tileable(), area) {
125
6
            Some(rects) => self.place(&rects),
126
2
            None => false,
127
        }
128
8
    }
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
9
    pub fn cascade(&mut self, area: Rect) -> bool {
133
9
        match arrange::cascade(self.tileable(), area) {
134
6
            Some(rects) => self.place(&rects),
135
3
            None => false,
136
        }
137
9
    }
138

            
139
17
    fn tileable(&self) -> usize {
140
17
        self.windows
141
17
            .iter()
142
113
            .filter(|window| window.caps.tile)
143
            .count()
144
17
    }
145

            
146
    /// Gives the tileable windows back to front the stored `rects`, unzoomed.
147
12
    fn place(&mut self, rects: &[Rect]) -> bool {
148
85
        let tileable = self.windows.iter_mut().filter(|window| window.caps.tile);
149
12
        for (window, rect) in tileable.zip(rects) {
150
82
            window.place = Place::from(*rect);
151
82
            window.zoomed = false;
152
        }
153
12
        true
154
12
    }
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
18
    pub fn resize(&mut self, old: Rect, new: Rect) {
159
18
        for window in &mut self.windows {
160
130
            window.set_place(window.place.scaled(old, new));
161
        }
162
18
    }
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
75119
    pub fn place_of(&self, id: Id, area: Rect) -> Option<Place> {
168
75119
        let window = self.windows.get(self.position(id)?)?;
169
75118
        match window.zoomed {
170
72762
            true => Some(Place::from(area)),
171
2356
            false => self.restored_place(id, area),
172
        }
173
75119
    }
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
21010
    pub fn restored_place(&self, id: Id, area: Rect) -> Option<Place> {
178
21010
        let window = self.windows.get(self.position(id)?)?;
179
21009
        Some(window.place.limited(area))
180
21010
    }
181

            
182
    /// True when the windows in front of `id` cover all the cells that show it.
183
14066
    pub fn occluded(&self, id: Id, area: Rect) -> bool {
184
14066
        let Some(index) = self.position(id) else {
185
1
            return false;
186
        };
187
14065
        let Some(place) = self.place_of(id, area) else {
188
            return false;
189
        };
190
14065
        let in_front: Vec<Rect> = self.windows[index + 1..]
191
14065
            .iter()
192
58561
            .filter_map(|window| self.place_of(window.id, area))
193
58561
            .map(|front| front.visible_in(area))
194
            .collect();
195
14065
        place
196
14065
            .visible_in(area)
197
14065
            .positions()
198
20891429
            .all(|position| in_front.iter().any(|front| front.contains(position)))
199
14066
    }
200

            
201
    /// The slot of `id` as it is now, to hand back to `restore`.
202
1776
    pub fn window(&self, id: Id) -> Option<Window<Id>> {
203
1776
        self.windows.get(self.position(id)?).copied()
204
1776
    }
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
132
    pub fn restore(&mut self, saved: Window<Id>) -> bool {
209
132
        let Some(index) = self.position(saved.id) else {
210
1
            return false;
211
        };
212
131
        self.windows[index] = saved;
213
131
        true
214
132
    }
215

            
216
    /// The windows in drawing order: the front one last.
217
81246
    pub fn iter_back_to_front(&self) -> Iter<'_, Window<Id>> {
218
81246
        self.windows.iter()
219
81246
    }
220

            
221
16
    fn window_mut(&mut self, id: Id) -> Option<&mut Window<Id>> {
222
16
        let index = self.position(id)?;
223
15
        self.windows.get_mut(index)
224
16
    }
225

            
226
136398
    fn position(&self, id: Id) -> Option<usize> {
227
844282
        self.windows.iter().position(|window| window.id == id)
228
136398
    }
229
}
230

            
231
/// Fills `area` with the desktop background pattern; the windows draw over it.
232
4238
pub fn render_background(area: Rect, buf: &mut Buffer, theme: &Theme) {
233
4238
    let style = theme.style(Role::Desktop);
234
4238
    for position in area.intersection(buf.area).positions() {
235
8120642
        if let Some(cell) = buf.cell_mut(position) {
236
8120642
            cell.set_symbol(BACKGROUND).set_style(style);
237
        }
238
    }
239
4238
}
240

            
241
#[cfg(test)]
242
mod caps_tests;
243
#[cfg(test)]
244
mod fit_tests;
245
#[cfg(test)]
246
mod tests;