1use core::fmt;
8use core::ops::{Add, Div, Mul, Sub};
9
10use crate::geometry::{Point, Rect, Size, Vector};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[cfg_attr(feature = "serde", serde(transparent))]
16pub struct Logical<T>(pub T);
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22#[cfg_attr(feature = "serde", serde(transparent))]
23pub struct Physical<T>(T);
24
25impl<T> Logical<T> {
26 pub fn get(self) -> T {
28 self.0
29 }
30}
31
32impl<T> Physical<T> {
33 pub const fn new(value: T) -> Self {
35 Self(value)
36 }
37
38 pub fn get(self) -> T {
40 self.0
41 }
42}
43
44impl From<(f32, f32)> for Logical<Size> {
45 fn from((width, height): (f32, f32)) -> Self {
46 Logical(Size::new(width, height))
47 }
48}
49
50impl<A: Add<B>, B> Add<Logical<B>> for Logical<A> {
51 type Output = Logical<A::Output>;
52
53 fn add(self, other: Logical<B>) -> Self::Output {
54 Logical(self.0 + other.0)
55 }
56}
57
58impl<A: Sub<B>, B> Sub<Logical<B>> for Logical<A> {
59 type Output = Logical<A::Output>;
60
61 fn sub(self, other: Logical<B>) -> Self::Output {
62 Logical(self.0 - other.0)
63 }
64}
65
66impl<A: Add<B>, B> Add<Physical<B>> for Physical<A> {
67 type Output = Physical<A::Output>;
68
69 fn add(self, other: Physical<B>) -> Self::Output {
70 Physical(self.0 + other.0)
71 }
72}
73
74impl<A: Sub<B>, B> Sub<Physical<B>> for Physical<A> {
75 type Output = Physical<A::Output>;
76
77 fn sub(self, other: Physical<B>) -> Self::Output {
78 Physical(self.0 - other.0)
79 }
80}
81
82mod sealed {
83 pub trait Sealed {}
84}
85
86pub trait Scalable: sealed::Sealed + Sized {
88 #[must_use]
90 fn scaled(self, factor: f32) -> Self;
91}
92
93impl sealed::Sealed for f32 {}
94impl Scalable for f32 {
95 fn scaled(self, factor: f32) -> Self {
96 self * factor
97 }
98}
99
100impl sealed::Sealed for Point {}
101impl Scalable for Point {
102 fn scaled(self, factor: f32) -> Self {
103 Point::new(self.x * factor, self.y * factor)
104 }
105}
106
107impl sealed::Sealed for Vector {}
108impl Scalable for Vector {
109 fn scaled(self, factor: f32) -> Self {
110 self * factor
111 }
112}
113
114impl sealed::Sealed for Size {}
115impl Scalable for Size {
116 fn scaled(self, factor: f32) -> Self {
117 self * factor
118 }
119}
120
121impl sealed::Sealed for Rect {}
122impl Scalable for Rect {
123 fn scaled(self, factor: f32) -> Self {
124 Rect::new(self.position().scaled(factor), self.size().scaled(factor))
125 }
126}
127
128impl<T: Scalable> Mul<ScaleFactor> for Logical<T> {
129 type Output = Physical<T>;
130
131 fn mul(self, factor: ScaleFactor) -> Physical<T> {
132 Physical(self.0.scaled(factor.0))
133 }
134}
135
136impl<T: Scalable> Div<ScaleFactor> for Physical<T> {
137 type Output = Logical<T>;
138
139 fn div(self, factor: ScaleFactor) -> Logical<T> {
140 Logical(self.0.scaled(1.0 / factor.0))
141 }
142}
143
144impl Logical<Size> {
145 #[must_use]
148 pub fn to_physical_pixels(self, factor: ScaleFactor) -> Physical<Size<u32>> {
149 let round = |value: f32| (f64::from(value) * f64::from(factor.0)).round() as u32;
150 Physical(Size::new(round(self.0.width), round(self.0.height)))
151 }
152}
153
154impl Physical<Size<u32>> {
155 #[must_use]
157 pub fn to_logical(self, factor: ScaleFactor) -> Logical<Size> {
158 let divide = |value: u32| (f64::from(value) / f64::from(factor.0)) as f32;
159 Logical(Size::new(divide(self.0.width), divide(self.0.height)))
160 }
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
165#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
166#[cfg_attr(feature = "serde", serde(try_from = "f32", into = "f32"))]
167pub struct ScaleFactor(f32);
168
169impl ScaleFactor {
170 pub const MIN: f32 = 0.5;
172 pub const MAX: f32 = 4.0;
174 pub const ONE: Self = Self(1.0);
176 pub const X1_25: Self = Self(1.25);
178 pub const X1_5: Self = Self(1.5);
180 pub const TWO: Self = Self(2.0);
182 pub const THREE: Self = Self(3.0);
184
185 pub const fn new(factor: f32) -> Result<Self, InvalidScaleFactor> {
187 if factor >= Self::MIN && factor <= Self::MAX {
188 return Ok(Self(factor));
189 }
190 Err(InvalidScaleFactor { factor })
191 }
192
193 #[must_use]
195 pub const fn get(self) -> f32 {
196 self.0
197 }
198}
199
200impl Default for ScaleFactor {
201 fn default() -> Self {
202 Self::ONE
203 }
204}
205
206impl TryFrom<f32> for ScaleFactor {
207 type Error = InvalidScaleFactor;
208
209 fn try_from(factor: f32) -> Result<Self, InvalidScaleFactor> {
210 Self::new(factor)
211 }
212}
213
214impl From<ScaleFactor> for f32 {
215 fn from(factor: ScaleFactor) -> f32 {
216 factor.0
217 }
218}
219
220impl fmt::Display for ScaleFactor {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 write!(f, "{}x", self.0)
224 }
225}
226
227#[derive(Debug, Clone, Copy, PartialEq)]
229pub struct InvalidScaleFactor {
230 factor: f32,
231}
232
233impl InvalidScaleFactor {
234 #[must_use]
236 pub const fn factor(self) -> f32 {
237 self.factor
238 }
239}
240
241impl fmt::Display for InvalidScaleFactor {
242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 write!(
244 f,
245 "scale {} is outside {} to {}",
246 self.factor,
247 ScaleFactor::MIN,
248 ScaleFactor::MAX
249 )
250 }
251}
252
253impl std::error::Error for InvalidScaleFactor {}
254
255#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
258#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
259#[cfg_attr(feature = "serde", serde(try_from = "f32", into = "f32"))]
260pub struct Ratio(f32);
261
262impl Ratio {
263 pub const ZERO: Self = Self(0.0);
265 pub const ONE: Self = Self(1.0);
267
268 pub const fn new(value: f32) -> Result<Self, InvalidRatio> {
270 if value >= 0.0 && value <= 1.0 {
271 return Ok(Self(value));
272 }
273 Err(InvalidRatio { value })
274 }
275
276 #[must_use]
278 pub const fn get(self) -> f32 {
279 self.0
280 }
281}
282
283impl TryFrom<f32> for Ratio {
284 type Error = InvalidRatio;
285
286 fn try_from(value: f32) -> Result<Self, InvalidRatio> {
287 Self::new(value)
288 }
289}
290
291impl From<Ratio> for f32 {
292 fn from(ratio: Ratio) -> f32 {
293 ratio.0
294 }
295}
296
297impl fmt::Display for Ratio {
298 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299 fmt::Display::fmt(&self.0, f)
300 }
301}
302
303#[derive(Debug, Clone, Copy, PartialEq)]
305pub struct InvalidRatio {
306 value: f32,
307}
308
309impl InvalidRatio {
310 #[must_use]
312 pub const fn value(self) -> f32 {
313 self.value
314 }
315}
316
317impl fmt::Display for InvalidRatio {
318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 write!(f, "ratio {} is outside 0 to 1", self.value)
320 }
321}
322
323impl std::error::Error for InvalidRatio {}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn scale_factor_rejects_out_of_range_and_non_finite() {
331 for bad in [
332 0.0,
333 -1.0,
334 0.49,
335 4.01,
336 f32::NAN,
337 f32::INFINITY,
338 f32::NEG_INFINITY,
339 ] {
340 assert!(ScaleFactor::new(bad).is_err(), "{bad}");
341 }
342 for good in [0.5, 1.0, 1.25, 4.0] {
343 assert_eq!(ScaleFactor::new(good).map(ScaleFactor::get), Ok(good));
344 }
345 assert_eq!(ScaleFactor::try_from(2.0), Ok(ScaleFactor::TWO));
346 assert_eq!(f32::from(ScaleFactor::X1_5), 1.5);
347 assert_eq!(ScaleFactor::default(), ScaleFactor::ONE);
348 }
349
350 #[test]
351 fn scale_factor_new_is_usable_in_const_items() {
352 const CUSTOM: Result<ScaleFactor, InvalidScaleFactor> = ScaleFactor::new(1.75);
353 assert_eq!(CUSTOM.map(ScaleFactor::get), Ok(1.75));
354 }
355
356 #[test]
357 fn named_scale_factors_are_valid() {
358 for factor in [
359 ScaleFactor::ONE,
360 ScaleFactor::X1_25,
361 ScaleFactor::X1_5,
362 ScaleFactor::TWO,
363 ScaleFactor::THREE,
364 ] {
365 assert_eq!(ScaleFactor::new(factor.get()), Ok(factor));
366 }
367 }
368
369 #[test]
370 fn scale_factor_errors_and_display() {
371 assert_eq!(ScaleFactor::TWO.to_string(), "2x");
372 assert_eq!(ScaleFactor::X1_25.to_string(), "1.25x");
373 let error = ScaleFactor::new(0.2).err();
374 assert_eq!(error.map(InvalidScaleFactor::factor), Some(0.2));
375 assert_eq!(
376 error.map(|e| e.to_string()).as_deref(),
377 Some("scale 0.2 is outside 0.5 to 4")
378 );
379 }
380
381 #[test]
382 fn logical_times_scale_is_physical_and_back() {
383 let logical = Logical(Size::new(100.0, 50.0));
384 let physical = logical * ScaleFactor::TWO;
385 assert_eq!(physical, Physical::new(Size::new(200.0, 100.0)));
386 assert_eq!(physical / ScaleFactor::TWO, logical);
387 assert_eq!(
388 Logical(Point::new(1.0, 2.0)) * ScaleFactor::THREE,
389 Physical::new(Point::new(3.0, 6.0))
390 );
391 assert_eq!(
392 Logical(Vector::new(1.0, -2.0)) * ScaleFactor::TWO,
393 Physical::new(Vector::new(2.0, -4.0))
394 );
395 assert_eq!(
396 Logical(Rect::new(Point::new(1.0, 2.0), Size::new(3.0, 4.0))) * ScaleFactor::TWO,
397 Physical::new(Rect::new(Point::new(2.0, 4.0), Size::new(6.0, 8.0)))
398 );
399 assert_eq!(Logical(4.0_f32) * ScaleFactor::X1_5, Physical::new(6.0));
400 }
401
402 #[test]
403 fn physical_pixels_round_like_winit() {
404 let size = Logical(Size::new(101.0, 33.0)).to_physical_pixels(ScaleFactor::X1_25);
405 assert_eq!(size, Physical::new(Size::new(126, 41)));
406 let size = Logical(Size::new(100.2, 100.5)).to_physical_pixels(ScaleFactor::ONE);
407 assert_eq!(size, Physical::new(Size::new(100, 101)));
408 assert_eq!(
409 Physical::new(Size::new(126_u32, 40)).to_logical(ScaleFactor::X1_25),
410 Logical(Size::new(100.8, 32.0))
411 );
412 }
413
414 #[test]
415 fn same_unit_arithmetic() {
416 assert_eq!(
417 Logical(Point::new(1.0, 1.0)) + Logical(Vector::new(2.0, 3.0)),
418 Logical(Point::new(3.0, 4.0))
419 );
420 assert_eq!(
421 Logical(Point::new(3.0, 4.0)) - Logical(Point::new(1.0, 1.0)),
422 Logical(Vector::new(2.0, 3.0))
423 );
424 assert_eq!(
425 Physical::new(2_u32) + Physical::new(3_u32),
426 Physical::new(5_u32)
427 );
428 assert_eq!(Physical::new(5_i32) - Physical::new(3), Physical::new(2));
429 assert_eq!(Logical(3.0_f32).get(), 3.0);
430 }
431
432 #[test]
433 fn tuples_make_logical_sizes() {
434 let size: Logical<Size> = (1280.0, 820.0).into();
435 assert_eq!(size, Logical(Size::new(1280.0, 820.0)));
436 }
437
438 #[test]
439 fn ratio_is_checked() {
440 for bad in [-0.01, 1.01, 10.0, f32::NAN] {
441 assert!(Ratio::new(bad).is_err(), "{bad}");
442 }
443 assert_eq!(Ratio::new(0.1).map(Ratio::get), Ok(0.1));
444 assert_eq!(Ratio::new(0.0), Ok(Ratio::ZERO));
445 assert_eq!(Ratio::new(1.0), Ok(Ratio::ONE));
446 assert_eq!(Ratio::try_from(0.5).map(f32::from), Ok(0.5));
447 assert_eq!(Ratio::default(), Ratio::ZERO);
448 assert_eq!(
449 Ratio::new(0.25).map(|r| r.to_string()),
450 Ok("0.25".to_owned())
451 );
452 let error = Ratio::new(10.0).err();
453 assert_eq!(error.map(InvalidRatio::value), Some(10.0));
454 assert_eq!(
455 error.map(|e| e.to_string()).as_deref(),
456 Some("ratio 10 is outside 0 to 1")
457 );
458 }
459
460 #[cfg(feature = "serde")]
461 #[test]
462 fn checked_numbers_validate_when_deserialised() -> Result<(), serde_json::Error> {
463 assert_eq!(serde_json::to_string(&ScaleFactor::TWO)?, "2.0");
464 assert_eq!(
465 serde_json::from_str::<ScaleFactor>("1.5")?,
466 ScaleFactor::X1_5
467 );
468 assert!(serde_json::from_str::<ScaleFactor>("0.1").is_err());
469 assert_eq!(
470 serde_json::from_str::<Ratio>("0.5")?,
471 Ratio::new(0.5).unwrap_or_default()
472 );
473 assert!(serde_json::from_str::<Ratio>("2").is_err());
474 assert_eq!(
475 serde_json::to_string(&Logical(Point::new(1.0, 2.0)))?,
476 r#"{"x":1.0,"y":2.0}"#
477 );
478 Ok(())
479 }
480}