Skip to main content

lichtung_plot/text/
layout.rs

1//! Validated text-local constraints, distinct from scientific references.
2
3use crate::{plots::LabelEndpoints, Error, Result};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub(crate) struct Finite(u64);
7impl Finite {
8    pub(crate) const fn constant(value: f64) -> Self {
9        Self(value.to_bits())
10    }
11    pub(crate) fn new(value: f64) -> Result<Self> {
12        if !value.is_finite() {
13            return Err(Error::Data("text layout coordinates must be finite".into()));
14        }
15        Ok(Self(if value == 0.0 { 0 } else { value.to_bits() }))
16    }
17    pub(crate) const fn get(self) -> f64 {
18        f64::from_bits(self.0)
19    }
20}
21
22/// A point of the complete measured block, independent of its line alignment.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct TextAnchor {
25    pub(crate) horizontal: Finite,
26    pub(crate) vertical: VerticalAnchor,
27}
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub(crate) enum VerticalAnchor {
30    Fraction(Finite),
31    FirstBaseline,
32    CenterBaseline,
33}
34impl TextAnchor {
35    /// Arbitrary finite justification in a top-down block frame; no 0..1 clamp.
36    pub fn fractions(horizontal: f64, vertical: f64) -> Result<Self> {
37        Ok(Self {
38            horizontal: Finite::new(horizontal)?,
39            vertical: VerticalAnchor::Fraction(Finite::new(vertical)?),
40        })
41    }
42    /// Attach to the actual first baseline at the chosen horizontal fraction.
43    pub fn first_baseline(horizontal: f64) -> Result<Self> {
44        Ok(Self {
45            horizontal: Finite::new(horizontal)?,
46            vertical: VerticalAnchor::FirstBaseline,
47        })
48    }
49    /// Attach to the midpoint of the first and last measured baselines.
50    pub fn center_baseline(horizontal: f64) -> Result<Self> {
51        Ok(Self {
52            horizontal: Finite::new(horizontal)?,
53            vertical: VerticalAnchor::CenterBaseline,
54        })
55    }
56
57    /// Authored horizontal fraction, without a 0..1 clamp.
58    #[must_use]
59    pub const fn get_horizontal(&self) -> f64 {
60        self.horizontal.get()
61    }
62
63    /// Authored vertical fraction, absent for either baseline choice.
64    #[must_use]
65    pub const fn get_vertical_fraction(&self) -> Option<f64> {
66        match self.vertical {
67            VerticalAnchor::Fraction(value) => Some(value.get()),
68            VerticalAnchor::FirstBaseline | VerticalAnchor::CenterBaseline => None,
69        }
70    }
71
72    /// Whether the vertical choice is the first baseline rather than its center.
73    #[must_use]
74    pub const fn is_first_baseline(&self) -> bool {
75        matches!(self.vertical, VerticalAnchor::FirstBaseline)
76    }
77}
78macro_rules! anchors {
79    ($($name:ident: ($x:literal,$y:literal)),+ $(,)?) => {impl TextAnchor {$(
80        #[doc = concat!("Attach the block's `",stringify!($name),"` point.")]
81        pub const fn $name() -> Self {Self {horizontal:Finite(($x as f64).to_bits()),vertical:VerticalAnchor::Fraction(Finite(($y as f64).to_bits()))}}
82    )+}};
83}
84anchors! {top_left:(0.0,0.0),top_center:(0.5,0.0),top_right:(1.0,0.0),center_left:(0.0,0.5),center:(0.5,0.5),center_right:(1.0,0.5),bottom_left:(0.0,1.0),bottom_center:(0.5,1.0),bottom_right:(1.0,1.0)}
85
86/// Coordinate frame for a signed CSS-pixel displacement.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum TextOffsetFrame {
89    /// Physical screen axes, positive y down.
90    Screen,
91    /// Axes rotating with the measured text block.
92    TextLocal,
93}
94/// One exact represented finite displacement, not a data coordinate.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub struct TextOffset {
97    pub(crate) dx: Finite,
98    pub(crate) dy: Finite,
99    pub(crate) frame: TextOffsetFrame,
100}
101impl TextOffset {
102    /// Construct finite signed CSS offsets in the selected frame.
103    pub fn new(dx: f64, dy: f64, frame: TextOffsetFrame) -> Result<Self> {
104        Ok(Self {
105            dx: Finite::new(dx)?,
106            dy: Finite::new(dy)?,
107            frame,
108        })
109    }
110
111    /// Signed CSS-pixel displacement along the frame's x axis.
112    #[must_use]
113    pub const fn get_dx(&self) -> f64 {
114        self.dx.get()
115    }
116
117    /// Signed CSS-pixel displacement along the frame's y axis.
118    #[must_use]
119    pub const fn get_dy(&self) -> f64 {
120        self.dy.get()
121    }
122
123    /// Coordinate frame of the displacement.
124    #[must_use]
125    pub const fn get_frame(&self) -> TextOffsetFrame {
126        self.frame
127    }
128}
129
130/// Explicit text-local finite maxima, independent of the parent's assigned region.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub struct TextBounds {
133    pub(crate) width: Option<Finite>,
134    pub(crate) height: Option<Finite>,
135    pub(crate) lines: Option<usize>,
136}
137impl TextBounds {
138    /// None leaves a maximum unspecified; zero is a real requested constraint.
139    pub fn new(
140        max_width: Option<f64>,
141        max_height: Option<f64>,
142        max_lines: Option<usize>,
143    ) -> Result<Self> {
144        let bound = |value: f64| {
145            if value < 0.0 {
146                return Err(Error::Data("text bounds must be nonnegative".into()));
147            }
148            Finite::new(value)
149        };
150        Ok(Self {
151            width: max_width.map(bound).transpose()?,
152            height: max_height.map(bound).transpose()?,
153            lines: max_lines,
154        })
155    }
156
157    /// Requested maximum width in CSS pixels; zero remains distinct from None.
158    #[must_use]
159    pub const fn get_max_width(&self) -> Option<f64> {
160        match self.width {
161            Some(value) => Some(value.get()),
162            None => None,
163        }
164    }
165
166    /// Requested maximum height in CSS pixels; zero remains distinct from None.
167    #[must_use]
168    pub const fn get_max_height(&self) -> Option<f64> {
169        match self.height {
170            Some(value) => Some(value.get()),
171            None => None,
172        }
173    }
174
175    /// Requested maximum line count; zero remains distinct from None.
176    #[must_use]
177    pub const fn get_max_lines(&self) -> Option<usize> {
178        self.lines
179    }
180}
181/// Soft-wrap policy; both choices preserve caller-authored mandatory breaks.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum TextWrapping {
184    /// Use ordinary Unicode legal soft breaks.
185    Legal,
186    /// Keep each mandatory paragraph intact.
187    NoSoftWrap,
188}
189/// Base paragraph direction, independent of physical line alignment.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
191pub enum TextDirection {
192    /// Infer each paragraph from its original source.
193    #[default]
194    Auto,
195    /// Use a left-to-right paragraph base.
196    LeftToRight,
197    /// Use a right-to-left paragraph base.
198    RightToLeft,
199}
200/// Which end of the original source an ellipsis removes.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum TextElision {
203    /// Remove the logical beginning.
204    Start,
205    /// Remove an interior span, retaining both ends.
206    Middle,
207    /// Remove the logical end.
208    End,
209    /// Remove the physical left end.
210    Left,
211    /// Remove the physical right end.
212    Right,
213}
214/// An explicit derived-display program; the original source is never replaced.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct TextEllipsis {
217    pub(crate) position: TextElision,
218    pub(crate) marker: String,
219    pub(crate) lines: Option<usize>,
220    pub(crate) distinct: Option<bool>,
221}
222impl TextEllipsis {
223    /// Use U+2026 and a one-line cap; distinctness follows the actual owner.
224    pub fn new(position: TextElision) -> Self {
225        Self {
226            position,
227            marker: "…".into(),
228            lines: Some(1),
229            distinct: None,
230        }
231    }
232    /// Replace the marker, including an empty string.
233    #[must_use]
234    pub fn marker(mut self, text: impl Into<String>) -> Self {
235        self.marker = text.into();
236        self
237    }
238    /// Replace the extra ellipsis line cap.
239    #[must_use]
240    pub const fn max_lines(mut self, value: Option<usize>) -> Self {
241        self.lines = value;
242        self
243    }
244    /// Require distinct displayed views in the actual label group.
245    #[must_use]
246    pub const fn distinct(mut self, value: bool) -> Self {
247        self.distinct = Some(value);
248        self
249    }
250
251    /// Requested logical or physical elision position.
252    #[must_use]
253    pub const fn get_position(&self) -> TextElision {
254        self.position
255    }
256
257    /// Borrow the marker verbatim, including an empty marker.
258    #[must_use]
259    pub fn get_marker(&self) -> &str {
260        &self.marker
261    }
262
263    /// Optional additional line cap; zero is a concrete request.
264    #[must_use]
265    pub const fn get_max_lines(&self) -> Option<usize> {
266        self.lines
267    }
268
269    /// Authored distinctness override, separate from the owner's default.
270    #[must_use]
271    pub const fn get_distinct(&self) -> Option<bool> {
272        self.distinct
273    }
274}
275/// Whether actual label/annotation ink must avoid its peer owners.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum TextOverlap {
278    /// Refuse intersecting required text.
279    RequireNonOverlap,
280    /// Deliberately permit intersecting text.
281    Allow,
282}
283/// Terminal action for an actual text-fit miss, never for font/projection errors.
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub enum TextFailure {
286    /// Refuse the complete operation.
287    Error,
288    /// Keep source but do not paint this text.
289    Hide,
290    /// Clip paint to the actual text region.
291    Clip,
292    /// Permit text overhang subject to the final output boundary.
293    Visible,
294}
295/// Complete-text presentation and its terminal fit action.
296#[derive(Debug, Clone, PartialEq, Eq)]
297pub struct TextOverflow {
298    pub(crate) failure: TextFailure,
299    pub(crate) ellipsis: Option<TextEllipsis>,
300}
301impl TextOverflow {
302    /// Retain the complete text and refuse a real fit miss.
303    pub const fn complete() -> Self {
304        Self {
305            failure: TextFailure::Error,
306            ellipsis: None,
307        }
308    }
309    /// Retain the complete text, clipping its paint to the assigned region.
310    pub const fn clip() -> Self {
311        Self {
312            failure: TextFailure::Clip,
313            ellipsis: None,
314        }
315    }
316    /// Retain complete text while allowing local overhang.
317    pub const fn visible() -> Self {
318        Self {
319            failure: TextFailure::Visible,
320            ellipsis: None,
321        }
322    }
323    /// Retain complete source and hide text only when it cannot fit.
324    pub const fn hide() -> Self {
325        Self {
326            failure: TextFailure::Hide,
327            ellipsis: None,
328        }
329    }
330    /// Try an explicitly abbreviated display before the selected terminal action.
331    pub fn ellipsis(value: TextEllipsis, failure: TextFailure) -> Self {
332        Self {
333            failure,
334            ellipsis: Some(value),
335        }
336    }
337
338    /// Terminal action for an actual spatial fit miss.
339    #[must_use]
340    pub const fn get_failure(&self) -> TextFailure {
341        self.failure
342    }
343
344    /// Borrow the optional abbreviation program.
345    #[must_use]
346    pub const fn get_ellipsis(&self) -> Option<&TextEllipsis> {
347        self.ellipsis.as_ref()
348    }
349}
350/// Explicit text eligibility, independent of scientific ticks and marks.
351#[derive(Debug, Clone, PartialEq, Eq)]
352pub struct TextVisibility {
353    pub(crate) hidden: bool,
354    pub(crate) program: VisibilityProgram,
355    pub(crate) endpoints: crate::plots::LabelEndpoints,
356    pub(crate) separation: Finite,
357    pub(crate) boundary: Option<Finite>,
358}
359
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
361pub(crate) enum VisibilityProgram {
362    All,
363    Every { stride: usize, offset: usize },
364    Greedy,
365    Parity,
366}
367
368impl TextVisibility {
369    /// Keep every otherwise eligible text occurrence.
370    pub const fn all() -> Self {
371        Self {
372            hidden: false,
373            program: VisibilityProgram::All,
374            endpoints: LabelEndpoints::None,
375            separation: Finite(0),
376            boundary: None,
377        }
378    }
379    /// Suppress this text without deleting its source or scientific geometry.
380    pub const fn hidden() -> Self {
381        Self {
382            hidden: true,
383            ..Self::all()
384        }
385    }
386
387    /// Select original occurrence indices modulo a positive stride, plus protected endpoints.
388    pub fn every(stride: usize, offset: usize, endpoints: LabelEndpoints) -> Result<Self> {
389        if stride == 0 || offset >= stride {
390            return Err(Error::Data(
391                "text visibility requires positive stride and offset below stride".into(),
392            ));
393        }
394        Ok(Self {
395            program: VisibilityProgram::Every { stride, offset },
396            endpoints,
397            ..Self::all()
398        })
399    }
400
401    /// Retain protected labels, then nonintersecting candidates in stable geometric order.
402    pub const fn greedy(endpoints: LabelEndpoints) -> Self {
403        Self {
404            program: VisibilityProgram::Greedy,
405            endpoints,
406            ..Self::all()
407        }
408    }
409
410    /// Repeatedly remove alternating unprotected candidates until remaining labels fit.
411    pub const fn parity(endpoints: LabelEndpoints) -> Self {
412        Self {
413            program: VisibilityProgram::Parity,
414            endpoints,
415            ..Self::all()
416        }
417    }
418
419    /// Set additional physical clearance for Greedy or Parity reduction only.
420    pub fn separation(mut self, value: f64) -> Result<Self> {
421        if !matches!(
422            self.program,
423            VisibilityProgram::Greedy | VisibilityProgram::Parity
424        ) || value < 0.0
425        {
426            return Err(Error::Data(
427                "text separation requires nonnegative clearance and an overlap reduction program"
428                    .into(),
429            ));
430        }
431        self.separation = Finite::new(value)?;
432        Ok(self)
433    }
434
435    /// Hide labels outside the actual group boundary, allowing signed CSS overhang.
436    pub fn boundary_tolerance(mut self, value: Option<f64>) -> Result<Self> {
437        self.boundary = value.map(Finite::new).transpose()?;
438        Ok(self)
439    }
440
441    /// Whether source text is suppressed independently of the selection program.
442    #[must_use]
443    pub const fn is_hidden(&self) -> bool {
444        self.hidden
445    }
446
447    /// Authored stride and offset, present only for the Every program.
448    #[must_use]
449    pub const fn get_every(&self) -> Option<(usize, usize)> {
450        match self.program {
451            VisibilityProgram::Every { stride, offset } => Some((stride, offset)),
452            VisibilityProgram::All | VisibilityProgram::Greedy | VisibilityProgram::Parity => None,
453        }
454    }
455
456    /// Whether the retained selection program is Greedy.
457    #[must_use]
458    pub const fn is_greedy(&self) -> bool {
459        matches!(self.program, VisibilityProgram::Greedy)
460    }
461
462    /// Whether the retained selection program is Parity.
463    #[must_use]
464    pub const fn is_parity(&self) -> bool {
465        matches!(self.program, VisibilityProgram::Parity)
466    }
467
468    /// Requested protected endpoints.
469    #[must_use]
470    pub const fn get_endpoints(&self) -> LabelEndpoints {
471        self.endpoints
472    }
473
474    /// Requested physical clearance for overlap reduction.
475    #[must_use]
476    pub const fn get_separation(&self) -> f64 {
477        self.separation.get()
478    }
479
480    /// Signed authored boundary overhang; present zero still requests reduction.
481    #[must_use]
482    pub const fn get_boundary_tolerance(&self) -> Option<f64> {
483        match self.boundary {
484            Some(value) => Some(value.get()),
485            None => None,
486        }
487    }
488
489    pub(crate) fn reduces(&self) -> bool {
490        !matches!(self.program, VisibilityProgram::All) || self.boundary.is_some()
491    }
492
493    pub(crate) fn protects(&self, index: usize, eligible: &[usize]) -> bool {
494        (matches!(self.endpoints, LabelEndpoints::First | LabelEndpoints::Both)
495            && eligible.first() == Some(&index))
496            || (matches!(self.endpoints, LabelEndpoints::Last | LabelEndpoints::Both)
497                && eligible.last() == Some(&index))
498    }
499
500    pub(crate) fn includes(&self, index: usize, eligible: &[usize]) -> bool {
501        !self.hidden
502            && (self.protects(index, eligible)
503                || match self.program {
504                    VisibilityProgram::Every { stride, offset } => index % stride == offset,
505                    _ => true,
506                })
507    }
508}