Skip to main content

waft_painting/
alignment.rs

1//! Flutter counterpart: `painting/alignment.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::basic_types::TextDirection;
9
10/// Base class for [`Alignment`] that allows for text-direction aware
11/// resolution.
12///
13/// A property or argument of this type accepts classes created either with
14/// [`Alignment`] and its variants, or [`AlignmentDirectional::new`].
15///
16/// To convert an [`AlignmentGeometry`] object of indeterminate type into an
17/// [`Alignment`] object, call the [`resolve`](AlignmentGeometry::resolve)
18/// method.
19///
20/// Non-exhaustive: Flutter may add a subclass.
21#[non_exhaustive]
22#[derive(Clone, Copy)]
23pub enum AlignmentGeometry {
24    /// Visual alignment — Dart's `Alignment`.
25    Alignment(Alignment),
26    /// Directional alignment — Dart's `AlignmentDirectional`.
27    Directional(AlignmentDirectional),
28    /// A visual and a directional horizontal coordinate at once — Dart's private
29    /// `_MixedAlignment`, what combining the two kinds produces.
30    Mixed {
31        /// The distance fraction in the horizontal direction.
32        x: f64,
33        /// The distance fraction in the horizontal direction from the start side.
34        start: f64,
35        /// The distance fraction in the vertical direction.
36        y: f64,
37    },
38}
39
40impl AlignmentGeometry {
41    /// Creates an [`Alignment`].
42    pub const fn xy(x: f64, y: f64) -> AlignmentGeometry {
43        AlignmentGeometry::Alignment(Alignment::new(x, y))
44    }
45
46    /// Creates a directional alignment, or [`AlignmentDirectional`].
47    pub const fn directional(start: f64, y: f64) -> AlignmentGeometry {
48        AlignmentGeometry::Directional(AlignmentDirectional::new(start, y))
49    }
50
51    /// The top left corner.
52    pub const TOP_LEFT: AlignmentGeometry = AlignmentGeometry::Alignment(Alignment::TOP_LEFT);
53    /// The center point along the top edge.
54    pub const TOP_CENTER: AlignmentGeometry = AlignmentGeometry::Alignment(Alignment::TOP_CENTER);
55    /// The top right corner.
56    pub const TOP_RIGHT: AlignmentGeometry = AlignmentGeometry::Alignment(Alignment::TOP_RIGHT);
57    /// The top corner on the "start" edge.
58    pub const TOP_START: AlignmentGeometry =
59        AlignmentGeometry::Directional(AlignmentDirectional::TOP_START);
60    /// The top corner on the "end" edge.
61    pub const TOP_END: AlignmentGeometry =
62        AlignmentGeometry::Directional(AlignmentDirectional::TOP_END);
63    /// The center point along the left edge.
64    pub const CENTER_LEFT: AlignmentGeometry = AlignmentGeometry::Alignment(Alignment::CENTER_LEFT);
65    /// The center point, both horizontally and vertically.
66    pub const CENTER: AlignmentGeometry = AlignmentGeometry::Alignment(Alignment::CENTER);
67    /// The center point along the right edge.
68    pub const CENTER_RIGHT: AlignmentGeometry =
69        AlignmentGeometry::Alignment(Alignment::CENTER_RIGHT);
70    /// The center point along the "start" edge.
71    pub const CENTER_START: AlignmentGeometry =
72        AlignmentGeometry::Directional(AlignmentDirectional::CENTER_START);
73    /// The center point along the "end" edge.
74    pub const CENTER_END: AlignmentGeometry =
75        AlignmentGeometry::Directional(AlignmentDirectional::CENTER_END);
76    /// The bottom left corner.
77    pub const BOTTOM_LEFT: AlignmentGeometry = AlignmentGeometry::Alignment(Alignment::BOTTOM_LEFT);
78    /// The center point along the bottom edge.
79    pub const BOTTOM_CENTER: AlignmentGeometry =
80        AlignmentGeometry::Alignment(Alignment::BOTTOM_CENTER);
81    /// The bottom right corner.
82    pub const BOTTOM_RIGHT: AlignmentGeometry =
83        AlignmentGeometry::Alignment(Alignment::BOTTOM_RIGHT);
84    /// The bottom corner on the "start" edge.
85    pub const BOTTOM_START: AlignmentGeometry =
86        AlignmentGeometry::Directional(AlignmentDirectional::BOTTOM_START);
87    /// The bottom corner on the "end" edge.
88    pub const BOTTOM_END: AlignmentGeometry =
89        AlignmentGeometry::Directional(AlignmentDirectional::BOTTOM_END);
90
91    fn x(&self) -> f64 {
92        match self {
93            AlignmentGeometry::Alignment(alignment) => alignment.x,
94            AlignmentGeometry::Directional(_) => 0.0,
95            AlignmentGeometry::Mixed { x, .. } => *x,
96        }
97    }
98
99    fn start(&self) -> f64 {
100        match self {
101            AlignmentGeometry::Alignment(_) => 0.0,
102            AlignmentGeometry::Directional(alignment) => alignment.start,
103            AlignmentGeometry::Mixed { start, .. } => *start,
104        }
105    }
106
107    fn y(&self) -> f64 {
108        match self {
109            AlignmentGeometry::Alignment(alignment) => alignment.y,
110            AlignmentGeometry::Directional(alignment) => alignment.y,
111            AlignmentGeometry::Mixed { y, .. } => *y,
112        }
113    }
114
115    /// Dart's private `_MixedAlignment`.
116    const fn mixed(x: f64, start: f64, y: f64) -> AlignmentGeometry {
117        AlignmentGeometry::Mixed { x, start, y }
118    }
119
120    /// Returns the sum of two [`AlignmentGeometry`] objects.
121    ///
122    /// If you know you are adding two [`Alignment`] or two
123    /// [`AlignmentDirectional`] objects, consider using the `+` operator
124    /// instead, which always returns an object of the same type as the operands,
125    /// and is typed accordingly.
126    ///
127    /// Applied to two objects of the same kind, the result is of that kind;
128    /// otherwise it is the mixed arm, which [`resolve`](Self::resolve) turns
129    /// into a concrete [`Alignment`].
130    #[allow(clippy::should_implement_trait)]
131    pub fn add(self, other: AlignmentGeometry) -> AlignmentGeometry {
132        match (self, other) {
133            (AlignmentGeometry::Alignment(a), AlignmentGeometry::Alignment(b)) => {
134                AlignmentGeometry::Alignment(a + b)
135            }
136            (AlignmentGeometry::Directional(a), AlignmentGeometry::Directional(b)) => {
137                AlignmentGeometry::Directional(a + b)
138            }
139            _ => AlignmentGeometry::mixed(
140                self.x() + other.x(),
141                self.start() + other.start(),
142                self.y() + other.y(),
143            ),
144        }
145    }
146
147    /// Integer divides the [`AlignmentGeometry`] object in each dimension by
148    /// the given factor.
149    pub fn truncating_div(&self, other: f64) -> AlignmentGeometry {
150        match self {
151            AlignmentGeometry::Alignment(alignment) => {
152                AlignmentGeometry::Alignment(alignment.truncating_div(other))
153            }
154            AlignmentGeometry::Directional(alignment) => {
155                AlignmentGeometry::Directional(alignment.truncating_div(other))
156            }
157            AlignmentGeometry::Mixed { .. } => AlignmentGeometry::mixed(
158                (self.x() / other).trunc(),
159                (self.start() / other).trunc(),
160                (self.y() / other).trunc(),
161            ),
162        }
163    }
164
165    /// Linearly interpolate between two [`AlignmentGeometry`] objects.
166    ///
167    /// If either is `None`, this function interpolates from
168    /// [`Alignment::CENTER`], and the result is of the same kind as the
169    /// non-`None` argument.
170    ///
171    /// Applied to two objects of the same kind, the result is of that kind;
172    /// otherwise it is the mixed arm, which [`resolve`](Self::resolve) turns
173    /// into a concrete [`Alignment`].
174    pub fn lerp(
175        a: Option<AlignmentGeometry>,
176        b: Option<AlignmentGeometry>,
177        t: f64,
178    ) -> Option<AlignmentGeometry> {
179        if a == b {
180            return a;
181        }
182        match (a, b) {
183            (None, None) => None,
184            (None, Some(b)) => Some(b * t),
185            (Some(a), None) => Some(a * (1.0 - t)),
186            (Some(AlignmentGeometry::Alignment(a)), Some(AlignmentGeometry::Alignment(b))) => {
187                Alignment::lerp(Some(a), Some(b), t).map(AlignmentGeometry::Alignment)
188            }
189            (Some(AlignmentGeometry::Directional(a)), Some(AlignmentGeometry::Directional(b))) => {
190                AlignmentDirectional::lerp(Some(a), Some(b), t).map(AlignmentGeometry::Directional)
191            }
192            (Some(a), Some(b)) => Some(AlignmentGeometry::mixed(
193                lerp_double(Some(a.x()), Some(b.x()), t).unwrap(),
194                lerp_double(Some(a.start()), Some(b.start()), t).unwrap(),
195                lerp_double(Some(a.y()), Some(b.y()), t).unwrap(),
196            )),
197        }
198    }
199
200    /// Convert this instance into an [`Alignment`], which uses literal
201    /// coordinates (the `x` coordinate being explicitly a distance from the
202    /// left).
203    ///
204    /// See also:
205    ///
206    ///  * [`Alignment`], for which this is a no-op (returns itself).
207    ///  * [`AlignmentDirectional`], which flips the horizontal direction based
208    ///    on the `direction` argument.
209    pub fn resolve(&self, direction: Option<TextDirection>) -> Alignment {
210        match self {
211            AlignmentGeometry::Alignment(alignment) => alignment.resolve(direction),
212            AlignmentGeometry::Directional(alignment) => alignment.resolve(direction),
213            AlignmentGeometry::Mixed { .. } => {
214                match direction.expect("AlignmentGeometry.resolve needs a TextDirection") {
215                    TextDirection::Rtl => Alignment::new(self.x() - self.start(), self.y()),
216                    TextDirection::Ltr => Alignment::new(self.x() + self.start(), self.y()),
217                }
218            }
219        }
220    }
221}
222
223impl PartialEq for AlignmentGeometry {
224    fn eq(&self, other: &AlignmentGeometry) -> bool {
225        other.x() == self.x() && other.start() == self.start() && other.y() == self.y()
226    }
227}
228
229impl From<Alignment> for AlignmentGeometry {
230    fn from(alignment: Alignment) -> AlignmentGeometry {
231        AlignmentGeometry::Alignment(alignment)
232    }
233}
234
235impl From<AlignmentDirectional> for AlignmentGeometry {
236    fn from(alignment: AlignmentDirectional) -> AlignmentGeometry {
237        AlignmentGeometry::Directional(alignment)
238    }
239}
240
241impl Neg for AlignmentGeometry {
242    type Output = AlignmentGeometry;
243
244    fn neg(self) -> AlignmentGeometry {
245        match self {
246            AlignmentGeometry::Alignment(alignment) => AlignmentGeometry::Alignment(-alignment),
247            AlignmentGeometry::Directional(alignment) => AlignmentGeometry::Directional(-alignment),
248            AlignmentGeometry::Mixed { .. } => {
249                AlignmentGeometry::mixed(-self.x(), -self.start(), -self.y())
250            }
251        }
252    }
253}
254
255impl Mul<f64> for AlignmentGeometry {
256    type Output = AlignmentGeometry;
257
258    fn mul(self, other: f64) -> AlignmentGeometry {
259        match self {
260            AlignmentGeometry::Alignment(alignment) => {
261                AlignmentGeometry::Alignment(alignment * other)
262            }
263            AlignmentGeometry::Directional(alignment) => {
264                AlignmentGeometry::Directional(alignment * other)
265            }
266            AlignmentGeometry::Mixed { .. } => {
267                AlignmentGeometry::mixed(self.x() * other, self.start() * other, self.y() * other)
268            }
269        }
270    }
271}
272
273impl Div<f64> for AlignmentGeometry {
274    type Output = AlignmentGeometry;
275
276    fn div(self, other: f64) -> AlignmentGeometry {
277        match self {
278            AlignmentGeometry::Alignment(alignment) => {
279                AlignmentGeometry::Alignment(alignment / other)
280            }
281            AlignmentGeometry::Directional(alignment) => {
282                AlignmentGeometry::Directional(alignment / other)
283            }
284            AlignmentGeometry::Mixed { .. } => {
285                AlignmentGeometry::mixed(self.x() / other, self.start() / other, self.y() / other)
286            }
287        }
288    }
289}
290
291impl Rem<f64> for AlignmentGeometry {
292    type Output = AlignmentGeometry;
293
294    fn rem(self, other: f64) -> AlignmentGeometry {
295        match self {
296            AlignmentGeometry::Alignment(alignment) => {
297                AlignmentGeometry::Alignment(alignment % other)
298            }
299            AlignmentGeometry::Directional(alignment) => {
300                AlignmentGeometry::Directional(alignment % other)
301            }
302            AlignmentGeometry::Mixed { .. } => {
303                AlignmentGeometry::mixed(self.x() % other, self.start() % other, self.y() % other)
304            }
305        }
306    }
307}
308
309impl Debug for AlignmentGeometry {
310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        if self.start() == 0.0 {
312            Alignment::stringify(self.x(), self.y(), f)
313        } else if self.x() == 0.0 {
314            AlignmentDirectional::stringify(self.start(), self.y(), f)
315        } else {
316            Alignment::stringify(self.x(), self.y(), f)?;
317            write!(f, " + ")?;
318            AlignmentDirectional::stringify(self.start(), 0.0, f)
319        }
320    }
321}
322
323/// A point within a rectangle.
324///
325/// `Alignment(0.0, 0.0)` represents the center of the rectangle. The distance
326/// from -1.0 to +1.0 is the distance from one side of the rectangle to the
327/// other side of the rectangle. Therefore, 2.0 units horizontally (or
328/// vertically) is equivalent to the width (or height) of the rectangle.
329///
330/// `Alignment(-1.0, -1.0)` represents the top left of the rectangle.
331///
332/// `Alignment(1.0, 1.0)` represents the bottom right of the rectangle.
333///
334/// `Alignment(0.0, 3.0)` represents a point that is horizontally centered with
335/// respect to the rectangle and vertically below the bottom of the rectangle by
336/// the height of the rectangle.
337///
338/// `Alignment(0.0, -0.5)` represents a point that is horizontally centered with
339/// respect to the rectangle and vertically half way between the top edge and
340/// the center.
341///
342/// `Alignment(x, y)` in a rectangle with height h and width w describes the
343/// point (x * w/2 + w/2, y * h/2 + h/2) in the coordinate system of the
344/// rectangle.
345///
346/// [`Alignment`] uses visual coordinates, which means increasing [`x`](Alignment::x)
347/// moves the point from left to right. To support layouts with a right-to-left
348/// [`TextDirection`], consider using [`AlignmentDirectional`], in which the
349/// direction the point moves when increasing the horizontal value depends on
350/// the [`TextDirection`].
351///
352/// A variety of widgets use [`Alignment`] in their configuration, most
353/// notably:
354///
355///  * `Align` positions a child according to an [`Alignment`].
356///
357/// See also:
358///
359///  * [`AlignmentDirectional`], which has a horizontal coordinate orientation
360///    that depends on the [`TextDirection`].
361///  * [`AlignmentGeometry`], which is an abstract type that is agnostic as to
362///    whether the horizontal direction depends on the [`TextDirection`].
363#[derive(Clone, Copy, PartialEq)]
364pub struct Alignment {
365    /// The distance fraction in the horizontal direction.
366    ///
367    /// A value of -1.0 corresponds to the leftmost edge. A value of 1.0
368    /// corresponds to the rightmost edge. Values are not limited to that range;
369    /// values less than -1.0 represent positions to the left of the left edge,
370    /// and values greater than 1.0 represent positions to the right of the
371    /// right edge.
372    pub x: f64,
373    /// The distance fraction in the vertical direction.
374    ///
375    /// A value of -1.0 corresponds to the topmost edge. A value of 1.0
376    /// corresponds to the bottommost edge. Values are not limited to that range;
377    /// values less than -1.0 represent positions above the top, and values
378    /// greater than 1.0 represent positions below the bottom.
379    pub y: f64,
380}
381
382impl Alignment {
383    /// Creates an alignment.
384    pub const fn new(x: f64, y: f64) -> Alignment {
385        Alignment { x, y }
386    }
387
388    /// The top left corner.
389    pub const TOP_LEFT: Alignment = Alignment::new(-1.0, -1.0);
390    /// The center point along the top edge.
391    pub const TOP_CENTER: Alignment = Alignment::new(0.0, -1.0);
392    /// The top right corner.
393    pub const TOP_RIGHT: Alignment = Alignment::new(1.0, -1.0);
394    /// The center point along the left edge.
395    pub const CENTER_LEFT: Alignment = Alignment::new(-1.0, 0.0);
396    /// The center point, both horizontally and vertically.
397    pub const CENTER: Alignment = Alignment::new(0.0, 0.0);
398    /// The center point along the right edge.
399    pub const CENTER_RIGHT: Alignment = Alignment::new(1.0, 0.0);
400    /// The bottom left corner.
401    pub const BOTTOM_LEFT: Alignment = Alignment::new(-1.0, 1.0);
402    /// The center point along the bottom edge.
403    pub const BOTTOM_CENTER: Alignment = Alignment::new(0.0, 1.0);
404    /// The bottom right corner.
405    pub const BOTTOM_RIGHT: Alignment = Alignment::new(1.0, 1.0);
406
407    /// Integer divides the [`Alignment`] in each dimension by the given factor.
408    pub fn truncating_div(&self, other: f64) -> Alignment {
409        Alignment::new((self.x / other).trunc(), (self.y / other).trunc())
410    }
411
412    /// Returns the offset that is this fraction in the direction of the given
413    /// offset.
414    pub fn along_offset(&self, other: Offset) -> Offset {
415        let center_x = other.dx() / 2.0;
416        let center_y = other.dy() / 2.0;
417        Offset::new(center_x + self.x * center_x, center_y + self.y * center_y)
418    }
419
420    /// Returns the offset that is this fraction within the given size.
421    pub fn along_size(&self, other: Size) -> Offset {
422        let center_x = other.width() / 2.0;
423        let center_y = other.height() / 2.0;
424        Offset::new(center_x + self.x * center_x, center_y + self.y * center_y)
425    }
426
427    /// Returns the point that is this fraction within the given rect.
428    pub fn within_rect(&self, rect: Rect) -> Offset {
429        let half_width = rect.width() / 2.0;
430        let half_height = rect.height() / 2.0;
431        Offset::new(
432            rect.left + half_width + self.x * half_width,
433            rect.top + half_height + self.y * half_height,
434        )
435    }
436
437    /// Returns a rect of the given size, aligned within given rect as specified
438    /// by this alignment.
439    ///
440    /// For example, a 100×100 size inscribed on a 200×200 rect using
441    /// [`Alignment::TOP_LEFT`] would be the 100×100 rect at the top left of the
442    /// 200×200 rect.
443    pub fn inscribe(&self, size: Size, rect: Rect) -> Rect {
444        let half_width_delta = (rect.width() - size.width()) / 2.0;
445        let half_height_delta = (rect.height() - size.height()) / 2.0;
446        Rect::from_ltwh(
447            rect.left + half_width_delta + self.x * half_width_delta,
448            rect.top + half_height_delta + self.y * half_height_delta,
449            size.width(),
450            size.height(),
451        )
452    }
453
454    /// Linearly interpolate between two [`Alignment`]s.
455    ///
456    /// If either is null, this function interpolates from [`Alignment::CENTER`].
457    pub fn lerp(a: Option<Alignment>, b: Option<Alignment>, t: f64) -> Option<Alignment> {
458        if a == b {
459            return a;
460        }
461        match (a, b) {
462            (None, None) => None,
463            (None, Some(b)) => Some(Alignment::new(
464                lerp_double(Some(0.0), Some(b.x), t).unwrap(),
465                lerp_double(Some(0.0), Some(b.y), t).unwrap(),
466            )),
467            (Some(a), None) => Some(Alignment::new(
468                lerp_double(Some(a.x), Some(0.0), t).unwrap(),
469                lerp_double(Some(a.y), Some(0.0), t).unwrap(),
470            )),
471            (Some(a), Some(b)) => Some(Alignment::new(
472                lerp_double(Some(a.x), Some(b.x), t).unwrap(),
473                lerp_double(Some(a.y), Some(b.y), t).unwrap(),
474            )),
475        }
476    }
477
478    /// Convert this instance into an [`Alignment`], which uses literal
479    /// coordinates.
480    pub fn resolve(&self, _direction: Option<TextDirection>) -> Alignment {
481        *self
482    }
483
484    fn stringify(x: f64, y: f64, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485        match (x, y) {
486            (-1.0, -1.0) => write!(f, "Alignment.topLeft"),
487            (0.0, -1.0) => write!(f, "Alignment.topCenter"),
488            (1.0, -1.0) => write!(f, "Alignment.topRight"),
489            (-1.0, 0.0) => write!(f, "Alignment.centerLeft"),
490            (0.0, 0.0) => write!(f, "Alignment.center"),
491            (1.0, 0.0) => write!(f, "Alignment.centerRight"),
492            (-1.0, 1.0) => write!(f, "Alignment.bottomLeft"),
493            (0.0, 1.0) => write!(f, "Alignment.bottomCenter"),
494            (1.0, 1.0) => write!(f, "Alignment.bottomRight"),
495            _ => write!(f, "Alignment({x:.1}, {y:.1})"),
496        }
497    }
498}
499
500impl Sub for Alignment {
501    type Output = Alignment;
502
503    fn sub(self, other: Alignment) -> Alignment {
504        Alignment::new(self.x - other.x, self.y - other.y)
505    }
506}
507
508impl Add for Alignment {
509    type Output = Alignment;
510
511    fn add(self, other: Alignment) -> Alignment {
512        Alignment::new(self.x + other.x, self.y + other.y)
513    }
514}
515
516impl Neg for Alignment {
517    type Output = Alignment;
518
519    fn neg(self) -> Alignment {
520        Alignment::new(-self.x, -self.y)
521    }
522}
523
524impl Mul<f64> for Alignment {
525    type Output = Alignment;
526
527    fn mul(self, other: f64) -> Alignment {
528        Alignment::new(self.x * other, self.y * other)
529    }
530}
531
532impl Div<f64> for Alignment {
533    type Output = Alignment;
534
535    fn div(self, other: f64) -> Alignment {
536        Alignment::new(self.x / other, self.y / other)
537    }
538}
539
540impl Rem<f64> for Alignment {
541    type Output = Alignment;
542
543    fn rem(self, other: f64) -> Alignment {
544        Alignment::new(self.x.rem_euclid(other), self.y.rem_euclid(other))
545    }
546}
547
548impl Debug for Alignment {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        Alignment::stringify(self.x, self.y, f)
551    }
552}
553
554/// An offset that's expressed as a fraction of a [`Size`], but whose horizontal
555/// component is dependent on the writing direction.
556///
557/// This can be used to indicate an offset from the left in [`TextDirection::Ltr`]
558/// text and an offset from the right in [`TextDirection::Rtl`] text without
559/// having to be aware of the current text direction.
560///
561/// See also:
562///
563///  * [`Alignment`], a variant that is defined in physical terms (i.e. whose
564///    horizontal component does not depend on the text direction).
565#[derive(Clone, Copy, PartialEq)]
566pub struct AlignmentDirectional {
567    /// The distance fraction in the horizontal direction.
568    ///
569    /// A value of -1.0 corresponds to the edge on the "start" side, which is
570    /// the left side in [`TextDirection::Ltr`] contexts and the right side in
571    /// [`TextDirection::Rtl`] contexts. A value of 1.0 corresponds to the
572    /// opposite edge, the "end" side. Values are not limited to that range;
573    /// values less than -1.0 represent positions beyond the start edge, and
574    /// values greater than 1.0 represent positions beyond the end edge.
575    ///
576    /// This value is normalized into an [`Alignment::x`] value by the
577    /// [`resolve`](Self::resolve) method.
578    pub start: f64,
579    /// The distance fraction in the vertical direction.
580    ///
581    /// A value of -1.0 corresponds to the topmost edge. A value of 1.0
582    /// corresponds to the bottommost edge. Values are not limited to that range;
583    /// values less than -1.0 represent positions above the top, and values
584    /// greater than 1.0 represent positions below the bottom.
585    ///
586    /// This value is passed through to [`Alignment::y`] unmodified by the
587    /// [`resolve`](Self::resolve) method.
588    pub y: f64,
589}
590
591impl AlignmentDirectional {
592    /// Creates a directional alignment.
593    pub const fn new(start: f64, y: f64) -> AlignmentDirectional {
594        AlignmentDirectional { start, y }
595    }
596
597    /// The top corner on the "start" side.
598    pub const TOP_START: AlignmentDirectional = AlignmentDirectional::new(-1.0, -1.0);
599    /// The center point along the top edge.
600    ///
601    /// Consider using [`Alignment::TOP_CENTER`] instead, as it does not need to
602    /// be [`resolve`](Self::resolve)d to be used.
603    pub const TOP_CENTER: AlignmentDirectional = AlignmentDirectional::new(0.0, -1.0);
604    /// The top corner on the "end" side.
605    pub const TOP_END: AlignmentDirectional = AlignmentDirectional::new(1.0, -1.0);
606    /// The center point along the "start" edge.
607    pub const CENTER_START: AlignmentDirectional = AlignmentDirectional::new(-1.0, 0.0);
608    /// The center point, both horizontally and vertically.
609    ///
610    /// Consider using [`Alignment::CENTER`] instead, as it does not need to be
611    /// [`resolve`](Self::resolve)d to be used.
612    pub const CENTER: AlignmentDirectional = AlignmentDirectional::new(0.0, 0.0);
613    /// The center point along the "end" edge.
614    pub const CENTER_END: AlignmentDirectional = AlignmentDirectional::new(1.0, 0.0);
615    /// The bottom corner on the "start" side.
616    pub const BOTTOM_START: AlignmentDirectional = AlignmentDirectional::new(-1.0, 1.0);
617    /// The center point along the bottom edge.
618    ///
619    /// Consider using [`Alignment::BOTTOM_CENTER`] instead, as it does not need
620    /// to be [`resolve`](Self::resolve)d to be used.
621    pub const BOTTOM_CENTER: AlignmentDirectional = AlignmentDirectional::new(0.0, 1.0);
622    /// The bottom corner on the "end" side.
623    pub const BOTTOM_END: AlignmentDirectional = AlignmentDirectional::new(1.0, 1.0);
624
625    /// Integer divides the [`AlignmentDirectional`] in each dimension by the
626    /// given factor.
627    pub fn truncating_div(&self, other: f64) -> AlignmentDirectional {
628        AlignmentDirectional::new((self.start / other).trunc(), (self.y / other).trunc())
629    }
630
631    /// Linearly interpolate between two [`AlignmentDirectional`]s.
632    ///
633    /// If either is null, this function interpolates from
634    /// [`AlignmentDirectional::CENTER`].
635    pub fn lerp(
636        a: Option<AlignmentDirectional>,
637        b: Option<AlignmentDirectional>,
638        t: f64,
639    ) -> Option<AlignmentDirectional> {
640        if a == b {
641            return a;
642        }
643        match (a, b) {
644            (None, None) => None,
645            (None, Some(b)) => Some(AlignmentDirectional::new(
646                lerp_double(Some(0.0), Some(b.start), t).unwrap(),
647                lerp_double(Some(0.0), Some(b.y), t).unwrap(),
648            )),
649            (Some(a), None) => Some(AlignmentDirectional::new(
650                lerp_double(Some(a.start), Some(0.0), t).unwrap(),
651                lerp_double(Some(a.y), Some(0.0), t).unwrap(),
652            )),
653            (Some(a), Some(b)) => Some(AlignmentDirectional::new(
654                lerp_double(Some(a.start), Some(b.start), t).unwrap(),
655                lerp_double(Some(a.y), Some(b.y), t).unwrap(),
656            )),
657        }
658    }
659
660    /// Convert this instance into an [`Alignment`], which uses literal
661    /// coordinates.
662    pub fn resolve(&self, direction: Option<TextDirection>) -> Alignment {
663        match direction.expect("No TextDirection found.") {
664            TextDirection::Rtl => Alignment::new(-self.start, self.y),
665            TextDirection::Ltr => Alignment::new(self.start, self.y),
666        }
667    }
668
669    fn stringify(start: f64, y: f64, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670        match (start, y) {
671            (-1.0, -1.0) => write!(f, "AlignmentDirectional.topStart"),
672            (0.0, -1.0) => write!(f, "AlignmentDirectional.topCenter"),
673            (1.0, -1.0) => write!(f, "AlignmentDirectional.topEnd"),
674            (-1.0, 0.0) => write!(f, "AlignmentDirectional.centerStart"),
675            (0.0, 0.0) => write!(f, "AlignmentDirectional.center"),
676            (1.0, 0.0) => write!(f, "AlignmentDirectional.centerEnd"),
677            (-1.0, 1.0) => write!(f, "AlignmentDirectional.bottomStart"),
678            (0.0, 1.0) => write!(f, "AlignmentDirectional.bottomCenter"),
679            (1.0, 1.0) => write!(f, "AlignmentDirectional.bottomEnd"),
680            _ => write!(f, "AlignmentDirectional({start:.1}, {y:.1})"),
681        }
682    }
683}
684
685impl Sub for AlignmentDirectional {
686    type Output = AlignmentDirectional;
687
688    fn sub(self, other: AlignmentDirectional) -> AlignmentDirectional {
689        AlignmentDirectional::new(self.start - other.start, self.y - other.y)
690    }
691}
692
693impl Add for AlignmentDirectional {
694    type Output = AlignmentDirectional;
695
696    fn add(self, other: AlignmentDirectional) -> AlignmentDirectional {
697        AlignmentDirectional::new(self.start + other.start, self.y + other.y)
698    }
699}
700
701impl Neg for AlignmentDirectional {
702    type Output = AlignmentDirectional;
703
704    fn neg(self) -> AlignmentDirectional {
705        AlignmentDirectional::new(-self.start, -self.y)
706    }
707}
708
709impl Mul<f64> for AlignmentDirectional {
710    type Output = AlignmentDirectional;
711
712    fn mul(self, other: f64) -> AlignmentDirectional {
713        AlignmentDirectional::new(self.start * other, self.y * other)
714    }
715}
716
717impl Div<f64> for AlignmentDirectional {
718    type Output = AlignmentDirectional;
719
720    fn div(self, other: f64) -> AlignmentDirectional {
721        AlignmentDirectional::new(self.start / other, self.y / other)
722    }
723}
724
725impl Rem<f64> for AlignmentDirectional {
726    type Output = AlignmentDirectional;
727
728    fn rem(self, other: f64) -> AlignmentDirectional {
729        AlignmentDirectional::new(self.start.rem_euclid(other), self.y.rem_euclid(other))
730    }
731}
732
733impl Debug for AlignmentDirectional {
734    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735        AlignmentDirectional::stringify(self.start, self.y, f)
736    }
737}
738
739/// The vertical alignment of text within an input box.
740///
741/// A single [`y`](TextAlignVertical::y) value that can range from -1.0 to 1.0.
742/// -1.0 aligns to the top of an input box so that the top of the first line of
743/// text fits within the box and its padding. 0.0 aligns to the center of the
744/// box. 1.0 aligns so that the bottom of the last line of text aligns with the
745/// bottom interior edge of the input box.
746///
747/// See also:
748///
749///  * `TextField.textAlignVertical`, which is passed on to the
750///    `InputDecorator`.
751///  * `CupertinoTextField.textAlignVertical`, which behaves in the same way as
752///    the parameter in TextField.
753///  * `InputDecorator.textAlignVertical`, which defines the alignment of
754///    prefix, input, and suffix within an `InputDecorator`.
755#[derive(Clone, Copy)]
756pub struct TextAlignVertical {
757    /// A value ranging from -1.0 to 1.0 that defines the topmost and bottommost
758    /// locations of the top and bottom of the input box.
759    pub y: f64,
760}
761
762impl TextAlignVertical {
763    /// Creates a TextAlignVertical from any y value between -1.0 and 1.0.
764    pub fn new(y: f64) -> TextAlignVertical {
765        debug_assert!((-1.0..=1.0).contains(&y));
766        TextAlignVertical { y }
767    }
768
769    /// Aligns a TextField's input Text with the topmost location within a
770    /// TextField's input box.
771    pub const TOP: TextAlignVertical = TextAlignVertical { y: -1.0 };
772    /// Aligns a TextField's input Text to the center of the TextField.
773    pub const CENTER: TextAlignVertical = TextAlignVertical { y: 0.0 };
774    /// Aligns a TextField's input Text with the bottommost location within a
775    /// TextField.
776    pub const BOTTOM: TextAlignVertical = TextAlignVertical { y: 1.0 };
777}
778
779impl Debug for TextAlignVertical {
780    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781        write!(f, "TextAlignVertical(y: {})", self.y)
782    }
783}
784
785/// Dart's `TextAlignVertical.toString`, which [`Debug`] already renders.
786impl std::fmt::Display for TextAlignVertical {
787    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
788        std::fmt::Debug::fmt(self, f)
789    }
790}
791
792/// Dart's `AlignmentGeometry.toString`, which [`Debug`] already renders.
793impl std::fmt::Display for AlignmentGeometry {
794    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
795        std::fmt::Debug::fmt(self, f)
796    }
797}
798
799/// Dart's `Alignment.toString`, which [`Debug`] already renders.
800impl std::fmt::Display for Alignment {
801    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
802        std::fmt::Debug::fmt(self, f)
803    }
804}
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809
810    #[test]
811    fn alignment_control_test() {
812        let alignment = Alignment::new(0.5, 0.25);
813        assert_eq!(alignment / 2.0, Alignment::new(0.25, 0.125));
814        assert_eq!(alignment.truncating_div(2.0), Alignment::CENTER);
815        assert_eq!(alignment % 5.0, Alignment::new(0.5, 0.25));
816    }
817
818    #[test]
819    fn alignment_lerp() {
820        let a = Alignment::TOP_LEFT;
821        let b = Alignment::TOP_CENTER;
822        assert_eq!(
823            Alignment::lerp(Some(a), Some(b), 0.25),
824            Some(Alignment::new(-0.75, -1.0))
825        );
826        assert_eq!(Alignment::lerp(None, None, 0.25), None);
827        assert_eq!(
828            Alignment::lerp(None, Some(b), 0.25),
829            Some(Alignment::new(0.0, -0.25))
830        );
831        assert_eq!(
832            Alignment::lerp(Some(a), None, 0.25),
833            Some(Alignment::new(-0.75, -0.75))
834        );
835        assert_eq!(
836            Alignment::lerp(Some(Alignment::TOP_LEFT), Some(Alignment::TOP_LEFT), 0.5),
837            Some(Alignment::TOP_LEFT)
838        );
839    }
840
841    #[test]
842    fn resolve_flips_start_in_rtl() {
843        assert_eq!(
844            AlignmentDirectional::new(0.25, 0.3).resolve(Some(TextDirection::Ltr)),
845            Alignment::new(0.25, 0.3)
846        );
847        assert_eq!(
848            AlignmentDirectional::new(0.25, 0.3).resolve(Some(TextDirection::Rtl)),
849            Alignment::new(-0.25, 0.3)
850        );
851        assert_eq!(
852            AlignmentDirectional::CENTER.resolve(Some(TextDirection::Ltr)),
853            Alignment::CENTER
854        );
855        assert_eq!(
856            AlignmentDirectional::CENTER.resolve(Some(TextDirection::Rtl)),
857            Alignment::CENTER
858        );
859        assert_eq!(
860            AlignmentDirectional::BOTTOM_END.resolve(Some(TextDirection::Ltr)),
861            Alignment::BOTTOM_RIGHT
862        );
863        assert_eq!(
864            AlignmentDirectional::BOTTOM_END.resolve(Some(TextDirection::Rtl)),
865            Alignment::BOTTOM_LEFT
866        );
867        assert_eq!(
868            AlignmentDirectional::CENTER_START.resolve(Some(TextDirection::Ltr)),
869            AlignmentDirectional::CENTER_END.resolve(Some(TextDirection::Rtl))
870        );
871    }
872
873    #[test]
874    fn zero_horizontal_alignments_compare_equal_across_kinds() {
875        assert_eq!(
876            AlignmentGeometry::from(Alignment::CENTER),
877            AlignmentGeometry::from(AlignmentDirectional::CENTER)
878        );
879        assert_ne!(
880            AlignmentGeometry::from(Alignment::TOP_LEFT),
881            AlignmentGeometry::from(AlignmentDirectional::TOP_START)
882        );
883        assert_eq!(
884            AlignmentGeometry::from(AlignmentDirectional::TOP_END * 0.0),
885            AlignmentGeometry::from(Alignment::CENTER)
886        );
887    }
888
889    #[test]
890    fn same_kind_operators() {
891        assert_eq!(
892            Alignment::new(1.0, 2.0) + Alignment::new(3.0, 5.0),
893            Alignment::new(4.0, 7.0)
894        );
895        assert_eq!(
896            Alignment::new(1.0, 2.0) - Alignment::new(3.0, 5.0),
897            Alignment::new(-2.0, -3.0)
898        );
899        assert_eq!(
900            AlignmentDirectional::new(1.0, 2.0) * 2.0,
901            AlignmentDirectional::new(2.0, 4.0)
902        );
903        assert_eq!(
904            AlignmentDirectional::new(1.0, 2.0) / 2.0,
905            AlignmentDirectional::new(0.5, 1.0)
906        );
907        assert_eq!(
908            AlignmentDirectional::new(1.0, 2.0) % 2.0,
909            AlignmentDirectional::CENTER_END
910        );
911        assert_eq!(
912            AlignmentDirectional::new(1.0, 2.0).truncating_div(2.0),
913            AlignmentDirectional::BOTTOM_CENTER
914        );
915        assert_eq!(Alignment::new(1.0, 2.0) * 2.0, Alignment::new(2.0, 4.0));
916        assert_eq!(Alignment::new(1.0, 2.0) % 2.0, Alignment::CENTER_RIGHT);
917        assert_eq!(
918            Alignment::new(1.0, 2.0).truncating_div(2.0),
919            Alignment::BOTTOM_CENTER
920        );
921    }
922
923    #[test]
924    fn debug_matches_darts_to_string() {
925        assert_eq!(
926            format!("{:?}", Alignment::new(1.0001, 2.0001)),
927            "Alignment(1.0, 2.0)"
928        );
929        assert_eq!(format!("{:?}", Alignment::CENTER), "Alignment.center");
930        assert_eq!(
931            format!("{:?}", Alignment::new(0.0001, 0.0001)),
932            "Alignment(0.0, 0.0)"
933        );
934        assert_eq!(
935            format!("{:?}", AlignmentDirectional::CENTER),
936            "AlignmentDirectional.center"
937        );
938    }
939
940    #[test]
941    fn factories_and_static_members() {
942        assert_eq!(
943            AlignmentGeometry::xy(4.0, 5.0),
944            AlignmentGeometry::from(Alignment::new(4.0, 5.0))
945        );
946        assert_eq!(
947            AlignmentGeometry::directional(4.0, 5.0),
948            AlignmentGeometry::from(AlignmentDirectional::new(4.0, 5.0))
949        );
950        assert_eq!(
951            AlignmentGeometry::TOP_LEFT,
952            AlignmentGeometry::from(Alignment::TOP_LEFT)
953        );
954        assert_eq!(
955            AlignmentGeometry::TOP_START,
956            AlignmentGeometry::from(AlignmentDirectional::TOP_START)
957        );
958        assert_eq!(
959            AlignmentGeometry::CENTER,
960            AlignmentGeometry::from(Alignment::CENTER)
961        );
962        assert_eq!(
963            AlignmentGeometry::BOTTOM_END,
964            AlignmentGeometry::from(AlignmentDirectional::BOTTOM_END)
965        );
966    }
967
968    #[test]
969    fn a_cross_kind_lerp_resolves_per_direction() {
970        let a = AlignmentGeometry::xy(1.0, 0.0);
971        let b = AlignmentGeometry::directional(1.0, 0.0);
972        let halfway = AlignmentGeometry::lerp(Some(a), Some(b), 0.5).expect("both ends are set");
973        assert!(matches!(halfway, AlignmentGeometry::Mixed { .. }));
974        assert_eq!(
975            halfway.resolve(Some(TextDirection::Ltr)),
976            Alignment::new(1.0, 0.0)
977        );
978        assert_eq!(
979            halfway.resolve(Some(TextDirection::Rtl)),
980            Alignment::new(0.0, 0.0)
981        );
982    }
983
984    #[test]
985    fn a_same_kind_lerp_keeps_the_kind() {
986        let lerp = |a, b, t| AlignmentGeometry::lerp(Some(a), Some(b), t).expect("both ends");
987        assert_eq!(
988            lerp(
989                AlignmentGeometry::TOP_LEFT,
990                AlignmentGeometry::BOTTOM_LEFT,
991                0.5
992            ),
993            AlignmentGeometry::Alignment(Alignment::CENTER_LEFT)
994        );
995        assert_eq!(
996            lerp(
997                AlignmentGeometry::TOP_START,
998                AlignmentGeometry::BOTTOM_START,
999                0.5
1000            ),
1001            AlignmentGeometry::Directional(AlignmentDirectional::CENTER_START)
1002        );
1003    }
1004
1005    #[test]
1006    fn a_lerp_from_none_starts_at_the_center() {
1007        let end = AlignmentGeometry::directional(1.0, 1.0);
1008        assert_eq!(
1009            AlignmentGeometry::lerp(None, Some(end), 0.5),
1010            Some(AlignmentGeometry::directional(0.5, 0.5))
1011        );
1012    }
1013
1014    #[test]
1015    fn a_cross_kind_add_is_the_mixed_arm() {
1016        let sum = AlignmentGeometry::xy(1.0, 2.0).add(AlignmentGeometry::directional(3.0, 4.0));
1017        assert_eq!(
1018            sum.resolve(Some(TextDirection::Ltr)),
1019            Alignment::new(4.0, 6.0)
1020        );
1021        assert_eq!(
1022            sum.resolve(Some(TextDirection::Rtl)),
1023            Alignment::new(-2.0, 6.0)
1024        );
1025    }
1026
1027    #[test]
1028    fn inscribe_puts_the_size_in_the_named_corner() {
1029        let rect = Rect::from_ltwh(0.0, 0.0, 200.0, 200.0);
1030        let size = Size::new(100.0, 100.0);
1031        assert_eq!(
1032            Alignment::TOP_LEFT.inscribe(size, rect),
1033            Rect::from_ltwh(0.0, 0.0, 100.0, 100.0)
1034        );
1035        assert_eq!(
1036            Alignment::CENTER.inscribe(size, rect),
1037            Rect::from_ltwh(50.0, 50.0, 100.0, 100.0)
1038        );
1039    }
1040}