Skip to main content

lichtung_plot/theme/
resolved.rs

1//! Built-in construction data and private operation-local appearance resolution.
2
3#![deny(missing_docs)]
4
5use std::sync::{Arc, Mutex, OnceLock};
6
7use sha2::{Digest, Sha256};
8
9use super::{
10    AnnotationTextRoles, AnnotationTheme, AxisSpacing, AxisTextRoles, AxisTheme,
11    CompositionTextRoles, ContrastTextRoles, FrameSides, FrameTheme, GuideTextRoles, LegendTheme,
12    MarkTheme, RootTextRoles, StrokeTheme, Theme, TickTheme, TypographyTheme,
13};
14use crate::font::canonical::PreparedFontEnvironment;
15use crate::layout::{
16    PhysicalTextAlignment, ResolvedTextPlan, TextLineHeight, TextPlanInput, TextPlanProvenance,
17};
18use crate::style::LinePattern;
19use crate::theme::{color_from_rgb, Color};
20use crate::theme::{
21    AccentPalette, ColorScales, DivergingGradient, OpaqueColor, QualitativePalette,
22    SequentialGradient,
23};
24use crate::{text::TextWeight, Error};
25
26/// Built-in axis tick-label font size in actual CSS pixels.
27const TICK_FONT_SIZE: u32 = 16;
28
29const MUTED_TEXT: (u8, u8, u8) = (80, 80, 80);
30const SIGNIFICANCE_FONT_SIZE: u32 = 16;
31
32/// A theme's full resolved visual specification. Layout and renderers consume
33/// this value to produce concrete backend styles and layout decisions.
34#[derive(Debug, Clone)]
35pub(crate) struct ResolvedTheme {
36    pub(crate) text_layouts: crate::text::roles::TextRoles,
37    appearance: Theme,
38    /// An explicit Plot inside Canvas composes over the Canvas owner's surface.
39    pub(crate) canvas_surface_override: Option<Color>,
40}
41
42impl std::ops::Deref for ResolvedTheme {
43    type Target = Theme;
44    fn deref(&self) -> &Theme {
45        &self.appearance
46    }
47}
48
49impl std::ops::DerefMut for ResolvedTheme {
50    fn deref_mut(&mut self) -> &mut Theme {
51        &mut self.appearance
52    }
53}
54
55#[derive(Debug, Default)]
56struct TextQueryCache {
57    profiles: Vec<usize>,
58    entries: Vec<CachedTextQuery>,
59    exact: Vec<TextQueryIndex>,
60    shaping: Vec<TextQueryIndex>,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
64struct TextQueryIndex {
65    fingerprint: [u8; 32],
66    entry: usize,
67}
68
69impl TextQueryCache {
70    fn profile_entry(&self, input: &TextPlanInput<'_>) -> Option<usize> {
71        let (mut low, mut high) = (0, self.profiles.len());
72        while low < high {
73            let middle = low + (high - low) / 2;
74            let index = self.profiles[middle];
75            match self.compare_profile(index, input) {
76                std::cmp::Ordering::Less => low = middle + 1,
77                std::cmp::Ordering::Greater => high = middle,
78                std::cmp::Ordering::Equal => {
79                    if self.entries[index].appearance.stack.same(input.stack) {
80                        return Some(index);
81                    }
82                    // Distinct literal stacks can share source/size/weight. They
83                    // stay distinct; inspect only this equal-source interval.
84                    for direction in [false, true] {
85                        let mut position = middle;
86                        loop {
87                            position = if direction {
88                                position + 1
89                            } else {
90                                let Some(previous) = position.checked_sub(1) else {
91                                    break;
92                                };
93                                previous
94                            };
95                            if position == self.profiles.len() {
96                                break;
97                            }
98                            let index = self.profiles[position];
99                            if self.compare_profile(index, input) != std::cmp::Ordering::Equal {
100                                break;
101                            }
102                            if self.entries[index].appearance.stack.same(input.stack) {
103                                return Some(index);
104                            }
105                        }
106                    }
107                    return None;
108                }
109            }
110        }
111        None
112    }
113
114    fn compare_profile(&self, index: usize, input: &TextPlanInput<'_>) -> std::cmp::Ordering {
115        let entry = &self.entries[index];
116        let metadata = (
117            entry.direction as u8,
118            entry.source.len(),
119            entry.appearance.font_size.to_bits(),
120            entry.appearance.weight as u8,
121        )
122            .cmp(&(
123                input.direction as u8,
124                input.source.len(),
125                input.font_size.to_bits(),
126                input.weight as u8,
127            ));
128        if metadata != std::cmp::Ordering::Equal {
129            return metadata;
130        }
131        if std::ptr::eq(entry.source.as_str(), input.source) {
132            return std::cmp::Ordering::Equal;
133        }
134        for index in 0..input.source.len() {
135            let ordering = entry.source.as_bytes()[index].cmp(&input.source.as_bytes()[index]);
136            if ordering != std::cmp::Ordering::Equal {
137                return ordering;
138            }
139        }
140        std::cmp::Ordering::Equal
141    }
142
143    fn profile_insertion_point(&self, input: &TextPlanInput<'_>) -> usize {
144        let (mut low, mut high) = (0, self.profiles.len());
145        while low < high {
146            let middle = low + (high - low) / 2;
147            if self.compare_profile(self.profiles[middle], input) == std::cmp::Ordering::Less {
148                low = middle + 1;
149            } else {
150                high = middle;
151            }
152        }
153        low
154    }
155
156    fn query_key(&self, input: &TextPlanInput<'_>, preferred_lines: Option<usize>) -> TextQueryKey {
157        let shaping_entry = self.profile_entry(input);
158
159        let shaping_state = if let Some(index) = shaping_entry {
160            self.entries[index].shaping_state.clone()
161        } else {
162            CachedTextQuery::shaping_state(input)
163        };
164        TextQueryKey {
165            shaping_entry,
166            shaping_fingerprint: shaping_state.clone().finalize().into(),
167            fingerprint: CachedTextQuery::presentation_fingerprint(
168                shaping_state.clone(),
169                input,
170                preferred_lines,
171            ),
172            shaping_state,
173            observed_entries: self.entries.len(),
174        }
175    }
176    fn lower_bound(index: &[TextQueryIndex], fingerprint: [u8; 32]) -> usize {
177        let (mut low, mut high) = (0, index.len());
178        while low < high {
179            let middle = low + (high - low) / 2;
180            if index[middle].fingerprint < fingerprint {
181                low = middle + 1;
182            } else {
183                high = middle;
184            }
185        }
186        low
187    }
188
189    fn find_query(
190        &self,
191        index: &[TextQueryIndex],
192        fingerprint: [u8; 32],
193        key: (&TextPlanInput<'_>, Option<usize>),
194        exact: bool,
195
196        shaping_entry: Option<usize>,
197    ) -> Option<usize> {
198        let (input, preferred_lines) = key;
199        let start = Self::lower_bound(index, fingerprint);
200        for candidate in &index[start..] {
201            if candidate.fingerprint != fingerprint {
202                break;
203            }
204            let query = &self.entries[candidate.entry];
205            if shaping_entry == Some(query.shaping_entry)
206                && (!exact
207                    || (query.width == input.maximum_width_quanta
208                        && query.matches_presentation(input, preferred_lines)))
209            {
210                return Some(candidate.entry);
211            }
212        }
213        None
214    }
215
216    fn reserve<T>(values: &mut Vec<T>) -> Result<(), Error> {
217        if values.len() < values.capacity() {
218            return Ok(());
219        }
220        let capacity = values
221            .len()
222            .checked_add(1)
223            .and_then(|required| {
224                values
225                    .capacity()
226                    .checked_mul(2)
227                    .map(|doubled| required.max(doubled))
228            })
229            .ok_or_else(|| Error::Render("text query cache capacity overflow".into()))?;
230
231        crate::operation::vector(values, capacity - values.len())?;
232        values
233            .try_reserve_exact(capacity - values.len())
234            .map_err(|_| Error::Render("cannot reserve text query cache".into()))
235    }
236
237    fn insertion_point(index: &[TextQueryIndex], value: TextQueryIndex) -> usize {
238        let (mut low, mut high) = (0, index.len());
239        while low < high {
240            let middle = low + (high - low) / 2;
241            if index[middle] < value {
242                low = middle + 1;
243            } else {
244                high = middle;
245            }
246        }
247        low
248    }
249}
250
251#[derive(Debug)]
252struct CachedTextQuery {
253    direction: crate::text::TextDirection,
254    shaping_entry: usize,
255    shaping_state: Sha256,
256    source: Arc<String>,
257    appearance: TextTheme,
258    alignment: PhysicalTextAlignment,
259    owner: String,
260    pair_ordinal: u32,
261    exact_override: bool,
262    width: i64,
263    preferred_lines: Option<usize>,
264    unwrapped_width: Option<i64>,
265    result: CachedTextResult,
266}
267
268#[derive(Debug, Clone)]
269enum CachedTextResult {
270    Plan(ResolvedTextPlan),
271    /// Lookup-only result: reuse analysis, never this plan's width-specific lines.
272    Reflow(ResolvedTextPlan),
273    PreferredWidth(i64),
274}
275
276struct TextQueryKey {
277    observed_entries: usize,
278    shaping_entry: Option<usize>,
279    shaping_state: Sha256,
280    shaping_fingerprint: [u8; 32],
281    fingerprint: [u8; 32],
282}
283
284impl CachedTextQuery {
285    fn shaping_state(input: &TextPlanInput<'_>) -> Sha256 {
286        let mut hash = Sha256::new();
287        // The complete, unnormalized source fixes paragraph bidi and scripts;
288        // language and Unicode policy are fixed for this renderer. The memo is
289        // shared only together with its immutable operation font environment.
290        hash.update((input.source.len() as u64).to_le_bytes());
291        hash.update(input.source.as_bytes());
292        hash.update([input.direction as u8]);
293        input.stack.hash_into(&mut hash);
294
295        hash.update(input.font_size.to_le_bytes());
296        hash.update([match input.weight {
297            TextWeight::Normal => 0,
298            TextWeight::Semibold => 1,
299            TextWeight::Bold => 2,
300        }]);
301        hash
302    }
303
304    fn presentation_fingerprint(
305        mut hash: Sha256,
306        input: &TextPlanInput<'_>,
307        preferred_lines: Option<usize>,
308    ) -> [u8; 32] {
309        hash.update((input.provenance.owner.len() as u64).to_le_bytes());
310        hash.update(input.provenance.owner.as_bytes());
311        hash.update(input.provenance.pair_ordinal.to_le_bytes());
312        hash.update(input.maximum_width_quanta.to_le_bytes());
313        hash.update([match input.alignment {
314            PhysicalTextAlignment::Start => 0,
315            PhysicalTextAlignment::Center => 1,
316            PhysicalTextAlignment::End => 2,
317        }]);
318        match input.line_height {
319            TextLineHeight::Multiplier(value) => {
320                hash.update([0]);
321                hash.update(value.to_bits().to_le_bytes());
322            }
323            TextLineHeight::ResolvedQuanta(value) => {
324                hash.update([1]);
325                hash.update(value.to_le_bytes());
326            }
327        }
328        hash.update([
329            input.paint.red(),
330            input.paint.green(),
331            input.paint.blue(),
332            u8::from(input.exact_override),
333        ]);
334        hash.update(input.paint.get_alpha().to_bits().to_le_bytes());
335        hash.update([u8::from(preferred_lines.is_some())]);
336        if let Some(lines) = preferred_lines {
337            hash.update((lines as u64).to_le_bytes());
338        }
339        hash.finalize().into()
340    }
341
342    fn matches_presentation(
343        &self,
344        input: &TextPlanInput<'_>,
345        preferred_lines: Option<usize>,
346    ) -> bool {
347        self.appearance.paint == input.paint
348            && input.line_height
349                == TextLineHeight::Multiplier(self.appearance.line_height_multiplier)
350            && self.alignment == input.alignment
351            && self.pair_ordinal == input.provenance.pair_ordinal
352            && self.exact_override == input.exact_override
353            && self.preferred_lines == preferred_lines
354            && crate::font::canonical::same_bytes(&self.owner, &input.provenance.owner)
355    }
356
357    fn matches_width(&self, width: i64) -> bool {
358        self.width == width
359            || self
360                .unwrapped_width
361                .is_some_and(|required| required <= width)
362    }
363}
364
365impl PartialEq for ResolvedTheme {
366    fn eq(&self, other: &Self) -> bool {
367        self.non_text_eq(other)
368            && self.axes == other.axes
369            && self.legend == other.legend
370            && self.composition == other.composition
371            && self.typography == other.typography
372            && self.text_layouts == other.text_layouts
373    }
374}
375
376impl ResolvedTheme {
377    pub(crate) fn apply_text_defaults(&mut self, kind: crate::plots::PlotKind) {
378        if kind == crate::plots::PlotKind::Heatmap {
379            for side in 0..2 {
380                if self.text_layouts.ticks[side].is_none() {
381                    self.text_layouts.ticks[side] = Some(
382                        crate::text::TextLayout::default()
383                            .wrapping(crate::text::TextWrapping::NoSoftWrap)
384                            .overflow(crate::text::TextOverflow::ellipsis(
385                                crate::text::TextEllipsis::new(crate::text::TextElision::End)
386                                    .marker("...")
387                                    .distinct(true),
388                                crate::text::TextFailure::Error,
389                            )),
390                    );
391                }
392            }
393        }
394    }
395    pub(crate) fn tick_text_appearance(
396        &self,
397        side: crate::layout::AxisSide,
398    ) -> crate::text::TextAppearance<'_> {
399        crate::text::TextAppearance::from(&self.typography.axes.tick_label).layout(
400            self.text_layouts.ticks[usize::from(side == crate::layout::AxisSide::Left)].as_ref(),
401        )
402    }
403    pub(crate) fn guide_text_appearance(
404        &self,
405        role: crate::guides::GuideTextRole,
406    ) -> crate::text::TextAppearance<'_> {
407        crate::text::TextAppearance::from(if role == crate::guides::GuideTextRole::Title {
408            &self.typography.guides.legend_title
409        } else {
410            &self.typography.guides.legend_label
411        })
412        .layout(self.text_layouts.guide[role.index()].as_ref())
413    }
414    pub(crate) fn new(appearance: Theme) -> Result<Self, Error> {
415        appearance.validate()?;
416        Ok(Self {
417            appearance,
418            text_layouts: crate::text::roles::TextRoles::default(),
419            canvas_surface_override: None,
420        })
421    }
422
423    fn non_text_eq(&self, other: &Self) -> bool {
424        self.color_scales == other.color_scales
425            && self.surfaces == other.surfaces
426            && self.canvas_surface_override == other.canvas_surface_override
427            && self.marks == other.marks
428            && self.annotations == other.annotations
429    }
430}
431
432impl ResolvedTheme {
433    #[expect(
434        clippy::type_complexity,
435        clippy::ref_option,
436        reason = "retains the original optional direction projection and comparison boundary"
437    )]
438    pub(crate) fn same_validated(
439        &self,
440        other: &Self,
441        direction: &Option<(
442            [(f64, f64); 2],
443            crate::layout::PixelRect,
444            [Option<Vec<(f64, f64)>>; 2],
445            Option<String>,
446        )>,
447        current: Option<crate::text::orientation::TextReferenceResolver<'_, '_>>,
448    ) -> Result<bool, Error> {
449        if !self.axes.same_validated(&other.axes)? {
450            return Ok(false);
451        }
452        if !self.legend.same(&other.legend) {
453            return Ok(false);
454        }
455        if !self.composition.same(&other.composition) {
456            return Ok(false);
457        }
458        if !self.non_text_eq(other)
459            || !direction
460                .as_ref()
461                .zip(current)
462                .is_none_or(|(saved, current)| current.matches_snapshot(saved))
463            || self.text_layouts != other.text_layouts
464        {
465            return Ok(false);
466        }
467        for (left, right) in self
468            .typography
469            .roles()
470            .into_iter()
471            .zip(other.typography.roles())
472        {
473            if !left.same(right) {
474                return Ok(false);
475            }
476        }
477        Ok(true)
478    }
479
480    /// Select a complete text role over one final variable-fill paint before
481    /// font preparation, using owner-local panel/root surfaces and backdrop.
482    pub(crate) fn contrasting_text(&self, fill: Color) -> Result<&TextTheme, Error> {
483        super::contrast::select(
484            fill,
485            self.surfaces.get_plot_panel(),
486            self.canvas_surface_override
487                .unwrap_or(self.surfaces.get_canvas_root()),
488            self.annotations.get_planning_backdrop().into(),
489            self.typography.get_annotations().get_contrast().get_light(),
490            self.typography.get_annotations().get_contrast().get_dark(),
491        )
492    }
493}
494
495/// One operation's font preparation and optional text/guide memo tables.
496#[derive(Debug, Default)]
497pub(crate) struct TextService {
498    pub(crate) fonts: OnceLock<PreparedFontEnvironment>,
499    queries: Mutex<TextQueryCache>,
500    pub(crate) guides: Mutex<crate::decorations::legend::GuideMeasurements>,
501}
502
503impl TextService {
504    /// Initialize this operation's canonical system-font environment.
505    pub(crate) fn prepare_font_environment(&self) -> Result<(), Error> {
506        self.prepared_font_environment().map(|_| ())
507    }
508
509    pub(crate) fn prepare_font_environment_from_census(
510        &self,
511        census: &mut crate::layout::PreparedTextCensus,
512        presence: Vec<u64>,
513        prepared_stage: &mut crate::layout::kernel::PreparedStage<'_>,
514    ) -> Result<(), Error> {
515        if self.fonts.get().is_none() {
516            let environment = census
517                .prepare_system_fonts(presence, prepared_stage)
518                .map_err(|error| Error::from(error).with_prefix("font preflight"))?;
519            self.fonts
520                .set(environment)
521                .map_err(|_| Error::Render("font environment already prepared".into()))?;
522        }
523        Ok(())
524    }
525
526    /// Borrow this operation's prepared canonical font environment.
527    pub(crate) fn prepared_font_environment(&self) -> Result<&PreparedFontEnvironment, Error> {
528        #[cfg(test)]
529        if self.fonts.get().is_none() {
530            let environment = PreparedFontEnvironment::discover_system()
531                .map_err(|error| Error::from(error).with_prefix("font preflight"))?;
532            let _ = self.fonts.set(environment);
533        }
534        self.fonts.get().ok_or_else(|| {
535            Error::Render("font environment was requested before canonical text preparation".into())
536        })
537    }
538}
539
540impl crate::text::TextRequestContext<'_, '_> {
541    pub(crate) fn measure_appearance_text<'a>(
542        &self,
543        source: &str,
544        appearance: impl Into<crate::text::TextAppearance<'a>>,
545        alignment: PhysicalTextAlignment,
546        owner: &str,
547    ) -> Result<ResolvedTextPlan, Error> {
548        crate::layout::fit::measured(crate::layout::text::request::measure_quanta(
549            self,
550            source,
551            appearance.into(),
552            i64::MAX,
553            alignment,
554            owner,
555            &crate::layout::fit::ROOT_SCOPE,
556        ))
557        .map_err(crate::layout::fit::PlanError::into_error)
558    }
559    /// Plan one foundational appearance within an exact finite pixel width.
560    #[cfg(test)]
561    pub(crate) fn plan_text(
562        &self,
563        source: &str,
564        appearance: &TextTheme,
565        maximum_width: f64,
566        alignment: PhysicalTextAlignment,
567        owner: &str,
568        exact_override: bool,
569    ) -> Result<ResolvedTextPlan, Error> {
570        if !maximum_width.is_finite() || maximum_width <= 0.0 {
571            return Err(Error::Render(
572                format!("{owner} has no positive finite width available for text layout").into(),
573            ));
574        }
575        let maximum_width_quanta = crate::layout::maximum_width_quanta(maximum_width)
576            .map_err(|error| Error::from(error).with_prefix(&format!("{owner} text planning")))?;
577        self.plan_text_quanta(
578            source,
579            appearance,
580            maximum_width_quanta,
581            alignment,
582            owner,
583            exact_override,
584        )
585    }
586
587    /// Common label width from contextual legal spans and the assigned row capacity.
588    #[expect(
589        clippy::cast_precision_loss,
590        reason = "axis label requirements are normalized layout quanta consumed by pixel adapters"
591    )]
592    pub(crate) fn intrinsic_tick_label_width<'a>(
593        &self,
594        labels: impl Iterator<Item = &'a str> + Clone,
595        available_height: f64,
596    ) -> Result<f64, crate::Error> {
597        self.text.prepare_font_environment()?;
598        let environment = self.text.prepared_font_environment()?;
599
600        let appearance = self.typography.get_axes().get_tick_label();
601        let height = crate::layout::maximum_width_quanta(available_height)
602            .map_err(|error| Error::from(error).with_prefix("axis row height"))?;
603        let count = i64::try_from(labels.clone().count().max(1))
604            .map_err(|_| crate::Error::Render("axis row count overflowed".into()))?;
605        let pitch = crate::layout::maximum_width_quanta(appearance.line_pitch_pixels())
606            .map_err(|error| Error::from(error).with_prefix("axis row pitch"))?;
607        if height < 0 || pitch <= 0 {
608            return Err(crate::Error::Render(
609                "axis row allocation requires nonnegative height and positive text pitch".into(),
610            ));
611        }
612        let preferred_lines = usize::try_from(((height / count - 4096).max(0) / pitch).max(1))
613            .map_err(|_| crate::Error::Render("axis row capacity overflowed".into()))?;
614        let mut width = 1_i64;
615        for source in labels {
616            let mut input = crate::layout::TextPlanInput {
617                size_trace: None,
618                direction: crate::text::TextDirection::Auto,
619                source,
620                stack: &appearance.stack,
621                weight: appearance.weight,
622                font_size: appearance.font_size,
623                line_height: crate::layout::TextLineHeight::Multiplier(
624                    appearance.line_height_multiplier,
625                ),
626                maximum_width_quanta: i64::MAX,
627                alignment: PhysicalTextAlignment::End,
628                paint: appearance.paint,
629                provenance: crate::layout::TextPlanProvenance {
630                    pair_ordinal: 0,
631                    owner: "y-axis tick label".into(),
632                },
633                exact_override: false,
634            };
635            input.provenance.pair_ordinal = environment
636                .admit_text(&appearance.stack, appearance.weight.into(), source, None)
637                .map_err(|error| Error::from(error).with_prefix("axis intrinsic text admission"))?;
638
639            let (cached, query_key) = self.cached_text_query(&input, Some(preferred_lines))?;
640            let preferred_width = if let Some(CachedTextResult::PreferredWidth(width)) = cached {
641                width
642            } else {
643                let analysis = if let Some(CachedTextResult::Reflow(plan)) = cached {
644                    plan
645                } else {
646                    let plan = environment.plan_text(input.clone()).map_err(|error| {
647                        Error::from(error).with_prefix("axis intrinsic text analysis")
648                    })?;
649                    self.cache_text_query(
650                        &input,
651                        appearance,
652                        None,
653                        CachedTextResult::Plan(plan.clone()),
654                        TextQueryKey {
655                            fingerprint: CachedTextQuery::presentation_fingerprint(
656                                query_key.shaping_state.clone(),
657                                &input,
658                                None,
659                            ),
660                            shaping_state: query_key.shaping_state.clone(),
661                            ..query_key
662                        },
663                    )?;
664                    plan
665                };
666                let requirements =
667                    analysis
668                        .intrinsic_from_analysis(preferred_lines)
669                        .map_err(|error| {
670                            Error::from(error).with_prefix("axis intrinsic text requirements")
671                        })?;
672                self.cache_text_query(
673                    &input,
674                    appearance,
675                    Some(preferred_lines),
676                    CachedTextResult::PreferredWidth(requirements.preferred_width_quanta),
677                    query_key,
678                )?;
679                requirements.preferred_width_quanta
680            };
681            width = width.max(preferred_width);
682        }
683        Ok(width as f64 / 1024.0)
684    }
685
686    /// Measure one foundational appearance without introducing a wrap boundary.
687    pub(crate) fn measure_text(
688        &self,
689        source: &str,
690        appearance: &TextTheme,
691        alignment: PhysicalTextAlignment,
692        owner: &str,
693        exact_override: bool,
694    ) -> Result<ResolvedTextPlan, Error> {
695        self.plan_text_quanta(
696            source,
697            appearance,
698            i64::MAX,
699            alignment,
700            owner,
701            exact_override,
702        )
703    }
704
705    fn plan_text_quanta(
706        &self,
707        source: &str,
708        appearance: &TextTheme,
709        maximum_width_quanta: i64,
710        alignment: PhysicalTextAlignment,
711        owner: &str,
712        exact_override: bool,
713    ) -> Result<ResolvedTextPlan, Error> {
714        self.plan_text_quanta_scoped(
715            source,
716            appearance,
717            maximum_width_quanta,
718            alignment,
719            owner,
720            exact_override,
721            crate::text::TextDirection::Auto,
722            &crate::layout::fit::ROOT_SCOPE,
723        )
724        .map_err(crate::layout::fit::PlanError::into_error)
725    }
726
727    #[expect(
728        clippy::too_many_arguments,
729        reason = "the shared adapter preserves every immutable text-plan input and the consuming fit scope"
730    )]
731    pub(crate) fn plan_text_quanta_scoped(
732        &self,
733        source: &str,
734        appearance: &TextTheme,
735        maximum_width_quanta: i64,
736        alignment: PhysicalTextAlignment,
737        owner: &str,
738        exact_override: bool,
739        direction: crate::text::TextDirection,
740        scope: &crate::layout::fit::FitScope,
741    ) -> Result<ResolvedTextPlan, crate::layout::fit::PlanError> {
742        let mut input = TextPlanInput {
743            size_trace: self.trial.size_trace.cloned(),
744            direction,
745            source,
746            stack: appearance.get_stack(),
747            weight: appearance.get_weight(),
748            font_size: appearance.get_font_size(),
749            line_height: TextLineHeight::Multiplier(appearance.get_line_height()),
750            maximum_width_quanta,
751            alignment,
752            paint: appearance.get_color(),
753            provenance: TextPlanProvenance {
754                pair_ordinal: 0,
755                owner: owner.to_owned(),
756            },
757            exact_override,
758        };
759        let environment = self.text.prepared_font_environment()?;
760        input.provenance.pair_ordinal = environment
761            .admit_text(
762                appearance.get_stack(),
763                appearance.get_weight().into(),
764                source,
765                None,
766            )
767            .map_err(|error| Error::from(error).with_prefix(&format!("{owner} text admission")))?;
768
769        // Size trials are deliberately not optional-cache entries: failed glyph
770        // arrays and their certificates die with this local candidate.
771        if self.trial.size_trace.is_some() {
772            return environment.plan_text(input).map_err(|error| match error {
773                crate::layout::TextPlanError::Fit(miss) => scope
774                    .failure(
775                        crate::layout::fit::FitKind::Text,
776                        format!("{owner} text planning: {miss}"),
777                    )
778                    .into(),
779                error => crate::layout::fit::PlanError::Fatal(
780                    Error::from(error).with_prefix(&format!("{owner} text planning")),
781                ),
782            });
783        }
784        let (cached, query_key) = self.cached_text_query(&input, None)?;
785
786        let result = match cached {
787            Some(CachedTextResult::Plan(plan)) => return Ok(plan),
788            Some(CachedTextResult::Reflow(plan)) => {
789                let (source, stack) = plan.analysis_profile().map_err(Error::from)?;
790                plan.reflow(TextPlanInput {
791                    source,
792                    stack,
793                    ..input.clone()
794                })
795            }
796            _ => environment.plan_text(input.clone()),
797        };
798        let plan = result.map_err(|error| match error {
799            crate::layout::TextPlanError::Fit(miss) => scope
800                .failure(
801                    crate::layout::fit::FitKind::Text,
802                    format!("{owner} text planning: {miss}"),
803                )
804                .into(),
805            error => crate::layout::fit::PlanError::Fatal(
806                Error::from(error).with_prefix(&format!("{owner} text planning")),
807            ),
808        })?;
809        self.cache_text_query(
810            &input,
811            appearance,
812            None,
813            CachedTextResult::Plan(plan.clone()),
814            query_key,
815        )?;
816
817        Ok(plan)
818    }
819
820    fn cached_text_query(
821        &self,
822        input: &TextPlanInput<'_>,
823        preferred_lines: Option<usize>,
824    ) -> Result<(Option<CachedTextResult>, TextQueryKey), Error> {
825        let cache = self
826            .text
827            .queries
828            .lock()
829            .map_err(|_| Error::Render("text query cache lock poisoned".into()))?;
830        let query_key = cache.query_key(input, preferred_lines);
831        let shaping_fingerprint = query_key.shaping_fingerprint;
832        let fingerprint = query_key.fingerprint;
833        let key = (input, preferred_lines);
834        if let Some(index) = cache.find_query(
835            &cache.exact,
836            fingerprint,
837            key,
838            true,
839            query_key.shaping_entry,
840        ) {
841            return Ok((Some(cache.entries[index].result.clone()), query_key));
842        }
843        if let Some(index) = cache.find_query(
844            &cache.shaping,
845            shaping_fingerprint,
846            key,
847            false,
848            query_key.shaping_entry,
849        ) {
850            let query = &cache.entries[index];
851
852            if query.matches_width(input.maximum_width_quanta)
853                && query.matches_presentation(input, preferred_lines)
854            {
855                return Ok((Some(query.result.clone()), query_key));
856            }
857            if let CachedTextResult::Plan(plan) = &query.result {
858                return Ok((Some(CachedTextResult::Reflow(plan.clone())), query_key));
859            }
860        }
861        Ok((None, query_key))
862    }
863
864    #[expect(
865        clippy::too_many_lines,
866        reason = "key proof, storage reservation, index insertion and payload freezing stay in one cache transaction"
867    )]
868    fn cache_text_query(
869        &self,
870        input: &TextPlanInput<'_>,
871        appearance: &TextTheme,
872        preferred_lines: Option<usize>,
873        result: CachedTextResult,
874        mut query_key: TextQueryKey,
875    ) -> Result<(), Error> {
876        let mut cache = self
877            .text
878            .queries
879            .lock()
880            .map_err(|_| Error::Render("text query cache lock poisoned".into()))?;
881        // This root-local memo is optional and bounded, never an all-width table.
882        if cache.entries.len() == 256 {
883            return Ok(());
884        }
885
886        if query_key.shaping_entry.is_none() && cache.entries.len() != query_key.observed_entries {
887            query_key.shaping_entry = cache.profile_entry(input);
888        }
889
890        let shaping_fingerprint = query_key.shaping_fingerprint;
891        let fingerprint = query_key.fingerprint;
892        let key = (input, preferred_lines);
893        if cache
894            .find_query(
895                &cache.exact,
896                fingerprint,
897                key,
898                true,
899                query_key.shaping_entry,
900            )
901            .is_some()
902        {
903            return Ok(());
904        }
905        let new_shaping = matches!(&result, CachedTextResult::Plan(_))
906            && cache
907                .find_query(
908                    &cache.shaping,
909                    shaping_fingerprint,
910                    key,
911                    false,
912                    query_key.shaping_entry,
913                )
914                .is_none();
915
916        TextQueryCache::reserve(&mut cache.entries)?;
917        TextQueryCache::reserve(&mut cache.exact)?;
918        if new_shaping {
919            TextQueryCache::reserve(&mut cache.shaping)?;
920            TextQueryCache::reserve(&mut cache.profiles)?;
921        }
922        let exact_record = TextQueryIndex {
923            fingerprint,
924            entry: cache.entries.len(),
925        };
926        let shaping_record = TextQueryIndex {
927            fingerprint: shaping_fingerprint,
928            entry: cache.entries.len(),
929        };
930        let exact_position = TextQueryCache::insertion_point(&cache.exact, exact_record);
931        let shaping_position = if new_shaping {
932            Some(TextQueryCache::insertion_point(
933                &cache.shaping,
934                shaping_record,
935            ))
936        } else {
937            None
938        };
939        let profile_position = if new_shaping {
940            Some(cache.profile_insertion_point(input))
941        } else {
942            None
943        };
944        let copy = |text: &str| -> Result<String, Error> {
945            let mut owned = String::new();
946            crate::operation::string(&owned, text.len())?;
947            owned
948                .try_reserve_exact(text.len())
949                .map_err(|_| Error::Render("cannot reserve text query key".into()))?;
950            owned.push_str(text);
951            Ok(owned)
952        };
953        let appearance = TextTheme::new(
954            appearance.get_stack().clone(),
955            appearance.get_color(),
956            appearance.get_font_size(),
957            appearance.get_weight(),
958            appearance.get_line_height(),
959        )?;
960        let source = if let Some(index) = query_key.shaping_entry {
961            Arc::clone(&cache.entries[index].source)
962        } else {
963            Arc::new(copy(input.source)?)
964        };
965        cache.entries.push(CachedTextQuery {
966            direction: input.direction,
967            shaping_entry: query_key.shaping_entry.unwrap_or(exact_record.entry),
968            shaping_state: query_key.shaping_state,
969            unwrapped_width: match &result {
970                CachedTextResult::Plan(plan) => plan
971                    .unwrapped_fit_width()
972                    .map_err(|error| Error::from(error).with_prefix("cached paragraph fit"))?,
973                CachedTextResult::PreferredWidth(_) | CachedTextResult::Reflow(_) => None,
974            },
975            source,
976            appearance,
977            alignment: input.alignment,
978            owner: copy(&input.provenance.owner)?,
979            pair_ordinal: input.provenance.pair_ordinal,
980            exact_override: input.exact_override,
981            width: input.maximum_width_quanta,
982            preferred_lines,
983            result,
984        });
985        cache.exact.insert(exact_position, exact_record);
986        if let Some(position) = shaping_position {
987            cache.shaping.insert(position, shaping_record);
988        }
989        if let Some(position) = profile_position {
990            cache.profiles.insert(position, exact_record.entry);
991        }
992        Ok(())
993    }
994}
995
996#[cfg(test)]
997const fn pair_ordinal(weight: TextWeight) -> u32 {
998    match weight {
999        TextWeight::Normal => 0,
1000        TextWeight::Semibold => 1,
1001        TextWeight::Bold => 2,
1002    }
1003}
1004
1005/// Paints applied to renderer-owned drawing surfaces.
1006#[derive(Debug, Clone, PartialEq)]
1007pub struct SurfaceTheme {
1008    /// Canvas root paint.
1009    pub(crate) canvas_root: Color,
1010    /// Plot panel paint.
1011    pub(crate) plot_panel: Color,
1012}
1013
1014impl SurfaceTheme {
1015    /// Construct complete surface paints; transparent paints are valid.
1016    pub fn new(canvas_root: Color, plot_panel: Color) -> Result<Self, Error> {
1017        Ok(Self {
1018            canvas_root,
1019            plot_panel,
1020        })
1021    }
1022
1023    /// Inspect the complete Canvas root paint.
1024    pub fn get_canvas_root(&self) -> Color {
1025        self.canvas_root
1026    }
1027
1028    /// Inspect the complete Plot panel paint.
1029    pub fn get_plot_panel(&self) -> Color {
1030        self.plot_panel
1031    }
1032
1033    /// Replace only the Canvas root paint.
1034    pub fn canvas_root(self, canvas_root: Color) -> Result<Self, Error> {
1035        Self::new(canvas_root, self.plot_panel)
1036    }
1037
1038    /// Replace only the Plot panel paint.
1039    pub fn plot_panel(self, plot_panel: Color) -> Result<Self, Error> {
1040        Self::new(self.canvas_root, plot_panel)
1041    }
1042}
1043
1044/// Complete text appearance for one semantic typography role.
1045#[derive(Debug, Clone, PartialEq)]
1046pub struct TextTheme {
1047    /// Ordered literal named and host-generic family preferences.
1048    pub(crate) stack: crate::font::canonical::FontStack,
1049    /// Text paint.
1050    pub(crate) paint: Color,
1051    /// Font size in actual CSS pixels.
1052    pub(crate) font_size: f64,
1053    /// Closed renderer-owned font weight.
1054    pub(crate) weight: TextWeight,
1055    /// Finite positive multiple of the font size used for line pitch.
1056    pub(crate) line_height_multiplier: f64,
1057}
1058
1059// Public construction/edits admit only finite positive leading, so complete
1060// field equality is reflexive and has no signed-zero normalization ambiguity.
1061impl Eq for TextTheme {}
1062
1063impl TextTheme {
1064    /// Construct one complete text role, using actual CSS pixels and a multiplier.
1065    pub fn new(
1066        stack: crate::font::canonical::FontStack,
1067        color: Color,
1068        font_size: f64,
1069        weight: TextWeight,
1070        line_height: f64,
1071    ) -> Result<Self, Error> {
1072        let value = Self {
1073            stack,
1074            paint: color,
1075            font_size,
1076            weight,
1077            line_height_multiplier: line_height,
1078        };
1079        value.validate()?;
1080        Ok(value)
1081    }
1082
1083    pub(crate) fn validate(&self) -> Result<(), Error> {
1084        if !self.font_size.is_finite() || self.font_size <= 0.0 {
1085            return Err(Error::Data(
1086                "text font size must be positive CSS pixels".into(),
1087            ));
1088        }
1089        if !self.line_height_multiplier.is_finite() || self.line_height_multiplier <= 0.0 {
1090            return Err(Error::Data(
1091                "text line height must be a finite positive multiplier".into(),
1092            ));
1093        }
1094        Ok(())
1095    }
1096
1097    /// Borrow this role's complete ordered font preferences.
1098    pub fn get_stack(&self) -> &crate::font::canonical::FontStack {
1099        &self.stack
1100    }
1101
1102    /// Inspect the complete text paint.
1103    pub fn get_color(&self) -> Color {
1104        self.paint
1105    }
1106
1107    /// Inspect the positive font size in actual CSS pixels.
1108    pub fn get_font_size(&self) -> f64 {
1109        self.font_size
1110    }
1111
1112    /// Inspect the closed font weight.
1113    pub fn get_weight(&self) -> TextWeight {
1114        self.weight
1115    }
1116
1117    /// Inspect the retained multiplier, without multiplying by the font size.
1118    pub fn get_line_height(&self) -> f64 {
1119        self.line_height_multiplier
1120    }
1121
1122    /// Replace only the complete font stack.
1123    pub fn stack(self, stack: crate::font::canonical::FontStack) -> Result<Self, Error> {
1124        Self::new(
1125            stack,
1126            self.paint,
1127            self.font_size,
1128            self.weight,
1129            self.line_height_multiplier,
1130        )
1131    }
1132
1133    /// Replace only the complete text paint.
1134    pub fn color(self, color: Color) -> Result<Self, Error> {
1135        Self::new(
1136            self.stack,
1137            color,
1138            self.font_size,
1139            self.weight,
1140            self.line_height_multiplier,
1141        )
1142    }
1143
1144    /// Replace only the positive CSS font size.
1145    pub fn font_size(self, font_size: f64) -> Result<Self, Error> {
1146        Self::new(
1147            self.stack,
1148            self.paint,
1149            font_size,
1150            self.weight,
1151            self.line_height_multiplier,
1152        )
1153    }
1154
1155    /// Replace only the font weight.
1156    pub fn weight(self, weight: TextWeight) -> Result<Self, Error> {
1157        Self::new(
1158            self.stack,
1159            self.paint,
1160            self.font_size,
1161            weight,
1162            self.line_height_multiplier,
1163        )
1164    }
1165
1166    /// Replace only the finite positive line-height multiplier.
1167    pub fn line_height(self, line_height: f64) -> Result<Self, Error> {
1168        Self::new(
1169            self.stack,
1170            self.paint,
1171            self.font_size,
1172            self.weight,
1173            line_height,
1174        )
1175    }
1176
1177    pub(crate) fn same(&self, other: &Self) -> bool {
1178        self.font_size.to_bits() == other.font_size.to_bits()
1179            && self.weight == other.weight
1180            && self.paint == other.paint
1181            && self.line_height_multiplier.to_bits() == other.line_height_multiplier.to_bits()
1182            && self.stack.same(&other.stack)
1183    }
1184
1185    pub(crate) fn try_copy(&self) -> Result<Self, Error> {
1186        Self::new(
1187            self.stack.try_copy().map_err(Error::from)?,
1188            self.get_color(),
1189            self.get_font_size(),
1190            self.get_weight(),
1191            self.get_line_height(),
1192        )
1193    }
1194    /// Resolve this role's current line pitch in pixels.
1195    pub(crate) fn line_pitch_pixels(&self) -> f64 {
1196        self.font_size * self.line_height_multiplier
1197    }
1198}
1199
1200#[allow(
1201    clippy::too_many_arguments,
1202    clippy::too_many_lines,
1203    reason = "the four closed presets provide one compact table of preserved scalar values"
1204)]
1205fn resolved_theme(
1206    colors: &[(u8, u8, u8)],
1207    foreground: (u8, u8, u8),
1208    axis_width: f32,
1209    bracket_width: f32,
1210    title_font_size: u32,
1211    subtitle_font_size: u32,
1212    caption_font_size: u32,
1213    axis_title_font_size: u32,
1214    grid_color: (u8, u8, u8),
1215) -> Result<Theme, Error> {
1216    let stack = crate::font::canonical::builtin_font_stack();
1217    let foreground_paint = color_from_rgb(foreground);
1218    let muted_paint = color_from_rgb(MUTED_TEXT);
1219    let opaque = |&(r, g, b): &(u8, u8, u8)| OpaqueColor::rgb(r, g, b);
1220    let color_scales = ColorScales::new(
1221        QualitativePalette::extendable(colors.iter().map(opaque))?,
1222        SequentialGradient::new(crate::theme::HEATMAP_SEQUENTIAL_STOPS)?,
1223        DivergingGradient::new(crate::theme::HEATMAP_DIVERGING_STOPS)?,
1224    )?;
1225    let accents = AccentPalette::new(colors.iter().map(opaque))?;
1226    let stroke = |width, pattern| StrokeTheme::new(foreground_paint, width, pattern);
1227    let text = |paint, font_size: u32, line_height| {
1228        TextTheme::new(
1229            stack.clone(),
1230            paint,
1231            f64::from(font_size),
1232            TextWeight::Normal,
1233            line_height,
1234        )
1235    };
1236
1237    let value = Theme {
1238        color_scales,
1239        surfaces: SurfaceTheme::new(Color::rgb(255, 255, 255), Color::rgb(255, 255, 255))?,
1240        typography: TypographyTheme::new(
1241            RootTextRoles::new(
1242                text(
1243                    foreground_paint,
1244                    title_font_size,
1245                    plus_six_line_height(title_font_size),
1246                )?,
1247                text(
1248                    muted_paint,
1249                    subtitle_font_size,
1250                    plus_six_line_height(subtitle_font_size),
1251                )?,
1252                text(
1253                    muted_paint,
1254                    caption_font_size,
1255                    plus_six_line_height(caption_font_size),
1256                )?,
1257            )?,
1258            AxisTextRoles::new(
1259                text(foreground_paint, axis_title_font_size, 1.2)?,
1260                text(foreground_paint, TICK_FONT_SIZE, 1.2)?,
1261            )?,
1262            GuideTextRoles::new(
1263                text(Color::rgb(60, 60, 60), 12, 1.2)?,
1264                text(Color::rgb(40, 40, 40), 11, 1.2)?,
1265            )?,
1266            CompositionTextRoles::new(
1267                text(foreground_paint, subtitle_font_size, 1.2)?,
1268                text(foreground_paint, title_font_size, 1.2)?,
1269                text(foreground_paint, title_font_size, 1.2)?,
1270                text(foreground_paint, axis_title_font_size, 1.2)?,
1271            )?,
1272            AnnotationTextRoles::new(
1273                text(foreground_paint, SIGNIFICANCE_FONT_SIZE, 1.2)?,
1274                text(foreground_paint, 14, 1.2)?,
1275                text(foreground_paint, 14, 1.2)?,
1276                text(foreground_paint, 10, 1.2)?,
1277                text(foreground_paint, 14, 1.2)?,
1278                ContrastTextRoles::new(
1279                    text(Color::rgb(255, 255, 255), 11, 1.2)?,
1280                    text(Color::rgb(0, 0, 0), 11, 1.2)?,
1281                )?,
1282            )?,
1283        )?,
1284        legend: LegendTheme::builtin()?,
1285        axes: AxisTheme::new(
1286            Some(FrameTheme::new(
1287                FrameSides::new(true, true, true, true)?,
1288                stroke(axis_width, LinePattern::Solid)?,
1289            )?),
1290            Some(FrameTheme::new(
1291                FrameSides::new(false, false, true, true)?,
1292                stroke(axis_width, LinePattern::Solid)?,
1293            )?),
1294            Some(TickTheme::new(stroke(axis_width, LinePattern::Solid)?, 5)?),
1295            Some(StrokeTheme::new(
1296                color_from_rgb(grid_color),
1297                0.5,
1298                LinePattern::MediumDash,
1299            )?),
1300            AxisSpacing::new(
1301                super::RelativeSpacing::ratio(8, 16)?,
1302                super::RelativeSpacing::ratio(6, 16)?,
1303                super::RelativeSpacing::ratio(8, axis_title_font_size)?,
1304                super::RelativeSpacing::ratio(16, axis_title_font_size)?,
1305                super::RelativeSpacing::ratio(16, axis_title_font_size)?,
1306                super::RelativeSpacing::ratio(12, axis_title_font_size)?,
1307            )?,
1308        )?,
1309        marks: MarkTheme::builtin(accents, opaque(&foreground), axis_width)?,
1310        annotations: AnnotationTheme::builtin(foreground_paint, bracket_width)?,
1311        composition: super::CompositionTheme::builtin(
1312            title_font_size,
1313            subtitle_font_size,
1314            caption_font_size,
1315            axis_title_font_size,
1316        )?,
1317    };
1318    Theme::new(
1319        value.surfaces,
1320        value.typography,
1321        value.axes,
1322        value.legend,
1323        value.composition,
1324        value.marks,
1325        value.annotations,
1326        value.color_scales,
1327    )
1328}
1329
1330fn plus_six_line_height(font_size: u32) -> f64 {
1331    (f64::from(font_size) + 6.0) / f64::from(font_size)
1332}
1333
1334pub(super) fn publication_theme() -> Result<Theme, Error> {
1335    // Okabe-Ito 8-color qualitative palette (colorblind-safe).
1336    resolved_theme(
1337        &[
1338            (0, 114, 178),
1339            (213, 94, 0),
1340            (0, 158, 115),
1341            (204, 121, 167),
1342            (86, 180, 233),
1343            (230, 159, 0),
1344            (240, 228, 66),
1345            (0, 0, 0),
1346        ],
1347        (0, 0, 0),
1348        0.8,
1349        1.0,
1350        20,
1351        15,
1352        15,
1353        17,
1354        (220, 220, 220),
1355    )
1356}
1357
1358pub(super) fn nature_theme() -> Result<Theme, Error> {
1359    resolved_theme(
1360        &[
1361            (40, 86, 130),
1362            (130, 160, 188),
1363            (200, 215, 230),
1364            (120, 130, 90),
1365            (180, 175, 130),
1366        ],
1367        (40, 40, 40),
1368        0.8,
1369        0.8,
1370        19,
1371        14,
1372        14,
1373        16,
1374        (230, 230, 230),
1375    )
1376}
1377
1378pub(super) fn science_theme() -> Result<Theme, Error> {
1379    resolved_theme(
1380        &[
1381            (255, 0, 0),
1382            (0, 0, 255),
1383            (0, 175, 0),
1384            (255, 175, 0),
1385            (160, 32, 240),
1386        ],
1387        (0, 0, 0),
1388        1.0,
1389        1.0,
1390        21,
1391        16,
1392        15,
1393        17,
1394        (200, 200, 200),
1395    )
1396}
1397
1398pub(super) fn chi_theme() -> Result<Theme, Error> {
1399    resolved_theme(
1400        &[
1401            (171, 199, 232),
1402            (243, 169, 175),
1403            (174, 224, 174),
1404            (244, 213, 152),
1405            (197, 176, 213),
1406        ],
1407        (60, 60, 60),
1408        0.8,
1409        0.8,
1410        19,
1411        15,
1412        15,
1413        17,
1414        (220, 220, 220),
1415    )
1416}
1417
1418#[cfg(test)]
1419mod tests {
1420    use super::*;
1421
1422    fn indexed_query_input<'a>(
1423        source: &'a str,
1424        appearance: &'a TextTheme,
1425        owner: &str,
1426    ) -> TextPlanInput<'a> {
1427        TextPlanInput {
1428            size_trace: None,
1429            direction: crate::text::TextDirection::Auto,
1430            source,
1431            stack: &appearance.stack,
1432            weight: appearance.weight,
1433            font_size: appearance.font_size,
1434            line_height: TextLineHeight::Multiplier(appearance.line_height_multiplier),
1435            maximum_width_quanta: 100 * 1024,
1436            alignment: PhysicalTextAlignment::Start,
1437            paint: appearance.paint,
1438            provenance: TextPlanProvenance {
1439                pair_ordinal: pair_ordinal(appearance.weight),
1440                owner: owner.into(),
1441            },
1442            exact_override: false,
1443        }
1444    }
1445
1446    #[test]
1447    #[expect(
1448        clippy::too_many_lines,
1449        reason = "one root verifies indexed lookup, stable collision order, and complete matching"
1450    )]
1451    fn indexed_text_queries_preserve_matching_and_collision_order() {
1452        let root = Theme::publication().resolve().unwrap();
1453        let text = TextService::default();
1454        let root = crate::text::TextRequestContext::new(&root, &text);
1455        root.text
1456            .fonts
1457            .set(PreparedFontEnvironment::synthetic())
1458            .unwrap();
1459        let environment = root.text.prepared_font_environment().unwrap();
1460        let resources = environment.operation().unwrap();
1461        environment.validate_operation(&resources).unwrap();
1462        let mut appearance = root.typography.root.caption.clone();
1463        appearance.stack = crate::font::canonical::named_stack(&["Test Sans"]);
1464        appearance.font_size = 10.0;
1465        let mut first = None;
1466        for index in 0..128 {
1467            let plan = root
1468                .plan_text(
1469                    "A",
1470                    &appearance,
1471                    100.0,
1472                    PhysicalTextAlignment::Start,
1473                    &format!("owner {index:03}"),
1474                    false,
1475                )
1476                .unwrap();
1477            if index == 0 {
1478                first = Some(plan);
1479            }
1480        }
1481        {
1482            let cache = root.text.queries.lock().unwrap();
1483            assert_eq!(cache.entries.len(), 128);
1484            assert_eq!(cache.exact.len(), 128);
1485            assert_eq!(
1486                cache.shaping.len(),
1487                1,
1488                "one analysis representative per compatible font/source profile"
1489            );
1490            assert!(cache.exact.windows(2).all(|pair| pair[0] < pair[1]));
1491        }
1492
1493        let hit = root
1494            .plan_text(
1495                "A",
1496                &appearance,
1497                100.0,
1498                PhysicalTextAlignment::Start,
1499                "owner 000",
1500                false,
1501            )
1502            .unwrap();
1503        assert!(first.unwrap().shares_payload(&hit));
1504
1505        root.plan_text(
1506            "AA",
1507            &appearance,
1508            100.0,
1509            PhysicalTextAlignment::Start,
1510            "collision",
1511            false,
1512        )
1513        .unwrap();
1514        let collision = indexed_query_input("AA", &appearance, "collision");
1515        let mut cache = root.text.queries.lock().unwrap();
1516        let expected = cache.entries.len() - 1;
1517        let TextQueryCache { exact, shaping, .. } = &mut *cache;
1518        for index in [exact, shaping] {
1519            for entry in index.iter_mut() {
1520                entry.fingerprint = [0; 32];
1521            }
1522            index.sort_unstable();
1523        }
1524
1525        assert_eq!(
1526            cache.find_query(
1527                &cache.exact,
1528                [0; 32],
1529                (&collision, None),
1530                true,
1531                Some(expected)
1532            ),
1533            Some(expected)
1534        );
1535
1536        assert_eq!(
1537            cache.find_query(
1538                &cache.shaping,
1539                [0; 32],
1540                (&collision, None),
1541                false,
1542                Some(expected)
1543            ),
1544            Some(expected)
1545        );
1546
1547        let mut wrong_provenance = collision.clone();
1548        wrong_provenance.provenance.pair_ordinal += 1;
1549        assert!(cache
1550            .find_query(
1551                &cache.exact,
1552                [0; 32],
1553                (&wrong_provenance, None),
1554                true,
1555                Some(expected)
1556            )
1557            .is_none());
1558        assert_eq!(
1559            cache.find_query(
1560                &cache.shaping,
1561                [0; 32],
1562                (&wrong_provenance, None),
1563                false,
1564                Some(expected)
1565            ),
1566            Some(expected)
1567        );
1568    }
1569
1570    #[test]
1571    fn retained_profile_does_not_trust_a_reused_mutable_input_address() {
1572        let theme = Theme::publication().resolve().unwrap();
1573        let text = TextService::default();
1574        let theme = crate::text::TextRequestContext::new(&theme, &text);
1575        theme
1576            .text
1577            .fonts
1578            .set(PreparedFontEnvironment::synthetic_faces(&[(
1579                "Literal",
1580                &['A', 'X'],
1581            )]))
1582            .unwrap();
1583        let appearance = TextTheme {
1584            stack: crate::font::canonical::named_stack(&["Literal"]),
1585            font_size: 10.0,
1586            ..theme.typography.root.caption.clone()
1587        };
1588        let mut source = String::with_capacity(16);
1589        source.push('A');
1590        let address = source.as_ptr();
1591        let first = theme
1592            .plan_text(
1593                &source,
1594                &appearance,
1595                100.0,
1596                PhysicalTextAlignment::Start,
1597                "mutable input",
1598                false,
1599            )
1600            .unwrap();
1601        source.replace_range(.., "X");
1602        assert_eq!(source.as_ptr(), address);
1603        let second = theme
1604            .plan_text(
1605                &source,
1606                &appearance,
1607                100.0,
1608                PhysicalTextAlignment::Start,
1609                "mutable input",
1610                false,
1611            )
1612            .unwrap();
1613        assert!(!first.shares_payload(&second));
1614        assert_eq!(second.source, "X");
1615        assert_eq!(theme.text.queries.lock().unwrap().profiles.len(), 2);
1616    }
1617
1618    #[test]
1619    fn later_font_admissions_preserve_cached_shapes_and_complete_request_payloads() {
1620        let theme = Theme::publication().resolve().unwrap();
1621        let text = TextService::default();
1622        let theme = crate::text::TextRequestContext::new(&theme, &text);
1623        theme
1624            .text
1625            .fonts
1626            .set(PreparedFontEnvironment::synthetic_faces(&[
1627                ("Base", &['A']),
1628                ("Complete", &['A', '\u{301}']),
1629            ]))
1630            .unwrap();
1631        let appearance = TextTheme {
1632            stack: crate::font::canonical::named_stack(&["Base", "Complete"]),
1633            ..theme.typography.root.caption.clone()
1634        };
1635        let measure = |source| {
1636            theme
1637                .measure_text(
1638                    source,
1639                    &appearance,
1640                    PhysicalTextAlignment::Start,
1641                    "actual source",
1642                    true,
1643                )
1644                .unwrap()
1645        };
1646        let first = measure("A");
1647        let marked = measure("A\u{301}");
1648        assert_ne!(first.lines[0].runs[0].face, marked.lines[0].runs[0].face);
1649        let counts = crate::font::canonical::planning_counts();
1650        assert!(first.shares_payload(&measure("A")));
1651        assert!(marked.shares_payload(&measure("A\u{301}")));
1652        assert_eq!(crate::font::canonical::planning_counts(), counts);
1653        theme
1654            .text
1655            .prepared_font_environment()
1656            .unwrap()
1657            .operation()
1658            .unwrap()
1659            .seal_fonts()
1660            .unwrap();
1661        let counts = crate::font::canonical::planning_counts();
1662        assert!(first.shares_payload(&measure("A")));
1663        assert!(marked.shares_payload(&measure("A\u{301}")));
1664        assert_eq!(crate::font::canonical::planning_counts(), counts);
1665        assert_eq!(theme.text.queries.lock().unwrap().entries.len(), 2);
1666    }
1667
1668    #[test]
1669    fn text_cache_stops_optional_insertion_without_refusing_rendering() {
1670        let root = Theme::publication().resolve().unwrap();
1671        let text = TextService::default();
1672        let root = crate::text::TextRequestContext::new(&root, &text);
1673        root.text
1674            .fonts
1675            .set(PreparedFontEnvironment::synthetic())
1676            .unwrap();
1677        let mut appearance = root.typography.root.caption.clone();
1678        appearance.stack = crate::font::canonical::named_stack(&["Test Sans"]);
1679        let render = |owner: &str| {
1680            root.measure_text("A", &appearance, PhysicalTextAlignment::Start, owner, false)
1681                .unwrap()
1682        };
1683        let first = render("first");
1684        for index in 1..256 {
1685            render(&format!("owner {index}"));
1686        }
1687        assert_eq!(root.text.queries.lock().unwrap().entries.len(), 256);
1688        assert_eq!(render("uncached owner").source, "A");
1689        assert_eq!(root.text.queries.lock().unwrap().entries.len(), 256);
1690        assert!(first.shares_payload(&render("first")));
1691    }
1692}