icedwright-types 0.1.0

Shared types for icedwright: roles and capabilities, pixel units, virtual time, frames, key chords and the Messages trait
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Pixel units and the checked numbers that go with them.
//!
//! [`Logical`] pixels are what layout and the semantic tree use. [`Physical`] pixels are what a
//! frame holds. The only way from one to the other is through a [`ScaleFactor`], so a value in
//! the wrong unit does not compile.

use core::fmt;
use core::ops::{Add, Div, Mul, Sub};

use crate::geometry::{Point, Rect, Size, Vector};

/// A value in logical pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Logical<T>(pub T);

/// A value in physical pixels. Made by multiplying a [`Logical`] value by a [`ScaleFactor`],
/// or with [`Physical::new`] where a value really is physical.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Physical<T>(T);

impl<T> Logical<T> {
    /// The value without its unit.
    pub fn get(self) -> T {
        self.0
    }
}

impl<T> Physical<T> {
    /// For values that really are physical pixels, such as a frame read from disk.
    pub const fn new(value: T) -> Self {
        Self(value)
    }

    /// The value without its unit.
    pub fn get(self) -> T {
        self.0
    }
}

impl From<(f32, f32)> for Logical<Size> {
    fn from((width, height): (f32, f32)) -> Self {
        Logical(Size::new(width, height))
    }
}

impl<A: Add<B>, B> Add<Logical<B>> for Logical<A> {
    type Output = Logical<A::Output>;

    fn add(self, other: Logical<B>) -> Self::Output {
        Logical(self.0 + other.0)
    }
}

impl<A: Sub<B>, B> Sub<Logical<B>> for Logical<A> {
    type Output = Logical<A::Output>;

    fn sub(self, other: Logical<B>) -> Self::Output {
        Logical(self.0 - other.0)
    }
}

impl<A: Add<B>, B> Add<Physical<B>> for Physical<A> {
    type Output = Physical<A::Output>;

    fn add(self, other: Physical<B>) -> Self::Output {
        Physical(self.0 + other.0)
    }
}

impl<A: Sub<B>, B> Sub<Physical<B>> for Physical<A> {
    type Output = Physical<A::Output>;

    fn sub(self, other: Physical<B>) -> Self::Output {
        Physical(self.0 - other.0)
    }
}

mod sealed {
    pub trait Sealed {}
}

/// Values that a [`ScaleFactor`] can scale between logical and physical pixels. Sealed.
pub trait Scalable: sealed::Sealed + Sized {
    /// The value multiplied by `factor`.
    #[must_use]
    fn scaled(self, factor: f32) -> Self;
}

impl sealed::Sealed for f32 {}
impl Scalable for f32 {
    fn scaled(self, factor: f32) -> Self {
        self * factor
    }
}

impl sealed::Sealed for Point {}
impl Scalable for Point {
    fn scaled(self, factor: f32) -> Self {
        Point::new(self.x * factor, self.y * factor)
    }
}

impl sealed::Sealed for Vector {}
impl Scalable for Vector {
    fn scaled(self, factor: f32) -> Self {
        self * factor
    }
}

impl sealed::Sealed for Size {}
impl Scalable for Size {
    fn scaled(self, factor: f32) -> Self {
        self * factor
    }
}

impl sealed::Sealed for Rect {}
impl Scalable for Rect {
    fn scaled(self, factor: f32) -> Self {
        Rect::new(self.position().scaled(factor), self.size().scaled(factor))
    }
}

impl<T: Scalable> Mul<ScaleFactor> for Logical<T> {
    type Output = Physical<T>;

    fn mul(self, factor: ScaleFactor) -> Physical<T> {
        Physical(self.0.scaled(factor.0))
    }
}

impl<T: Scalable> Div<ScaleFactor> for Physical<T> {
    type Output = Logical<T>;

    fn div(self, factor: ScaleFactor) -> Logical<T> {
        Logical(self.0.scaled(1.0 / factor.0))
    }
}

impl Logical<Size> {
    /// The size in whole physical pixels, rounded the way winit rounds a window's size.
    #[must_use]
    pub fn to_physical_pixels(self, factor: ScaleFactor) -> Physical<Size<u32>> {
        let round = |value: f32| (f64::from(value) * f64::from(factor.0)).round() as u32;
        Physical(Size::new(round(self.0.width), round(self.0.height)))
    }
}

impl Physical<Size<u32>> {
    /// The size in logical pixels, divided the way winit divides a window's size.
    #[must_use]
    pub fn to_logical(self, factor: ScaleFactor) -> Logical<Size> {
        let divide = |value: u32| (f64::from(value) / f64::from(factor.0)) as f32;
        Logical(Size::new(divide(self.0.width), divide(self.0.height)))
    }
}

/// The ratio of physical to logical pixels: finite and from 0.5 to 4.0.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "f32", into = "f32"))]
pub struct ScaleFactor(f32);

