lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Validated text-local constraints, distinct from scientific references.

use crate::{plots::LabelEndpoints, Error, Result};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Finite(u64);
impl Finite {
    pub(crate) const fn constant(value: f64) -> Self {
        Self(value.to_bits())
    }
    pub(crate) fn new(value: f64) -> Result<Self> {
        if !value.is_finite() {
            return Err(Error::Data("text layout coordinates must be finite".into()));
        }
        Ok(Self(if value == 0.0 { 0 } else { value.to_bits() }))
    }
    pub(crate) const fn get(self) -> f64 {
        f64::from_bits(self.0)
    }
}

/// A point of the complete measured block, independent of its line alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TextAnchor {
    pub(crate) horizontal: Finite,
    pub(crate) vertical: VerticalAnchor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VerticalAnchor {
    Fraction(Finite),
    FirstBaseline,
    CenterBaseline,
}
impl TextAnchor {
    /// Arbitrary finite justification in a top-down block frame; no 0..1 clamp.
    pub fn fractions(horizontal: f64, vertical: f64) -> Result<Self> {
        Ok(Self {
            horizontal: Finite::new(horizontal)?,
            vertical: VerticalAnchor::Fraction(Finite::new(vertical)?),
        })
    }
    /// Attach to the actual first baseline at the chosen horizontal fraction.
    pub fn first_baseline(horizontal: f64) -> Result<Self> {
        Ok(Self {
            horizontal: Finite::new(horizontal)?,
            vertical: VerticalAnchor::FirstBaseline,
        })
    }
    /// Attach to the midpoint of the first and last measured baselines.
    pub fn center_baseline(horizontal: f64) -> Result<Self> {
        Ok(Self {
            horizontal: Finite::new(horizontal)?,
            vertical: VerticalAnchor::CenterBaseline,
        })
    }

    /// Authored horizontal fraction, without a 0..1 clamp.
    #[must_use]
    pub const fn get_horizontal(&self) -> f64 {
        self.horizontal.get()
    }

    /// Authored vertical fraction, absent for either baseline choice.
    #[must_use]
    pub const fn get_vertical_fraction(&self) -> Option<f64> {
        match self.vertical {
            VerticalAnchor::Fraction(value) => Some(value.get()),
            VerticalAnchor::FirstBaseline | VerticalAnchor::CenterBaseline => None,
        }
    }

    /// Whether the vertical choice is the first baseline rather than its center.
    #[must_use]
    pub const fn is_first_baseline(&self) -> bool {
        matches!(self.vertical, VerticalAnchor::FirstBaseline)
    }
}
macro_rules! anchors {
    ($($name:ident: ($x:literal,$y:literal)),+ $(,)?) => {impl TextAnchor {$(
        #[doc = concat!("Attach the block's `",stringify!($name),"` point.")]
        pub const fn $name() -> Self {Self {horizontal:Finite(($x as f64).to_bits()),vertical:VerticalAnchor::Fraction(Finite(($y as f64).to_bits()))}}
    )+}};
}
anchors! {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)}

/// Coordinate frame for a signed CSS-pixel displacement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextOffsetFrame {
    /// Physical screen axes, positive y down.
    Screen,
    /// Axes rotating with the measured text block.
    TextLocal,
}
/// One exact represented finite displacement, not a data coordinate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TextOffset {
    pub(crate) dx: Finite,
    pub(crate) dy: Finite,
    pub(crate) frame: TextOffsetFrame,
}
impl TextOffset {
    /// Construct finite signed CSS offsets in the selected frame.
    pub fn new(dx: f64, dy: f64, frame: TextOffsetFrame) -> Result<Self> {
        Ok(Self {
            dx: Finite::new(dx)?,
            dy: Finite::new(dy)?,
            frame,
        })
    }

    /// Signed CSS-pixel displacement along the frame's x axis.
    #[must_use]
    pub const fn get_dx(&self) -> f64 {
        self.dx.get()
    }

    /// Signed CSS-pixel displacement along the frame's y axis.
    #[must_use]
    pub const fn get_dy(&self) -> f64 {
        self.dy.get()
    }

    /// Coordinate frame of the displacement.
    #[must_use]
    pub const fn get_frame(&self) -> TextOffsetFrame {
        self.frame
    }
}

/// Explicit text-local finite maxima, independent of the parent's assigned region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TextBounds {
    pub(crate) width: Option<Finite>,
    pub(crate) height: Option<Finite>,
    pub(crate) lines: Option<usize>,
}
impl TextBounds {
    /// None leaves a maximum unspecified; zero is a real requested constraint.
    pub fn new(
        max_width: Option<f64>,
        max_height: Option<f64>,
        max_lines: Option<usize>,
    ) -> Result<Self> {
        let bound = |value: f64| {
            if value < 0.0 {
                return Err(Error::Data("text bounds must be nonnegative".into()));
            }
            Finite::new(value)
        };
        Ok(Self {
            width: max_width.map(bound).transpose()?,
            height: max_height.map(bound).transpose()?,
            lines: max_lines,
        })
    }

