Skip to main content

nsh_core/geometry/
units.rs

1//! The units: [`Points`] (what NSH lays out in), [`DevicePixels`] (at
2//! platform boundaries), [`Rems`], [`Percentage`] and [`Radians`].
3
4use std::{
5    fmt,
6    hash::{Hash, Hasher},
7    iter::Sum,
8    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
9};
10
11use serde::{Deserialize, Serialize};
12
13/// Implements what a unit that wraps one `f32` shares: arithmetic within
14/// the unit, scaling by `f32`, a ratio of two values, bitwise equality for
15/// `Eq` / `Hash` (as map keys and in hashed declarations), and conversions
16/// to and from `f32`.
17macro_rules! f32_unit {
18    ($unit:ident) => {
19        impl Add for $unit {
20            type Output = Self;
21            #[inline]
22            fn add(self, rhs: Self) -> Self {
23                Self(self.0 + rhs.0)
24            }
25        }
26
27        impl Sub for $unit {
28            type Output = Self;
29            #[inline]
30            fn sub(self, rhs: Self) -> Self {
31                Self(self.0 - rhs.0)
32            }
33        }
34
35        impl Neg for $unit {
36            type Output = Self;
37            #[inline]
38            fn neg(self) -> Self {
39                Self(-self.0)
40            }
41        }
42
43        impl AddAssign for $unit {
44            #[inline]
45            fn add_assign(&mut self, rhs: Self) {
46                self.0 += rhs.0;
47            }
48        }
49
50        impl SubAssign for $unit {
51            #[inline]
52            fn sub_assign(&mut self, rhs: Self) {
53                self.0 -= rhs.0;
54            }
55        }
56
57        impl Mul<f32> for $unit {
58            type Output = Self;
59            #[inline]
60            fn mul(self, rhs: f32) -> Self {
61                Self(self.0 * rhs)
62            }
63        }
64
65        impl Mul<$unit> for f32 {
66            type Output = $unit;
67            #[inline]
68            fn mul(self, rhs: $unit) -> $unit {
69                $unit(self * rhs.0)
70            }
71        }
72
73        impl MulAssign<f32> for $unit {
74            #[inline]
75            fn mul_assign(&mut self, rhs: f32) {
76                self.0 *= rhs;
77            }
78        }
79
80        impl Div<f32> for $unit {
81            type Output = Self;
82            #[inline]
83            fn div(self, rhs: f32) -> Self {
84                Self(self.0 / rhs)
85            }
86        }
87
88        impl DivAssign<f32> for $unit {
89            #[inline]
90            fn div_assign(&mut self, rhs: f32) {
91                self.0 /= rhs;
92            }
93        }
94
95        /// The ratio of two values.
96        impl Div for $unit {
97            type Output = f32;
98            #[inline]
99            fn div(self, rhs: Self) -> f32 {
100                self.0 / rhs.0
101            }
102        }
103
104        impl Sum for $unit {
105            fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
106                Self(iter.map(|v| v.0).sum())
107            }
108        }
109
110        impl<'a> Sum<&'a $unit> for $unit {
111            fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
112                Self(iter.map(|v| v.0).sum())
113            }
114        }
115
116        // Equal values hash alike: `PartialEq` is `f32`'s, so `-0.0 == 0.0`
117        // and NaN differs from itself (frames start as NaN to be sent once
118        // set). `Eq` lets the unit sit in hashed declarations and keys, as
119        // GPUI's `Pixels` does; NaN never reaches them.
120        impl Eq for $unit {}
121
122        impl Hash for $unit {
123            fn hash<H: Hasher>(&self, state: &mut H) {
124                // `0.0` and `-0.0` are equal, so they hash alike.
125                let v = if self.0 == 0.0 { 0.0f32 } else { self.0 };
126                v.to_bits().hash(state);
127            }
128        }
129
130        impl PartialOrd for $unit {
131            #[inline]
132            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
133                self.0.partial_cmp(&other.0)
134            }
135        }
136
137        impl From<f32> for $unit {
138            #[inline]
139            fn from(v: f32) -> Self {
140                Self(v)
141            }
142        }
143
144        impl From<$unit> for f32 {
145            #[inline]
146            fn from(v: $unit) -> f32 {
147                v.0
148            }
149        }
150
151        impl IsZero for $unit {
152            #[inline]
153            fn is_zero(&self) -> bool {
154                self.0 == 0.0
155            }
156        }
157
158        impl Half for $unit {
159            #[inline]
160            fn half(&self) -> Self {
161                Self(self.0 / 2.0)
162            }
163        }
164
165        impl $unit {
166            /// Zero.
167            pub const ZERO: Self = Self(0.0);
168
169            /// The value as a bare `f32`, for a platform API or an encoder.
170            #[inline]
171            pub const fn as_f32(self) -> f32 {
172                self.0
173            }
174
175            /// The absolute value.
176            #[inline]
177            pub fn abs(self) -> Self {
178                Self(self.0.abs())
179            }
180
181            /// The smaller of two values.
182            #[inline]
183            pub fn min(self, other: Self) -> Self {
184                Self(self.0.min(other.0))
185            }
186
187            /// The larger of two values.
188            #[inline]
189            pub fn max(self, other: Self) -> Self {
190                Self(self.0.max(other.0))
191            }
192
193            /// The value within `min..=max`.
194            #[inline]
195            pub fn clamp(self, min: Self, max: Self) -> Self {
196                Self(self.0.clamp(min.0, max.0))
197            }
198
199            /// Rounded down.
200            #[inline]
201            pub fn floor(self) -> Self {
202                Self(self.0.floor())
203            }
204
205            /// Rounded to the nearest whole value.
206            #[inline]
207            pub fn round(self) -> Self {
208                Self(self.0.round())
209            }
210
211            /// Rounded up.
212            #[inline]
213            pub fn ceil(self) -> Self {
214                Self(self.0.ceil())
215            }
216
217            /// Whether the value is neither infinite nor NaN.
218            #[inline]
219            pub fn is_finite(self) -> bool {
220                self.0.is_finite()
221            }
222
223            /// Whether the value is NaN.
224            #[inline]
225            pub fn is_nan(self) -> bool {
226                self.0.is_nan()
227            }
228        }
229    };
230}
231
232/// A value that can be zero.
233pub trait IsZero {
234    /// Whether the value is zero.
235    fn is_zero(&self) -> bool;
236}
237
238/// A value that can be halved (the center of a [`Bounds`](super::Bounds)).
239pub trait Half {
240    /// Half the value.
241    fn half(&self) -> Self;
242}
243
244impl Half for f32 {
245    #[inline]
246    fn half(&self) -> Self {
247        self / 2.0
248    }
249}
250
251impl Half for i32 {
252    #[inline]
253    fn half(&self) -> Self {
254        self / 2
255    }
256}
257
258/// A length in points, the unit NSH lays out in (GPUI's `Pixels`): the
259/// platform's density-independent unit (iOS / macOS points, Android dp,
260/// CSS `px` on the web, DIPs on Windows). Style strings' `px` and bare
261/// numbers are points. Device pixels are [`DevicePixels`] /
262/// [`ScaledPixels`], met only where a platform draws or reports them.
263#[derive(Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
264#[repr(transparent)]
265pub struct Points(pub f32);
266
267f32_unit!(Points);
268
269impl Points {
270    /// In device pixels at `scale_factor` device pixels per point,
271    /// rounded to the nearest pixel.
272    #[inline]
273    pub fn to_device_pixels(self, scale_factor: f32) -> DevicePixels {
274        DevicePixels((self.0 * scale_factor).round() as i32)
275    }
276
277    /// Scaled by `scale_factor` device pixels per point, unrounded (a
278    /// fractional device position).
279    #[inline]
280    pub fn scale(self, scale_factor: f32) -> ScaledPixels {
281        ScaledPixels(self.0 * scale_factor)
282    }
283
284    /// In rems of `rem_size`.
285    #[inline]
286    pub fn to_rems(self, rem_size: Points) -> Rems {
287        Rems(self.0 / rem_size.0)
288    }
289}
290
291impl fmt::Debug for Points {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        write!(f, "{}pt", self.0)
294    }
295}
296
297impl fmt::Display for Points {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        write!(f, "{}pt", self.0)
300    }
301}
302
303/// `points` points. The name is GPUI's and CSS's: a CSS `px` is a point.
304#[inline]
305pub const fn px(points: f32) -> Points {
306    Points(points)
307}
308
309/// The points of one rem in NSH's style strings and Tailwind's default
310/// theme (CSS's 16px).
311pub const REM_SIZE: Points = Points(16.0);
312
313/// A length in rems: multiples of a root font size (16 points in style
314/// strings, [`REM_SIZE`]).
315#[derive(Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
316#[repr(transparent)]
317pub struct Rems(pub f32);
318
319f32_unit!(Rems);
320
321impl Rems {
322    /// In points, with a rem of `rem_size`.
323    #[inline]
324    pub fn to_points(self, rem_size: Points) -> Points {
325        Points(self.0 * rem_size.0)
326    }
327}
328
329impl fmt::Debug for Rems {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        write!(f, "{}rem", self.0)
332    }
333}
334
335impl fmt::Display for Rems {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        write!(f, "{}rem", self.0)
338    }
339}
340
341/// `rems` rems.
342#[inline]
343pub const fn rems(rems: f32) -> Rems {
344    Rems(rems)
345}
346
347/// A fraction of a whole: `0.5` is 50%, `1.0` all of it. NSH keeps CSS
348/// percentages as fractions everywhere (styles, gradients, transform
349/// origins). Values outside `0..=1` are taken (a gradient stop at 150%,
350/// a `-50%` translation).
351#[derive(Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
352#[repr(transparent)]
353pub struct Percentage(pub f32);
354
355f32_unit!(Percentage);
356
357impl Percentage {
358    /// This fraction of `whole`.
359    #[inline]
360    pub fn of(self, whole: Points) -> Points {
361        Points(self.0 * whole.0)
362    }
363}
364
365impl fmt::Debug for Percentage {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        write!(f, "{}%", self.0 * 100.0)
368    }
369}
370
371impl fmt::Display for Percentage {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        write!(f, "{}%", self.0 * 100.0)
374    }
375}
376
377/// `value` as a fraction of a whole (`percentage(0.5)` is 50%).
378#[inline]
379pub const fn percentage(value: f32) -> Percentage {
380    Percentage(value)
381}
382
383/// An angle in radians. Which way it turns and where 0 points is the
384/// API's that takes it (CSS: 0 points up, clockwise). [`deg`], [`turn`]
385/// and [`grad`] make one from CSS's other angle units.
386#[derive(Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
387#[repr(transparent)]
388pub struct Radians(pub f32);
389
390f32_unit!(Radians);
391
392impl Radians {
393    /// In degrees.
394    #[inline]
395    pub fn to_degrees(self) -> f32 {
396        self.0.to_degrees()
397    }
398
399    /// In whole turns.
400    #[inline]
401    pub fn to_turns(self) -> f32 {
402        self.0 / std::f32::consts::TAU
403    }
404
405    /// The sine and cosine.
406    #[inline]
407    pub fn sin_cos(self) -> (f32, f32) {
408        self.0.sin_cos()
409    }
410}
411
412/// A fraction of a full turn (`Radians::from(percentage(0.25))` is a
413/// quarter turn), as in GPUI.
414impl From<Percentage> for Radians {
415    #[inline]
416    fn from(value: Percentage) -> Self {
417        Radians(value.0 * std::f32::consts::TAU)
418    }
419}
420
421impl fmt::Debug for Radians {
422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423        write!(f, "{}rad", self.0)
424    }
425}
426
427impl fmt::Display for Radians {
428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429        write!(f, "{}rad", self.0)
430    }
431}
432
433/// `value` radians.
434#[inline]
435pub const fn radians(value: f32) -> Radians {
436    Radians(value)
437}
438
439/// `degrees` degrees, in radians (CSS `deg`).
440#[inline]
441pub fn deg(degrees: f32) -> Radians {
442    Radians(degrees.to_radians())
443}
444
445/// `turns` whole turns, in radians (CSS `turn`).
446#[inline]
447pub fn turn(turns: f32) -> Radians {
448    Radians(turns * std::f32::consts::TAU)
449}
450
451/// `gradians` gradians, in radians: 400 to a turn (CSS `grad`).
452#[inline]
453pub fn grad(gradians: f32) -> Radians {
454    Radians(gradians * (std::f32::consts::PI / 200.0))
455}
456
457/// Physical pixels of a display: what a platform's bitmaps, swap chains
458/// and pointer events in pixels count. NSH's own values are [`Points`];
459/// conversions happen at the platform boundary, with the surface's scale
460/// factor.
461#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
462#[repr(transparent)]
463pub struct DevicePixels(pub i32);
464
465impl DevicePixels {
466    /// In points at `scale_factor` device pixels per point.
467    #[inline]
468    pub fn to_points(self, scale_factor: f32) -> Points {
469        Points(self.0 as f32 / scale_factor)
470    }
471}
472
473impl fmt::Debug for DevicePixels {
474    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475        write!(f, "{}px (device)", self.0)
476    }
477}
478
479impl From<i32> for DevicePixels {
480    #[inline]
481    fn from(v: i32) -> Self {
482        Self(v)
483    }
484}
485
486impl From<DevicePixels> for i32 {
487    #[inline]
488    fn from(v: DevicePixels) -> i32 {
489        v.0
490    }
491}
492
493impl Add for DevicePixels {
494    type Output = Self;
495    #[inline]
496    fn add(self, rhs: Self) -> Self {
497        Self(self.0 + rhs.0)
498    }
499}
500
501impl Sub for DevicePixels {
502    type Output = Self;
503    #[inline]
504    fn sub(self, rhs: Self) -> Self {
505        Self(self.0 - rhs.0)
506    }
507}
508
509impl IsZero for DevicePixels {
510    #[inline]
511    fn is_zero(&self) -> bool {
512        self.0 == 0
513    }
514}
515
516impl Half for DevicePixels {
517    #[inline]
518    fn half(&self) -> Self {
519        Self(self.0 / 2)
520    }
521}
522
523/// Points scaled to device pixels without rounding: a fractional device
524/// position, as a platform draws at ([`Points::scale`]).
525#[derive(Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
526#[repr(transparent)]
527pub struct ScaledPixels(pub f32);
528
529f32_unit!(ScaledPixels);
530
531impl ScaledPixels {
532    /// Rounded to whole device pixels.
533    #[inline]
534    pub fn to_device_pixels(self) -> DevicePixels {
535        DevicePixels(self.0.round() as i32)
536    }
537}
538
539impl fmt::Debug for ScaledPixels {
540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541        write!(f, "{}px (scaled)", self.0)
542    }
543}