Skip to main content

plotters_ternary/series/
text.rs

1use std::fmt;
2
3use plotters::style::{Color, FontTransform};
4use plotters_backend::text_anchor::{HPos, Pos, VPos};
5
6use crate::chart::AxisTextStyle;
7use crate::coord::{Normalization, TernaryPoint, Tolerance};
8
9/// Owned text attributes for [`TernaryText`].
10///
11/// This is an alias of [`AxisTextStyle`] so annotation text uses the same
12/// final-output-pixel font, weight, and RGBA colour model as mesh labels.
13pub type AnnotationTextStyle = AxisTextStyle;
14
15/// Horizontal placement of an annotation relative to its ternary anchor.
16#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
17pub enum HorizontalAnchor {
18    Left,
19    #[default]
20    Center,
21    Right,
22}
23
24/// Vertical placement of an annotation relative to its ternary anchor.
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub enum VerticalAnchor {
27    Top,
28    #[default]
29    Center,
30    Bottom,
31    /// Baseline is currently mapped to Plotters' closest portable `Bottom`
32    /// anchor. Exact baseline metrics are backend-specific.
33    Baseline,
34}
35
36/// A portable two-dimensional text anchor.
37#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
38pub struct TextAnchor {
39    horizontal: HorizontalAnchor,
40    vertical: VerticalAnchor,
41}
42
43impl TextAnchor {
44    pub const fn new(horizontal: HorizontalAnchor, vertical: VerticalAnchor) -> Self {
45        Self {
46            horizontal,
47            vertical,
48        }
49    }
50    pub const fn horizontal(self) -> HorizontalAnchor {
51        self.horizontal
52    }
53    pub const fn vertical(self) -> VerticalAnchor {
54        self.vertical
55    }
56    pub const fn center() -> Self {
57        Self::new(HorizontalAnchor::Center, VerticalAnchor::Center)
58    }
59    pub(crate) fn plotters_pos(self) -> Pos {
60        let horizontal = match self.horizontal {
61            HorizontalAnchor::Left => HPos::Left,
62            HorizontalAnchor::Center => HPos::Center,
63            HorizontalAnchor::Right => HPos::Right,
64        };
65        let vertical = match self.vertical {
66            VerticalAnchor::Top => VPos::Top,
67            VerticalAnchor::Center => VPos::Center,
68            VerticalAnchor::Bottom | VerticalAnchor::Baseline => VPos::Bottom,
69        };
70        Pos::new(horizontal, vertical)
71    }
72}
73
74/// Explicit annotation visibility policy for the invisible logical viewport.
75#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
76pub enum AnnotationClipMode {
77    /// Emit text only if its logical ternary anchor is in or on the viewport.
78    #[default]
79    Anchor,
80    /// Submit text even when the logical anchor lies outside the viewport.
81    None,
82}
83
84/// Plotters-native, portable quarter-turn annotation rotation.
85#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
86pub enum TextRotation {
87    #[default]
88    None,
89    Rotate90,
90    Rotate180,
91    Rotate270,
92}
93
94impl TextRotation {
95    pub(crate) const fn plotters_transform(self) -> FontTransform {
96        match self {
97            Self::None => FontTransform::None,
98            Self::Rotate90 => FontTransform::Rotate90,
99            Self::Rotate180 => FontTransform::Rotate180,
100            Self::Rotate270 => FontTransform::Rotate270,
101        }
102    }
103}
104
105/// A text annotation anchored in ternary composition space.
106///
107/// Content and style are owned. Pixel offsets are applied after projection and
108/// are final-output pixels, so geometry supersampling never changes their
109/// final placement.
110pub struct TernaryText {
111    point: TernaryPoint,
112    text: String,
113    style: AnnotationTextStyle,
114    anchor: TextAnchor,
115    offset: (i32, i32),
116    clip_mode: AnnotationClipMode,
117    rotation: TextRotation,
118    normalization: Normalization,
119    tolerance: Tolerance,
120}
121
122impl TernaryText {
123    /// Create a final-resolution, centred, anchor-clipped annotation.
124    pub fn new<S: Into<String>>(point: TernaryPoint, text: S) -> Self {
125        Self {
126            point,
127            text: text.into(),
128            style: AxisTextStyle::sans_serif(
129                22,
130                plotters::style::FontStyle::Normal,
131                plotters::style::BLACK.to_rgba(),
132            ),
133            anchor: TextAnchor::default(),
134            offset: (0, 0),
135            clip_mode: AnnotationClipMode::default(),
136            rotation: TextRotation::default(),
137            normalization: Normalization::RequireUnitSum,
138            tolerance: Tolerance::default(),
139        }
140    }
141
142    /// Set the owned text attributes.
143    pub fn style(mut self, style: AnnotationTextStyle) -> Self {
144        self.style = style;
145        self
146    }
147    /// Set the local horizontal/vertical anchor.
148    pub const fn anchor(mut self, anchor: TextAnchor) -> Self {
149        self.anchor = anchor;
150        self
151    }
152    /// Set a final-output-pixel offset from the projected ternary anchor.
153    pub const fn offset(mut self, offset: (i32, i32)) -> Self {
154        self.offset = offset;
155        self
156    }
157    /// Select anchor clipping or unrestricted submission.
158    pub const fn clip_mode(mut self, clip_mode: AnnotationClipMode) -> Self {
159        self.clip_mode = clip_mode;
160        self
161    }
162    /// Use only a Plotters-native quarter-turn text transform.
163    pub const fn rotation(mut self, rotation: TextRotation) -> Self {
164        self.rotation = rotation;
165        self
166    }
167    /// Select explicit validation or normalisation.
168    pub const fn normalization(mut self, normalization: Normalization) -> Self {
169        self.normalization = normalization;
170        self
171    }
172    /// Select the tolerance for validation and anchor clipping.
173    pub const fn tolerance(mut self, tolerance: Tolerance) -> Self {
174        self.tolerance = tolerance;
175        self
176    }
177
178    pub const fn point(&self) -> TernaryPoint {
179        self.point
180    }
181    pub fn text(&self) -> &str {
182        &self.text
183    }
184    pub const fn offset_value(&self) -> (i32, i32) {
185        self.offset
186    }
187    pub const fn text_anchor(&self) -> TextAnchor {
188        self.anchor
189    }
190    pub const fn annotation_clip_mode(&self) -> AnnotationClipMode {
191        self.clip_mode
192    }
193
194    pub(crate) fn into_parts(
195        self,
196    ) -> (
197        TernaryPoint,
198        String,
199        AnnotationTextStyle,
200        TextAnchor,
201        (i32, i32),
202        AnnotationClipMode,
203        TextRotation,
204        Normalization,
205        Tolerance,
206    ) {
207        (
208            self.point,
209            self.text,
210            self.style,
211            self.anchor,
212            self.offset,
213            self.clip_mode,
214            self.rotation,
215            self.normalization,
216            self.tolerance,
217        )
218    }
219}
220
221/// Annotation preparation errors.
222#[derive(Clone, Debug, PartialEq)]
223#[non_exhaustive]
224pub enum AnnotationError {
225    /// The composition anchor could not be validated or projected.
226    InvalidAnchor { source: crate::coord::Error },
227}
228
229impl fmt::Display for AnnotationError {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        match self {
232            Self::InvalidAnchor { source } => write!(f, "invalid ternary text anchor: {source}"),
233        }
234    }
235}
236
237impl std::error::Error for AnnotationError {
238    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
239        match self {
240            Self::InvalidAnchor { source } => Some(source),
241        }
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn anchor_defaults_and_final_pixel_offsets_are_stable() {
251        let annotation = TernaryText::new(TernaryPoint::new(0.4, 0.3, 0.3), "Liquid + α")
252            .anchor(TextAnchor::new(
253                HorizontalAnchor::Right,
254                VerticalAnchor::Bottom,
255            ))
256            .offset((8, -10));
257        assert_eq!(annotation.text(), "Liquid + α");
258        assert_eq!(annotation.offset_value(), (8, -10));
259        assert_eq!(
260            annotation.text_anchor().horizontal(),
261            HorizontalAnchor::Right
262        );
263        assert_eq!(annotation.text_anchor().vertical(), VerticalAnchor::Bottom);
264    }
265}