lichtung-plot 0.2.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
//! Shared source syntax for authored and prepared display text.

pub use crate::font::canonical::{
    check_fonts, check_fonts_with_operation, font_families, font_families_with_operation,
    FontDiscovery, FontFamily, FontFamilyReport, FontScope, FontSourceIssue, FontStack, FontStyle,
    FontSupport, FontVariantReport, GenericFontFamily,
};
pub use crate::spec::TextWeight;

mod fit;
pub(crate) mod layout;
pub(crate) mod value;
pub use fit::{TextFit, TextFitGrouping, TextFitPriority};
pub(crate) mod orientation;
pub(crate) mod position;
pub use orientation::{TextOrientation, TextRotation, TextRotationMode};
pub(crate) mod roles;
mod service;
pub use layout::{
    TextAnchor, TextBounds, TextDirection, TextElision, TextEllipsis, TextFailure, TextOffset,
    TextOffsetFrame, TextOverflow, TextOverlap, TextVisibility, TextWrapping,
};
pub use position::{TextCoordinate, TextPosition};
pub(crate) use service::{TextRequestContext, TextService};

/// Optional text layout instructions. Omitted fields retain owner defaults.
///
/// A supplied default request is an explicit reset, distinct from no request.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextLayout {
    pub(crate) alignment: Option<TextAlignment>,
    instructions: Option<std::sync::Arc<TextInstructions>>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct TextInstructions {
    pub(crate) fit: Option<TextFit>,
    pub(crate) fit_priority: Option<TextFitPriority>,
    pub(crate) direction: Option<TextDirection>,
    pub(crate) orientation: Option<TextOrientation>,
    pub(crate) rotation_mode: Option<TextRotationMode>,
    pub(crate) anchor: Option<TextAnchor>,
    pub(crate) offset: Option<TextOffset>,
    pub(crate) bounds: Option<TextBounds>,
    pub(crate) wrapping: Option<TextWrapping>,
    pub(crate) overflow: Option<TextOverflow>,
    pub(crate) overlap: Option<TextOverlap>,
    pub(crate) visibility: Option<TextVisibility>,
}

impl TextLayout {
    /// Inspect the requested physical line alignment.
    #[must_use]
    pub const fn get_alignment(&self) -> Option<TextAlignment> {
        self.alignment
    }

    /// Inspect the requested font-size program.
    #[must_use]
    pub fn get_fit(&self) -> Option<TextFit> {
        self.instructions().fit
    }

    /// Inspect the requested fitting and abbreviation priority.
    #[must_use]
    pub fn get_fit_priority(&self) -> Option<TextFitPriority> {
        self.instructions().fit_priority
    }

    /// Inspect the requested paragraph direction.
    #[must_use]
    pub fn get_direction(&self) -> Option<TextDirection> {
        self.instructions().direction
    }

    /// Borrow the requested orientation program.
    #[must_use]
    pub fn get_orientation(&self) -> Option<&TextOrientation> {
        self.instructions().orientation.as_ref()
    }

    /// Inspect the requested rotation-anchor relationship.
    #[must_use]
    pub fn get_rotation_mode(&self) -> Option<TextRotationMode> {
        self.instructions().rotation_mode
    }

    /// Inspect the requested measured-block anchor.
    #[must_use]
    pub fn get_anchor(&self) -> Option<TextAnchor> {
        self.instructions().anchor
    }

    /// Inspect the requested signed CSS-pixel displacement.
    #[must_use]
    pub fn get_offset(&self) -> Option<TextOffset> {
        self.instructions().offset
    }

    /// Inspect the requested text-local maxima.
    #[must_use]
    pub fn get_bounds(&self) -> Option<TextBounds> {
        self.instructions().bounds
    }

    /// Inspect the requested soft-wrap policy.
    #[must_use]
    pub fn get_wrapping(&self) -> Option<TextWrapping> {
        self.instructions().wrapping
    }

    /// Borrow the requested overflow program.
    #[must_use]
    pub fn get_overflow(&self) -> Option<&TextOverflow> {
        self.instructions().overflow.as_ref()
    }

