Skip to main content

lichtung_plot/layout/text/
requirements.rs

1//! Canonically ordered text and font-pair preparation requirements.
2
3use std::borrow::Cow;
4
5use crate::builder::PlotDescription;
6#[cfg(test)]
7use crate::font::canonical::RequestedWeight;
8use crate::font::canonical::{
9    self, CensusSource, FontPairPreparationRequest, FontStack, PreparedFontEnvironment,
10};
11use crate::layout::kernel::ComponentAddress;
12use crate::theme::TextTheme;
13use crate::{plots::PlotKind, text::TextWeight, Error};
14
15const SCALAR_MAP_WORDS: usize = 0x11_0000 / u64::BITS as usize;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18pub(crate) enum PreparedTextRole {
19    Title,
20    Subtitle,
21    Caption,
22    AxisTitle,
23    TickLabel,
24    SignificanceLabel,
25    LegendTitle,
26    LegendLabel,
27    Header,
28    Annotation,
29    Body,
30    PreferenceMetric,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub(crate) struct PreparedTextRequirement {
35    pub(crate) component_address: ComponentAddress,
36    pub(crate) text_role: PreparedTextRole,
37    pub(crate) local_index: u32,
38    pub(crate) source: String,
39    pub(crate) generated_alphabet: Box<[char]>,
40    pub(crate) stack: FontStack,
41    pub(crate) weight: TextWeight,
42    pub(crate) pair_ordinal: u32,
43}
44
45impl PreparedTextRequirement {
46    /// Role-local `ch` metrics are known actual sources, prepared along with
47    /// authored text before bounded layout starts.
48    pub(crate) fn append_preference_metrics(
49        requirements: &mut Vec<Self>,
50        theme: &crate::text::TextRequestContext<'_, '_>,
51        owner: &ComponentAddress,
52        stage: &mut crate::layout::kernel::PreparedStage<'_>,
53    ) -> Result<(), Error> {
54        for (index, appearance) in [
55            &theme.typography.root.title,
56            &theme.typography.root.subtitle,
57            &theme.typography.root.caption,
58            &theme.typography.axes.tick_label,
59            &theme.typography.guides.legend_title,
60            &theme.typography.guides.legend_label,
61            &theme.typography.composition.composition_header,
62            &theme.typography.composition.text_panel_title,
63            &theme.typography.composition.facet_header,
64            &theme.typography.composition.body,
65        ]
66        .into_iter()
67        .enumerate()
68        {
69            let mut used = false;
70            for requirement in requirements.iter() {
71                if requirement.weight == appearance.weight
72                    && requirement.stack.same(&appearance.stack)
73                {
74                    used = true;
75                    break;
76                }
77            }
78            if !used {
79                continue;
80            }
81            let address = owner.child(
82                crate::layout::AddressRole::PreferenceMetric,
83                u32::try_from(index).map_err(|_| {
84                    Error::Render("preference metric census address overflowed".into())
85                })?,
86            )?;
87            Self::push_into(
88                requirements,
89                address,
90                PreparedTextRole::PreferenceMetric,
91                0,
92                "0",
93                &[],
94                appearance,
95                Some(stage),
96            )
97            .map_err(|error| Error::from(error).with_prefix("preference metric census"))?;
98        }
99        Ok(())
100    }
101    #[expect(
102        clippy::too_many_arguments,
103        reason = "admission receives the complete borrowed text identity"
104    )]
105    pub(crate) fn push_into<'a, 'b>(
106        requirements: &mut Vec<Self>,
107        address: ComponentAddress,
108        role: PreparedTextRole,
109        local_index: u32,
110        source: impl Into<CensusSource<'a>>,
111        generated_alphabet: &[char],
112        appearance: impl Into<crate::text::TextAppearance<'b>>,
113        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
114    ) -> Result<(), PreparedTextCensusError> {
115        let appearance = appearance.into();
116        if appearance.hidden() {
117            return Ok(());
118        }
119        #[cfg(not(test))]
120        if prepared_stage.is_none() {
121            return Err(PreparedTextCensusError::MissingPreparedStage);
122        }
123        reserve_census_vec(
124            requirements,
125            1,
126            "prepared text requirements",
127            prepared_stage.as_deref_mut(),
128        )?;
129        requirements.push(Self::new_with_stage(
130            address,
131            role,
132            local_index,
133            source,
134            generated_alphabet,
135            appearance.theme,
136            prepared_stage,
137        )?);
138        Ok(())
139    }
140
141    #[cfg(test)]
142    pub(crate) fn new<'a>(
143        component_address: ComponentAddress,
144        text_role: PreparedTextRole,
145        local_index: u32,
146        source: impl Into<CensusSource<'a>>,
147        generated_alphabet: &[char],
148        appearance: &TextTheme,
149    ) -> Result<Self, PreparedTextCensusError> {
150        Self::new_with_stage(
151            component_address,
152            text_role,
153            local_index,
154            source,
155            generated_alphabet,
156            appearance,
157            None,
158        )
159    }
160
161    fn new_with_stage<'a>(
162        component_address: ComponentAddress,
163        text_role: PreparedTextRole,
164        local_index: u32,
165        source: impl Into<CensusSource<'a>>,
166        generated_alphabet: &[char],
167        appearance: &TextTheme,
168        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
169    ) -> Result<Self, PreparedTextCensusError> {
170        if generated_alphabet.windows(2).any(|pair| pair[0] >= pair[1]) {
171            return Err(PreparedTextCensusError::GeneratedAlphabetOrder);
172        }
173        let source = source.into();
174        let stack_source = &appearance.stack;
175
176        let (source, formatted) = match source {
177            CensusSource::Text(source) => (source, false),
178            CensusSource::Formatted(arguments) => (
179                Cow::Owned(canonical::format_census_source(
180                    arguments,
181                    prepared_stage.as_deref_mut(),
182                )?),
183                true,
184            ),
185        };
186        crate::text::validate(&source).map_err(|error| {
187            canonical::FontError::UnsupportedControl {
188                scalar: error.scalar,
189            }
190        })?;
191        let retained_source = match source {
192            Cow::Borrowed(source) => {
193                let mut retained = String::new();
194                reserve_census_string(
195                    &mut retained,
196                    source.len(),
197                    "prepared text source",
198                    prepared_stage.as_deref_mut(),
199                )?;
200                retained.push_str(source);
201                retained
202            }
203            Cow::Owned(mut source) => {
204                // Semantic display producers already own this string; transfer it,
205                // rather than allocating a second census copy.
206                if let Some(stage) = prepared_stage.as_deref_mut().filter(|_| !formatted) {
207                    stage
208                        .reserve_prepared_string(&mut source, 0, "prepared semantic text source")
209                        .map_err(PreparedTextCensusError::Reservation)?;
210                }
211                source
212            }
213        };
214        let mut retained_alphabet = Vec::new();
215        reserve_census_vec(
216            &mut retained_alphabet,
217            generated_alphabet.len(),
218            "prepared generated alphabet",
219            prepared_stage.as_deref_mut(),
220        )?;
221        let stack = stack_source.copy_with_stage(prepared_stage)?;
222        retained_alphabet.extend_from_slice(generated_alphabet);
223        Ok(Self {
224            component_address,
225            text_role,
226            local_index,
227            source: retained_source,
228            generated_alphabet: retained_alphabet.into_boxed_slice(),
229            stack,
230            weight: appearance.weight,
231            pair_ordinal: u32::MAX,
232        })
233    }
234
235    fn scalar_occurrence_count(&self) -> Result<u64, PreparedTextCensusError> {
236        self.source
237            .chars()
238            .count()
239            .checked_add(usize::from(self.source.contains('\u{00AD}')))
240            .and_then(|count| count.checked_add(self.generated_alphabet.len()))
241            .and_then(|count| u64::try_from(count).ok())
242            .ok_or(PreparedTextCensusError::Arithmetic(
243                "prepared text scalar occurrences",
244            ))
245    }
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub(crate) struct PreparedFontPairRequirement {
250    pub(crate) pair_ordinal: u32,
251    pub(crate) stack: FontStack,
252    pub(crate) weight: TextWeight,
253    pub(crate) required_scalars: Vec<char>,
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257pub(crate) struct PreparedTextCensusCounts {
258    pub(crate) requirements: u128,
259    pub(crate) pairs: u128,
260    pub(crate) structural_addresses: u128,
261    pub(crate) scalar_occurrences: u128,
262    pub(crate) unique_pair_scalars: u128,
263}
264
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub(crate) struct PreparedTextCensus {
267    pub(crate) requirements: Vec<PreparedTextRequirement>,
268    pub(crate) pairs: Vec<PreparedFontPairRequirement>,
269    pub(crate) counts: PreparedTextCensusCounts,
270}
271
272impl PreparedTextCensus {
273    pub(crate) fn structural_address_count(
274        requirements: &[PreparedTextRequirement],
275    ) -> Result<u128, PreparedTextCensusError> {
276        requirements
277            .iter()
278            .enumerate()
279            .filter(|(index, requirement)| {
280                !requirements[..*index]
281                    .iter()
282                    .any(|earlier| earlier.component_address == requirement.component_address)
283            })
284            .try_fold(0_u128, |count, _| {
285                count
286                    .checked_add(1)
287                    .ok_or(PreparedTextCensusError::Arithmetic(
288                        "prepared text structural addresses",
289                    ))
290            })
291    }
292
293    #[expect(
294        clippy::too_many_lines,
295        reason = "the census reserves all pair shells before assigning canonical first-use ordinals"
296    )]
297    pub(crate) fn materialize(
298        mut requirements: Vec<PreparedTextRequirement>,
299        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
300        scalar_presence: Option<&mut [u64]>,
301    ) -> Result<Self, PreparedTextCensusError> {
302        #[cfg(not(test))]
303        if prepared_stage.is_none() {
304            return Err(PreparedTextCensusError::MissingPreparedStage);
305        }
306
307        requirements.sort_unstable_by(|left, right| {
308            left.component_address
309                .canonical_text_cmp(&right.component_address)
310                .then_with(|| left.text_role.cmp(&right.text_role))
311                .then_with(|| left.local_index.cmp(&right.local_index))
312        });
313        if requirements.windows(2).any(|pair| {
314            pair[0].component_address == pair[1].component_address
315                && pair[0].text_role == pair[1].text_role
316                && pair[0].local_index == pair[1].local_index
317        }) {
318            return Err(PreparedTextCensusError::DuplicateIdentity);
319        }
320        let mut pair_count = 0;
321        for index in 0..requirements.len() {
322            if pair_first_use(&requirements, index) {
323                pair_count += 1;
324            }
325        }
326        let mut first_use_indices = Vec::new();
327        reserve_census_vec(
328            &mut first_use_indices,
329            pair_count,
330            "prepared font pair first uses",
331            prepared_stage.as_deref_mut(),
332        )?;
333        for index in 0..requirements.len() {
334            if pair_first_use(&requirements, index) {
335                first_use_indices.push(index);
336            }
337        }
338        let mut retained_stacks = Vec::new();
339        reserve_census_vec(
340            &mut retained_stacks,
341            pair_count,
342            "prepared font pair retained stacks",
343            prepared_stage.as_deref_mut(),
344        )?;
345        for index in &first_use_indices {
346            retained_stacks.push(retain_family_stack(
347                &requirements[*index].stack,
348                prepared_stage.as_deref_mut(),
349            )?);
350        }
351        let mut pairs: Vec<PreparedFontPairRequirement> = Vec::new();
352        reserve_census_vec(
353            &mut pairs,
354            pair_count,
355            "prepared font pairs",
356            prepared_stage.as_deref_mut(),
357        )?;
358        for (pair_index, (&requirement_index, stack)) in
359            first_use_indices.iter().zip(retained_stacks).enumerate()
360        {
361            let requirement = &requirements[requirement_index];
362            pairs.push(PreparedFontPairRequirement {
363                pair_ordinal: u32::try_from(pair_index)
364                    .map_err(|_| PreparedTextCensusError::Arithmetic("font pair ordinal"))?,
365                stack,
366                weight: requirement.weight,
367                required_scalars: Vec::new(),
368            });
369        }
370        for requirement_index in 0..requirements.len() {
371            let mut pair_index = None;
372            for (ordinal, index) in first_use_indices.iter().enumerate() {
373                if requirements[*index].weight == requirements[requirement_index].weight
374                    && requirements[*index]
375                        .stack
376                        .same(&requirements[requirement_index].stack)
377                {
378                    pair_index = Some(ordinal);
379                    break;
380                }
381            }
382            let pair_index = pair_index.ok_or(PreparedTextCensusError::MissingPair)?;
383            requirements[requirement_index].pair_ordinal = u32::try_from(pair_index)
384                .map_err(|_| PreparedTextCensusError::Arithmetic("font pair ordinal"))?;
385        }
386        let unique_pair_scalars = if let Some(presence) = scalar_presence {
387            reserve_required_scalar_capacities(&requirements, &mut pairs, presence, prepared_stage)?
388        } else {
389            0
390        };
391
392        if pairs.len() != pair_count {
393            return Err(PreparedTextCensusError::Arithmetic(
394                "prepared font pair count/materialization mismatch",
395            ));
396        }
397        let structural_addresses = Self::structural_address_count(&requirements)?;
398        let scalar_occurrences = requirements.iter().try_fold(0_u128, |total, requirement| {
399            total
400                .checked_add(u128::from(requirement.scalar_occurrence_count()?))
401                .ok_or(PreparedTextCensusError::Arithmetic(
402                    "prepared text scalar occurrences",
403                ))
404        })?;
405
406        Ok(Self {
407            counts: PreparedTextCensusCounts {
408                requirements: requirements.len() as u128,
409                pairs: pairs.len() as u128,
410                structural_addresses,
411                scalar_occurrences,
412                unique_pair_scalars,
413            },
414            requirements,
415            pairs,
416        })
417    }
418
419    pub(crate) fn pair_ordinal(
420        &self,
421        stack: &FontStack,
422        weight: TextWeight,
423    ) -> Result<u32, PreparedTextCensusError> {
424        for pair in &self.pairs {
425            if pair.weight == weight && pair.stack.same(stack) {
426                return Ok(pair.pair_ordinal);
427            }
428        }
429        Err(PreparedTextCensusError::MissingPair)
430    }
431
432    pub(crate) fn prepare_system_fonts(
433        &mut self,
434        mut presence: Vec<u64>,
435        prepared_stage: &mut crate::layout::kernel::PreparedStage<'_>,
436    ) -> Result<PreparedFontEnvironment, PreparedTextCensusError> {
437        self.materialize_required_scalars(&mut presence, Some(prepared_stage))?;
438        let environment =
439            PreparedFontEnvironment::discover_for_operation(presence, prepared_stage)?;
440        self.prepare_pairs_in(&environment, Some(prepared_stage))?;
441        Ok(environment)
442    }
443
444    fn scalar_occurrence_count(&self) -> Result<u64, PreparedTextCensusError> {
445        u64::try_from(self.counts.scalar_occurrences)
446            .map_err(|_| PreparedTextCensusError::Arithmetic("prepared text scalar occurrences"))
447    }
448
449    fn materialize_required_scalars(
450        &mut self,
451        presence: &mut [u64],
452        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
453    ) -> Result<(), PreparedTextCensusError> {
454        if presence.len() != SCALAR_MAP_WORDS {
455            return Err(PreparedTextCensusError::Arithmetic(
456                "Unicode scalar presence map",
457            ));
458        }
459        let mut capacities = Vec::new();
460        reserve_census_vec(
461            &mut capacities,
462            self.pairs.len(),
463            "required pair scalar capacities",
464            prepared_stage.as_deref_mut(),
465        )?;
466        let mut unique_pair_scalars = 0_u128;
467        for pair in &self.pairs {
468            presence.fill(0);
469            let mut unique_count = 0_usize;
470            visit_pair_scalars(&self.requirements, pair.pair_ordinal, |scalar| {
471                let value = scalar as usize;
472                let word = &mut presence[value / u64::BITS as usize];
473                let bit = 1_u64 << (value % u64::BITS as usize);
474                if *word & bit == 0 {
475                    *word |= bit;
476                    unique_count =
477                        unique_count
478                            .checked_add(1)
479                            .ok_or(PreparedTextCensusError::Arithmetic(
480                                "prepared text unique scalars",
481                            ))?;
482                }
483                Ok(())
484            })?;
485            unique_pair_scalars = unique_pair_scalars
486                .checked_add(unique_count as u128)
487                .ok_or(PreparedTextCensusError::Arithmetic(
488                    "prepared text unique scalars",
489                ))?;
490            capacities.push(unique_count);
491        }
492        if capacities.len() != self.pairs.len() {
493            return Err(PreparedTextCensusError::Arithmetic(
494                "required pair scalar capacity count/materialization mismatch",
495            ));
496        }
497        for (pair, unique_count) in self.pairs.iter_mut().zip(&capacities) {
498            if pair.required_scalars.capacity() - pair.required_scalars.len() >= *unique_count {
499                continue;
500            }
501            if let Some(stage) = prepared_stage.as_deref_mut() {
502                stage
503                    .reserve_prepared(
504                        &mut pair.required_scalars,
505                        *unique_count,
506                        "required pair scalars",
507                    )
508                    .map_err(PreparedTextCensusError::Reservation)?;
509            } else {
510                crate::operation::vector(&pair.required_scalars, *unique_count)
511                    .map_err(PreparedTextCensusError::Reservation)?;
512                pair.required_scalars
513                    .try_reserve_exact(*unique_count)
514                    .map_err(|_| PreparedTextCensusError::Allocation("required pair scalars"))?;
515            }
516        }
517        for (pair, unique_count) in self.pairs.iter_mut().zip(capacities) {
518            presence.fill(0);
519            visit_pair_scalars(&self.requirements, pair.pair_ordinal, |scalar| {
520                let value = scalar as usize;
521                let word = &mut presence[value / u64::BITS as usize];
522                let bit = 1_u64 << (value % u64::BITS as usize);
523                if *word & bit == 0 {
524                    *word |= bit;
525                    pair.required_scalars.push(scalar);
526                }
527                Ok(())
528            })?;
529            if pair.required_scalars.len() != unique_count {
530                return Err(PreparedTextCensusError::Arithmetic(
531                    "prepared scalar count/materialization mismatch",
532                ));
533            }
534        }
535        self.counts.unique_pair_scalars = unique_pair_scalars;
536        Ok(())
537    }
538
539    fn prepare_fonts_in(
540        &mut self,
541        environment: &PreparedFontEnvironment,
542        presence: &mut [u64],
543    ) -> Result<(), PreparedTextCensusError> {
544        self.materialize_required_scalars(presence, None)?;
545        self.prepare_pairs_in(environment, None)
546    }
547
548    fn prepare_pairs_in(
549        &self,
550        environment: &PreparedFontEnvironment,
551        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
552    ) -> Result<(), PreparedTextCensusError> {
553        environment.prepare_pairs(
554            self.pairs.iter().map(|pair| {
555                FontPairPreparationRequest::new(
556                    pair.pair_ordinal,
557                    &pair.stack,
558                    pair.weight.into(),
559                    &pair.required_scalars,
560                )
561            }),
562            prepared_stage.as_deref_mut(),
563        )?;
564        for requirement in &self.requirements {
565            environment.admit_text(
566                &requirement.stack,
567                requirement.weight.into(),
568                &requirement.source,
569                prepared_stage.as_deref_mut(),
570            )?;
571        }
572        Ok(())
573    }
574}
575
576fn pair_first_use(requirements: &[PreparedTextRequirement], index: usize) -> bool {
577    let requirement = &requirements[index];
578    for earlier in &requirements[..index] {
579        if earlier.weight == requirement.weight && earlier.stack.same(&requirement.stack) {
580            return false;
581        }
582    }
583    true
584}
585
586fn reserve_census_vec<T>(
587    values: &mut Vec<T>,
588    additional: usize,
589    payload: &'static str,
590    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
591) -> Result<(), PreparedTextCensusError> {
592    if let Some(stage) = prepared_stage {
593        stage
594            .reserve_prepared(values, additional, payload)
595            .map_err(PreparedTextCensusError::Reservation)
596    } else {
597        crate::operation::vector(values, additional)
598            .map_err(PreparedTextCensusError::Reservation)?;
599        values
600            .try_reserve_exact(additional)
601            .map_err(|_| PreparedTextCensusError::Allocation(payload))
602    }
603}
604
605fn reserve_census_string(
606    value: &mut String,
607    additional: usize,
608    payload: &'static str,
609    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
610) -> Result<(), PreparedTextCensusError> {
611    if let Some(stage) = prepared_stage {
612        stage
613            .reserve_prepared_string(value, additional, payload)
614            .map_err(PreparedTextCensusError::Reservation)
615    } else {
616        crate::operation::string(value, additional)
617            .map_err(PreparedTextCensusError::Reservation)?;
618        value
619            .try_reserve_exact(additional)
620            .map_err(|_| PreparedTextCensusError::Allocation(payload))
621    }
622}
623
624fn retain_family_stack(
625    source: &FontStack,
626    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
627) -> Result<FontStack, PreparedTextCensusError> {
628    Ok(source.copy_with_stage(prepared_stage)?)
629}
630
631fn reserve_required_scalar_capacities(
632    requirements: &[PreparedTextRequirement],
633    pairs: &mut [PreparedFontPairRequirement],
634    presence: &mut [u64],
635    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
636) -> Result<u128, PreparedTextCensusError> {
637    if presence.len() != SCALAR_MAP_WORDS {
638        return Err(PreparedTextCensusError::Arithmetic(
639            "Unicode scalar presence map",
640        ));
641    }
642    let mut capacities = Vec::new();
643    reserve_census_vec(
644        &mut capacities,
645        pairs.len(),
646        "required pair scalar capacities",
647        prepared_stage.as_deref_mut(),
648    )?;
649    let mut unique_pair_scalars = 0_u128;
650    for pair in pairs.iter() {
651        presence.fill(0);
652        let mut unique_count = 0_usize;
653        visit_pair_scalars(requirements, pair.pair_ordinal, |scalar| {
654            let value = scalar as usize;
655            let word = &mut presence[value / u64::BITS as usize];
656            let bit = 1_u64 << (value % u64::BITS as usize);
657            if *word & bit == 0 {
658                *word |= bit;
659                unique_count =
660                    unique_count
661                        .checked_add(1)
662                        .ok_or(PreparedTextCensusError::Arithmetic(
663                            "prepared text unique scalars",
664                        ))?;
665            }
666            Ok(())
667        })?;
668        unique_pair_scalars = unique_pair_scalars
669            .checked_add(unique_count as u128)
670            .ok_or(PreparedTextCensusError::Arithmetic(
671                "prepared text unique scalars",
672            ))?;
673        capacities.push(unique_count);
674    }
675    for (pair, capacity) in pairs.iter_mut().zip(capacities) {
676        reserve_census_vec(
677            &mut pair.required_scalars,
678            capacity,
679            "required pair scalars",
680            prepared_stage.as_deref_mut(),
681        )?;
682    }
683    Ok(unique_pair_scalars)
684}
685
686fn prepared_address_child(
687    base: &ComponentAddress,
688    role: crate::layout::kernel::AddressRole,
689    slot_index: u32,
690    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
691) -> Result<ComponentAddress, Error> {
692    prepared_stage.ok_or_else(|| {
693        Error::Render(
694            PreparedTextCensusError::MissingPreparedStage
695                .to_string()
696                .into(),
697        )
698    })?;
699    base.child(role, slot_index)
700}
701
702#[expect(
703    clippy::similar_names,
704    clippy::too_many_arguments,
705    reason = "the closed text census keeps both axis policies and canonical producer order explicit"
706)]
707pub(crate) fn foundational_plot_requirements(
708    plots: Option<&[crate::orchestrator::registration::PlotRegistration<'_>]>,
709    root_guide: Option<&std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
710    plot: &PlotDescription,
711    kind: PlotKind,
712    theme: &crate::text::TextRequestContext<'_, '_>,
713    base: &ComponentAddress,
714    include_caption: bool,
715    filter_point_label_x_to_limits: bool,
716    filter_point_label_y_to_limits: bool,
717    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
718) -> Result<Vec<PreparedTextRequirement>, Error> {
719    let mut requirements = Vec::new();
720    PreparedTextRequirement::append_plot(
721        plots,
722        root_guide,
723        &mut requirements,
724        plot,
725        kind,
726        theme,
727        base,
728        include_caption,
729        filter_point_label_x_to_limits,
730        filter_point_label_y_to_limits,
731        prepared_stage,
732    )?;
733    Ok(requirements)
734}
735
736impl PreparedTextRequirement {
737    #[expect(
738        clippy::similar_names,
739        clippy::too_many_arguments,
740        clippy::too_many_lines,
741        reason = "the closed producer traversal preserves axis policies and visible source identities"
742    )]
743    pub(crate) fn append_plot(
744        plots: Option<&[crate::orchestrator::registration::PlotRegistration<'_>]>,
745        root_guide: Option<&std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
746        requirements: &mut Vec<Self>,
747        plot: &PlotDescription,
748        kind: PlotKind,
749        theme: &crate::text::TextRequestContext<'_, '_>,
750        base: &ComponentAddress,
751        include_caption: bool,
752        filter_point_label_x_to_limits: bool,
753        filter_point_label_y_to_limits: bool,
754        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
755    ) -> Result<(), Error> {
756        use crate::layout::kernel::AddressRole;
757
758        if prepared_stage.is_none() {
759            return Err(Error::Render(
760                PreparedTextCensusError::MissingPreparedStage
761                    .to_string()
762                    .into(),
763            ));
764        }
765        let title_address = prepared_address_child(
766            base,
767            AddressRole::RootTitle,
768            0,
769            prepared_stage.as_deref_mut(),
770        )?;
771        Self::push_authored(
772            requirements,
773            title_address,
774            PreparedTextRole::Title,
775            plot.prose()[0],
776            &theme.typography.root.title,
777            true,
778            prepared_stage.as_deref_mut(),
779        )?;
780        let subtitle_address = prepared_address_child(
781            base,
782            AddressRole::RootSubtitle,
783            0,
784            prepared_stage.as_deref_mut(),
785        )?;
786        Self::push_authored(
787            requirements,
788            subtitle_address,
789            PreparedTextRole::Subtitle,
790            plot.prose()[1],
791            &theme.typography.root.subtitle,
792            true,
793            prepared_stage.as_deref_mut(),
794        )?;
795        if kind != PlotKind::Matrix {
796            let [x_title, y_title] = plot.prepare_axis_labels(
797                plots
798                    .and_then(|plots| plots.first())
799                    .map(|registered| &registered.policy.labels),
800            )?;
801            if let Some(plots) = plots {
802                for registered in plots {
803                    registered
804                        .axes
805                        .retain_axis_labels([x_title.as_ref(), y_title.as_ref()])?;
806                }
807            }
808            let x_axis = prepared_address_child(
809                base,
810                AddressRole::AxisBottom,
811                0,
812                prepared_stage.as_deref_mut(),
813            )?;
814            let y_axis = prepared_address_child(
815                base,
816                AddressRole::AxisLeft,
817                0,
818                prepared_stage.as_deref_mut(),
819            )?;
820            for (address, title) in [(&x_axis, x_title.as_ref()), (&y_axis, y_title.as_ref())] {
821                Self::push_authored(
822                    requirements,
823                    address.clone(),
824                    PreparedTextRole::AxisTitle,
825                    title,
826                    &theme.typography.axes.axis_title,
827                    false,
828                    prepared_stage.as_deref_mut(),
829                )?;
830            }
831            push_plot_axis_ticks(
832                plots,
833                requirements,
834                plot,
835                kind,
836                theme,
837                base,
838                prepared_stage.as_deref_mut(),
839            )?;
840            if matches!(
841                crate::layout::interior::InteriorRoute::classify(kind),
842                crate::layout::interior::InteriorRoute::StandardCoordinate(_)
843            ) {
844                let address = prepared_address_child(
845                    base,
846                    AddressRole::PanelInterior,
847                    0,
848                    prepared_stage.as_deref_mut(),
849                )?;
850                push_owned(
851                    requirements,
852                    address,
853                    PreparedTextRole::TickLabel,
854                    0,
855                    "0",
856                    &[],
857                    &theme.typography.axes.tick_label,
858                    prepared_stage.as_deref_mut(),
859                )?;
860                let address = prepared_address_child(
861                    base,
862                    AddressRole::PanelInterior,
863                    1,
864                    prepared_stage.as_deref_mut(),
865                )?;
866                push_owned(
867                    requirements,
868                    address,
869                    PreparedTextRole::TickLabel,
870                    0,
871                    "0.5",
872                    &[],
873                    &theme.typography.axes.tick_label,
874                    prepared_stage.as_deref_mut(),
875                )?;
876            }
877        }
878
879        let significance = theme.effective_significance(plot.significance_mark_style_override())?;
880        for (index, annotation) in plot.significance_annotations().iter().enumerate() {
881            if kind == PlotKind::Coefficient {
882                continue;
883            }
884            let eligible = crate::data::source::collect_source(
885                plot.significance_annotations()
886                    .iter()
887                    .enumerate()
888                    .filter(|(_, other)| {
889                        other.endpoints().is_some() == annotation.endpoints().is_some()
890                    })
891                    .map(|(index, _)| Ok(index)),
892            )?;
893            if !crate::text::TextAppearance::from(&significance.label)
894                .layout(theme.text_layouts.significance.as_ref())
895                .includes(index, &eligible)
896            {
897                continue;
898            }
899            let address = prepared_address_child(
900                base,
901                AddressRole::Annotation,
902                u32::try_from(index)
903                    .map_err(|_| Error::Render("significance census index overflowed".into()))?,
904                prepared_stage.as_deref_mut(),
905            )?;
906            push_owned(
907                requirements,
908                address,
909                PreparedTextRole::SignificanceLabel,
910                0,
911                annotation.mark().glyph()?,
912                &[],
913                crate::text::TextAppearance::from(&significance.label)
914                    .layout(theme.text_layouts.significance.as_ref()),
915                prepared_stage.as_deref_mut(),
916            )?;
917        }
918        if crate::orchestrator::registration::discrete_guide_use(
919            plot,
920            plots.and_then(|plots| plots.first()),
921        ) == crate::decorations::legend::discrete::scoped::GuideUse::Local
922        {
923            if let Some(plots) = plots {
924                if plot.has_facets() && matches!(kind, PlotKind::Heatmap | PlotKind::Beeswarm) {
925                    for (index, panel) in plots.iter().enumerate() {
926                        if let Some(guide) = &panel.guide.descriptor {
927                            let index = u32::try_from(index).map_err(|_| {
928                                Error::Render("native guide facet index overflow".into())
929                            })?;
930                            let owner = base
931                                .child(AddressRole::FacetCell, index)?
932                                .child(AddressRole::OutsideGuideRight, 0)?;
933                            guide.append_requirements(
934                                requirements,
935                                theme,
936                                &owner,
937                                prepared_stage.as_deref_mut(),
938                            )?;
939                        }
940                    }
941                } else if let Some(guide) = root_guide {
942                    let guide_parent =
943                        if plot.has_facets() || base.leaf_role() == AddressRole::CanvasCell {
944                            base.clone()
945                        } else {
946                            base.child(AddressRole::PlotBody, 0)?
947                        };
948                    let role = if kind == PlotKind::Matrix {
949                        AddressRole::InsideGuide
950                    } else if matches!(kind, PlotKind::Heatmap | PlotKind::Beeswarm) {
951                        AddressRole::OutsideGuideRight
952                    } else {
953                        crate::decorations::legend::address_role(plot.legend_position_spec())
954                    };
955                    guide.append_requirements(
956                        requirements,
957                        theme,
958                        &guide_parent.child(role, 0)?,
959                        prepared_stage.as_deref_mut(),
960                    )?;
961                }
962            }
963        }
964        push_deferred_plot_requirements(
965            plots,
966            requirements,
967            plot,
968            kind,
969            theme,
970            base,
971            filter_point_label_x_to_limits,
972            filter_point_label_y_to_limits,
973            prepared_stage.as_deref_mut(),
974        )?;
975        if include_caption {
976            let caption_address = prepared_address_child(
977                base,
978                AddressRole::RootCaption,
979                0,
980                prepared_stage.as_deref_mut(),
981            )?;
982            Self::push_authored(
983                requirements,
984                caption_address,
985                PreparedTextRole::Caption,
986                plot.prose()[2],
987                &theme.typography.root.caption,
988                true,
989                prepared_stage,
990            )?;
991        }
992        Ok(())
993    }
994}
995
996#[expect(
997    clippy::similar_names,
998    clippy::too_many_arguments,
999    clippy::too_many_lines,
1000    reason = "one closed plot-kind match keeps both range filters and every deferred T5b/T5e census source auditable"
1001)]
1002fn push_deferred_plot_requirements(
1003    plots: Option<&[crate::orchestrator::registration::PlotRegistration<'_>]>,
1004    requirements: &mut Vec<PreparedTextRequirement>,
1005    plot: &PlotDescription,
1006    kind: PlotKind,
1007    theme: &crate::text::TextRequestContext<'_, '_>,
1008    base: &ComponentAddress,
1009    filter_point_label_x_to_limits: bool,
1010    filter_point_label_y_to_limits: bool,
1011    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1012) -> Result<(), Error> {
1013    use crate::layout::kernel::AddressRole;
1014
1015    let body_address = prepared_address_child(
1016        base,
1017        AddressRole::SpecializedInterior,
1018        0,
1019        prepared_stage.as_deref_mut(),
1020    )?;
1021    let mut body_index = 0_u32;
1022
1023    for annotation in plot.panel_text_annotations() {
1024        let appearance = annotation
1025            .content()
1026            .appearance(&theme.typography.annotations.panel_text);
1027        if appearance.hidden() {
1028            continue;
1029        }
1030        push_deferred_body(
1031            requirements,
1032            &body_address,
1033            &mut body_index,
1034            annotation.text(),
1035            &[],
1036            appearance.theme,
1037            prepared_stage.as_deref_mut(),
1038        )?;
1039    }
1040    if plot.has_facets() {
1041        crate::orchestrator::facet_text_census_labels(plot, plots, |label| {
1042            push_deferred_body(
1043                requirements,
1044                &body_address,
1045                &mut body_index,
1046                label,
1047                &[],
1048                &theme.typography.composition.facet_header,
1049                prepared_stage.as_deref_mut(),
1050            )
1051        })?;
1052    }
1053    for layer in plot.point_layers() {
1054        if layer
1055            .label_layout
1056            .as_ref()
1057            .is_some_and(crate::text::TextLayout::hidden)
1058        {
1059            continue;
1060        }
1061        if let Some(labels) = layer.label_values() {
1062            let appearance =
1063                layer.label_appearance(&theme.typography.annotations.point_layer_label)?;
1064            let eligible = crate::data::source::collect_source(
1065                (0..labels.len())
1066                    .filter(|&row| {
1067                        point_layer_row_is_visible(
1068                            plot,
1069                            layer,
1070                            row,
1071                            filter_point_label_x_to_limits,
1072                            filter_point_label_y_to_limits,
1073                        )
1074                    })
1075                    .map(Ok),
1076            )?;
1077            for row in 0..labels.len() {
1078                let Some(Some(label)) = labels.get(row) else {
1079                    continue;
1080                };
1081                if crate::text::TextAppearance::from(&appearance)
1082                    .layout(layer.label_layout.as_ref())
1083                    .includes(row, &eligible)
1084                    && point_layer_row_is_visible(
1085                        plot,
1086                        layer,
1087                        row,
1088                        filter_point_label_x_to_limits,
1089                        filter_point_label_y_to_limits,
1090                    )
1091                {
1092                    push_deferred_body(
1093                        requirements,
1094                        &body_address,
1095                        &mut body_index,
1096                        label,
1097                        &[],
1098                        &appearance,
1099                        prepared_stage.as_deref_mut(),
1100                    )?;
1101                }
1102            }
1103        }
1104    }
1105
1106    if kind == PlotKind::Matrix {
1107        for variable in plot
1108            .matrix_variables()
1109            .into_iter()
1110            .flat_map(crate::data::VariableValues::columns)
1111            .map(crate::NumericValues::raw_name)
1112        {
1113            for role in 0..2 {
1114                let address = body_address.clone();
1115                push_owned(
1116                    requirements,
1117                    address,
1118                    PreparedTextRole::AxisTitle,
1119                    body_index,
1120                    plot.resolve_label(variable)?,
1121                    &[],
1122                    crate::text::TextAppearance::from(&theme.typography.axes.axis_title)
1123                        .layout(theme.text_layouts.matrix[role].as_ref()),
1124                    prepared_stage.as_deref_mut(),
1125                )?;
1126                body_index = body_index
1127                    .checked_add(1)
1128                    .ok_or_else(|| Error::Render("deferred text census index overflowed".into()))?;
1129            }
1130        }
1131        push_owned(
1132            requirements,
1133            body_address,
1134            PreparedTextRole::TickLabel,
1135            body_index,
1136            String::new(),
1137            &[],
1138            &theme.typography.axes.tick_label,
1139            prepared_stage,
1140        )?;
1141    } else if kind == PlotKind::Waterfall {
1142        let waterfall = plots
1143            .filter(|_| plot.kind() == PlotKind::Waterfall)
1144            .ok_or_else(|| {
1145                Error::Render("waterfall census requires root-prepared semantics".into())
1146            })?;
1147        for registered in waterfall {
1148            let crate::orchestrator::registration::PreparedFamily::Waterfall(marks) =
1149                &registered.family
1150            else {
1151                continue;
1152            };
1153            for label in marks.total_font_sources(theme.text_layouts.total.as_ref()) {
1154                push_deferred_body(
1155                    requirements,
1156                    &body_address,
1157                    &mut body_index,
1158                    label.as_str(),
1159                    &[],
1160                    label.appearance(
1161                        crate::text::TextAppearance::from(
1162                            &theme.typography.annotations.waterfall_total,
1163                        )
1164                        .layout(theme.text_layouts.total.as_ref()),
1165                    ),
1166                    prepared_stage.as_deref_mut(),
1167                )?;
1168            }
1169        }
1170    } else if kind == PlotKind::Heatmap {
1171        let heatmap = plots
1172            .filter(|_| plot.kind() == PlotKind::Heatmap)
1173            .ok_or_else(|| {
1174                Error::Render("heatmap census requires root-prepared semantics".into())
1175            })?;
1176        for registered in heatmap {
1177            let crate::orchestrator::registration::PreparedFamily::Heatmap(marks) =
1178                &registered.family
1179            else {
1180                continue;
1181            };
1182            if let Some(text) = marks.numeric_explanation() {
1183                push_deferred_body(
1184                    requirements,
1185                    &body_address,
1186                    &mut body_index,
1187                    text.as_str(),
1188                    &[],
1189                    text.appearance(theme.contrasting_text(theme.surfaces.get_plot_panel())?)
1190                        .theme,
1191                    prepared_stage.as_deref_mut(),
1192                )?;
1193            }
1194            let eligible = crate::data::source::collect_source(
1195                marks
1196                    .annotation_labels(theme.marks.get_cells().get_fill_alpha())
1197                    .map(|(index, _, _)| Ok(index)),
1198            )?;
1199            for (index, label, fill) in
1200                marks.annotation_labels(theme.marks.get_cells().get_fill_alpha())
1201            {
1202                if !crate::text::TextAppearance::from(theme.contrasting_text(fill)?)
1203                    .layout(theme.text_layouts.value.as_ref())
1204                    .includes(index, &eligible)
1205                {
1206                    continue;
1207                }
1208                push_deferred_body(
1209                    requirements,
1210                    &body_address,
1211                    &mut body_index,
1212                    label,
1213                    &[],
1214                    crate::text::TextAppearance::from(theme.contrasting_text(fill)?)
1215                        .layout(theme.text_layouts.value.as_ref()),
1216                    prepared_stage.as_deref_mut(),
1217                )?;
1218            }
1219            let eligible = crate::data::source::collect_source(
1220                marks.null_row_sources().map(|(index, _)| Ok(index)),
1221            )?;
1222            for (index, annotation) in marks.null_row_sources() {
1223                if !annotation
1224                    .appearance(
1225                        crate::text::TextAppearance::from(
1226                            theme.contrasting_text(theme.marks.get_cells().get_missing_fill())?,
1227                        )
1228                        .layout(theme.text_layouts.null_row.as_ref()),
1229                    )
1230                    .includes(index, &eligible)
1231                {
1232                    continue;
1233                }
1234                push_deferred_body(
1235                    requirements,
1236                    &body_address,
1237                    &mut body_index,
1238                    annotation.as_str(),
1239                    &[],
1240                    annotation.appearance(
1241                        crate::text::TextAppearance::from(
1242                            theme.contrasting_text(theme.marks.get_cells().get_missing_fill())?,
1243                        )
1244                        .layout(theme.text_layouts.null_row.as_ref()),
1245                    ),
1246                    prepared_stage.as_deref_mut(),
1247                )?;
1248            }
1249        }
1250    } else if matches!(
1251        kind,
1252        PlotKind::Coefficient | PlotKind::Forest | PlotKind::PointInterval
1253    ) {
1254        let estimates = plots
1255            .filter(|_| {
1256                matches!(
1257                    plot.kind(),
1258                    PlotKind::Coefficient | PlotKind::Forest | PlotKind::PointInterval
1259                )
1260            })
1261            .ok_or_else(|| {
1262                Error::Render("estimate detail census requires root-prepared semantics".into())
1263            })?;
1264        for registered in estimates {
1265            let crate::orchestrator::registration::PreparedFamily::Estimate { marks, .. } =
1266                &registered.family
1267            else {
1268                continue;
1269            };
1270            if let Some(text) = marks.numeric_explanation() {
1271                push_deferred_body(
1272                    requirements,
1273                    &body_address,
1274                    &mut body_index,
1275                    text.as_str(),
1276                    &[],
1277                    text.appearance(&theme.typography.annotations.estimate_detail)
1278                        .theme,
1279                    prepared_stage.as_deref_mut(),
1280                )?;
1281            }
1282            let significance =
1283                theme.effective_significance(plot.significance_mark_style_override())?;
1284            for (index, source, is_significance) in marks.text_occurrences() {
1285                let eligible = crate::data::source::collect_source(
1286                    marks
1287                        .text_occurrences()
1288                        .filter(|(_, _, significance)| *significance == is_significance)
1289                        .map(|(index, _, _)| Ok(index)),
1290                )?;
1291                let selected = crate::text::TextAppearance::from(if is_significance {
1292                    &significance.label
1293                } else {
1294                    &theme.typography.annotations.estimate_detail
1295                });
1296                let selected = selected.layout(if is_significance {
1297                    theme.text_layouts.significance.as_ref()
1298                } else {
1299                    theme.text_layouts.estimate.as_ref()
1300                });
1301                if !selected.includes(index, &eligible) {
1302                    continue;
1303                }
1304                push_deferred_body(
1305                    requirements,
1306                    &body_address,
1307                    &mut body_index,
1308                    source,
1309                    &[],
1310                    selected,
1311                    prepared_stage.as_deref_mut(),
1312                )?;
1313            }
1314        }
1315    }
1316
1317    Ok(())
1318}
1319
1320fn push_deferred_body<'a, 'b>(
1321    requirements: &mut Vec<PreparedTextRequirement>,
1322    body_address: &ComponentAddress,
1323    body_index: &mut u32,
1324    source: impl Into<CensusSource<'a>>,
1325    generated: &[char],
1326    appearance: impl Into<crate::text::TextAppearance<'b>>,
1327    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1328) -> Result<(), Error> {
1329    let address = body_address.clone();
1330    push_owned(
1331        requirements,
1332        address,
1333        PreparedTextRole::Body,
1334        *body_index,
1335        source,
1336        generated,
1337        appearance,
1338        prepared_stage,
1339    )?;
1340    *body_index = body_index
1341        .checked_add(1)
1342        .ok_or_else(|| Error::Render("deferred text census index overflowed".into()))?;
1343    Ok(())
1344}
1345
1346#[expect(
1347    clippy::similar_names,
1348    reason = "independent x and y limit filters are part of the Canvas shared-range contract"
1349)]
1350fn point_layer_row_is_visible(
1351    plot: &PlotDescription,
1352    layer: &crate::elements::PointLayer,
1353    row: usize,
1354    filter_x_to_limits: bool,
1355    filter_y_to_limits: bool,
1356) -> bool {
1357    let x = layer.x_values().get(row).flatten();
1358    let y = layer.y_values().get(row).flatten();
1359    x.is_some_and(|x| {
1360        x.is_finite()
1361            && (!filter_x_to_limits
1362                || plot
1363                    .x_axis_spec()
1364                    .window
1365                    .map(crate::layout::RawWindow::pair)
1366                    .is_none_or(|limits| x >= limits.0 && x <= limits.1))
1367    }) && y.is_some_and(|y| {
1368        y.is_finite()
1369            && (!filter_y_to_limits
1370                || plot
1371                    .y_axis_spec()
1372                    .window
1373                    .map(crate::layout::RawWindow::pair)
1374                    .is_none_or(|limits| y >= limits.0 && y <= limits.1))
1375    })
1376}
1377
1378impl PreparedTextRequirement {
1379    pub(crate) fn push_authored<'a>(
1380        requirements: &mut Vec<PreparedTextRequirement>,
1381        address: ComponentAddress,
1382        role: PreparedTextRole,
1383        source: Option<&'a crate::Text>,
1384        appearance: impl Into<crate::text::TextAppearance<'a>>,
1385        preferred_width_metric: bool,
1386        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1387    ) -> Result<(), Error> {
1388        if let Some(source) = source {
1389            let selected = source.appearance(appearance);
1390            if selected.hidden() {
1391                return Ok(());
1392            }
1393            let appearance = selected.theme;
1394            let metric_address = preferred_width_metric
1395                .then(|| address.child(crate::layout::AddressRole::PreferenceMetric, 0))
1396                .transpose()?;
1397            push_owned(
1398                requirements,
1399                address,
1400                role,
1401                0,
1402                source.as_str(),
1403                &[],
1404                appearance,
1405                prepared_stage.as_deref_mut(),
1406            )?;
1407            if let Some(address) = metric_address {
1408                push_owned(
1409                    requirements,
1410                    address,
1411                    PreparedTextRole::PreferenceMetric,
1412                    0,
1413                    "0",
1414                    &[],
1415                    appearance,
1416                    prepared_stage,
1417                )?;
1418            }
1419        }
1420        Ok(())
1421    }
1422}
1423
1424fn push_plot_axis_ticks(
1425    plots: Option<&[crate::orchestrator::registration::PlotRegistration<'_>]>,
1426    requirements: &mut Vec<PreparedTextRequirement>,
1427    plot: &PlotDescription,
1428    kind: PlotKind,
1429    theme: &crate::text::TextRequestContext<'_, '_>,
1430    base: &ComponentAddress,
1431    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1432) -> Result<(), Error> {
1433    let alphabet = None;
1434    if let Some(plots) = plots {
1435        for (index, registered) in plots.iter().enumerate() {
1436            let Some(axes) = registered.axes.coordinate() else {
1437                continue;
1438            };
1439            let owner = if plot.has_facets() {
1440                base.child(
1441                    crate::layout::AddressRole::FacetCell,
1442                    u32::try_from(index)
1443                        .map_err(|_| Error::Render("facet axis census address overflow".into()))?,
1444                )?
1445            } else {
1446                base.clone()
1447            };
1448            for side in 0..2 {
1449                if plot.text_layouts().ticks[side]
1450                    .as_ref()
1451                    .is_some_and(crate::text::TextLayout::hidden)
1452                {
1453                    continue;
1454                }
1455                if side == 1 && !registered.policy.axis_text.tick_labels[1] {
1456                    continue;
1457                }
1458                let address = owner.child(
1459                    if side == 0 {
1460                        crate::layout::AddressRole::AxisBottom
1461                    } else {
1462                        crate::layout::AddressRole::AxisLeft
1463                    },
1464                    0,
1465                )?;
1466                let categories =
1467                    axes.categories(side)
1468                        .map(|labels| {
1469                            crate::data::source::collect_source(
1470                                labels.ticks.iter().map(|tick| {
1471                                    crate::data::source::copy_source_string(&tick.label)
1472                                }),
1473                            )
1474                        })
1475                        .transpose()?;
1476                push_axis_ticks(
1477                    requirements,
1478                    &address,
1479                    axes.axis(registered.source, side)
1480                        .authored()
1481                        .expect("coordinate authored intent"),
1482                    categories,
1483                    alphabet,
1484                    theme.tick_text_appearance(if side == 0 {
1485                        crate::layout::AxisSide::Bottom
1486                    } else {
1487                        crate::layout::AxisSide::Left
1488                    }),
1489                    prepared_stage.as_deref_mut(),
1490                )?;
1491            }
1492        }
1493    } else {
1494        for (side, spec) in [plot.x_axis_spec(), plot.y_axis_spec()]
1495            .into_iter()
1496            .enumerate()
1497        {
1498            if plot.text_layouts().ticks[side]
1499                .as_ref()
1500                .is_some_and(crate::text::TextLayout::hidden)
1501            {
1502                continue;
1503            }
1504            let address = base.child(
1505                if side == 0 {
1506                    crate::layout::AddressRole::AxisBottom
1507                } else {
1508                    crate::layout::AddressRole::AxisLeft
1509                },
1510                0,
1511            )?;
1512            push_axis_ticks(
1513                requirements,
1514                &address,
1515                spec,
1516                automatic_category_labels(plot, kind, side == 0)?,
1517                alphabet,
1518                theme.tick_text_appearance(if side == 0 {
1519                    crate::layout::AxisSide::Bottom
1520                } else {
1521                    crate::layout::AxisSide::Left
1522                }),
1523                prepared_stage.as_deref_mut(),
1524            )?;
1525        }
1526    }
1527    Ok(())
1528}
1529
1530fn push_axis_ticks<'a>(
1531    requirements: &mut Vec<PreparedTextRequirement>,
1532    axis: &ComponentAddress,
1533    spec: &crate::layout::AuthoredAxisSpec,
1534    automatic_categories: Option<Vec<String>>,
1535    category_generated_alphabet: Option<&[char]>,
1536    appearance: impl Into<crate::text::TextAppearance<'a>>,
1537    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1538) -> Result<(), Error> {
1539    let appearance = appearance.into();
1540    let policy = appearance
1541        .layout
1542        .and_then(|request| request.instructions().visibility.as_ref());
1543    let exact = spec.exact_ticks.as_deref();
1544    if let Some(ticks) = exact {
1545        let eligible = crate::data::source::collect_source((0..ticks.len()).map(Ok))?;
1546        for (index, tick) in ticks.iter().enumerate() {
1547            if policy.is_some_and(|policy| !policy.includes(index, &eligible)) {
1548                continue;
1549            }
1550            let address = axis.clone();
1551            push_owned(
1552                requirements,
1553                address,
1554                PreparedTextRole::TickLabel,
1555                u32::try_from(index)
1556                    .map_err(|_| Error::Render("exact tick census index overflowed".into()))?,
1557                &tick.label,
1558                &[],
1559                appearance,
1560                prepared_stage.as_deref_mut(),
1561            )?;
1562        }
1563    } else if let Some(categories) = automatic_categories {
1564        let count = categories.len();
1565        let eligible =
1566            crate::data::source::collect_source(spec.category_labels.indices(count).map(Ok))?;
1567        for (index, category) in categories.into_iter().enumerate() {
1568            if !spec.category_labels.includes(index, count)
1569                || policy.is_some_and(|policy| !policy.includes(index, &eligible))
1570            {
1571                continue;
1572            }
1573            let address = axis.clone();
1574            push_owned(
1575                requirements,
1576                address,
1577                PreparedTextRole::TickLabel,
1578                u32::try_from(index).map_err(|_| {
1579                    Error::Render("categorical tick census index overflowed".into())
1580                })?,
1581                category,
1582                category_generated_alphabet.unwrap_or_default(),
1583                appearance,
1584                prepared_stage.as_deref_mut(),
1585            )?;
1586        }
1587    } else {
1588        let address = axis.clone();
1589        push_owned(
1590            requirements,
1591            address,
1592            PreparedTextRole::TickLabel,
1593            0,
1594            String::new(),
1595            &[],
1596            appearance,
1597            prepared_stage,
1598        )?;
1599    }
1600    Ok(())
1601}
1602
1603fn automatic_category_labels(
1604    plot: &PlotDescription,
1605    kind: PlotKind,
1606    x_axis: bool,
1607) -> Result<Option<Vec<String>>, Error> {
1608    if kind == PlotKind::Raincloud && x_axis {
1609        if let Some(input) = plot.raincloud_geometry_input() {
1610            return plot
1611                .resolve_label_domain(
1612                    "x-axis categories",
1613                    (0..input.data.category.len())
1614                        .filter_map(|row| input.data.category.get(row).flatten()),
1615                )
1616                .map(Some);
1617        }
1618    }
1619    plot.automatic_axis_category_values(kind, x_axis)
1620        .map(|values| {
1621            let normalized = matches!(
1622                (kind, x_axis),
1623                (PlotKind::Trajectory | PlotKind::Heatmap, true)
1624                    | (
1625                        PlotKind::Dumbbell | PlotKind::PointInterval | PlotKind::Heatmap,
1626                        false
1627                    )
1628            );
1629            let levels = if normalized {
1630                Cow::Owned(
1631                    values
1632                        .levels()
1633                        .iter()
1634                        .map(|value| crate::data::collapse_whitespace(value))
1635                        .collect::<Vec<_>>(),
1636                )
1637            } else {
1638                Cow::Borrowed(values.levels())
1639            };
1640            plot.resolve_label_domain(
1641                if x_axis {
1642                    "x-axis categories"
1643                } else {
1644                    "y-axis categories"
1645                },
1646                levels.iter().map(String::as_str),
1647            )
1648        })
1649        .transpose()
1650}
1651
1652#[expect(
1653    clippy::too_many_arguments,
1654    reason = "one census insertion keeps the complete structural text identity explicit"
1655)]
1656fn push_owned<'a, 'b>(
1657    requirements: &mut Vec<PreparedTextRequirement>,
1658    address: ComponentAddress,
1659    role: PreparedTextRole,
1660    local_index: u32,
1661    source: impl Into<CensusSource<'a>>,
1662    generated_alphabet: &[char],
1663    appearance: impl Into<crate::text::TextAppearance<'b>>,
1664    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1665) -> Result<(), Error> {
1666    PreparedTextRequirement::push_into(
1667        requirements,
1668        address,
1669        role,
1670        local_index,
1671        source,
1672        generated_alphabet,
1673        appearance,
1674        prepared_stage,
1675    )
1676    .map_err(|error| Error::from(error).with_prefix("prepared text census"))
1677}
1678
1679fn visit_pair_scalars(
1680    requirements: &[PreparedTextRequirement],
1681    pair_ordinal: u32,
1682    mut visit: impl FnMut(char) -> Result<(), PreparedTextCensusError>,
1683) -> Result<(), PreparedTextCensusError> {
1684    for requirement in requirements
1685        .iter()
1686        .filter(|requirement| requirement.pair_ordinal == pair_ordinal)
1687    {
1688        let mut needs_hyphen = false;
1689        for scalar in requirement.source.chars() {
1690            needs_hyphen |= scalar == '\u{00AD}';
1691            visit(scalar)?;
1692        }
1693        // A selected discretionary break paints this scalar in the owning pair.
1694        // Keep its occurrence in admission even if an explicit alphabet repeats it.
1695        if needs_hyphen {
1696            visit('-')?;
1697        }
1698        for &scalar in &requirement.generated_alphabet {
1699            visit(scalar)?;
1700        }
1701    }
1702    Ok(())
1703}
1704
1705#[derive(Debug, thiserror::Error)]
1706pub(crate) enum PreparedTextCensusError {
1707    #[error("production text census requires the root prepared stage")]
1708    MissingPreparedStage,
1709    #[error(transparent)]
1710    Font(#[from] canonical::FontError),
1711    #[error("prepared generated text alphabet must be strictly ascending")]
1712    GeneratedAlphabetOrder,
1713    #[error("prepared text census contains a duplicate address/role/index identity")]
1714    DuplicateIdentity,
1715    #[error("prepared text census is missing the requested font stack/weight pair")]
1716    MissingPair,
1717    #[error("prepared text census arithmetic overflow while calculating {0}")]
1718    Arithmetic(&'static str),
1719    #[error("prepared text census could not reserve {0}")]
1720    Allocation(&'static str),
1721    #[error("{0}")]
1722    Reservation(crate::Error),
1723}
1724
1725impl From<PreparedTextCensusError> for Error {
1726    fn from(error: PreparedTextCensusError) -> Self {
1727        match error {
1728            PreparedTextCensusError::Font(error) => error.into(),
1729            PreparedTextCensusError::Reservation(error) => error,
1730            error => Error::Render(error.to_string().into()),
1731        }
1732    }
1733}
1734
1735#[cfg(test)]
1736mod tests {
1737    use super::*;
1738    use crate::theme::Color;
1739
1740    fn appearance(stack: &str, weight: TextWeight) -> TextTheme {
1741        TextTheme::new(
1742            canonical::named_stack(&[stack]),
1743            Color::rgb(0, 0, 0),
1744            12.0,
1745            weight,
1746            1.2,
1747        )
1748        .unwrap()
1749    }
1750
1751    fn requirement(
1752        address: ComponentAddress,
1753        role: PreparedTextRole,
1754        index: u32,
1755        source: &str,
1756        generated: &[char],
1757        appearance: &TextTheme,
1758    ) -> PreparedTextRequirement {
1759        PreparedTextRequirement::new(address, role, index, source, generated, appearance).unwrap()
1760    }
1761
1762    #[test]
1763    fn census_resolves_each_pair_once_with_its_complete_scalar_union() {
1764        let normal = appearance("Test Sans", TextWeight::Normal);
1765        let bold = appearance("Test Sans", TextWeight::Bold);
1766        let mut census = PreparedTextCensus::materialize(
1767            vec![
1768                requirement(
1769                    ComponentAddress::root(),
1770                    PreparedTextRole::Title,
1771                    0,
1772                    "A",
1773                    &[],
1774                    &normal,
1775                ),
1776                requirement(
1777                    ComponentAddress::root(),
1778                    PreparedTextRole::SignificanceLabel,
1779                    0,
1780                    " ",
1781                    &[],
1782                    &bold,
1783                ),
1784            ],
1785            None,
1786            None,
1787        )
1788        .unwrap();
1789        let environment = PreparedFontEnvironment::synthetic();
1790        let mut presence = vec![0; SCALAR_MAP_WORDS];
1791
1792        crate::font::canonical::FONT_PAIR_RESOLUTION_CALLS.with(|calls| calls.set(0));
1793        census
1794            .prepare_fonts_in(&environment, &mut presence)
1795            .unwrap();
1796
1797        let stack = canonical::named_stack(&["Test Sans"]);
1798        assert_eq!(
1799            environment
1800                .prepared_pair(&stack, RequestedWeight::Normal)
1801                .unwrap()
1802                .unwrap()
1803                .selected_scalars
1804                .len(),
1805            1
1806        );
1807        assert_eq!(
1808            environment
1809                .prepared_pair(&stack, RequestedWeight::Bold)
1810                .unwrap()
1811                .unwrap()
1812                .provenance
1813                .pair_ordinal,
1814            1
1815        );
1816        crate::font::canonical::FONT_PAIR_RESOLUTION_CALLS.with(|calls| assert_eq!(calls.get(), 2));
1817
1818        environment
1819            .plan_text(crate::layout::TextPlanInput {
1820                size_trace: None,
1821                direction: crate::text::TextDirection::Auto,
1822                source: "A",
1823                stack: canonical::test_sans_stack(),
1824                weight: TextWeight::Normal,
1825                font_size: 10.0,
1826                line_height: crate::layout::TextLineHeight::Multiplier(1.2),
1827                maximum_width_quanta: i64::MAX,
1828                alignment: crate::layout::PhysicalTextAlignment::Start,
1829                paint: Color::rgb(0, 0, 0),
1830                provenance: crate::layout::TextPlanProvenance {
1831                    pair_ordinal: u32::MAX,
1832                    owner: "prepared census test".into(),
1833                },
1834                exact_override: false,
1835            })
1836            .unwrap();
1837        crate::font::canonical::FONT_PAIR_RESOLUTION_CALLS.with(|calls| assert_eq!(calls.get(), 2));
1838
1839        environment.operation().unwrap().seal_fonts().unwrap();
1840        let missing = environment
1841            .plan_text(crate::layout::TextPlanInput {
1842                size_trace: None,
1843                direction: crate::text::TextDirection::Auto,
1844                source: "B",
1845                stack: canonical::test_sans_stack(),
1846                weight: TextWeight::Normal,
1847                font_size: 10.0,
1848                line_height: crate::layout::TextLineHeight::Multiplier(1.2),
1849                maximum_width_quanta: i64::MAX,
1850                alignment: crate::layout::PhysicalTextAlignment::Start,
1851                paint: Color::rgb(0, 0, 0),
1852                provenance: crate::layout::TextPlanProvenance {
1853                    pair_ordinal: u32::MAX,
1854                    owner: "uncensused scalar test".into(),
1855                },
1856                exact_override: false,
1857            })
1858            .unwrap_err();
1859        assert!(matches!(
1860            missing,
1861            crate::layout::TextPlanError::Font(canonical::FontError::PreparedPairAfterSeal {
1862                pair_ordinal: 0
1863            })
1864        ));
1865        crate::font::canonical::FONT_PAIR_RESOLUTION_CALLS.with(|calls| assert_eq!(calls.get(), 2));
1866    }
1867}