Skip to main content

glory_render/
viewport_layer.rs

1use crate::{Error, Rect};
2
3/// A manually positioned viewport layer. Position is independent of its logical
4/// ancestors and never implies a popup anchor or a source lookup.
5#[derive(Clone, Copy, Debug, PartialEq)]
6pub struct ViewportPlacement {
7    pub x: f64,
8    pub y: f64,
9    pub viewport_padding: f64,
10    pub constrain: bool,
11}
12impl Default for ViewportPlacement {
13    fn default() -> Self {
14        Self {
15            x: 48.,
16            y: 48.,
17            viewport_padding: 8.,
18            constrain: true,
19        }
20    }
21}
22impl ViewportPlacement {
23    pub fn validate(self) -> Result<(), Error> {
24        if ![self.x, self.y]
25            .iter()
26            .all(|v| v.is_finite() && v.abs() <= 1_000_000.)
27            || !self.viewport_padding.is_finite()
28            || !(0. ..=4096.).contains(&self.viewport_padding)
29        {
30            return Err(Error::InvalidProps(
31                "viewport layer position and padding exceed finite bounds",
32            ));
33        }
34        Ok(())
35    }
36    /// Preserve dimensions; oversized panels start at the padded viewport edge.
37    pub fn resolve(self, panel: Rect, viewport: Rect) -> Result<Rect, Error> {
38        self.validate()?;
39        for rect in [panel, viewport] {
40            if ![
41                rect.x,
42                rect.y,
43                rect.width,
44                rect.height,
45                rect.x + rect.width,
46                rect.y + rect.height,
47            ]
48            .iter()
49            .all(|v| v.is_finite())
50                || rect.width < 0.
51                || rect.height < 0.
52            {
53                return Err(Error::InvalidProps(
54                    "viewport layer geometry must be finite and nonnegative",
55                ));
56            }
57        }
58        let min_x = viewport.x + self.viewport_padding;
59        let min_y = viewport.y + self.viewport_padding;
60        let max_x = viewport.x + viewport.width - self.viewport_padding - panel.width;
61        let max_y = viewport.y + viewport.height - self.viewport_padding - panel.height;
62        if ![min_x, min_y, max_x, max_y].iter().all(|v| v.is_finite()) {
63            return Err(Error::InvalidProps(
64                "viewport layer geometry arithmetic overflow",
65            ));
66        }
67        Ok(Rect {
68            x: if self.constrain {
69                self.x.clamp(min_x, max_x.max(min_x))
70            } else {
71                self.x
72            },
73            y: if self.constrain {
74                self.y.clamp(min_y, max_y.max(min_y))
75            } else {
76                self.y
77            },
78            ..panel
79        })
80    }
81}