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