impl ScaleFactor {
    /// The smallest factor accepted.
    pub const MIN: f32 = 0.5;
    /// The largest factor accepted.
    pub const MAX: f32 = 4.0;
    /// One physical pixel per logical pixel.
    pub const ONE: Self = Self(1.0);
    /// 125 per cent.
    pub const X1_25: Self = Self(1.25);
    /// 150 per cent.
    pub const X1_5: Self = Self(1.5);
    /// Two physical pixels per logical pixel.
    pub const TWO: Self = Self(2.0);
    /// Three physical pixels per logical pixel.
    pub const THREE: Self = Self(3.0);

    /// A factor from 0.5 to 4.0. `const`, so an invalid factor in a `const` item fails the build.
    pub const fn new(factor: f32) -> Result<Self, InvalidScaleFactor> {
        if factor >= Self::MIN && factor <= Self::MAX {
            return Ok(Self(factor));
        }
        Err(InvalidScaleFactor { factor })
    }

    /// The factor as a number.
    #[must_use]
    pub const fn get(self) -> f32 {
        self.0
    }
}

impl Default for ScaleFactor {
    fn default() -> Self {
        Self::ONE
    }
}

impl TryFrom<f32> for ScaleFactor {
    type Error = InvalidScaleFactor;

    fn try_from(factor: f32) -> Result<Self, InvalidScaleFactor> {
        Self::new(factor)
    }
}

impl From<ScaleFactor> for f32 {
    fn from(factor: ScaleFactor) -> f32 {
        factor.0
    }
}

/// Prints `2x` or `1.25x`, the form used in snapshot file names.
impl fmt::Display for ScaleFactor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}x", self.0)
    }
}

/// A scale factor that is not finite or lies outside 0.5 to 4.0.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct InvalidScaleFactor {
    factor: f32,
}

impl InvalidScaleFactor {
    /// The rejected factor.
    #[must_use]
    pub const fn factor(self) -> f32 {
        self.factor
    }
}

impl fmt::Display for InvalidScaleFactor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "scale {} is outside {} to {}",
            self.factor,
            ScaleFactor::MIN,
            ScaleFactor::MAX
        )
    }
}

impl std::error::Error for InvalidScaleFactor {}

/// A number from 0 to 1 inclusive, such as a diff threshold, so that a percentage cannot be
/// passed by mistake.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "f32", into = "f32"))]
pub struct Ratio(f32);

impl Ratio {
    /// Nothing.
    pub const ZERO: Self = Self(0.0);
    /// Everything.
    pub const ONE: Self = Self(1.0);

    /// A ratio from 0 to 1 inclusive.
    pub const fn new(value: f32) -> Result<Self, InvalidRatio> {
        if value >= 0.0 && value <= 1.0 {
            return Ok(Self(value));
        }
        Err(InvalidRatio { value })
    }

    /// The ratio as a number.
    #[must_use]
    pub const fn get(self) -> f32 {
        self.0
    }
}

impl TryFrom<f32> for Ratio {
    type Error = InvalidRatio;

    fn try_from(value: f32) -> Result<Self, InvalidRatio> {
        Self::new(value)
    }
}

impl From<Ratio> for f32 {
    fn from(ratio: Ratio) -> f32 {
        ratio.0
    }
}

impl fmt::Display for Ratio {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// A ratio that is not finite or lies outside 0 to 1.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct InvalidRatio {
    value: f32,
}

impl InvalidRatio {
    /// The rejected value.
    #[must_use]
    pub const fn value(self) -> f32 {
        self.value
    }
}

impl fmt::Display for InvalidRatio {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ratio {} is outside 0 to 1", self.value)
    }
}

impl std::error::Error for InvalidRatio {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scale_factor_rejects_out_of_range_and_non_finite() {
        for bad in [
            0.0,
            -1.0,
            0.49,
            4.01,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
        ] {
            assert!(ScaleFactor::new(bad).is_err(), "{bad}");
        }
        for good in [0.5, 1.0, 1.25, 4.0] {
            assert_eq!(ScaleFactor::new(good).map(ScaleFactor::get), Ok(good));
        }
        assert_eq!(ScaleFactor::try_from(2.0), Ok(ScaleFactor::TWO));
        assert_eq!(f32::from(ScaleFactor::X1_5), 1.5);
        assert_eq!(ScaleFactor::default(), ScaleFactor::ONE);
    }

    #[test]
    fn scale_factor_new_is_usable_in_const_items() {
        const CUSTOM: Result<ScaleFactor, InvalidScaleFactor> = ScaleFactor::new(1.75);
        assert_eq!(CUSTOM.map(ScaleFactor::get), Ok(1.75));
    }

    #[test]
    fn named_scale_factors_are_valid() {
        for factor in [
            ScaleFactor::ONE,
            ScaleFactor::X1_25,
            ScaleFactor::X1_5,
            ScaleFactor::TWO,
            ScaleFactor::THREE,
        ] {
            assert_eq!(ScaleFactor::new(factor.get()), Ok(factor));
        }
    }

