Skip to main content

lichtung_plot/
text.rs

1//! Shared source syntax for authored and prepared display text.
2
3pub use crate::font::canonical::{
4    check_fonts, check_fonts_with_operation, font_families, font_families_with_operation,
5    FontDiscovery, FontFamily, FontFamilyReport, FontScope, FontSourceIssue, FontStack, FontStyle,
6    FontSupport, FontVariantReport, GenericFontFamily,
7};
8pub use crate::spec::TextWeight;
9
10mod fit;
11pub(crate) mod layout;
12pub(crate) mod value;
13pub use fit::{TextFit, TextFitGrouping, TextFitPriority};
14pub(crate) mod orientation;
15pub(crate) mod position;
16pub use orientation::{TextOrientation, TextRotation, TextRotationMode};
17pub(crate) mod roles;
18mod service;
19pub use layout::{
20    TextAnchor, TextBounds, TextDirection, TextElision, TextEllipsis, TextFailure, TextOffset,
21    TextOffsetFrame, TextOverflow, TextOverlap, TextVisibility, TextWrapping,
22};
23pub use position::{TextCoordinate, TextPosition};
24pub(crate) use service::{TextRequestContext, TextService};
25
26/// Optional text layout instructions. Omitted fields retain owner defaults.
27///
28/// A supplied default request is an explicit reset, distinct from no request.
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30pub struct TextLayout {
31    pub(crate) alignment: Option<TextAlignment>,
32    instructions: Option<std::sync::Arc<TextInstructions>>,
33}
34
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub(crate) struct TextInstructions {
37    pub(crate) fit: Option<TextFit>,
38    pub(crate) fit_priority: Option<TextFitPriority>,
39    pub(crate) direction: Option<TextDirection>,
40    pub(crate) orientation: Option<TextOrientation>,
41    pub(crate) rotation_mode: Option<TextRotationMode>,
42    pub(crate) anchor: Option<TextAnchor>,
43    pub(crate) offset: Option<TextOffset>,
44    pub(crate) bounds: Option<TextBounds>,
45    pub(crate) wrapping: Option<TextWrapping>,
46    pub(crate) overflow: Option<TextOverflow>,
47    pub(crate) overlap: Option<TextOverlap>,
48    pub(crate) visibility: Option<TextVisibility>,
49}
50
51impl TextLayout {
52    /// Inspect the requested physical line alignment.
53    #[must_use]
54    pub const fn get_alignment(&self) -> Option<TextAlignment> {
55        self.alignment
56    }
57
58    /// Inspect the requested font-size program.
59    #[must_use]
60    pub fn get_fit(&self) -> Option<TextFit> {
61        self.instructions().fit
62    }
63
64    /// Inspect the requested fitting and abbreviation priority.
65    #[must_use]
66    pub fn get_fit_priority(&self) -> Option<TextFitPriority> {
67        self.instructions().fit_priority
68    }
69
70    /// Inspect the requested paragraph direction.
71    #[must_use]
72    pub fn get_direction(&self) -> Option<TextDirection> {
73        self.instructions().direction
74    }
75
76    /// Borrow the requested orientation program.
77    #[must_use]
78    pub fn get_orientation(&self) -> Option<&TextOrientation> {
79        self.instructions().orientation.as_ref()
80    }
81
82    /// Inspect the requested rotation-anchor relationship.
83    #[must_use]
84    pub fn get_rotation_mode(&self) -> Option<TextRotationMode> {
85        self.instructions().rotation_mode
86    }
87
88    /// Inspect the requested measured-block anchor.
89    #[must_use]
90    pub fn get_anchor(&self) -> Option<TextAnchor> {
91        self.instructions().anchor
92    }
93
94    /// Inspect the requested signed CSS-pixel displacement.
95    #[must_use]
96    pub fn get_offset(&self) -> Option<TextOffset> {
97        self.instructions().offset
98    }
99
100    /// Inspect the requested text-local maxima.
101    #[must_use]
102    pub fn get_bounds(&self) -> Option<TextBounds> {
103        self.instructions().bounds
104    }
105
106    /// Inspect the requested soft-wrap policy.
107    #[must_use]
108    pub fn get_wrapping(&self) -> Option<TextWrapping> {
109        self.instructions().wrapping
110    }
111
112    /// Borrow the requested overflow program.
113    #[must_use]
114    pub fn get_overflow(&self) -> Option<&TextOverflow> {
115        self.instructions().overflow.as_ref()
116    }
117
118    /// Inspect the requested peer-overlap policy.
119    #[must_use]
120    pub fn get_overlap(&self) -> Option<TextOverlap> {
121        self.instructions().overlap
122    }
123
124    /// Borrow the requested text-eligibility program.
125    #[must_use]
126    pub fn get_visibility(&self) -> Option<&TextVisibility> {
127        self.instructions().visibility.as_ref()
128    }
129
130    pub(crate) fn hidden(&self) -> bool {
131        self.instructions()
132            .visibility
133            .as_ref()
134            .is_some_and(|visibility| visibility.hidden)
135    }
136    pub(crate) const EMPTY: Self = Self {
137        alignment: None,
138        instructions: None,
139    };
140
141    pub(crate) fn instructions(&self) -> &TextInstructions {
142        static EMPTY: TextInstructions = TextInstructions {
143            fit: None,
144            fit_priority: None,
145            direction: None,
146            orientation: None,
147            rotation_mode: None,
148            anchor: None,
149            offset: None,
150            bounds: None,
151            wrapping: None,
152            overflow: None,
153            overlap: None,
154            visibility: None,
155        };
156        self.instructions.as_deref().unwrap_or(&EMPTY)
157    }
158    pub(crate) fn edit_instructions(&mut self) -> &mut TextInstructions {
159        std::sync::Arc::make_mut(
160            self.instructions
161                .get_or_insert_with(|| std::sync::Arc::new(TextInstructions::default())),
162        )
163    }
164    /// Set physical line alignment within the text block.
165    #[must_use]
166    pub const fn alignment(mut self, alignment: TextAlignment) -> Self {
167        self.alignment = Some(alignment);
168        self
169    }
170}
171
172macro_rules! layout_edits {
173    ($($field:ident:$value:ty),+ $(,)?) => {impl TextLayout {$(
174        #[doc = concat!("Replace this request's `",stringify!($field),"` instruction.")]
175        #[must_use]
176        pub fn $field(mut self,value:$value) -> Self {self.edit_instructions().$field=Some(value);self}
177    )+}};
178}
179layout_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}
180impl TextLayout {
181    /// Replace orientation with one fixed screen angle.
182    #[must_use]
183    pub fn rotation(self, value: TextRotation) -> Self {
184        self.orientation(TextOrientation::fixed(value))
185    }
186}
187
188/// One immutable selected role, including exact-appearance provenance.
189#[derive(Clone, Copy)]
190pub(crate) struct TextAppearance<'a> {
191    pub(crate) theme: &'a crate::theme::TextTheme,
192    pub(crate) exact_override: bool,
193    pub(crate) layout: Option<&'a TextLayout>,
194}
195
196impl<'a> From<&'a crate::theme::TextTheme> for TextAppearance<'a> {
197    fn from(theme: &'a crate::theme::TextTheme) -> Self {
198        Self {
199            theme,
200            exact_override: false,
201            layout: None,
202        }
203    }
204}
205
206impl TextAppearance<'_> {
207    pub(crate) fn require_single(self) -> crate::Result<Self> {
208        if !self.hidden()
209            && self
210                .layout
211                .and_then(|request| request.instructions().orientation.as_ref())
212                .is_some_and(|orientation| {
213                    matches!(orientation.0, orientation::Orientation::Automatic(_))
214                })
215        {
216            return Err(crate::Error::Data(
217                "automatic orientation requires an actual tick group".into(),
218            ));
219        }
220        if self
221            .layout
222            .and_then(|request| request.instructions().visibility.as_ref())
223            .is_some_and(crate::text::TextVisibility::reduces)
224        {
225            return Err(crate::Error::Data("text visibility reduction requires an actual label group, not an independent authored slot".into()));
226        }
227        Ok(self)
228    }
229    pub(crate) fn includes(self, index: usize, eligible: &[usize]) -> bool {
230        self.layout
231            .and_then(|request| request.instructions().visibility.as_ref())
232            .is_none_or(|policy| policy.includes(index, eligible))
233    }
234    pub(crate) fn hidden(self) -> bool {
235        self.layout.is_some_and(|layout| {
236            layout
237                .instructions()
238                .visibility
239                .as_ref()
240                .is_some_and(|visibility| visibility.hidden)
241        })
242    }
243}
244
245impl<'a> TextAppearance<'a> {
246    pub(crate) fn layout(mut self, layout: Option<&'a TextLayout>) -> Self {
247        self.layout = layout;
248        self
249    }
250}
251
252/// Physical horizontal alignment within a text owner's local span.
253///
254/// Start and End mean physical left and right, including for right-to-left text.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub enum TextAlignment {
257    /// Align to the physical left edge of the local span.
258    Start,
259    /// Align to the physical midpoint of the local span.
260    Center,
261    /// Align to the physical right edge of the local span.
262    End,
263}
264
265impl TextAlignment {
266    /// Resolve one physical x coordinate and backend anchor.
267    pub(crate) fn resolve_physical(
268        self,
269        span_start: f64,
270        span_end: f64,
271    ) -> (f64, crate::render::backend::TextAnchor) {
272        use crate::render::backend::TextAnchor;
273        match self {
274            Self::Start => (span_start, TextAnchor::Start),
275            Self::Center => (
276                span_start + (span_end - span_start) / 2.0,
277                TextAnchor::Middle,
278            ),
279            Self::End => (span_end, TextAnchor::End),
280        }
281    }
282}
283
284#[derive(Debug, Clone, Copy, thiserror::Error)]
285#[error("display text contains unsupported control character U+{scalar:04X}")]
286pub(crate) struct UnsupportedControl {
287    pub(crate) scalar: u32,
288    start: usize,
289    end: usize,
290}
291
292/// Validate content without trimming, rewriting or treating empty text as absence.
293pub(crate) fn validate(source: &str) -> Result<(), UnsupportedControl> {
294    match source
295        .char_indices()
296        .find(|(_, scalar)| is_unsupported_control(*scalar))
297    {
298        Some((start, scalar)) => Err(UnsupportedControl {
299            scalar: scalar as u32,
300            start,
301            end: start + scalar.len_utf8(),
302        }),
303        None => Ok(()),
304    }
305}
306
307pub(crate) fn validate_for(source: &str, role: &str) -> crate::Result<()> {
308    if let Err(error) = validate(source) {
309        use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, TextSpan};
310        return Err(crate::Error::Data(
311            Diagnostic::new(
312                DiagnosticKind::InvalidValue {
313                    value: Some(crate::data::RawKey::from(&source[error.start..error.end])),
314                    constraint: "supported text scalar".to_owned(),
315                },
316                format!("{role}: {error}"),
317            )
318            .with_context(ErrorContext::new().with_span(TextSpan::new(
319                source,
320                error.start,
321                error.end,
322            )?)),
323        ));
324    }
325    Ok(())
326}
327
328pub(crate) fn is_unsupported_control(scalar: char) -> bool {
329    scalar.is_control()
330        && !is_nonrendering_mandatory_break(scalar)
331        && !is_nonpainting_control(scalar)
332}
333
334// UAX #14 BK, CR, LF, and NL controls partition paragraphs and do not paint.
335// They remain in the census, but are not glyph-coverage requirements.
336pub(crate) const fn is_nonrendering_mandatory_break(scalar: char) -> bool {
337    matches!(
338        scalar,
339        '\u{000A}' | '\u{000B}' | '\u{000C}' | '\u{000D}' | '\u{0085}' | '\u{2028}' | '\u{2029}'
340    )
341}
342
343/// Unicode 16 Default_Ignorable_Code_Point plus bidi controls.
344pub(crate) const fn is_nonpainting_control(scalar: char) -> bool {
345    matches!(scalar as u32, 0x00AD | 0x034F | 0x061C | 0x115F..=0x1160
346        | 0x17B4..=0x17B5 | 0x180B..=0x180F | 0x200B..=0x200F
347        | 0x202A..=0x202E | 0x2060..=0x206F | 0x3164 | 0xFE00..=0xFE0F
348        | 0xFEFF | 0xFFA0 | 0xFFF0..=0xFFF8 | 0x1BCA0..=0x1BCA3
349        | 0x1D173..=0x1D17A | 0xE0000..=0xE0FFF)
350}
351
352#[cfg(test)]
353mod tests {
354    use crate::{
355        coordinates::{AxisTick, DataAreaCorner},
356        elements::PlotTextAnnotation,
357        formatting::Labels,
358        layout::TextPanel,
359        Canvas, NumericValues, Plot,
360    };
361
362    #[test]
363    fn content_replacement_retains_instructions_until_a_whole_request_replaces_them() {
364        use crate::{
365            text::{TextAlignment, TextLayout},
366            Text,
367        };
368        const BEFORE_CONTENT: Text = {
369            let mut slot = Text::UNSET;
370            slot.edit_alignment(TextAlignment::End);
371            slot
372        };
373        let mut slot = BEFORE_CONTENT;
374        assert!(slot.provided().is_none());
375        let style = crate::Theme::publication()
376            .typography()
377            .get_root()
378            .get_title()
379            .clone();
380        slot.replace_from(Text::new("first").style(style.clone()))
381            .unwrap();
382        slot.replace_from(Text::new("replacement")).unwrap();
383        assert_eq!(
384            slot.provided(),
385            Some(
386                &Text::new("replacement")
387                    .style(style.clone())
388                    .alignment(TextAlignment::End)
389            )
390        );
391        slot.replace_from(Text::new("reset").layout(TextLayout::default()))
392            .unwrap();
393        assert_eq!(
394            slot.provided(),
395            Some(
396                &Text::new("reset")
397                    .style(style.clone())
398                    .layout(TextLayout::default())
399            )
400        );
401        slot.edit_alignment(TextAlignment::Start);
402        assert_eq!(
403            slot.provided(),
404            Some(
405                &Text::new("reset")
406                    .style(style)
407                    .alignment(TextAlignment::Start)
408            )
409        );
410    }
411
412    #[test]
413    fn required_reception_rejects_unset_before_mutating_instructions() {
414        use crate::{text::TextAlignment, Text};
415
416        let mut text = Text::new("retained").alignment(TextAlignment::End);
417        let previous = text.clone();
418        assert!(matches!(
419            text.replace_from(Text::UNSET),
420            Err(crate::Error::Render(_))
421        ));
422        assert_eq!(text, previous);
423        assert!(matches!(
424            Text::UNSET.required_source("required"),
425            Err(crate::Error::Render(_))
426        ));
427        assert_eq!(Text::new("").required_source("required").unwrap(), "");
428        assert!(matches!(
429            Text::new("invalid\tcontrol").required_source("required"),
430            Err(crate::Error::Data(_))
431        ));
432        assert!(TextPanel::new(Text::UNSET, "body").is_err());
433        assert!(PlotTextAnnotation::new(DataAreaCorner::TopLeft, Text::UNSET).is_err());
434    }
435
436    #[test]
437    fn unsupported_display_controls_fail_before_font_discovery() {
438        let before = crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get);
439        let plot = || {
440            Plot::scatter(
441                NumericValues::new("x", [0.0, 1.0]),
442                NumericValues::new("y", [1.0, 0.0]),
443            )
444        };
445        let canvas = || {
446            Canvas::grid(1, 1)
447                .unwrap()
448                .panel(0, 0, TextPanel::new("", "body").unwrap())
449                .unwrap()
450        };
451        let errors = [
452            PlotTextAnnotation::new(DataAreaCorner::TopLeft, "a\tb").unwrap_err(),
453            TextPanel::new("title", "a\tb").unwrap_err(),
454            canvas().column_header(0, 1, "a\tb").err().unwrap(),
455            canvas().title("a\tb").preflight().unwrap_err(),
456            plot().caption("a\tb").preflight().unwrap_err(),
457            plot().x_label("a\tb").preflight().unwrap_err(),
458            plot()
459                .x_ticks(vec![AxisTick::new(0.0, "a\tb")])
460                .preflight()
461                .unwrap_err(),
462            Labels::humanized()
463                .alias("raw", "a\tb")
464                .resolve("raw")
465                .unwrap_err(),
466        ];
467        for error in errors {
468            assert!(
469                error
470                    .to_string()
471                    .contains("unsupported control character U+0009"),
472                "{error}"
473            );
474        }
475        assert_eq!(
476            crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get),
477            before
478        );
479    }
480}