Skip to main content

tvui/desktop/
fit.rs

1//! Where a new window opens: sized to its content and kept on the desktop.
2
3use ratatui::layout::Rect;
4
5use super::Desktop;
6use super::place::{Place, cell, within};
7
8impl<Id: Copy + Eq> Desktop<Id> {
9    /// The rect of a new window of `size`, at most the desktop's, one cell down and right of the
10    /// front window's drawn place and kept inside `area`; the corner of `area` with no window.
11    #[must_use]
12    pub fn fitted_rect(&self, (width, height): (u16, u16), area: Rect) -> Rect {
13        let width = width.min(area.width);
14        let height = height.min(area.height);
15        let (x, y) = self
16            .front()
17            .and_then(|id| self.place_of(id, area))
18            .map_or((i32::from(area.x), i32::from(area.y)), |front| {
19                (front.x + 1, front.y + 1)
20            });
21        let x = within(
22            x,
23            i32::from(area.x),
24            i32::from(area.right()) - i32::from(width),
25        );
26        let y = within(
27            y,
28            i32::from(area.y),
29            i32::from(area.bottom()) - i32::from(height),
30        );
31        Rect::new(cell(x), cell(y), width, height)
32    }
33
34    /// Sizes `id` to `size`, at most `area`'s, and moves it back inside `area` when it would
35    /// overhang; nothing when it is not open. A size equal to the stored one keeps the place.
36    pub fn set_size(&mut self, id: Id, (width, height): (u16, u16), area: Rect) {
37        let Some(window) = self.window_mut(id) else {
38            return;
39        };
40        let width = width.min(area.width);
41        let height = height.min(area.height);
42        if (width, height) == (window.place.width, window.place.height) {
43            return;
44        }
45        let right = i32::from(area.right()) - i32::from(width);
46        let bottom = i32::from(area.bottom()) - i32::from(height);
47        window.place = Place {
48            x: within(window.place.x, i32::from(area.x), right),
49            y: within(window.place.y, i32::from(area.y), bottom),
50            width,
51            height,
52        };
53    }
54}