reda_geometry/shape/
text.rs

1use num_traits::NumCast;
2
3use crate::shape::Point;
4use crate::traits::{BoundingBox, Cast, MapPoint, TryBoundingBox};
5use std::fmt;
6use std::hash::Hash;
7use std::ops::Deref;
8
9use super::Rect;
10
11pub trait TextType: Eq + Hash + Clone + fmt::Debug {}
12
13#[derive(Debug, Clone, Hash, PartialEq, Eq)]
14pub struct Text<T, S = String> {
15    location: Point<T>,
16    text: S,
17}
18
19impl<T, S: TextType> Text<T, S> {
20    /// Create a new text object.
21    pub fn new(text: S, location: Point<T>) -> Self {
22        Text { location, text }
23    }
24
25    /// Get a reference to the text string.
26    pub fn text(&self) -> &S {
27        &self.text
28    }
29}
30
31impl<T: Copy, S: TextType> Text<T, S> {
32    /// Get location of the text label.
33    #[inline]
34    pub fn location(&self) -> Point<T> {
35        self.location
36    }
37
38    /// Get x-coordinate of the label location.
39    #[inline]
40    pub fn x(&self) -> T {
41        self.location.x
42    }
43
44    /// Get y-coordinate of the label location.
45    #[inline]
46    pub fn y(&self) -> T {
47        self.location.y
48    }
49}
50
51/// Display format of the text label.
52impl<T, S> fmt::Display for Text<T, S>
53where
54    T: fmt::Display,
55    S: TextType + fmt::Display,
56{
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        write!(f, "Text({}, {})", self.text, self.location)
59    }
60}
61
62impl<T, S> Deref for Text<T, S>
63where
64    S: Deref<Target = String>,
65{
66    type Target = String;
67
68    /// Dereference to String.
69    fn deref(&self) -> &Self::Target {
70        self.text.deref()
71    }
72}
73
74impl<T, S> MapPoint<T> for Text<T, S>
75where
76    T: Copy,
77    S: Clone,
78{
79    /// Point wise transformation.
80    #[inline]
81    fn transform<F>(&self, transformation: F) -> Self
82    where
83        F: Fn(Point<T>) -> Point<T>,
84    {
85        Text {
86            location: transformation(self.location),
87            text: self.text.clone(),
88        }
89    }
90}
91
92impl<T: Copy + PartialOrd, S> BoundingBox<T> for Text<T, S> {
93    fn bounding_box(&self) -> Rect<T> {
94        Rect::new(self.location, self.location)
95    }
96}
97
98impl<T: Copy + PartialOrd, S> TryBoundingBox<T> for Text<T, S> {
99    fn try_bounding_box(&self) -> Option<Rect<T>> {
100        Some(Rect::new(self.location, self.location))
101    }
102}
103
104impl<T, Dst, S> Cast<T, Dst> for Text<T, S>
105where
106    T: Copy + NumCast,
107    Dst: Copy + NumCast,
108    S: Clone,
109{
110    type Output = Text<Dst, S>;
111
112    fn try_cast(&self) -> Option<Self::Output> {
113        self.location.try_cast().map(|loc| Text {
114            location: loc,
115            text: self.text.clone(),
116        })
117    }
118}