    /// Requested maximum width in CSS pixels; zero remains distinct from None.
    #[must_use]
    pub const fn get_max_width(&self) -> Option<f64> {
        match self.width {
            Some(value) => Some(value.get()),
            None => None,
        }
    }

    /// Requested maximum height in CSS pixels; zero remains distinct from None.
    #[must_use]
    pub const fn get_max_height(&self) -> Option<f64> {
        match self.height {
            Some(value) => Some(value.get()),
            None => None,
        }
    }

    /// Requested maximum line count; zero remains distinct from None.
    #[must_use]
    pub const fn get_max_lines(&self) -> Option<usize> {
        self.lines
    }
}
/// Soft-wrap policy; both choices preserve caller-authored mandatory breaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextWrapping {
    /// Use ordinary Unicode legal soft breaks.
    Legal,
    /// Keep each mandatory paragraph intact.
    NoSoftWrap,
}
/// Base paragraph direction, independent of physical line alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextDirection {
    /// Infer each paragraph from its original source.
    #[default]
    Auto,
    /// Use a left-to-right paragraph base.
    LeftToRight,
    /// Use a right-to-left paragraph base.
    RightToLeft,
}
/// Which end of the original source an ellipsis removes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextElision {
    /// Remove the logical beginning.
    Start,
    /// Remove an interior span, retaining both ends.
    Middle,
    /// Remove the logical end.
    End,
    /// Remove the physical left end.
    Left,
    /// Remove the physical right end.
    Right,
}
/// An explicit derived-display program; the original source is never replaced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextEllipsis {
    pub(crate) position: TextElision,
    pub(crate) marker: String,
    pub(crate) lines: Option<usize>,
    pub(crate) distinct: Option<bool>,
}
impl TextEllipsis {
    /// Use U+2026 and a one-line cap; distinctness follows the actual owner.
    pub fn new(position: TextElision) -> Self {
        Self {
            position,
            marker: "…".into(),
            lines: Some(1),
            distinct: None,
        }
    }
    /// Replace the marker, including an empty string.
    #[must_use]
    pub fn marker(mut self, text: impl Into<String>) -> Self {
        self.marker = text.into();
        self
    }
    /// Replace the extra ellipsis line cap.
    #[must_use]
    pub const fn max_lines(mut self, value: Option<usize>) -> Self {
        self.lines = value;
        self
    }
    /// Require distinct displayed views in the actual label group.
    #[must_use]
    pub const fn distinct(mut self, value: bool) -> Self {
        self.distinct = Some(value);
        self
    }

    /// Requested logical or physical elision position.
    #[must_use]
    pub const fn get_position(&self) -> TextElision {
        self.position
    }

    /// Borrow the marker verbatim, including an empty marker.
    #[must_use]
    pub fn get_marker(&self) -> &str {
        &self.marker
    }

    /// Optional additional line cap; zero is a concrete request.
    #[must_use]
    pub const fn get_max_lines(&self) -> Option<usize> {
        self.lines
    }

    /// Authored distinctness override, separate from the owner's default.
    #[must_use]
    pub const fn get_distinct(&self) -> Option<bool> {
        self.distinct
    }
}
/// Whether actual label/annotation ink must avoid its peer owners.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextOverlap {
    /// Refuse intersecting required text.
    RequireNonOverlap,
    /// Deliberately permit intersecting text.
    Allow,
}
/// Terminal action for an actual text-fit miss, never for font/projection errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextFailure {
    /// Refuse the complete operation.
    Error,
    /// Keep source but do not paint this text.
    Hide,
    /// Clip paint to the actual text region.
    Clip,
    /// Permit text overhang subject to the final output boundary.
    Visible,
}
/// Complete-text presentation and its terminal fit action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextOverflow {
    pub(crate) failure: TextFailure,
    pub(crate) ellipsis: Option<TextEllipsis>,
}
impl TextOverflow {
    /// Retain the complete text and refuse a real fit miss.
    pub const fn complete() -> Self {
        Self {
            failure: TextFailure::Error,
            ellipsis: None,
        }
    }
    /// Retain the complete text, clipping its paint to the assigned region.
    pub const fn clip() -> Self {
        Self {
            failure: TextFailure::Clip,
            ellipsis: None,
        }
    }
    /// Retain complete text while allowing local overhang.
    pub const fn visible() -> Self {
        Self {
            failure: TextFailure::Visible,
            ellipsis: None,
        }
    }
    /// Retain complete source and hide text only when it cannot fit.
    pub const fn hide() -> Self {
        Self {
            failure: TextFailure::Hide,
            ellipsis: None,
        }
    }
    /// Try an explicitly abbreviated display before the selected terminal action.
    pub fn ellipsis(value: TextEllipsis, failure: TextFailure) -> Self {
        Self {
            failure,
            ellipsis: Some(value),
        }
    }

    /// Terminal action for an actual spatial fit miss.
    #[must_use]
    pub const fn get_failure(&self) -> TextFailure {
        self.failure
    }