    #[test]
    fn scale_factor_errors_and_display() {
        assert_eq!(ScaleFactor::TWO.to_string(), "2x");
        assert_eq!(ScaleFactor::X1_25.to_string(), "1.25x");
        let error = ScaleFactor::new(0.2).err();
        assert_eq!(error.map(InvalidScaleFactor::factor), Some(0.2));
        assert_eq!(
            error.map(|e| e.to_string()).as_deref(),
            Some("scale 0.2 is outside 0.5 to 4")
        );
    }

    #[test]
    fn logical_times_scale_is_physical_and_back() {
        let logical = Logical(Size::new(100.0, 50.0));
        let physical = logical * ScaleFactor::TWO;
        assert_eq!(physical, Physical::new(Size::new(200.0, 100.0)));
        assert_eq!(physical / ScaleFactor::TWO, logical);
        assert_eq!(
            Logical(Point::new(1.0, 2.0)) * ScaleFactor::THREE,
            Physical::new(Point::new(3.0, 6.0))
        );
        assert_eq!(
            Logical(Vector::new(1.0, -2.0)) * ScaleFactor::TWO,
            Physical::new(Vector::new(2.0, -4.0))
        );
        assert_eq!(
            Logical(Rect::new(Point::new(1.0, 2.0), Size::new(3.0, 4.0))) * ScaleFactor::TWO,
            Physical::new(Rect::new(Point::new(2.0, 4.0), Size::new(6.0, 8.0)))
        );
        assert_eq!(Logical(4.0_f32) * ScaleFactor::X1_5, Physical::new(6.0));
    }

    #[test]
    fn physical_pixels_round_like_winit() {
        let size = Logical(Size::new(101.0, 33.0)).to_physical_pixels(ScaleFactor::X1_25);
        assert_eq!(size, Physical::new(Size::new(126, 41)));
        let size = Logical(Size::new(100.2, 100.5)).to_physical_pixels(ScaleFactor::ONE);
        assert_eq!(size, Physical::new(Size::new(100, 101)));
        assert_eq!(
            Physical::new(Size::new(126_u32, 40)).to_logical(ScaleFactor::X1_25),
            Logical(Size::new(100.8, 32.0))
        );
    }

    #[test]
    fn same_unit_arithmetic() {
        assert_eq!(
            Logical(Point::new(1.0, 1.0)) + Logical(Vector::new(2.0, 3.0)),
            Logical(Point::new(3.0, 4.0))
        );
        assert_eq!(
            Logical(Point::new(3.0, 4.0)) - Logical(Point::new(1.0, 1.0)),
            Logical(Vector::new(2.0, 3.0))
        );
        assert_eq!(
            Physical::new(2_u32) + Physical::new(3_u32),
            Physical::new(5_u32)
        );
        assert_eq!(Physical::new(5_i32) - Physical::new(3), Physical::new(2));
        assert_eq!(Logical(3.0_f32).get(), 3.0);
    }

    #[test]
    fn tuples_make_logical_sizes() {
        let size: Logical<Size> = (1280.0, 820.0).into();
        assert_eq!(size, Logical(Size::new(1280.0, 820.0)));
    }

    #[test]
    fn ratio_is_checked() {
        for bad in [-0.01, 1.01, 10.0, f32::NAN] {
            assert!(Ratio::new(bad).is_err(), "{bad}");
        }
        assert_eq!(Ratio::new(0.1).map(Ratio::get), Ok(0.1));
        assert_eq!(Ratio::new(0.0), Ok(Ratio::ZERO));
        assert_eq!(Ratio::new(1.0), Ok(Ratio::ONE));
        assert_eq!(Ratio::try_from(0.5).map(f32::from), Ok(0.5));
        assert_eq!(Ratio::default(), Ratio::ZERO);
        assert_eq!(
            Ratio::new(0.25).map(|r| r.to_string()),
            Ok("0.25".to_owned())
        );
        let error = Ratio::new(10.0).err();
        assert_eq!(error.map(InvalidRatio::value), Some(10.0));
        assert_eq!(
            error.map(|e| e.to_string()).as_deref(),
            Some("ratio 10 is outside 0 to 1")
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn checked_numbers_validate_when_deserialised() -> Result<(), serde_json::Error> {
        assert_eq!(serde_json::to_string(&ScaleFactor::TWO)?, "2.0");
        assert_eq!(
            serde_json::from_str::<ScaleFactor>("1.5")?,
            ScaleFactor::X1_5
        );
        assert!(serde_json::from_str::<ScaleFactor>("0.1").is_err());
        assert_eq!(
            serde_json::from_str::<Ratio>("0.5")?,
            Ratio::new(0.5).unwrap_or_default()
        );
        assert!(serde_json::from_str::<Ratio>("2").is_err());
        assert_eq!(
            serde_json::to_string(&Logical(Point::new(1.0, 2.0)))?,
            r#"{"x":1.0,"y":2.0}"#
        );
        Ok(())
    }
}