    /// Inspect the requested peer-overlap policy.
    #[must_use]
    pub fn get_overlap(&self) -> Option<TextOverlap> {
        self.instructions().overlap
    }

    /// Borrow the requested text-eligibility program.
    #[must_use]
    pub fn get_visibility(&self) -> Option<&TextVisibility> {
        self.instructions().visibility.as_ref()
    }

    pub(crate) fn hidden(&self) -> bool {
        self.instructions()
            .visibility
            .as_ref()
            .is_some_and(|visibility| visibility.hidden)
    }
    pub(crate) const EMPTY: Self = Self {
        alignment: None,
        instructions: None,
    };

    pub(crate) fn instructions(&self) -> &TextInstructions {
        static EMPTY: TextInstructions = TextInstructions {
            fit: None,
            fit_priority: None,
            direction: None,
            orientation: None,
            rotation_mode: None,
            anchor: None,
            offset: None,
            bounds: None,
            wrapping: None,
            overflow: None,
            overlap: None,
            visibility: None,
        };
        self.instructions.as_deref().unwrap_or(&EMPTY)
    }
    pub(crate) fn edit_instructions(&mut self) -> &mut TextInstructions {
        std::sync::Arc::make_mut(
            self.instructions
                .get_or_insert_with(|| std::sync::Arc::new(TextInstructions::default())),
        )
    }
    /// Set physical line alignment within the text block.
    #[must_use]
    pub const fn alignment(mut self, alignment: TextAlignment) -> Self {
        self.alignment = Some(alignment);
        self
    }
}

macro_rules! layout_edits {
    ($($field:ident:$value:ty),+ $(,)?) => {impl TextLayout {$(
        #[doc = concat!("Replace this request's `",stringify!($field),"` instruction.")]
        #[must_use]
        pub fn $field(mut self,value:$value) -> Self {self.edit_instructions().$field=Some(value);self}
    )+}};
}
layout_edits! {anchor:TextAnchor,offset:TextOffset,bounds:TextBounds,wrapping:TextWrapping,overflow:TextOverflow,overlap:TextOverlap,visibility:TextVisibility,orientation:TextOrientation,rotation_mode:TextRotationMode,direction:TextDirection,fit:TextFit,fit_priority:TextFitPriority}
impl TextLayout {
    /// Replace orientation with one fixed screen angle.
    #[must_use]
    pub fn rotation(self, value: TextRotation) -> Self {
        self.orientation(TextOrientation::fixed(value))
    }
}

/// One immutable selected role, including exact-appearance provenance.
#[derive(Clone, Copy)]
pub(crate) struct TextAppearance<'a> {
    pub(crate) theme: &'a crate::theme::TextTheme,
    pub(crate) exact_override: bool,
    pub(crate) layout: Option<&'a TextLayout>,
}

impl<'a> From<&'a crate::theme::TextTheme> for TextAppearance<'a> {
    fn from(theme: &'a crate::theme::TextTheme) -> Self {
        Self {
            theme,
            exact_override: false,
            layout: None,
        }
    }
}

impl TextAppearance<'_> {
    pub(crate) fn require_single(self) -> crate::Result<Self> {
        if !self.hidden()
            && self
                .layout
                .and_then(|request| request.instructions().orientation.as_ref())
                .is_some_and(|orientation| {
                    matches!(orientation.0, orientation::Orientation::Automatic(_))
                })
        {
            return Err(crate::Error::Data(
                "automatic orientation requires an actual tick group".into(),
            ));
        }
        if self
            .layout
            .and_then(|request| request.instructions().visibility.as_ref())
            .is_some_and(crate::text::TextVisibility::reduces)
        {
            return Err(crate::Error::Data("text visibility reduction requires an actual label group, not an independent authored slot".into()));
        }
        Ok(self)
    }
    pub(crate) fn includes(self, index: usize, eligible: &[usize]) -> bool {
        self.layout
            .and_then(|request| request.instructions().visibility.as_ref())
            .is_none_or(|policy| policy.includes(index, eligible))
    }
    pub(crate) fn hidden(self) -> bool {
        self.layout.is_some_and(|layout| {
            layout
                .instructions()
                .visibility
                .as_ref()
                .is_some_and(|visibility| visibility.hidden)
        })
    }
}