    /// Borrow the optional abbreviation program.
    #[must_use]
    pub const fn get_ellipsis(&self) -> Option<&TextEllipsis> {
        self.ellipsis.as_ref()
    }
}
/// Explicit text eligibility, independent of scientific ticks and marks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextVisibility {
    pub(crate) hidden: bool,
    pub(crate) program: VisibilityProgram,
    pub(crate) endpoints: crate::plots::LabelEndpoints,
    pub(crate) separation: Finite,
    pub(crate) boundary: Option<Finite>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VisibilityProgram {
    All,
    Every { stride: usize, offset: usize },
    Greedy,
    Parity,
}

impl TextVisibility {
    /// Keep every otherwise eligible text occurrence.
    pub const fn all() -> Self {
        Self {
            hidden: false,
            program: VisibilityProgram::All,
            endpoints: LabelEndpoints::None,
            separation: Finite(0),
            boundary: None,
        }
    }
    /// Suppress this text without deleting its source or scientific geometry.
    pub const fn hidden() -> Self {
        Self {
            hidden: true,
            ..Self::all()
        }
    }

    /// Select original occurrence indices modulo a positive stride, plus protected endpoints.
    pub fn every(stride: usize, offset: usize, endpoints: LabelEndpoints) -> Result<Self> {
        if stride == 0 || offset >= stride {
            return Err(Error::Data(
                "text visibility requires positive stride and offset below stride".into(),
            ));
        }
        Ok(Self {
            program: VisibilityProgram::Every { stride, offset },
            endpoints,
            ..Self::all()
        })
    }

    /// Retain protected labels, then nonintersecting candidates in stable geometric order.
    pub const fn greedy(endpoints: LabelEndpoints) -> Self {
        Self {
            program: VisibilityProgram::Greedy,
            endpoints,
            ..Self::all()
        }
    }

    /// Repeatedly remove alternating unprotected candidates until remaining labels fit.
    pub const fn parity(endpoints: LabelEndpoints) -> Self {
        Self {
            program: VisibilityProgram::Parity,
            endpoints,
            ..Self::all()
        }
    }

    /// Set additional physical clearance for Greedy or Parity reduction only.
    pub fn separation(mut self, value: f64) -> Result<Self> {
        if !matches!(
            self.program,
            VisibilityProgram::Greedy | VisibilityProgram::Parity
        ) || value < 0.0
        {
            return Err(Error::Data(
                "text separation requires nonnegative clearance and an overlap reduction program"
                    .into(),
            ));
        }
        self.separation = Finite::new(value)?;
        Ok(self)
    }

    /// Hide labels outside the actual group boundary, allowing signed CSS overhang.
    pub fn boundary_tolerance(mut self, value: Option<f64>) -> Result<Self> {
        self.boundary = value.map(Finite::new).transpose()?;
        Ok(self)
    }

    /// Whether source text is suppressed independently of the selection program.
    #[must_use]
    pub const fn is_hidden(&self) -> bool {
        self.hidden
    }

    /// Authored stride and offset, present only for the Every program.
    #[must_use]
    pub const fn get_every(&self) -> Option<(usize, usize)> {
        match self.program {
            VisibilityProgram::Every { stride, offset } => Some((stride, offset)),
            VisibilityProgram::All | VisibilityProgram::Greedy | VisibilityProgram::Parity => None,
        }
    }

    /// Whether the retained selection program is Greedy.
    #[must_use]
    pub const fn is_greedy(&self) -> bool {
        matches!(self.program, VisibilityProgram::Greedy)
    }

    /// Whether the retained selection program is Parity.
    #[must_use]
    pub const fn is_parity(&self) -> bool {
        matches!(self.program, VisibilityProgram::Parity)
    }

    /// Requested protected endpoints.
    #[must_use]
    pub const fn get_endpoints(&self) -> LabelEndpoints {
        self.endpoints
    }

    /// Requested physical clearance for overlap reduction.
    #[must_use]
    pub const fn get_separation(&self) -> f64 {
        self.separation.get()
    }

    /// Signed authored boundary overhang; present zero still requests reduction.
    #[must_use]
    pub const fn get_boundary_tolerance(&self) -> Option<f64> {
        match self.boundary {
            Some(value) => Some(value.get()),
            None => None,
        }
    }

    pub(crate) fn reduces(&self) -> bool {
        !matches!(self.program, VisibilityProgram::All) || self.boundary.is_some()
    }

    pub(crate) fn protects(&self, index: usize, eligible: &[usize]) -> bool {
        (matches!(self.endpoints, LabelEndpoints::First | LabelEndpoints::Both)
            && eligible.first() == Some(&index))
            || (matches!(self.endpoints, LabelEndpoints::Last | LabelEndpoints::Both)
                && eligible.last() == Some(&index))
    }

    pub(crate) fn includes(&self, index: usize, eligible: &[usize]) -> bool {
        !self.hidden
            && (self.protects(index, eligible)
                || match self.program {
                    VisibilityProgram::Every { stride, offset } => index % stride == offset,
                    _ => true,
                })
    }
}