gemini_engine/ascii/
alignment.rs

1use crate::core::Vec2D;
2
3/// An enum to determine the alignment of an [ascii](super) element's content
4#[derive(Debug, Clone, Copy)]
5pub enum TextAlign {
6    /// Align to the beginning of the text
7    Begin,
8    /// Align to the center of the text
9    Centered,
10    /// Align to the end of the text
11    End,
12}
13
14impl TextAlign {
15    /// Align the given 1-dimentional coordinate as dictated by the `TextAlign` enum variation
16    #[must_use]
17    pub const fn apply_to(&self, pos: i64, text_length: i64) -> i64 {
18        match self {
19            Self::Begin => pos,
20            Self::Centered => pos - text_length / 2,
21            Self::End => pos - text_length,
22        }
23    }
24}
25
26/// Two-dimensional text align, used by [`Sprite`](super::Sprite) and [`AnimatedSprite`](super::AnimatedSprite)
27#[derive(Debug, Clone, Copy)]
28pub struct TextAlign2D {
29    /// X coordinate [`TextAlign`]. `TextAlign::Begin` is left
30    x: TextAlign,
31    /// Y coordinate [`TextAlign`]. `TextAlign::Begin` is top
32    y: TextAlign,
33}
34
35impl Default for TextAlign2D {
36    fn default() -> Self {
37        Self::new(TextAlign::Begin, TextAlign::Begin)
38    }
39}
40
41impl TextAlign2D {
42    /// Align to centre of text in both X and Y axes
43    pub const CENTERED: Self = Self::new(TextAlign::Centered, TextAlign::Centered);
44
45    /// Create a new `TextAlign2D` with a given x and y align
46    #[must_use]
47    pub const fn new(x_align: TextAlign, y_align: TextAlign) -> Self {
48        Self {
49            x: x_align,
50            y: y_align,
51        }
52    }
53
54    /// Align the given position as dictated by the X and Y `TextAlign` enum variations
55    #[must_use]
56    pub const fn apply_to(&self, pos: Vec2D, text_block_size: Vec2D) -> Vec2D {
57        Vec2D::new(
58            self.x.apply_to(pos.x, text_block_size.x),
59            self.y.apply_to(pos.y, text_block_size.y),
60        )
61    }
62}