Skip to main content

sui_core/
dpi.rs

1use crate::Size;
2
3#[derive(Debug, Clone, Copy, Default, PartialEq)]
4pub struct SafeAreaInsets {
5    pub left: f32,
6    pub top: f32,
7    pub right: f32,
8    pub bottom: f32,
9}
10
11impl SafeAreaInsets {
12    pub const ZERO: Self = Self::new(0.0, 0.0, 0.0, 0.0);
13
14    pub const fn new(left: f32, top: f32, right: f32, bottom: f32) -> Self {
15        Self {
16            left,
17            top,
18            right,
19            bottom,
20        }
21    }
22
23    pub fn normalized(self) -> Self {
24        Self::new(
25            normalize_inset(self.left),
26            normalize_inset(self.top),
27            normalize_inset(self.right),
28            normalize_inset(self.bottom),
29        )
30    }
31
32    pub fn horizontal(self) -> f32 {
33        self.left + self.right
34    }
35
36    pub fn vertical(self) -> f32 {
37        self.top + self.bottom
38    }
39}
40
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub struct DpiInfo {
43    pub scale_factor: f32,
44    pub raw_dpi: Option<f32>,
45    pub viewport: Size,
46    pub surface_size: Size,
47    pub safe_area: SafeAreaInsets,
48}
49
50impl DpiInfo {
51    pub const BASE_DPI: f32 = 96.0;
52
53    pub fn new(
54        scale_factor: f32,
55        raw_dpi: Option<f32>,
56        viewport: Size,
57        surface_size: Size,
58    ) -> Self {
59        Self {
60            scale_factor: normalize_scale_factor(scale_factor),
61            raw_dpi: raw_dpi.filter(|value| value.is_finite() && *value > 0.0),
62            viewport,
63            surface_size,
64            safe_area: SafeAreaInsets::ZERO,
65        }
66    }
67
68    pub fn with_safe_area(mut self, safe_area: SafeAreaInsets) -> Self {
69        self.safe_area = safe_area.normalized();
70        self
71    }
72
73    pub fn effective_dpi(self) -> f32 {
74        self.scale_factor * Self::BASE_DPI
75    }
76
77    pub fn pixels_per_point(self) -> f32 {
78        self.scale_factor
79    }
80
81    pub fn physical_pixels_to_logical(self, pixels: f32) -> f32 {
82        pixels / self.scale_factor
83    }
84
85    pub fn logical_to_physical_pixels(self, logical: f32) -> f32 {
86        logical * self.scale_factor
87    }
88
89    pub fn hairline_width(self) -> f32 {
90        self.physical_pixels_to_logical(1.0)
91    }
92}
93
94impl Default for DpiInfo {
95    fn default() -> Self {
96        Self::new(1.0, None, Size::ZERO, Size::ZERO)
97    }
98}
99
100fn normalize_scale_factor(scale_factor: f32) -> f32 {
101    if scale_factor.is_finite() && scale_factor > 0.0 {
102        scale_factor
103    } else {
104        1.0
105    }
106}
107
108fn normalize_inset(inset: f32) -> f32 {
109    if inset.is_finite() {
110        inset.max(0.0)
111    } else {
112        0.0
113    }
114}