Skip to main content

waft_painting/
fractional_offset.rs

1//! Flutter counterpart: `painting/fractional_offset.dart`.
2
3use std::fmt::{self, Debug};
4use std::ops::{Add, Div, Mul, Neg, Rem, Sub};
5
6use waft_embedder::{Offset, Rect, Size, lerp_double};
7
8use crate::alignment::Alignment;
9
10/// An offset that's expressed as a fraction of a [`Size`].
11///
12/// `FractionalOffset(1.0, 0.0)` represents the top right of the [`Size`].
13///
14/// `FractionalOffset(0.0, 1.0)` represents the bottom left of the [`Size`].
15///
16/// `FractionalOffset(0.5, 2.0)` represents a point half way across the [`Size`],
17/// below the bottom of the rectangle by the height of the [`Size`].
18///
19/// The [`FractionalOffset`] class specifies offsets in terms of a distance from
20/// the top left, regardless of the [`crate::TextDirection`].
21///
22/// ## Design discussion
23///
24/// [`FractionalOffset`] and [`Alignment`] are two different representations of
25/// the same information: the location within a rectangle relative to the size
26/// of the rectangle. The difference between the two classes is in the
27/// coordinate system they use to represent the location.
28///
29/// [`FractionalOffset`] uses a coordinate system with an origin in the top-left
30/// corner of the rectangle whereas [`Alignment`] uses a coordinate system with
31/// an origin in the center of the rectangle.
32///
33/// See also:
34///
35///  * [`Alignment`], which uses a coordinate system based on the center of the
36///    rectangle instead of the top left corner of the rectangle.
37#[derive(Clone, Copy, PartialEq)]
38pub struct FractionalOffset {
39    /// The distance fraction in the horizontal direction in [`Alignment`]
40    /// coordinates (`dx * 2 - 1`).
41    pub x: f64,
42    /// The distance fraction in the vertical direction in [`Alignment`]
43    /// coordinates (`dy * 2 - 1`).
44    pub y: f64,
45}
46
47impl FractionalOffset {
48    /// Creates a fractional offset.
49    pub const fn new(dx: f64, dy: f64) -> FractionalOffset {
50        FractionalOffset {
51            x: dx * 2.0 - 1.0,
52            y: dy * 2.0 - 1.0,
53        }
54    }
55
56    /// Creates a fractional offset from a specific offset and size.
57    ///
58    /// The returned [`FractionalOffset`] describes the position of the
59    /// [`Offset`] in the [`Size`], as a fraction of the [`Size`].
60    pub fn from_offset_and_size(offset: Offset, size: Size) -> FractionalOffset {
61        FractionalOffset::new(offset.dx() / size.width(), offset.dy() / size.height())
62    }
63
64    /// Creates a fractional offset from a specific offset and rectangle.
65    ///
66    /// The offset is assumed to be relative to the same origin as the rectangle.
67    ///
68    /// If the offset is relative to the top left of the rectangle, use
69    /// [`from_offset_and_size`](Self::from_offset_and_size) instead, passing
70    /// `rect.size()`.
71    ///
72    /// The returned [`FractionalOffset`] describes the position of the
73    /// [`Offset`] in the [`Rect`], as a fraction of the [`Rect`].
74    pub fn from_offset_and_rect(offset: Offset, rect: Rect) -> FractionalOffset {
75        FractionalOffset::from_offset_and_size(offset - rect.top_left(), rect.size())
76    }
77
78    /// The distance fraction in the horizontal direction.
79    ///
80    /// A value of 0.0 corresponds to the leftmost edge. A value of 1.0
81    /// corresponds to the rightmost edge. Values are not limited to that range;
82    /// negative values represent positions to the left of the left edge, and
83    /// values greater than 1.0 represent positions to the right of the right
84    /// edge.
85    pub const fn dx(&self) -> f64 {
86        (self.x + 1.0) / 2.0
87    }
88
89    /// The distance fraction in the vertical direction.
90    ///
91    /// A value of 0.0 corresponds to the topmost edge. A value of 1.0
92    /// corresponds to the bottommost edge. Values are not limited to that range;
93    /// negative values represent positions above the top, and values greater
94    /// than 1.0 represent positions below the bottom.
95    pub const fn dy(&self) -> f64 {
96        (self.y + 1.0) / 2.0
97    }
98
99    /// The top left corner.
100    pub const TOP_LEFT: FractionalOffset = FractionalOffset::new(0.0, 0.0);
101    /// The center point along the top edge.
102    pub const TOP_CENTER: FractionalOffset = FractionalOffset::new(0.5, 0.0);
103    /// The top right corner.
104    pub const TOP_RIGHT: FractionalOffset = FractionalOffset::new(1.0, 0.0);
105    /// The center point along the left edge.
106    pub const CENTER_LEFT: FractionalOffset = FractionalOffset::new(0.0, 0.5);
107    /// The center point, both horizontally and vertically.
108    pub const CENTER: FractionalOffset = FractionalOffset::new(0.5, 0.5);
109    /// The center point along the right edge.
110    pub const CENTER_RIGHT: FractionalOffset = FractionalOffset::new(1.0, 0.5);
111    /// The bottom left corner.
112    pub const BOTTOM_LEFT: FractionalOffset = FractionalOffset::new(0.0, 1.0);
113    /// The center point along the bottom edge.
114    pub const BOTTOM_CENTER: FractionalOffset = FractionalOffset::new(0.5, 1.0);
115    /// The bottom right corner.
116    pub const BOTTOM_RIGHT: FractionalOffset = FractionalOffset::new(1.0, 1.0);
117
118    /// Integer divides the [`FractionalOffset`] in each dimension by the given
119    /// factor.
120    pub fn truncating_div(&self, other: f64) -> FractionalOffset {
121        FractionalOffset::new((self.dx() / other).trunc(), (self.dy() / other).trunc())
122    }
123
124    /// Linearly interpolate between two [`FractionalOffset`]s.
125    ///
126    /// If either is null, this function interpolates from
127    /// [`FractionalOffset::CENTER`].
128    pub fn lerp(
129        a: Option<FractionalOffset>,
130        b: Option<FractionalOffset>,
131        t: f64,
132    ) -> Option<FractionalOffset> {
133        if a == b {
134            return a;
135        }
136        match (a, b) {
137            (None, None) => None,
138            (None, Some(b)) => Some(FractionalOffset::new(
139                lerp_double(Some(0.5), Some(b.dx()), t).unwrap(),
140                lerp_double(Some(0.5), Some(b.dy()), t).unwrap(),
141            )),
142            (Some(a), None) => Some(FractionalOffset::new(
143                lerp_double(Some(a.dx()), Some(0.5), t).unwrap(),
144                lerp_double(Some(a.dy()), Some(0.5), t).unwrap(),
145            )),
146            (Some(a), Some(b)) => Some(FractionalOffset::new(
147                lerp_double(Some(a.dx()), Some(b.dx()), t).unwrap(),
148                lerp_double(Some(a.dy()), Some(b.dy()), t).unwrap(),
149            )),
150        }
151    }
152}
153
154impl From<FractionalOffset> for Alignment {
155    fn from(offset: FractionalOffset) -> Alignment {
156        Alignment::new(offset.x, offset.y)
157    }
158}
159
160impl PartialEq<Alignment> for FractionalOffset {
161    fn eq(&self, other: &Alignment) -> bool {
162        self.x == other.x && self.y == other.y
163    }
164}
165
166impl PartialEq<FractionalOffset> for Alignment {
167    fn eq(&self, other: &FractionalOffset) -> bool {
168        self.x == other.x && self.y == other.y
169    }
170}
171
172impl Sub for FractionalOffset {
173    type Output = FractionalOffset;
174
175    fn sub(self, other: FractionalOffset) -> FractionalOffset {
176        FractionalOffset::new(self.dx() - other.dx(), self.dy() - other.dy())
177    }
178}
179
180impl Sub<Alignment> for FractionalOffset {
181    type Output = Alignment;
182
183    fn sub(self, other: Alignment) -> Alignment {
184        Alignment::from(self) - other
185    }
186}
187
188impl Add for FractionalOffset {
189    type Output = FractionalOffset;
190
191    fn add(self, other: FractionalOffset) -> FractionalOffset {
192        FractionalOffset::new(self.dx() + other.dx(), self.dy() + other.dy())
193    }
194}
195
196impl Add<Alignment> for FractionalOffset {
197    type Output = Alignment;
198
199    fn add(self, other: Alignment) -> Alignment {
200        Alignment::from(self) + other
201    }
202}
203
204impl Neg for FractionalOffset {
205    type Output = FractionalOffset;
206
207    fn neg(self) -> FractionalOffset {
208        FractionalOffset::new(-self.dx(), -self.dy())
209    }
210}
211
212impl Mul<f64> for FractionalOffset {
213    type Output = FractionalOffset;
214
215    fn mul(self, other: f64) -> FractionalOffset {
216        FractionalOffset::new(self.dx() * other, self.dy() * other)
217    }
218}
219
220impl Div<f64> for FractionalOffset {
221    type Output = FractionalOffset;
222
223    fn div(self, other: f64) -> FractionalOffset {
224        FractionalOffset::new(self.dx() / other, self.dy() / other)
225    }
226}
227
228impl Rem<f64> for FractionalOffset {
229    type Output = FractionalOffset;
230
231    fn rem(self, other: f64) -> FractionalOffset {
232        FractionalOffset::new(self.dx() % other, self.dy() % other)
233    }
234}
235
236impl Debug for FractionalOffset {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        // Dart `toStringAsFixed(1)` rounds half away from zero.
239        let dx = (self.dx() * 10.0).round() / 10.0;
240        let dy = (self.dy() * 10.0).round() / 10.0;
241        write!(f, "FractionalOffset({dx:.1}, {dy:.1})")
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    // fractional_offset_test.dart 'FractionalOffset control test'.
250    #[test]
251    fn fractional_offset_control_test() {
252        let a = FractionalOffset::new(0.5, 0.25);
253        let b = FractionalOffset::new(1.25, 0.75);
254
255        assert_eq!(format!("{a:?}"), "FractionalOffset(0.5, 0.3)");
256
257        assert_eq!(-a, FractionalOffset::new(-0.5, -0.25));
258        assert_eq!(a - b, FractionalOffset::new(-0.75, -0.5));
259        assert_eq!(a + b, FractionalOffset::new(1.75, 1.0));
260        assert_eq!(a * 2.0, FractionalOffset::CENTER_RIGHT);
261        assert_eq!(a / 2.0, FractionalOffset::new(0.25, 0.125));
262        assert_eq!(a.truncating_div(2.0), FractionalOffset::TOP_LEFT);
263        assert_eq!(a % 5.0, FractionalOffset::new(0.5, 0.25));
264    }
265
266    // fractional_offset_test.dart 'FractionalOffset.lerp()'.
267    #[test]
268    fn fractional_offset_lerp() {
269        let a = FractionalOffset::TOP_LEFT;
270        let b = FractionalOffset::TOP_CENTER;
271        assert_eq!(
272            FractionalOffset::lerp(Some(a), Some(b), 0.25),
273            Some(FractionalOffset::new(0.125, 0.0))
274        );
275        assert_eq!(FractionalOffset::lerp(None, None, 0.25), None);
276        assert_eq!(
277            FractionalOffset::lerp(None, Some(b), 0.25),
278            Some(FractionalOffset::new(0.5, 0.5 - 0.125))
279        );
280        assert_eq!(
281            FractionalOffset::lerp(Some(a), None, 0.25),
282            Some(FractionalOffset::new(0.125, 0.125))
283        );
284    }
285
286    // fractional_offset_test.dart 'FractionalOffset.lerp identical a,b'.
287    #[test]
288    fn fractional_offset_lerp_identical() {
289        assert_eq!(FractionalOffset::lerp(None, None, 0.0), None);
290        let decoration = FractionalOffset::new(1.0, 2.0);
291        assert_eq!(
292            FractionalOffset::lerp(Some(decoration), Some(decoration), 0.5),
293            Some(decoration)
294        );
295    }
296
297    // fractional_offset_test.dart 'FractionalOffset.fromOffsetAndSize()'.
298    #[test]
299    fn from_offset_and_size() {
300        let a = FractionalOffset::from_offset_and_size(
301            Offset::new(100.0, 100.0),
302            Size::new(200.0, 400.0),
303        );
304        assert_eq!(a, FractionalOffset::new(0.5, 0.25));
305    }
306
307    // fractional_offset_test.dart 'FractionalOffset.fromOffsetAndRect()'.
308    #[test]
309    fn from_offset_and_rect() {
310        let a = FractionalOffset::from_offset_and_rect(
311            Offset::new(150.0, 120.0),
312            Rect::from_ltwh(50.0, 20.0, 200.0, 400.0),
313        );
314        assert_eq!(a, FractionalOffset::new(0.5, 0.25));
315    }
316
317    #[test]
318    fn converts_to_alignment() {
319        assert_eq!(Alignment::from(FractionalOffset::CENTER), Alignment::CENTER);
320        assert_eq!(FractionalOffset::TOP_LEFT, Alignment::TOP_LEFT);
321    }
322}