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]
147 pub fn to_physical_pixels(self, factor: ScaleFactor) -> Physical<Size<u32>> {
148 let round = |value: f32| (f64::from(value) * f64::from(factor.0)).round() as u32;
149 Physical(Size::new(round(self.0.width), round(self.0.height)))
150 }
151}
152
153impl Physical<Size<u32>> {
154 #[must_use]
156 pub fn to_logical(self, factor: ScaleFactor) -> Logical<Size> {
157 let divide = |value: u32| (f64::from(value) / f64::from(factor.0)) as f32;
158 Logical(Size::new(divide(self.0.width), divide(self.0.height)))
159 }
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
164#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
165#[cfg_attr(feature = "serde", serde(try_from = "f32", into = "f32"))]
166pub struct ScaleFactor(f32);
167
168impl ScaleFactor {
169 pub const MIN: f32 = 0.5;
171 pub const MAX: f32 = 4.0;
173 pub const ONE: Self = Self(1.0);
175 pub const X1_25: Self = Self(1.25);
177 pub const X1_5: Self = Self(1.5);
179 pub const TWO: Self = Self(2.0);
181 pub const THREE: Self = Self(3.0);
183
184 pub const fn new(factor: f32) -> Result<Self, InvalidScaleFactor> {
186 if factor >= Self::MIN && factor <= Self::MAX {
187 return Ok(Self(factor));
188 }
189 Err(InvalidScaleFactor { factor })
190 }
191
192 #[must_use]
194 pub const fn get(self) -> f32 {
195 self.0
196 }
197}
198
199impl Default for ScaleFactor {
200 fn default() -> Self {
201 Self::ONE
202 }
203}
204
205impl TryFrom<f32> for ScaleFactor {
206 type Error = InvalidScaleFactor;
207
208 fn try_from(factor: f32) -> Result<Self, InvalidScaleFactor> {
209 Self::new(factor)
210 }
211}
212
213impl From<ScaleFactor> for f32 {
214 fn from(factor: ScaleFactor) -> f32 {
215 factor.0
216 }
217}
218
219impl fmt::Display for ScaleFactor {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 write!(f, "{}x", self.0)
223 }
224}
225
226#[derive(Debug, Clone, Copy, PartialEq)]
228pub struct InvalidScaleFactor {
229 factor: f32,
230}
231
232impl InvalidScaleFactor {
233 #[must_use]
235 pub const fn factor(self) -> f32 {
236 self.factor
237 }
238}
239
240impl fmt::Display for InvalidScaleFactor {
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 write!(
243 f,
244 "scale {} is outside {} to {}",
245 self.factor,
246 ScaleFactor::MIN,
247 ScaleFactor::MAX
248 )
249 }
250}
251
252impl std::error::Error for InvalidScaleFactor {}
253
254#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
257#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
258#[cfg_attr(feature = "serde", serde(try_from = "f32", into = "f32"))]
259pub struct Ratio(f32);
260
261impl Ratio {
262 pub const ZERO: Self = Self(0.0);
264 pub const ONE: Self = Self(1.0);
266
267 pub const fn new(value: f32) -> Result<Self, InvalidRatio> {
269 if value >= 0.0 && value <= 1.0 {
270 return Ok(Self(value));
271 }
272 Err(InvalidRatio { value })
273 }
274
275 #[must_use]
277 pub const fn get(self) -> f32 {
278 self.0
279 }
280}
281
282impl TryFrom<f32> for Ratio {
283 type Error = InvalidRatio;
284
285 fn try_from(value: f32) -> Result<Self, InvalidRatio> {
286 Self::new(value)
287 }
288}
289
290impl From<Ratio> for f32 {
291 fn from(ratio: Ratio) -> f32 {
292 ratio.0
293 }
294}
295
296impl fmt::Display for Ratio {
297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298 fmt::Display::fmt(&self.0, f)
299 }
300}
301
302#[derive(Debug, Clone, Copy, PartialEq)]
304pub struct InvalidRatio {
305 value: f32,
306}
307
308impl InvalidRatio {
309 #[must_use]
311 pub const fn value(self) -> f32 {
312 self.value
313 }
314}
315
316impl fmt::Display for InvalidRatio {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 write!(f, "ratio {} is outside 0 to 1", self.value)
319 }
320}
321
322impl std::error::Error for InvalidRatio {}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327
328 #[test]
329 fn scale_factor_rejects_out_of_range_and_non_finite() {
330 for bad in [
331 0.0,
332 -1.0,
333 0.49,
334 4.01,
335 f32::NAN,
336 f32::INFINITY,
337 f32::NEG_INFINITY,
338 ] {
339 assert!(ScaleFactor::new(bad).is_err(), "{bad}");
340 }
341 for good in [0.5, 1.0, 1.25, 4.0] {
342 assert_eq!(ScaleFactor::new(good).map(ScaleFactor::get), Ok(good));
343 }
344 assert_eq!(ScaleFactor::try_from(2.0), Ok(ScaleFactor::TWO));
345 assert_eq!(f32::from(ScaleFactor::X1_5), 1.5);
346 assert_eq!(ScaleFactor::default(), ScaleFactor::ONE);
347 }
348
349 #[test]
350 fn scale_factor_new_is_usable_in_const_items() {
351 const CUSTOM: Result<ScaleFactor, InvalidScaleFactor> = ScaleFactor::new(1.75);
352 assert_eq!(CUSTOM.map(ScaleFactor::get), Ok(1.75));
353 }
354
355 #[test]
356 fn named_scale_factors_are_valid() {
357 for factor in [
358 ScaleFactor::ONE,
359 ScaleFactor::X1_25,
360 ScaleFactor::X1_5,
361 ScaleFactor::TWO,
362 ScaleFactor::THREE,
363 ] {
364 assert_eq!(ScaleFactor::new(factor.get()), Ok(factor));
365 }
366 }
367
368 #[test]
369 fn scale_factor_errors_and_display() {
370 assert_eq!(ScaleFactor::TWO.to_string(), "2x");
371 assert_eq!(ScaleFactor::X1_25.to_string(), "1.25x");
372 let error = ScaleFactor::new(0.2).err();
373 assert_eq!(error.map(InvalidScaleFactor::factor), Some(0.2));
374 assert_eq!(
375 error.map(|e| e.to_string()).as_deref(),
376 Some("scale 0.2 is outside 0.5 to 4")
377 );
378 }
379
380 #[test]
381 fn logical_times_scale_is_physical_and_back() {
382 let logical = Logical(Size::new(100.0, 50.0));
383 let physical = logical * ScaleFactor::TWO;
384 assert_eq!(physical, Physical::new(Size::new(200.0, 100.0)));
385 assert_eq!(physical / ScaleFactor::TWO, logical);
386 assert_eq!(
387 Logical(Point::new(1.0, 2.0)) * ScaleFactor::THREE,
388 Physical::new(Point::new(3.0, 6.0))
389 );
390 assert_eq!(
391 Logical(Vector::new(1.0, -2.0)) * ScaleFactor::TWO,
392 Physical::new(Vector::new(2.0, -4.0))
393 );
394 assert_eq!(
395 Logical(Rect::new(Point::new(1.0, 2.0), Size::new(3.0, 4.0))) * ScaleFactor::TWO,
396 Physical::new(Rect::new(Point::new(2.0, 4.0), Size::new(6.0, 8.0)))
397 );
398 assert_eq!(Logical(4.0_f32) * ScaleFactor::X1_5, Physical::new(6.0));
399 }
400
401 #[test]
402 fn physical_pixels_round_like_winit() {
403 let size = Logical(Size::new(101.0, 33.0)).to_physical_pixels(ScaleFactor::X1_25);
404 assert_eq!(size, Physical::new(Size::new(126, 41)));
405 let size = Logical(Size::new(100.2, 100.5)).to_physical_pixels(ScaleFactor::ONE);
406 assert_eq!(size, Physical::new(Size::new(100, 101)));
407 assert_eq!(
408 Physical::new(Size::new(126_u32, 40)).to_logical(ScaleFactor::X1_25),
409 Logical(Size::new(100.8, 32.0))
410 );
411 }
412
413 #[test]
414 fn same_unit_arithmetic() {
415 assert_eq!(
416 Logical(Point::new(1.0, 1.0)) + Logical(Vector::new(2.0, 3.0)),
417 Logical(Point::new(3.0, 4.0))
418 );
419 assert_eq!(
420 Logical(Point::new(3.0, 4.0)) - Logical(Point::new(1.0, 1.0)),
421 Logical(Vector::new(2.0, 3.0))
422 );
423 assert_eq!(
424 Physical::new(2_u32) + Physical::new(3_u32),
425 Physical::new(5_u32)
426 );
427 assert_eq!(Physical::new(5_i32) - Physical::new(3), Physical::new(2));
428 assert_eq!(Logical(3.0_f32).get(), 3.0);
429 }
430
431 #[test]
432 fn tuples_make_logical_sizes() {
433 let size: Logical<Size> = (1280.0, 820.0).into();
434 assert_eq!(size, Logical(Size::new(1280.0, 820.0)));
435 }
436
437 #[test]
438 fn ratio_is_checked() {
439 for bad in [-0.01, 1.01, 10.0, f32::NAN] {
440 assert!(Ratio::new(bad).is_err(), "{bad}");
441 }
442 assert_eq!(Ratio::new(0.1).map(Ratio::get), Ok(0.1));
443 assert_eq!(Ratio::new(0.0), Ok(Ratio::ZERO));
444 assert_eq!(Ratio::new(1.0), Ok(Ratio::ONE));
445 assert_eq!(Ratio::try_from(0.5).map(f32::from), Ok(0.5));
446 assert_eq!(Ratio::default(), Ratio::ZERO);
447 assert_eq!(
448 Ratio::new(0.25).map(|r| r.to_string()),
449 Ok("0.25".to_owned())
450 );
451 let error = Ratio::new(10.0).err();
452 assert_eq!(error.map(InvalidRatio::value), Some(10.0));
453 assert_eq!(
454 error.map(|e| e.to_string()).as_deref(),
455 Some("ratio 10 is outside 0 to 1")
456 );
457 }
458
459 #[cfg(feature = "serde")]
460 #[test]
461 fn checked_numbers_validate_when_deserialised() -> Result<(), serde_json::Error> {
462 assert_eq!(serde_json::to_string(&ScaleFactor::TWO)?, "2.0");
463 assert_eq!(
464 serde_json::from_str::<ScaleFactor>("1.5")?,
465 ScaleFactor::X1_5
466 );
467 assert!(serde_json::from_str::<ScaleFactor>("0.1").is_err());
468 assert_eq!(
469 serde_json::from_str::<Ratio>("0.5")?,
470 Ratio::new(0.5).unwrap_or_default()
471 );
472 assert!(serde_json::from_str::<Ratio>("2").is_err());
473 assert_eq!(
474 serde_json::to_string(&Logical(Point::new(1.0, 2.0)))?,
475 r#"{"x":1.0,"y":2.0}"#
476 );
477 Ok(())
478 }
479}