Skip to main content

lichtung_plot/
text.rs

1//! Shared source syntax for authored and prepared display text.
2
3mod fit;
4pub(crate) mod layout;
5pub use fit::{TextFit, TextFitGrouping, TextFitPriority};
6pub(crate) mod orientation;
7pub(crate) mod position;
8pub use orientation::{TextOrientation, TextRotation, TextRotationMode};
9pub(crate) mod roles;
10mod service;
11pub use layout::{
12    TextAnchor, TextBounds, TextDirection, TextElision, TextEllipsis, TextFailure, TextOffset,
13    TextOffsetFrame, TextOverflow, TextOverlap, TextVisibility, TextWrapping,
14};
15pub use position::{DataCoordinate, DataPosition, TextCoordinate, TextPosition};
16pub use roles::GuideTextRole;
17pub(crate) use service::{TextRequestContext, TextService};
18
19/// Authored display text with optional complete appearance and layout instructions.
20///
21/// Plain strings carry no local instructions. Content validation happens
22/// at the receiving constructor or preflight, without rewriting the source.
23/// Clones share immutable source bytes and retain complete local instructions.
24///
25/// ```
26/// use lichtung_plot::{NumericValues, DataAreaCorner, PlotTextAnnotation, Plot, Text, TextAlignment, TextLayout, TextPanel, Theme};
27/// let style = Theme::publication().typography().get_composition()
28///     .get_text_panel_title().clone().font_size(24.0)?;
29/// let title = Text::new("Study\ncontext").style(style).alignment(TextAlignment::End);
30/// let note = PlotTextAnnotation::new(DataAreaCorner::TopLeft, title.clone())?;
31/// let plot = Plot::scatter(NumericValues::new("x", [0.0, 1.0]),
32///     NumericValues::new("y", [1.0, 0.0]))
33///     .title(title.clone()).title("Updated heading")
34///     .caption(Text::new("Centered caption").alignment(TextAlignment::Center));
35/// let panel = TextPanel::new(title, Text::new("Independent body")
36///     .layout(TextLayout::default().alignment(TextAlignment::Start)))?;
37/// assert_eq!(panel.title(), "Study\ncontext");
38/// assert_eq!(note.text(), panel.title());
39/// # let _ = plot;
40/// # Ok::<(), lichtung_plot::Error>(())
41/// ```
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Text {
44    source: Option<std::sync::Arc<String>>,
45    style: Option<crate::TextTheme>,
46    layout: Option<TextLayout>,
47}
48
49impl Text {
50    /// Retain one verbatim display source.
51    #[must_use]
52    pub fn new(source: impl Into<String>) -> Self {
53        Self {
54            source: Some(std::sync::Arc::new(source.into())),
55            style: None,
56            layout: None,
57        }
58    }
59
60    /// Borrow the original source.
61    #[must_use]
62    pub fn as_str(&self) -> &str {
63        self.source.as_ref().map_or("", |source| source.as_str())
64    }
65
66    /// Replace the complete exact appearance.
67    #[must_use]
68    pub fn style(mut self, style: crate::TextTheme) -> Self {
69        self.style = Some(style);
70        self
71    }
72
73    /// Remove local appearance without changing content or layout.
74    /// The receiving owner's Theme role supplies appearance when this value is used.
75    #[must_use]
76    pub fn clear_style(mut self) -> Self {
77        self.edit_clear_style();
78        self
79    }
80
81    /// Inspect local appearance presence.
82    #[must_use]
83    pub const fn get_style(&self) -> Option<&crate::TextTheme> {
84        self.style.as_ref()
85    }
86
87    /// Supply a whole layout request, including an explicit default reset.
88    #[must_use]
89    pub fn layout(mut self, layout: TextLayout) -> Self {
90        self.layout = Some(layout);
91        self
92    }
93
94    /// Remove the local layout request, rather than attach a present default.
95    /// Passing this value to an existing slot still follows omission/preserve rules.
96    #[must_use]
97    pub fn clear_layout(mut self) -> Self {
98        self.edit_clear_layout();
99        self
100    }
101
102    /// Distinguish an omitted layout from a present request.
103    #[must_use]
104    pub const fn get_layout(&self) -> Option<&TextLayout> {
105        self.layout.as_ref()
106    }
107
108    /// Edit alignment within this text's one layout request.
109    #[must_use]
110    pub fn alignment(mut self, alignment: TextAlignment) -> Self {
111        self.edit_alignment(alignment);
112        self
113    }
114
115    pub(crate) const fn edit_alignment(&mut self, alignment: TextAlignment) {
116        if self.layout.is_none() {
117            // The replaced value is known None. Forget only that empty value so
118            // this existing const edit does not require const Arc destruction.
119            std::mem::forget(self.layout.replace(TextLayout::EMPTY));
120        }
121        if let Some(layout) = &mut self.layout {
122            layout.alignment = Some(alignment);
123        }
124    }
125
126    pub(crate) const fn alignment_request(&self) -> Option<TextAlignment> {
127        match &self.layout {
128            Some(layout) => layout.alignment,
129            None => None,
130        }
131    }
132
133    pub(crate) fn try_copy(&self) -> crate::Result<Self> {
134        Ok(Self {
135            source: self.source.clone(),
136            style: self
137                .style
138                .as_ref()
139                .map(crate::TextTheme::try_copy)
140                .transpose()?,
141            layout: self.layout.clone(),
142        })
143    }
144
145    pub(crate) fn try_copy_with_source(&self, source: String) -> crate::Result<Self> {
146        Ok(Self {
147            source: Some(adopt_text_source_checked(source)?),
148            style: self
149                .style
150                .as_ref()
151                .map(crate::TextTheme::try_copy)
152                .transpose()?,
153            layout: self.layout.clone(),
154        })
155    }
156
157    pub(crate) fn appearance<'a>(
158        &'a self,
159        role: impl Into<TextAppearance<'a>>,
160    ) -> TextAppearance<'a> {
161        let role = role.into();
162        TextAppearance {
163            theme: self.style.as_ref().unwrap_or(role.theme),
164            exact_override: self.style.is_some() || role.exact_override,
165            layout: self.layout.as_ref().or(role.layout),
166        }
167    }
168
169    pub(crate) fn resolved_alignment(&self, default: TextAlignment) -> TextAlignment {
170        self.alignment_request().unwrap_or(default)
171    }
172}
173
174impl Text {
175    pub(crate) const UNSET: Self = Self {
176        source: None,
177        style: None,
178        layout: None,
179    };
180
181    pub(crate) const fn is_provided(&self) -> bool {
182        self.source.is_some()
183    }
184
185    pub(crate) const fn provided(&self) -> Option<&Self> {
186        if self.is_provided() {
187            Some(self)
188        } else {
189            None
190        }
191    }
192
193    pub(crate) fn required_source(&self, role: &str) -> crate::Result<&str> {
194        let source = self.source.as_ref().ok_or_else(|| {
195            crate::Error::Render(format!("{role}: required text source is unset"))
196        })?;
197        validate_for(source, role)?;
198        Ok(source)
199    }
200
201    pub(crate) fn edit_style(&mut self, style: crate::TextTheme) {
202        self.style = Some(style);
203    }
204    pub(crate) fn edit_layout(&mut self, layout: TextLayout) {
205        self.layout = Some(layout);
206    }
207    pub(crate) fn edit_clear_style(&mut self) {
208        self.style = None;
209    }
210    pub(crate) fn edit_clear_layout(&mut self) {
211        self.layout = None;
212    }
213    pub(crate) fn resolve_source(&self, source: String) -> crate::Result<Text> {
214        if self.is_provided() {
215            self.try_copy()
216        } else {
217            self.try_copy_with_source(source)
218        }
219    }
220    pub(crate) fn observe_feedback(
221        &self,
222        round: &mut crate::layout::kernel::FeedbackRound,
223    ) -> crate::Result<()> {
224        round.observe_count(usize::from(self.is_provided()))?;
225        round.observe_authored_text(self)
226    }
227
228    pub(crate) fn replace_from(&mut self, incoming: Text) -> crate::Result<()> {
229        if !incoming.is_provided() {
230            return Err(crate::Error::Render(
231                "text replacement: required text source is unset".into(),
232            ));
233        }
234        self.source = incoming.source;
235        if incoming.style.is_some() {
236            self.style = incoming.style;
237        }
238        if incoming.layout.is_some() {
239            self.layout = incoming.layout;
240        }
241        Ok(())
242    }
243}
244
245fn adopt_text_source_checked(source: String) -> crate::Result<std::sync::Arc<String>> {
246    crate::data::source::source_arc(source)
247}
248
249impl From<String> for Text {
250    fn from(source: String) -> Self {
251        Self::new(source)
252    }
253}
254
255impl From<&str> for Text {
256    fn from(source: &str) -> Self {
257        Self::new(source)
258    }
259}
260
261impl From<&String> for Text {
262    fn from(source: &String) -> Self {
263        Self::new(source)
264    }
265}
266
267/// Optional text layout instructions. Omitted fields retain owner defaults.
268///
269/// A supplied default request is an explicit reset, distinct from no request.
270#[derive(Debug, Clone, Default, PartialEq, Eq)]
271pub struct TextLayout {
272    pub(crate) alignment: Option<TextAlignment>,
273    instructions: Option<std::sync::Arc<TextInstructions>>,
274}
275
276#[derive(Debug, Clone, Default, PartialEq, Eq)]
277pub(crate) struct TextInstructions {
278    pub(crate) fit: Option<TextFit>,
279    pub(crate) fit_priority: Option<TextFitPriority>,
280    pub(crate) direction: Option<TextDirection>,
281    pub(crate) orientation: Option<TextOrientation>,
282    pub(crate) rotation_mode: Option<TextRotationMode>,
283    pub(crate) anchor: Option<TextAnchor>,
284    pub(crate) offset: Option<TextOffset>,
285    pub(crate) bounds: Option<TextBounds>,
286    pub(crate) wrapping: Option<TextWrapping>,
287    pub(crate) overflow: Option<TextOverflow>,
288    pub(crate) overlap: Option<TextOverlap>,
289    pub(crate) visibility: Option<TextVisibility>,
290}
291
292impl TextLayout {
293    /// Inspect the requested physical line alignment.
294    #[must_use]
295    pub const fn get_alignment(&self) -> Option<TextAlignment> {
296        self.alignment
297    }
298
299    /// Inspect the requested font-size program.
300    #[must_use]
301    pub fn get_fit(&self) -> Option<TextFit> {
302        self.instructions().fit
303    }
304
305    /// Inspect the requested fitting and abbreviation priority.
306    #[must_use]
307    pub fn get_fit_priority(&self) -> Option<TextFitPriority> {
308        self.instructions().fit_priority
309    }
310
311    /// Inspect the requested paragraph direction.
312    #[must_use]
313    pub fn get_direction(&self) -> Option<TextDirection> {
314        self.instructions().direction
315    }
316
317    /// Borrow the requested orientation program.
318    #[must_use]
319    pub fn get_orientation(&self) -> Option<&TextOrientation> {
320        self.instructions().orientation.as_ref()
321    }
322
323    /// Inspect the requested rotation-anchor relationship.
324    #[must_use]
325    pub fn get_rotation_mode(&self) -> Option<TextRotationMode> {
326        self.instructions().rotation_mode
327    }
328
329    /// Inspect the requested measured-block anchor.
330    #[must_use]
331    pub fn get_anchor(&self) -> Option<TextAnchor> {
332        self.instructions().anchor
333    }
334
335    /// Inspect the requested signed CSS-pixel displacement.
336    #[must_use]
337    pub fn get_offset(&self) -> Option<TextOffset> {
338        self.instructions().offset
339    }
340
341    /// Inspect the requested text-local maxima.
342    #[must_use]
343    pub fn get_bounds(&self) -> Option<TextBounds> {
344        self.instructions().bounds
345    }
346
347    /// Inspect the requested soft-wrap policy.
348    #[must_use]
349    pub fn get_wrapping(&self) -> Option<TextWrapping> {
350        self.instructions().wrapping
351    }
352
353    /// Borrow the requested overflow program.
354    #[must_use]
355    pub fn get_overflow(&self) -> Option<&TextOverflow> {
356        self.instructions().overflow.as_ref()
357    }
358
359    /// Inspect the requested peer-overlap policy.
360    #[must_use]
361    pub fn get_overlap(&self) -> Option<TextOverlap> {
362        self.instructions().overlap
363    }
364
365    /// Borrow the requested text-eligibility program.
366    #[must_use]
367    pub fn get_visibility(&self) -> Option<&TextVisibility> {
368        self.instructions().visibility.as_ref()
369    }
370
371    pub(crate) fn hidden(&self) -> bool {
372        self.instructions()
373            .visibility
374            .as_ref()
375            .is_some_and(|visibility| visibility.hidden)
376    }
377    pub(crate) const EMPTY: Self = Self {
378        alignment: None,
379        instructions: None,
380    };
381
382    pub(crate) fn instructions(&self) -> &TextInstructions {
383        static EMPTY: TextInstructions = TextInstructions {
384            fit: None,
385            fit_priority: None,
386            direction: None,
387            orientation: None,
388            rotation_mode: None,
389            anchor: None,
390            offset: None,
391            bounds: None,
392            wrapping: None,
393            overflow: None,
394            overlap: None,
395            visibility: None,
396        };
397        self.instructions.as_deref().unwrap_or(&EMPTY)
398    }
399    pub(crate) fn edit_instructions(&mut self) -> &mut TextInstructions {
400        std::sync::Arc::make_mut(
401            self.instructions
402                .get_or_insert_with(|| std::sync::Arc::new(TextInstructions::default())),
403        )
404    }
405    /// Set physical line alignment within the text block.
406    #[must_use]
407    pub const fn alignment(mut self, alignment: TextAlignment) -> Self {
408        self.alignment = Some(alignment);
409        self
410    }
411}
412
413macro_rules! layout_edits {
414    ($($field:ident:$value:ty),+ $(,)?) => {impl TextLayout {$(
415        #[doc = concat!("Replace this request's `",stringify!($field),"` instruction.")]
416        #[must_use]
417        pub fn $field(mut self,value:$value) -> Self {self.edit_instructions().$field=Some(value);self}
418    )+}};
419}
420layout_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}
421impl TextLayout {
422    /// Replace orientation with one fixed screen angle.
423    #[must_use]
424    pub fn rotation(self, value: TextRotation) -> Self {
425        self.orientation(TextOrientation::fixed(value))
426    }
427}
428
429/// One immutable selected role, including exact-appearance provenance.
430#[derive(Clone, Copy)]
431pub(crate) struct TextAppearance<'a> {
432    pub(crate) theme: &'a crate::TextTheme,
433    pub(crate) exact_override: bool,
434    pub(crate) layout: Option<&'a TextLayout>,
435}
436
437impl<'a> From<&'a crate::TextTheme> for TextAppearance<'a> {
438    fn from(theme: &'a crate::TextTheme) -> Self {
439        Self {
440            theme,
441            exact_override: false,
442            layout: None,
443        }
444    }
445}
446
447impl TextAppearance<'_> {
448    pub(crate) fn require_single(self) -> crate::Result<Self> {
449        if !self.hidden()
450            && self
451                .layout
452                .and_then(|request| request.instructions().orientation.as_ref())
453                .is_some_and(|orientation| {
454                    matches!(orientation.0, orientation::Orientation::Automatic(_))
455                })
456        {
457            return Err(crate::Error::Data(
458                "automatic orientation requires an actual tick group".into(),
459            ));
460        }
461        if self
462            .layout
463            .and_then(|request| request.instructions().visibility.as_ref())
464            .is_some_and(crate::TextVisibility::reduces)
465        {
466            return Err(crate::Error::Data("text visibility reduction requires an actual label group, not an independent authored slot".into()));
467        }
468        Ok(self)
469    }
470    pub(crate) fn includes(self, index: usize, eligible: &[usize]) -> bool {
471        self.layout
472            .and_then(|request| request.instructions().visibility.as_ref())
473            .is_none_or(|policy| policy.includes(index, eligible))
474    }
475    pub(crate) fn hidden(self) -> bool {
476        self.layout.is_some_and(|layout| {
477            layout
478                .instructions()
479                .visibility
480                .as_ref()
481                .is_some_and(|visibility| visibility.hidden)
482        })
483    }
484}
485
486impl<'a> TextAppearance<'a> {
487    pub(crate) fn layout(mut self, layout: Option<&'a TextLayout>) -> Self {
488        self.layout = layout;
489        self
490    }
491}
492
493/// Physical horizontal alignment within a text owner's local span.
494///
495/// Start and End mean physical left and right, including for right-to-left text.
496#[derive(Debug, Clone, Copy, PartialEq, Eq)]
497pub enum TextAlignment {
498    /// Align to the physical left edge of the local span.
499    Start,
500    /// Align to the physical midpoint of the local span.
501    Center,
502    /// Align to the physical right edge of the local span.
503    End,
504}
505
506impl TextAlignment {
507    /// Resolve one physical x coordinate and backend anchor.
508    pub(crate) fn resolve_physical(
509        self,
510        span_start: f64,
511        span_end: f64,
512    ) -> (f64, crate::render::backend::TextAnchor) {
513        use crate::render::backend::TextAnchor;
514        match self {
515            Self::Start => (span_start, TextAnchor::Start),
516            Self::Center => (
517                span_start + (span_end - span_start) / 2.0,
518                TextAnchor::Middle,
519            ),
520            Self::End => (span_end, TextAnchor::End),
521        }
522    }
523}
524
525#[derive(Debug, Clone, Copy, thiserror::Error)]
526#[error("display text contains unsupported control character U+{scalar:04X}")]
527pub(crate) struct UnsupportedControl {
528    pub(crate) scalar: u32,
529}
530
531/// Validate content without trimming, rewriting or treating empty text as absence.
532pub(crate) fn validate(source: &str) -> Result<(), UnsupportedControl> {
533    match source
534        .chars()
535        .find(|&scalar| is_unsupported_control(scalar))
536    {
537        Some(scalar) => Err(UnsupportedControl {
538            scalar: scalar as u32,
539        }),
540        None => Ok(()),
541    }
542}
543
544pub(crate) fn validate_for(source: &str, role: &str) -> crate::Result<()> {
545    validate(source).map_err(|error| crate::Error::Data(format!("{role}: {error}")))
546}
547
548pub(crate) fn is_unsupported_control(scalar: char) -> bool {
549    scalar.is_control()
550        && !is_nonrendering_mandatory_break(scalar)
551        && !is_nonpainting_control(scalar)
552}
553
554// UAX #14 BK, CR, LF, and NL controls partition paragraphs and do not paint.
555// They remain in the census, but are not glyph-coverage requirements.
556pub(crate) const fn is_nonrendering_mandatory_break(scalar: char) -> bool {
557    matches!(
558        scalar,
559        '\u{000A}' | '\u{000B}' | '\u{000C}' | '\u{000D}' | '\u{0085}' | '\u{2028}' | '\u{2029}'
560    )
561}
562
563/// Unicode 16 Default_Ignorable_Code_Point plus bidi controls.
564pub(crate) const fn is_nonpainting_control(scalar: char) -> bool {
565    matches!(scalar as u32, 0x00AD | 0x034F | 0x061C | 0x115F..=0x1160
566        | 0x17B4..=0x17B5 | 0x180B..=0x180F | 0x200B..=0x200F
567        | 0x202A..=0x202E | 0x2060..=0x206F | 0x3164 | 0xFE00..=0xFE0F
568        | 0xFEFF | 0xFFA0 | 0xFFF0..=0xFFF8 | 0x1BCA0..=0x1BCA3
569        | 0x1D173..=0x1D17A | 0xE0000..=0xE0FFF)
570}
571
572#[cfg(test)]
573mod tests {
574    use crate::{
575        AxisTick, Canvas, DataAreaCorner, Labels, NumericValues, Plot, PlotTextAnnotation,
576        TextPanel,
577    };
578
579    #[test]
580    fn content_replacement_retains_instructions_until_a_whole_request_replaces_them() {
581        use super::{Text, TextAlignment, TextLayout};
582        const BEFORE_CONTENT: Text = {
583            let mut slot = Text::UNSET;
584            slot.edit_alignment(TextAlignment::End);
585            slot
586        };
587        let mut slot = BEFORE_CONTENT;
588        assert!(slot.provided().is_none());
589        let style = crate::Theme::publication()
590            .typography()
591            .get_root()
592            .get_title()
593            .clone();
594        slot.replace_from(Text::new("first").style(style.clone()))
595            .unwrap();
596        slot.replace_from(Text::new("replacement")).unwrap();
597        assert_eq!(
598            slot.provided(),
599            Some(
600                &Text::new("replacement")
601                    .style(style.clone())
602                    .alignment(TextAlignment::End)
603            )
604        );
605        slot.replace_from(Text::new("reset").layout(TextLayout::default()))
606            .unwrap();
607        assert_eq!(
608            slot.provided(),
609            Some(
610                &Text::new("reset")
611                    .style(style.clone())
612                    .layout(TextLayout::default())
613            )
614        );
615        slot.edit_alignment(TextAlignment::Start);
616        assert_eq!(
617            slot.provided(),
618            Some(
619                &Text::new("reset")
620                    .style(style)
621                    .alignment(TextAlignment::Start)
622            )
623        );
624    }
625
626    #[test]
627    fn required_reception_rejects_unset_before_mutating_instructions() {
628        use super::{Text, TextAlignment};
629
630        let mut text = Text::new("retained").alignment(TextAlignment::End);
631        let previous = text.clone();
632        assert!(matches!(
633            text.replace_from(Text::UNSET),
634            Err(crate::Error::Render(_))
635        ));
636        assert_eq!(text, previous);
637        assert!(matches!(
638            Text::UNSET.required_source("required"),
639            Err(crate::Error::Render(_))
640        ));
641        assert_eq!(Text::new("").required_source("required").unwrap(), "");
642        assert!(matches!(
643            Text::new("invalid\tcontrol").required_source("required"),
644            Err(crate::Error::Data(_))
645        ));
646        assert!(TextPanel::new(Text::UNSET, "body").is_err());
647        assert!(PlotTextAnnotation::new(DataAreaCorner::TopLeft, Text::UNSET).is_err());
648    }
649
650    #[test]
651    fn unsupported_display_controls_fail_before_font_discovery() {
652        let before = crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get);
653        let plot = || {
654            Plot::scatter(
655                NumericValues::new("x", [0.0, 1.0]),
656                NumericValues::new("y", [1.0, 0.0]),
657            )
658        };
659        let canvas = || {
660            Canvas::grid(1, 1)
661                .unwrap()
662                .text_panel(0, 0, TextPanel::new("", "body").unwrap())
663                .unwrap()
664        };
665        let errors = [
666            PlotTextAnnotation::new(DataAreaCorner::TopLeft, "a\tb").unwrap_err(),
667            TextPanel::new("title", "a\tb").unwrap_err(),
668            canvas().column_header(0, 1, "a\tb").err().unwrap(),
669            canvas().title("a\tb").preflight().unwrap_err(),
670            plot().caption("a\tb").preflight().unwrap_err(),
671            plot().x_label("a\tb").preflight().unwrap_err(),
672            plot()
673                .x_ticks(vec![AxisTick::new(0.0, "a\tb")])
674                .preflight()
675                .unwrap_err(),
676            Labels::humanized()
677                .alias("raw", "a\tb")
678                .resolve("raw")
679                .unwrap_err(),
680        ];
681        for error in errors {
682            assert!(
683                error
684                    .to_string()
685                    .contains("unsupported control character U+0009"),
686                "{error}"
687            );
688        }
689        assert_eq!(
690            crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get),
691            before
692        );
693    }
694}