impl<'a> TextAppearance<'a> {
    pub(crate) fn layout(mut self, layout: Option<&'a TextLayout>) -> Self {
        self.layout = layout;
        self
    }
}

/// Physical horizontal alignment within a text owner's local span.
///
/// Start and End mean physical left and right, including for right-to-left text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextAlignment {
    /// Align to the physical left edge of the local span.
    Start,
    /// Align to the physical midpoint of the local span.
    Center,
    /// Align to the physical right edge of the local span.
    End,
}

impl TextAlignment {
    /// Resolve one physical x coordinate and backend anchor.
    pub(crate) fn resolve_physical(
        self,
        span_start: f64,
        span_end: f64,
    ) -> (f64, crate::render::backend::TextAnchor) {
        use crate::render::backend::TextAnchor;
        match self {
            Self::Start => (span_start, TextAnchor::Start),
            Self::Center => (
                span_start + (span_end - span_start) / 2.0,
                TextAnchor::Middle,
            ),
            Self::End => (span_end, TextAnchor::End),
        }
    }
}

#[derive(Debug, Clone, Copy, thiserror::Error)]
#[error("display text contains unsupported control character U+{scalar:04X}")]
pub(crate) struct UnsupportedControl {
    pub(crate) scalar: u32,
    start: usize,
    end: usize,
}

/// Validate content without trimming, rewriting or treating empty text as absence.
pub(crate) fn validate(source: &str) -> Result<(), UnsupportedControl> {
    match source
        .char_indices()
        .find(|(_, scalar)| is_unsupported_control(*scalar))
    {
        Some((start, scalar)) => Err(UnsupportedControl {
            scalar: scalar as u32,
            start,
            end: start + scalar.len_utf8(),
        }),
        None => Ok(()),
    }
}

pub(crate) fn validate_for(source: &str, role: &str) -> crate::Result<()> {
    if let Err(error) = validate(source) {
        use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, TextSpan};
        return Err(crate::Error::Data(
            Diagnostic::new(
                DiagnosticKind::InvalidValue {
                    value: Some(crate::data::RawKey::from(&source[error.start..error.end])),
                    constraint: "supported text scalar".to_owned(),
                },
                format!("{role}: {error}"),
            )
            .with_context(ErrorContext::new().with_span(TextSpan::new(
                source,
                error.start,
                error.end,
            )?)),
        ));
    }
    Ok(())
}

pub(crate) fn is_unsupported_control(scalar: char) -> bool {
    scalar.is_control()
        && !is_nonrendering_mandatory_break(scalar)
        && !is_nonpainting_control(scalar)
}

// UAX #14 BK, CR, LF, and NL controls partition paragraphs and do not paint.
// They remain in the census, but are not glyph-coverage requirements.
pub(crate) const fn is_nonrendering_mandatory_break(scalar: char) -> bool {
    matches!(
        scalar,
        '\u{000A}' | '\u{000B}' | '\u{000C}' | '\u{000D}' | '\u{0085}' | '\u{2028}' | '\u{2029}'
    )
}

/// Unicode 16 Default_Ignorable_Code_Point plus bidi controls.
pub(crate) const fn is_nonpainting_control(scalar: char) -> bool {
    matches!(scalar as u32, 0x00AD | 0x034F | 0x061C | 0x115F..=0x1160
        | 0x17B4..=0x17B5 | 0x180B..=0x180F | 0x200B..=0x200F
        | 0x202A..=0x202E | 0x2060..=0x206F | 0x3164 | 0xFE00..=0xFE0F
        | 0xFEFF | 0xFFA0 | 0xFFF0..=0xFFF8 | 0x1BCA0..=0x1BCA3
        | 0x1D173..=0x1D17A | 0xE0000..=0xE0FFF)
}

