Skip to main content

lichtung_plot/text/
orientation.rs

1//! Finite screen angles and scientific direction requests.
2
3use super::layout::Finite;
4use crate::{coordinates::DataPosition, Error, Result};
5
6pub(crate) fn components(angle: f64) -> (f64, f64) {
7    match angle {
8        0.0 => (0.0, 1.0),
9        90.0 => (1.0, 0.0),
10        -90.0 => (-1.0, 0.0),
11        -180.0 => (0.0, -1.0),
12        _ => angle.to_radians().sin_cos(),
13    }
14}
15
16/// One normalized clockwise screen angle, without decimal quantization.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct TextRotation(pub(crate) Finite);
19impl TextRotation {
20    /// Normalize finite degrees to [-180, 180), including signed zero.
21    pub fn degrees(value: f64) -> Result<Self> {
22        if !value.is_finite() {
23            return Err(Error::Data("text rotation must be finite".into()));
24        }
25        let value = value % 360.0;
26        Ok(Self(Finite::new(if value >= 180.0 {
27            value - 360.0
28        } else if value < -180.0 {
29            value + 360.0
30        } else {
31            value
32        })?))
33    }
34    /// No rotation.
35    pub const fn horizontal() -> Self {
36        Self(Finite::constant(0.0))
37    }
38    /// Forty-five degrees counterclockwise on screen.
39    pub const fn tilt_up() -> Self {
40        Self(Finite::constant(-45.0))
41    }
42    /// Forty-five degrees clockwise on screen.
43    pub const fn tilt_down() -> Self {
44        Self(Finite::constant(45.0))
45    }
46    /// Text reads upward on screen.
47    pub const fn vertical_up() -> Self {
48        Self(Finite::constant(-90.0))
49    }
50    /// Text reads downward on screen.
51    pub const fn vertical_down() -> Self {
52        Self(Finite::constant(90.0))
53    }
54
55    /// Retained normalized clockwise screen angle in degrees.
56    #[must_use]
57    pub const fn get_degrees(&self) -> f64 {
58        self.0.get()
59    }
60}
61
62/// How the selected block point relates to a rotation.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum TextRotationMode {
65    /// Rotate the complete block around its selected point.
66    RotateAboutAnchor,
67    /// Align the rotated bounding box to the reference.
68    AlignAfterRotation,
69}
70
71/// A fixed screen angle, projected data direction or ordered tick-angle program.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct TextOrientation(pub(crate) Orientation);
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) enum Orientation {
76    Fixed(TextRotation),
77    Data(DataPosition, DataPosition),
78    Automatic(Vec<TextRotation>),
79}
80impl TextOrientation {
81    /// Use one fixed screen angle.
82    pub const fn fixed(value: TextRotation) -> Self {
83        Self(Orientation::Fixed(value))
84    }
85    /// Follow the direction between two actual scientific references.
86    pub fn data_direction(from: DataPosition, to: DataPosition) -> Self {
87        Self(Orientation::Data(from, to))
88    }
89    /// Try the retained angle order on an actual tick group.
90    pub fn automatic_ticks(angles: Vec<TextRotation>) -> Self {
91        Self(Orientation::Automatic(angles))
92    }
93
94    /// Fixed screen rotation, absent for the other orientation programs.
95    #[must_use]
96    pub const fn get_fixed_rotation(&self) -> Option<TextRotation> {
97        match &self.0 {
98            Orientation::Fixed(rotation) => Some(*rotation),
99            Orientation::Data(..) | Orientation::Automatic(_) => None,
100        }
101    }
102
103    /// Borrow the authored data-direction endpoints without projecting them.
104    #[must_use]
105    pub const fn get_data_direction(&self) -> Option<(&DataPosition, &DataPosition)> {
106        match &self.0 {
107            Orientation::Data(from, to) => Some((from, to)),
108            Orientation::Fixed(_) | Orientation::Automatic(_) => None,
109        }
110    }
111
112    /// Borrow the retained tick-angle order; an empty program remains present.
113    #[must_use]
114    pub fn get_automatic_angles(&self) -> Option<&[TextRotation]> {
115        match &self.0 {
116            Orientation::Automatic(angles) => Some(angles),
117            Orientation::Fixed(_) | Orientation::Data(..) => None,
118        }
119    }
120}
121
122#[derive(Clone, Copy)]
123pub(crate) struct TextReferenceResolver<'v, 'src> {
124    pub(crate) registered: &'v crate::orchestrator::registration::PlotRegistration<'src>,
125    pub(crate) layout: &'v crate::layout::Layout,
126    pub(crate) dimensions: crate::orchestrator::assignment::PlotMeasureDimensions,
127}
128impl std::fmt::Debug for TextReferenceResolver<'_, '_> {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        f.debug_struct("TextReferenceResolver")
131            .field("layout", &self.layout)
132            .finish_non_exhaustive()
133    }
134}
135impl TextReferenceResolver<'_, '_> {
136    #[expect(
137        clippy::type_complexity,
138        reason = "preserves the original narrow direction comparison projection"
139    )]
140    pub(crate) fn snapshot(
141        &self,
142    ) -> (
143        [(f64, f64); 2],
144        crate::layout::PixelRect,
145        [Option<Vec<(f64, f64)>>; 2],
146        Option<String>,
147    ) {
148        (
149            [
150                self.layout.projection.x_range(),
151                self.layout.projection.y_range(),
152            ],
153            self.layout.projection.panel_box(),
154            [
155                self.layout.x_axis.assigned_cells.clone(),
156                self.layout.y_axis.assigned_cells.clone(),
157            ],
158            self.registered.scope.render_name.clone(),
159        )
160    }
161
162    #[expect(
163        clippy::type_complexity,
164        reason = "preserves the original narrow direction comparison projection"
165    )]
166    pub(crate) fn matches_snapshot(
167        &self,
168        other: &(
169            [(f64, f64); 2],
170            crate::layout::PixelRect,
171            [Option<Vec<(f64, f64)>>; 2],
172            Option<String>,
173        ),
174    ) -> bool {
175        other.0[0] == self.layout.projection.x_range()
176            && other.0[1] == self.layout.projection.y_range()
177            && other.1 == self.layout.projection.panel_box()
178            && other.2[0] == self.layout.x_axis.assigned_cells
179            && other.2[1] == self.layout.y_axis.assigned_cells
180            && other.3.as_deref() == self.registered.scope.render_name.as_deref()
181    }
182    pub(crate) fn rotation(
183        &self,
184        from: &DataPosition,
185        to: &DataPosition,
186        theme: &crate::theme::ResolvedTheme,
187    ) -> Result<TextRotation> {
188        let point = |point: &DataPosition| {
189            let position = crate::text::TextPosition::new(
190                crate::text::TextCoordinate::data(point.x.clone()),
191                crate::text::TextCoordinate::data(point.y.clone()),
192            );
193            Ok::<_, Error>(crate::text::position::resolve::point(
194                crate::text::position::resolve::resolve(&position, self, theme)?,
195                self.layout.projection.panel_box(),
196            ))
197        };
198        let a = point(from)?;
199        let b = point(to)?;
200        if a.x.to_bits() == b.x.to_bits() && a.y.to_bits() == b.y.to_bits() {
201            return Err(Error::Render(
202                "text data direction projects to coincident points".into(),
203            ));
204        }
205        TextRotation::degrees((a.y - b.y).atan2(b.x - a.x).to_degrees())
206    }
207}