#[cfg(test)]
mod tests {
    use crate::{
        coordinates::{AxisTick, DataAreaCorner},
        elements::PlotTextAnnotation,
        formatting::Labels,
        layout::TextPanel,
        Canvas, NumericValues, Plot,
    };

    #[test]
    fn content_replacement_retains_instructions_until_a_whole_request_replaces_them() {
        use crate::{
            text::{TextAlignment, TextLayout},
            Text,
        };
        const BEFORE_CONTENT: Text = {
            let mut slot = Text::UNSET;
            slot.edit_alignment(TextAlignment::End);
            slot
        };
        let mut slot = BEFORE_CONTENT;
        assert!(slot.provided().is_none());
        let style = crate::Theme::publication()
            .typography()
            .get_root()
            .get_title()
            .clone();
        slot.replace_from(Text::new("first").style(style.clone()))
            .unwrap();
        slot.replace_from(Text::new("replacement")).unwrap();
        assert_eq!(
            slot.provided(),
            Some(
                &Text::new("replacement")
                    .style(style.clone())
                    .alignment(TextAlignment::End)
            )
        );
        slot.replace_from(Text::new("reset").layout(TextLayout::default()))
            .unwrap();
        assert_eq!(
            slot.provided(),
            Some(
                &Text::new("reset")
                    .style(style.clone())
                    .layout(TextLayout::default())
            )
        );
        slot.edit_alignment(TextAlignment::Start);
        assert_eq!(
            slot.provided(),
            Some(
                &Text::new("reset")
                    .style(style)
                    .alignment(TextAlignment::Start)
            )
        );
    }

    #[test]
    fn required_reception_rejects_unset_before_mutating_instructions() {
        use crate::{text::TextAlignment, Text};

        let mut text = Text::new("retained").alignment(TextAlignment::End);
        let previous = text.clone();
        assert!(matches!(
            text.replace_from(Text::UNSET),
            Err(crate::Error::Render(_))
        ));
        assert_eq!(text, previous);
        assert!(matches!(
            Text::UNSET.required_source("required"),
            Err(crate::Error::Render(_))
        ));
        assert_eq!(Text::new("").required_source("required").unwrap(), "");
        assert!(matches!(
            Text::new("invalid\tcontrol").required_source("required"),
            Err(crate::Error::Data(_))
        ));
        assert!(TextPanel::new(Text::UNSET, "body").is_err());
        assert!(PlotTextAnnotation::new(DataAreaCorner::TopLeft, Text::UNSET).is_err());
    }

    #[test]
    fn unsupported_display_controls_fail_before_font_discovery() {
        let before = crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get);
        let plot = || {
            Plot::scatter(
                NumericValues::new("x", [0.0, 1.0]),
                NumericValues::new("y", [1.0, 0.0]),
            )
        };
        let canvas = || {
            Canvas::grid(1, 1)
                .unwrap()
                .text_panel(0, 0, TextPanel::new("", "body").unwrap())
                .unwrap()
        };
        let errors = [
            PlotTextAnnotation::new(DataAreaCorner::TopLeft, "a\tb").unwrap_err(),
            TextPanel::new("title", "a\tb").unwrap_err(),
            canvas().column_header(0, 1, "a\tb").err().unwrap(),
            canvas().title("a\tb").preflight().unwrap_err(),
            plot().caption("a\tb").preflight().unwrap_err(),
            plot().x_label("a\tb").preflight().unwrap_err(),
            plot()
                .x_ticks(vec![AxisTick::new(0.0, "a\tb")])
                .preflight()
                .unwrap_err(),
            Labels::humanized()
                .alias("raw", "a\tb")
                .resolve("raw")
                .unwrap_err(),
        ];
        for error in errors {
            assert!(
                error
                    .to_string()
                    .contains("unsupported control character U+0009"),
                "{error}"
            );
        }
        assert_eq!(
            crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get),
            before
        );
    }
}