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::check().map_err(PreparedTextCensusError::Reservation)?;
511                pair.required_scalars
512                    .try_reserve_exact(*unique_count)
513                    .map_err(|_| PreparedTextCensusError::Allocation("required pair scalars"))?;
514            }
515        }
516        for (pair, unique_count) in self.pairs.iter_mut().zip(capacities) {
517            presence.fill(0);
518            visit_pair_scalars(&self.requirements, pair.pair_ordinal, |scalar| {
519                let value = scalar as usize;
520                let word = &mut presence[value / u64::BITS as usize];
521                let bit = 1_u64 << (value % u64::BITS as usize);
522                if *word & bit == 0 {
523                    *word |= bit;
524                    pair.required_scalars.push(scalar);
525                }
526                Ok(())
527            })?;
528            if pair.required_scalars.len() != unique_count {
529                return Err(PreparedTextCensusError::Arithmetic(
530                    "prepared scalar count/materialization mismatch",
531                ));
532            }
533        }
534        self.counts.unique_pair_scalars = unique_pair_scalars;
535        Ok(())
536    }
537
538    fn prepare_fonts_in(
539        &mut self,
540        environment: &PreparedFontEnvironment,
541        presence: &mut [u64],
542    ) -> Result<(), PreparedTextCensusError> {
543        self.materialize_required_scalars(presence, None)?;
544        self.prepare_pairs_in(environment, None)
545    }
546
547    fn prepare_pairs_in(
548        &self,
549        environment: &PreparedFontEnvironment,
550        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
551    ) -> Result<(), PreparedTextCensusError> {
552        environment.prepare_pairs(
553            self.pairs.iter().map(|pair| {
554                FontPairPreparationRequest::new(
555                    pair.pair_ordinal,
556                    &pair.stack,
557                    pair.weight.into(),
558                    &pair.required_scalars,
559                )
560            }),
561            prepared_stage.as_deref_mut(),
562        )?;
563        for requirement in &self.requirements {
564            environment.admit_text(
565                &requirement.stack,
566                requirement.weight.into(),
567                &requirement.source,
568                prepared_stage.as_deref_mut(),
569            )?;
570        }
571        Ok(())
572    }
573}
574
575fn pair_first_use(requirements: &[PreparedTextRequirement], index: usize) -> bool {
576    let requirement = &requirements[index];
577    for earlier in &requirements[..index] {
578        if earlier.weight == requirement.weight && earlier.stack.same(&requirement.stack) {
579            return false;
580        }
581    }
582    true
583}
584
585fn reserve_census_vec<T>(
586    values: &mut Vec<T>,
587    additional: usize,
588    payload: &'static str,
589    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
590) -> Result<(), PreparedTextCensusError> {
591    if let Some(stage) = prepared_stage {
592        stage
593            .reserve_prepared(values, additional, payload)
594            .map_err(PreparedTextCensusError::Reservation)
595    } else {
596        crate::operation::check().map_err(PreparedTextCensusError::Reservation)?;
597        values
598            .try_reserve_exact(additional)
599            .map_err(|_| PreparedTextCensusError::Allocation(payload))
600    }
601}
602
603fn reserve_census_string(
604    value: &mut String,
605    additional: usize,
606    payload: &'static str,
607    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
608) -> Result<(), PreparedTextCensusError> {
609    if let Some(stage) = prepared_stage {
610        stage
611            .reserve_prepared_string(value, additional, payload)
612            .map_err(PreparedTextCensusError::Reservation)
613    } else {
614        crate::operation::check().map_err(PreparedTextCensusError::Reservation)?;
615        value
616            .try_reserve_exact(additional)
617            .map_err(|_| PreparedTextCensusError::Allocation(payload))
618    }
619}
620
621fn retain_family_stack(
622    source: &FontStack,
623    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
624) -> Result<FontStack, PreparedTextCensusError> {
625    Ok(source.copy_with_stage(prepared_stage)?)
626}
627
628fn reserve_required_scalar_capacities(
629    requirements: &[PreparedTextRequirement],
630    pairs: &mut [PreparedFontPairRequirement],
631    presence: &mut [u64],
632    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
633) -> Result<u128, PreparedTextCensusError> {
634    if presence.len() != SCALAR_MAP_WORDS {
635        return Err(PreparedTextCensusError::Arithmetic(
636            "Unicode scalar presence map",
637        ));
638    }
639    let mut capacities = Vec::new();
640    reserve_census_vec(
641        &mut capacities,
642        pairs.len(),
643        "required pair scalar capacities",
644        prepared_stage.as_deref_mut(),
645    )?;
646    let mut unique_pair_scalars = 0_u128;
647    for pair in pairs.iter() {
648        presence.fill(0);
649        let mut unique_count = 0_usize;
650        visit_pair_scalars(requirements, pair.pair_ordinal, |scalar| {
651            let value = scalar as usize;
652            let word = &mut presence[value / u64::BITS as usize];
653            let bit = 1_u64 << (value % u64::BITS as usize);
654            if *word & bit == 0 {
655                *word |= bit;
656                unique_count =
657                    unique_count
658                        .checked_add(1)
659                        .ok_or(PreparedTextCensusError::Arithmetic(
660                            "prepared text unique scalars",
661                        ))?;
662            }
663            Ok(())
664        })?;
665        unique_pair_scalars = unique_pair_scalars
666            .checked_add(unique_count as u128)
667            .ok_or(PreparedTextCensusError::Arithmetic(
668                "prepared text unique scalars",
669            ))?;
670        capacities.push(unique_count);
671    }
672    for (pair, capacity) in pairs.iter_mut().zip(capacities) {
673        reserve_census_vec(
674            &mut pair.required_scalars,
675            capacity,
676            "required pair scalars",
677            prepared_stage.as_deref_mut(),
678        )?;
679    }
680    Ok(unique_pair_scalars)
681}
682
683fn prepared_address_child(
684    base: &ComponentAddress,
685    role: crate::layout::kernel::AddressRole,
686    slot_index: u32,
687    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
688) -> Result<ComponentAddress, Error> {
689    prepared_stage.ok_or_else(|| {
690        Error::Render(
691            PreparedTextCensusError::MissingPreparedStage
692                .to_string()
693                .into(),
694        )
695    })?;
696    base.child(role, slot_index)
697}
698
699#[expect(
700    clippy::similar_names,
701    clippy::too_many_arguments,
702    reason = "the closed text census keeps both axis policies and canonical producer order explicit"
703)]
704pub(crate) fn foundational_plot_requirements(
705    plots: Option<&[crate::orchestrator::registration::PlotRegistration<'_>]>,
706    root_guide: Option<&std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
707    plot: &PlotDescription,
708    kind: PlotKind,
709    theme: &crate::text::TextRequestContext<'_, '_>,
710    base: &ComponentAddress,
711    include_caption: bool,
712    filter_point_label_x_to_limits: bool,
713    filter_point_label_y_to_limits: bool,
714    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
715) -> Result<Vec<PreparedTextRequirement>, Error> {
716    let mut requirements = Vec::new();
717    PreparedTextRequirement::append_plot(
718        plots,
719        root_guide,
720        &mut requirements,
721        plot,
722        kind,
723        theme,
724        base,
725        include_caption,
726        filter_point_label_x_to_limits,
727        filter_point_label_y_to_limits,
728        prepared_stage,
729    )?;
730    Ok(requirements)
731}
732
733impl PreparedTextRequirement {
734    #[expect(
735        clippy::similar_names,
736        clippy::too_many_arguments,
737        clippy::too_many_lines,
738        reason = "the closed producer traversal preserves axis policies and visible source identities"
739    )]
740    pub(crate) fn append_plot(
741        plots: Option<&[crate::orchestrator::registration::PlotRegistration<'_>]>,
742        root_guide: Option<&std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
743        requirements: &mut Vec<Self>,
744        plot: &PlotDescription,
745        kind: PlotKind,
746        theme: &crate::text::TextRequestContext<'_, '_>,
747        base: &ComponentAddress,
748        include_caption: bool,
749        filter_point_label_x_to_limits: bool,
750        filter_point_label_y_to_limits: bool,
751        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
752    ) -> Result<(), Error> {
753        use crate::layout::kernel::AddressRole;
754
755        if prepared_stage.is_none() {
756            return Err(Error::Render(
757                PreparedTextCensusError::MissingPreparedStage
758                    .to_string()
759                    .into(),
760            ));
761        }
762        let title_address = prepared_address_child(
763            base,
764            AddressRole::RootTitle,
765            0,
766            prepared_stage.as_deref_mut(),
767        )?;
768        Self::push_authored(
769            requirements,
770            title_address,
771            PreparedTextRole::Title,
772            plot.prose()[0],
773            &theme.typography.root.title,
774            true,
775            prepared_stage.as_deref_mut(),
776        )?;
777        let subtitle_address = prepared_address_child(
778            base,
779            AddressRole::RootSubtitle,
780            0,
781            prepared_stage.as_deref_mut(),
782        )?;
783        Self::push_authored(
784            requirements,
785            subtitle_address,
786            PreparedTextRole::Subtitle,
787            plot.prose()[1],
788            &theme.typography.root.subtitle,
789            true,
790            prepared_stage.as_deref_mut(),
791        )?;
792        if kind != PlotKind::Matrix {
793            let [x_title, y_title] = plot.prepare_axis_labels(
794                plots
795                    .and_then(|plots| plots.first())
796                    .map(|registered| &registered.policy.labels),
797            )?;
798            if let Some(plots) = plots {
799                for registered in plots {
800                    registered
801                        .axes
802                        .retain_axis_labels([x_title.as_ref(), y_title.as_ref()])?;
803                }
804            }
805            let x_axis = prepared_address_child(
806                base,
807                AddressRole::AxisBottom,
808                0,
809                prepared_stage.as_deref_mut(),
810            )?;
811            let y_axis = prepared_address_child(
812                base,
813                AddressRole::AxisLeft,
814                0,
815                prepared_stage.as_deref_mut(),
816            )?;
817            for (address, title) in [(&x_axis, x_title.as_ref()), (&y_axis, y_title.as_ref())] {
818                Self::push_authored(
819                    requirements,
820                    address.clone(),
821                    PreparedTextRole::AxisTitle,
822                    title,
823                    &theme.typography.axes.axis_title,
824                    false,
825                    prepared_stage.as_deref_mut(),
826                )?;
827            }
828            push_plot_axis_ticks(
829                plots,
830                requirements,
831                plot,
832                kind,
833                theme,
834                base,
835                prepared_stage.as_deref_mut(),
836            )?;
837            if matches!(
838                crate::layout::interior::InteriorRoute::classify(kind),
839                crate::layout::interior::InteriorRoute::StandardCoordinate(_)
840            ) {
841                let address = prepared_address_child(
842                    base,
843                    AddressRole::PanelInterior,
844                    0,
845                    prepared_stage.as_deref_mut(),
846                )?;
847                push_owned(
848                    requirements,
849                    address,
850                    PreparedTextRole::TickLabel,
851                    0,
852                    "0",
853                    &[],
854                    &theme.typography.axes.tick_label,
855                    prepared_stage.as_deref_mut(),
856                )?;
857                let address = prepared_address_child(
858                    base,
859                    AddressRole::PanelInterior,
860                    1,
861                    prepared_stage.as_deref_mut(),
862                )?;
863                push_owned(
864                    requirements,
865                    address,
866                    PreparedTextRole::TickLabel,
867                    0,
868                    "0.5",
869                    &[],
870                    &theme.typography.axes.tick_label,
871                    prepared_stage.as_deref_mut(),
872                )?;
873            }
874        }
875
876        let significance = theme.effective_significance(plot.significance_mark_style_override())?;
877        for (index, annotation) in plot.significance_annotations().iter().enumerate() {
878            if kind == PlotKind::Coefficient {
879                continue;
880            }
881            let eligible = crate::data::source::collect_source(
882                plot.significance_annotations()
883                    .iter()
884                    .enumerate()
885                    .filter(|(_, other)| {
886                        other.endpoints().is_some() == annotation.endpoints().is_some()
887                    })
888                    .map(|(index, _)| Ok(index)),
889            )?;
890            if !crate::text::TextAppearance::from(&significance.label)
891                .layout(theme.text_layouts.significance.as_ref())
892                .includes(index, &eligible)
893            {
894                continue;
895            }
896            let address = prepared_address_child(
897                base,
898                AddressRole::Annotation,
899                u32::try_from(index)
900                    .map_err(|_| Error::Render("significance census index overflowed".into()))?,
901                prepared_stage.as_deref_mut(),
902            )?;
903            push_owned(
904                requirements,
905                address,
906                PreparedTextRole::SignificanceLabel,
907                0,
908                annotation.mark().glyph()?,
909                &[],
910                crate::text::TextAppearance::from(&significance.label)
911                    .layout(theme.text_layouts.significance.as_ref()),
912                prepared_stage.as_deref_mut(),
913            )?;
914        }
915        if crate::orchestrator::registration::discrete_guide_use(
916            plot,
917            plots.and_then(|plots| plots.first()),
918        ) == crate::decorations::legend::discrete::scoped::GuideUse::Local
919        {
920            if let Some(plots) = plots {
921                if plot.has_facets() && matches!(kind, PlotKind::Heatmap | PlotKind::Beeswarm) {
922                    for (index, panel) in plots.iter().enumerate() {
923                        if let Some(guide) = &panel.guide.descriptor {
924                            let index = u32::try_from(index).map_err(|_| {
925                                Error::Render("native guide facet index overflow".into())
926                            })?;
927                            let owner = base
928                                .child(AddressRole::FacetCell, index)?
929                                .child(AddressRole::OutsideGuideRight, 0)?;
930                            guide.append_requirements(
931                                requirements,
932                                theme,
933                                &owner,
934                                prepared_stage.as_deref_mut(),
935                            )?;
936                        }
937                    }
938                } else if let Some(guide) = root_guide {
939                    let guide_parent =
940                        if plot.has_facets() || base.leaf_role() == AddressRole::CanvasCell {
941                            base.clone()
942                        } else {
943                            base.child(AddressRole::PlotBody, 0)?
944                        };
945                    let role = if kind == PlotKind::Matrix {
946                        AddressRole::InsideGuide
947                    } else if matches!(kind, PlotKind::Heatmap | PlotKind::Beeswarm) {
948                        AddressRole::OutsideGuideRight
949                    } else {
950                        crate::decorations::legend::address_role(plot.legend_position_spec())
951                    };
952                    guide.append_requirements(
953                        requirements,
954                        theme,
955                        &guide_parent.child(role, 0)?,
956                        prepared_stage.as_deref_mut(),
957                    )?;
958                }
959            }
960        }
961        push_deferred_plot_requirements(
962            plots,
963            requirements,
964            plot,
965            kind,
966            theme,
967            base,
968            filter_point_label_x_to_limits,
969            filter_point_label_y_to_limits,
970            prepared_stage.as_deref_mut(),
971        )?;
972        if include_caption {
973            let caption_address = prepared_address_child(
974                base,
975                AddressRole::RootCaption,
976                0,
977                prepared_stage.as_deref_mut(),
978            )?;
979            Self::push_authored(
980                requirements,
981                caption_address,
982                PreparedTextRole::Caption,
983                plot.prose()[2],
984                &theme.typography.root.caption,
985                true,
986                prepared_stage,
987            )?;
988        }
989        Ok(())
990    }
991}
992
993#[expect(
994    clippy::similar_names,
995    clippy::too_many_arguments,
996    clippy::too_many_lines,
997    reason = "one closed plot-kind match keeps both range filters and every deferred T5b/T5e census source auditable"
998)]
999fn push_deferred_plot_requirements(
1000    plots: Option<&[crate::orchestrator::registration::PlotRegistration<'_>]>,
1001    requirements: &mut Vec<PreparedTextRequirement>,
1002    plot: &PlotDescription,
1003    kind: PlotKind,
1004    theme: &crate::text::TextRequestContext<'_, '_>,
1005    base: &ComponentAddress,
1006    filter_point_label_x_to_limits: bool,
1007    filter_point_label_y_to_limits: bool,
1008    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1009) -> Result<(), Error> {
1010    use crate::layout::kernel::AddressRole;
1011
1012    let body_address = prepared_address_child(
1013        base,
1014        AddressRole::SpecializedInterior,
1015        0,
1016        prepared_stage.as_deref_mut(),
1017    )?;
1018    let mut body_index = 0_u32;
1019
1020    for annotation in plot.panel_text_annotations() {
1021        let appearance = annotation
1022            .content()
1023            .appearance(&theme.typography.annotations.panel_text);
1024        if appearance.hidden() {
1025            continue;
1026        }
1027        push_deferred_body(
1028            requirements,
1029            &body_address,
1030            &mut body_index,
1031            annotation.text(),
1032            &[],
1033            appearance.theme,
1034            prepared_stage.as_deref_mut(),
1035        )?;
1036    }
1037    if plot.has_facets() {
1038        crate::orchestrator::facet_text_census_labels(plot, plots, |label| {
1039            push_deferred_body(
1040                requirements,
1041                &body_address,
1042                &mut body_index,
1043                label,
1044                &[],
1045                &theme.typography.composition.facet_header,
1046                prepared_stage.as_deref_mut(),
1047            )
1048        })?;
1049    }
1050    for layer in plot.point_layers() {
1051        if layer
1052            .label_layout
1053            .as_ref()
1054            .is_some_and(crate::text::TextLayout::hidden)
1055        {
1056            continue;
1057        }
1058        if let Some(labels) = layer.label_values() {
1059            let appearance =
1060                layer.label_appearance(&theme.typography.annotations.point_layer_label)?;
1061            let eligible = crate::data::source::collect_source(
1062                (0..labels.len())
1063                    .filter(|&row| {
1064                        point_layer_row_is_visible(
1065                            plot,
1066                            layer,
1067                            row,
1068                            filter_point_label_x_to_limits,
1069                            filter_point_label_y_to_limits,
1070                        )
1071                    })
1072                    .map(Ok),
1073            )?;
1074            for row in 0..labels.len() {
1075                let Some(Some(label)) = labels.get(row) else {
1076                    continue;
1077                };
1078                if crate::text::TextAppearance::from(&appearance)
1079                    .layout(layer.label_layout.as_ref())
1080                    .includes(row, &eligible)
1081                    && point_layer_row_is_visible(
1082                        plot,
1083                        layer,
1084                        row,
1085                        filter_point_label_x_to_limits,
1086                        filter_point_label_y_to_limits,
1087                    )
1088                {
1089                    push_deferred_body(
1090                        requirements,
1091                        &body_address,
1092                        &mut body_index,
1093                        label,
1094                        &[],
1095                        &appearance,
1096                        prepared_stage.as_deref_mut(),
1097                    )?;
1098                }
1099            }
1100        }
1101    }
1102
1103    if kind == PlotKind::Matrix {
1104        for variable in plot
1105            .matrix_variables()
1106            .into_iter()
1107            .flat_map(crate::data::VariableValues::columns)
1108            .map(crate::NumericValues::raw_name)
1109        {
1110            for role in 0..2 {
1111                let address = body_address.clone();
1112                push_owned(
1113                    requirements,
1114                    address,
1115                    PreparedTextRole::AxisTitle,
1116                    body_index,
1117                    plot.resolve_label(variable)?,
1118                    &[],
1119                    crate::text::TextAppearance::from(&theme.typography.axes.axis_title)
1120                        .layout(theme.text_layouts.matrix[role].as_ref()),
1121                    prepared_stage.as_deref_mut(),
1122                )?;
1123                body_index = body_index
1124                    .checked_add(1)
1125                    .ok_or_else(|| Error::Render("deferred text census index overflowed".into()))?;
1126            }
1127        }
1128        push_owned(
1129            requirements,
1130            body_address,
1131            PreparedTextRole::TickLabel,
1132            body_index,
1133            String::new(),
1134            &[],
1135            &theme.typography.axes.tick_label,
1136            prepared_stage,
1137        )?;
1138    } else if kind == PlotKind::Waterfall {
1139        let waterfall = plots
1140            .filter(|_| plot.kind() == PlotKind::Waterfall)
1141            .ok_or_else(|| {
1142                Error::Render("waterfall census requires root-prepared semantics".into())
1143            })?;
1144        for registered in waterfall {
1145            let crate::orchestrator::registration::PreparedFamily::Waterfall(marks) =
1146                &registered.family
1147            else {
1148                continue;
1149            };
1150            for label in marks.total_font_sources(theme.text_layouts.total.as_ref()) {
1151                push_deferred_body(
1152                    requirements,
1153                    &body_address,
1154                    &mut body_index,
1155                    label.as_str(),
1156                    &[],
1157                    label.appearance(
1158                        crate::text::TextAppearance::from(
1159                            &theme.typography.annotations.waterfall_total,
1160                        )
1161                        .layout(theme.text_layouts.total.as_ref()),
1162                    ),
1163                    prepared_stage.as_deref_mut(),
1164                )?;
1165            }
1166        }
1167    } else if kind == PlotKind::Heatmap {
1168        let heatmap = plots
1169            .filter(|_| plot.kind() == PlotKind::Heatmap)
1170            .ok_or_else(|| {
1171                Error::Render("heatmap census requires root-prepared semantics".into())
1172            })?;
1173        for registered in heatmap {
1174            let crate::orchestrator::registration::PreparedFamily::Heatmap(marks) =
1175                &registered.family
1176            else {
1177                continue;
1178            };
1179            if let Some(text) = marks.numeric_explanation() {
1180                push_deferred_body(
1181                    requirements,
1182                    &body_address,
1183                    &mut body_index,
1184                    text.as_str(),
1185                    &[],
1186                    text.appearance(theme.contrasting_text(theme.surfaces.get_plot_panel())?)
1187                        .theme,
1188                    prepared_stage.as_deref_mut(),
1189                )?;
1190            }
1191            let eligible = crate::data::source::collect_source(
1192                marks
1193                    .annotation_labels(theme.marks.get_cells().get_fill_alpha())
1194                    .map(|(index, _, _)| Ok(index)),
1195            )?;
1196            for (index, label, fill) in
1197                marks.annotation_labels(theme.marks.get_cells().get_fill_alpha())
1198            {
1199                if !crate::text::TextAppearance::from(theme.contrasting_text(fill)?)
1200                    .layout(theme.text_layouts.value.as_ref())
1201                    .includes(index, &eligible)
1202                {
1203                    continue;
1204                }
1205                push_deferred_body(
1206                    requirements,
1207                    &body_address,
1208                    &mut body_index,
1209                    label,
1210                    &[],
1211                    crate::text::TextAppearance::from(theme.contrasting_text(fill)?)
1212                        .layout(theme.text_layouts.value.as_ref()),
1213                    prepared_stage.as_deref_mut(),
1214                )?;
1215            }
1216            let eligible = crate::data::source::collect_source(
1217                marks.null_row_sources().map(|(index, _)| Ok(index)),
1218            )?;
1219            for (index, annotation) in marks.null_row_sources() {
1220                if !annotation
1221                    .appearance(
1222                        crate::text::TextAppearance::from(
1223                            theme.contrasting_text(theme.marks.get_cells().get_missing_fill())?,
1224                        )
1225                        .layout(theme.text_layouts.null_row.as_ref()),
1226                    )
1227                    .includes(index, &eligible)
1228                {
1229                    continue;
1230                }
1231                push_deferred_body(
1232                    requirements,
1233                    &body_address,
1234                    &mut body_index,
1235                    annotation.as_str(),
1236                    &[],
1237                    annotation.appearance(
1238                        crate::text::TextAppearance::from(
1239                            theme.contrasting_text(theme.marks.get_cells().get_missing_fill())?,
1240                        )
1241                        .layout(theme.text_layouts.null_row.as_ref()),
1242                    ),
1243                    prepared_stage.as_deref_mut(),
1244                )?;
1245            }
1246        }
1247    } else if matches!(
1248        kind,
1249        PlotKind::Coefficient | PlotKind::Forest | PlotKind::PointInterval
1250    ) {
1251        let estimates = plots
1252            .filter(|_| {
1253                matches!(
1254                    plot.kind(),
1255                    PlotKind::Coefficient | PlotKind::Forest | PlotKind::PointInterval
1256                )
1257            })
1258            .ok_or_else(|| {
1259                Error::Render("estimate detail census requires root-prepared semantics".into())
1260            })?;
1261        for registered in estimates {
1262            let crate::orchestrator::registration::PreparedFamily::Estimate { marks, .. } =
1263                &registered.family
1264            else {
1265                continue;
1266            };
1267            if let Some(text) = marks.numeric_explanation() {
1268                push_deferred_body(
1269                    requirements,
1270                    &body_address,
1271                    &mut body_index,
1272                    text.as_str(),
1273                    &[],
1274                    text.appearance(&theme.typography.annotations.estimate_detail)
1275                        .theme,
1276                    prepared_stage.as_deref_mut(),
1277                )?;
1278            }
1279            let significance =
1280                theme.effective_significance(plot.significance_mark_style_override())?;
1281            for (index, source, is_significance) in marks.text_occurrences() {
1282                let eligible = crate::data::source::collect_source(
1283                    marks
1284                        .text_occurrences()
1285                        .filter(|(_, _, significance)| *significance == is_significance)
1286                        .map(|(index, _, _)| Ok(index)),
1287                )?;
1288                let selected = crate::text::TextAppearance::from(if is_significance {
1289                    &significance.label
1290                } else {
1291                    &theme.typography.annotations.estimate_detail
1292                });
1293                let selected = selected.layout(if is_significance {
1294                    theme.text_layouts.significance.as_ref()
1295                } else {
1296                    theme.text_layouts.estimate.as_ref()
1297                });
1298                if !selected.includes(index, &eligible) {
1299                    continue;
1300                }
1301                push_deferred_body(
1302                    requirements,
1303                    &body_address,
1304                    &mut body_index,
1305                    source,
1306                    &[],
1307                    selected,
1308                    prepared_stage.as_deref_mut(),
1309                )?;
1310            }
1311        }
1312    }
1313
1314    Ok(())
1315}
1316
1317fn push_deferred_body<'a, 'b>(
1318    requirements: &mut Vec<PreparedTextRequirement>,
1319    body_address: &ComponentAddress,
1320    body_index: &mut u32,
1321    source: impl Into<CensusSource<'a>>,
1322    generated: &[char],
1323    appearance: impl Into<crate::text::TextAppearance<'b>>,
1324    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1325) -> Result<(), Error> {
1326    let address = body_address.clone();
1327    push_owned(
1328        requirements,
1329        address,
1330        PreparedTextRole::Body,
1331        *body_index,
1332        source,
1333        generated,
1334        appearance,
1335        prepared_stage,
1336    )?;
1337    *body_index = body_index
1338        .checked_add(1)
1339        .ok_or_else(|| Error::Render("deferred text census index overflowed".into()))?;
1340    Ok(())
1341}
1342
1343#[expect(
1344    clippy::similar_names,
1345    reason = "independent x and y limit filters are part of the Canvas shared-range contract"
1346)]
1347fn point_layer_row_is_visible(
1348    plot: &PlotDescription,
1349    layer: &crate::elements::PointLayer,
1350    row: usize,
1351    filter_x_to_limits: bool,
1352    filter_y_to_limits: bool,
1353) -> bool {
1354    let x = layer.x_values().get(row).flatten();
1355    let y = layer.y_values().get(row).flatten();
1356    x.is_some_and(|x| {
1357        x.is_finite()
1358            && (!filter_x_to_limits
1359                || plot
1360                    .x_axis_spec()
1361                    .window
1362                    .map(crate::layout::RawWindow::pair)
1363                    .is_none_or(|limits| x >= limits.0 && x <= limits.1))
1364    }) && y.is_some_and(|y| {
1365        y.is_finite()
1366            && (!filter_y_to_limits
1367                || plot
1368                    .y_axis_spec()
1369                    .window
1370                    .map(crate::layout::RawWindow::pair)
1371                    .is_none_or(|limits| y >= limits.0 && y <= limits.1))
1372    })
1373}
1374
1375impl PreparedTextRequirement {
1376    pub(crate) fn push_authored<'a>(
1377        requirements: &mut Vec<PreparedTextRequirement>,
1378        address: ComponentAddress,
1379        role: PreparedTextRole,
1380        source: Option<&'a crate::Text>,
1381        appearance: impl Into<crate::text::TextAppearance<'a>>,
1382        preferred_width_metric: bool,
1383        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1384    ) -> Result<(), Error> {
1385        if let Some(source) = source {
1386            let selected = source.appearance(appearance);
1387            if selected.hidden() {
1388                return Ok(());
1389            }
1390            let appearance = selected.theme;
1391            let metric_address = preferred_width_metric
1392                .then(|| address.child(crate::layout::AddressRole::PreferenceMetric, 0))
1393                .transpose()?;
1394            push_owned(
1395                requirements,
1396                address,
1397                role,
1398                0,
1399                source.as_str(),
1400                &[],
1401                appearance,
1402                prepared_stage.as_deref_mut(),
1403            )?;
1404            if let Some(address) = metric_address {
1405                push_owned(
1406                    requirements,
1407                    address,
1408                    PreparedTextRole::PreferenceMetric,
1409                    0,
1410                    "0",
1411                    &[],
1412                    appearance,
1413                    prepared_stage,
1414                )?;
1415            }
1416        }
1417        Ok(())
1418    }
1419}
1420
1421fn push_plot_axis_ticks(
1422    plots: Option<&[crate::orchestrator::registration::PlotRegistration<'_>]>,
1423    requirements: &mut Vec<PreparedTextRequirement>,
1424    plot: &PlotDescription,
1425    kind: PlotKind,
1426    theme: &crate::text::TextRequestContext<'_, '_>,
1427    base: &ComponentAddress,
1428    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1429) -> Result<(), Error> {
1430    let alphabet = None;
1431    if let Some(plots) = plots {
1432        for (index, registered) in plots.iter().enumerate() {
1433            let Some(axes) = registered.axes.coordinate() else {
1434                continue;
1435            };
1436            let owner = if plot.has_facets() {
1437                base.child(
1438                    crate::layout::AddressRole::FacetCell,
1439                    u32::try_from(index)
1440                        .map_err(|_| Error::Render("facet axis census address overflow".into()))?,
1441                )?
1442            } else {
1443                base.clone()
1444            };
1445            for side in 0..2 {
1446                if plot.text_layouts().ticks[side]
1447                    .as_ref()
1448                    .is_some_and(crate::text::TextLayout::hidden)
1449                {
1450                    continue;
1451                }
1452                if side == 1 && !registered.policy.axis_text.tick_labels[1] {
1453                    continue;
1454                }
1455                let address = owner.child(
1456                    if side == 0 {
1457                        crate::layout::AddressRole::AxisBottom
1458                    } else {
1459                        crate::layout::AddressRole::AxisLeft
1460                    },
1461                    0,
1462                )?;
1463                let categories =
1464                    axes.categories(side)
1465                        .map(|labels| {
1466                            crate::data::source::collect_source(
1467                                labels.ticks.iter().map(|tick| {
1468                                    crate::data::source::copy_source_string(&tick.label)
1469                                }),
1470                            )
1471                        })
1472                        .transpose()?;
1473                push_axis_ticks(
1474                    requirements,
1475                    &address,
1476                    axes.axis(registered.source, side)
1477                        .authored()
1478                        .expect("coordinate authored intent"),
1479                    categories,
1480                    alphabet,
1481                    theme.tick_text_appearance(if side == 0 {
1482                        crate::layout::AxisSide::Bottom
1483                    } else {
1484                        crate::layout::AxisSide::Left
1485                    }),
1486                    prepared_stage.as_deref_mut(),
1487                )?;
1488            }
1489        }
1490    } else {
1491        for (side, spec) in [plot.x_axis_spec(), plot.y_axis_spec()]
1492            .into_iter()
1493            .enumerate()
1494        {
1495            if plot.text_layouts().ticks[side]
1496                .as_ref()
1497                .is_some_and(crate::text::TextLayout::hidden)
1498            {
1499                continue;
1500            }
1501            let address = base.child(
1502                if side == 0 {
1503                    crate::layout::AddressRole::AxisBottom
1504                } else {
1505                    crate::layout::AddressRole::AxisLeft
1506                },
1507                0,
1508            )?;
1509            push_axis_ticks(
1510                requirements,
1511                &address,
1512                spec,
1513                automatic_category_labels(plot, kind, side == 0)?,
1514                alphabet,
1515                theme.tick_text_appearance(if side == 0 {
1516                    crate::layout::AxisSide::Bottom
1517                } else {
1518                    crate::layout::AxisSide::Left
1519                }),
1520                prepared_stage.as_deref_mut(),
1521            )?;
1522        }
1523    }
1524    Ok(())
1525}
1526
1527fn push_axis_ticks<'a>(
1528    requirements: &mut Vec<PreparedTextRequirement>,
1529    axis: &ComponentAddress,
1530    spec: &crate::layout::AuthoredAxisSpec,
1531    automatic_categories: Option<Vec<String>>,
1532    category_generated_alphabet: Option<&[char]>,
1533    appearance: impl Into<crate::text::TextAppearance<'a>>,
1534    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1535) -> Result<(), Error> {
1536    let appearance = appearance.into();
1537    let policy = appearance
1538        .layout
1539        .and_then(|request| request.instructions().visibility.as_ref());
1540    let exact = spec.exact_ticks.as_deref();
1541    if let Some(ticks) = exact {
1542        let eligible = crate::data::source::collect_source((0..ticks.len()).map(Ok))?;
1543        for (index, tick) in ticks.iter().enumerate() {
1544            if policy.is_some_and(|policy| !policy.includes(index, &eligible)) {
1545                continue;
1546            }
1547            let address = axis.clone();
1548            push_owned(
1549                requirements,
1550                address,
1551                PreparedTextRole::TickLabel,
1552                u32::try_from(index)
1553                    .map_err(|_| Error::Render("exact tick census index overflowed".into()))?,
1554                &tick.label,
1555                &[],
1556                appearance,
1557                prepared_stage.as_deref_mut(),
1558            )?;
1559        }
1560    } else if let Some(categories) = automatic_categories {
1561        let count = categories.len();
1562        let eligible =
1563            crate::data::source::collect_source(spec.category_labels.indices(count).map(Ok))?;
1564        for (index, category) in categories.into_iter().enumerate() {
1565            if !spec.category_labels.includes(index, count)
1566                || policy.is_some_and(|policy| !policy.includes(index, &eligible))
1567            {
1568                continue;
1569            }
1570            let address = axis.clone();
1571            push_owned(
1572                requirements,
1573                address,
1574                PreparedTextRole::TickLabel,
1575                u32::try_from(index).map_err(|_| {
1576                    Error::Render("categorical tick census index overflowed".into())
1577                })?,
1578                category,
1579                category_generated_alphabet.unwrap_or_default(),
1580                appearance,
1581                prepared_stage.as_deref_mut(),
1582            )?;
1583        }
1584    } else {
1585        let address = axis.clone();
1586        push_owned(
1587            requirements,
1588            address,
1589            PreparedTextRole::TickLabel,
1590            0,
1591            String::new(),
1592            &[],
1593            appearance,
1594            prepared_stage,
1595        )?;
1596    }
1597    Ok(())
1598}
1599
1600fn automatic_category_labels(
1601    plot: &PlotDescription,
1602    kind: PlotKind,
1603    x_axis: bool,
1604) -> Result<Option<Vec<String>>, Error> {
1605    if kind == PlotKind::Raincloud && x_axis {
1606        if let Some(input) = plot.raincloud_geometry_input() {
1607            return plot
1608                .resolve_label_domain(
1609                    "x-axis categories",
1610                    (0..input.data.category.len())
1611                        .filter_map(|row| input.data.category.get(row).flatten()),
1612                )
1613                .map(Some);
1614        }
1615    }
1616    plot.automatic_axis_category_values(kind, x_axis)
1617        .map(|values| {
1618            let normalized = matches!(
1619                (kind, x_axis),
1620                (PlotKind::Trajectory | PlotKind::Heatmap, true)
1621                    | (
1622                        PlotKind::Dumbbell | PlotKind::PointInterval | PlotKind::Heatmap,
1623                        false
1624                    )
1625            );
1626            let levels = if normalized {
1627                Cow::Owned(
1628                    values
1629                        .levels()
1630                        .iter()
1631                        .map(|value| crate::data::collapse_whitespace(value))
1632                        .collect::<Vec<_>>(),
1633                )
1634            } else {
1635                Cow::Borrowed(values.levels())
1636            };
1637            plot.resolve_label_domain(
1638                if x_axis {
1639                    "x-axis categories"
1640                } else {
1641                    "y-axis categories"
1642                },
1643                levels.iter().map(String::as_str),
1644            )
1645        })
1646        .transpose()
1647}
1648
1649#[expect(
1650    clippy::too_many_arguments,
1651    reason = "one census insertion keeps the complete structural text identity explicit"
1652)]
1653fn push_owned<'a, 'b>(
1654    requirements: &mut Vec<PreparedTextRequirement>,
1655    address: ComponentAddress,
1656    role: PreparedTextRole,
1657    local_index: u32,
1658    source: impl Into<CensusSource<'a>>,
1659    generated_alphabet: &[char],
1660    appearance: impl Into<crate::text::TextAppearance<'b>>,
1661    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1662) -> Result<(), Error> {
1663    PreparedTextRequirement::push_into(
1664        requirements,
1665        address,
1666        role,
1667        local_index,
1668        source,
1669        generated_alphabet,
1670        appearance,
1671        prepared_stage,
1672    )
1673    .map_err(|error| Error::from(error).with_prefix("prepared text census"))
1674}
1675
1676fn visit_pair_scalars(
1677    requirements: &[PreparedTextRequirement],
1678    pair_ordinal: u32,
1679    mut visit: impl FnMut(char) -> Result<(), PreparedTextCensusError>,
1680) -> Result<(), PreparedTextCensusError> {
1681    for requirement in requirements
1682        .iter()
1683        .filter(|requirement| requirement.pair_ordinal == pair_ordinal)
1684    {
1685        let mut needs_hyphen = false;
1686        for scalar in requirement.source.chars() {
1687            needs_hyphen |= scalar == '\u{00AD}';
1688            visit(scalar)?;
1689        }
1690        // A selected discretionary break paints this scalar in the owning pair.
1691        // Keep its occurrence in admission even if an explicit alphabet repeats it.
1692        if needs_hyphen {
1693            visit('-')?;
1694        }
1695        for &scalar in &requirement.generated_alphabet {
1696            visit(scalar)?;
1697        }
1698    }
1699    Ok(())
1700}
1701
1702#[derive(Debug, thiserror::Error)]
1703pub(crate) enum PreparedTextCensusError {
1704    #[error("production text census requires the root prepared stage")]
1705    MissingPreparedStage,
1706    #[error(transparent)]
1707    Font(#[from] canonical::FontError),
1708    #[error("prepared generated text alphabet must be strictly ascending")]
1709    GeneratedAlphabetOrder,
1710    #[error("prepared text census contains a duplicate address/role/index identity")]
1711    DuplicateIdentity,
1712    #[error("prepared text census is missing the requested font stack/weight pair")]
1713    MissingPair,
1714    #[error("prepared text census arithmetic overflow while calculating {0}")]
1715    Arithmetic(&'static str),
1716    #[error("prepared text census could not reserve {0}")]
1717    Allocation(&'static str),
1718    #[error("{0}")]
1719    Reservation(crate::Error),
1720}
1721
1722impl From<PreparedTextCensusError> for Error {
1723    fn from(error: PreparedTextCensusError) -> Self {
1724        match error {
1725            PreparedTextCensusError::Font(error) => error.into(),
1726            PreparedTextCensusError::Reservation(error) => error,
1727            error => Error::Render(error.to_string().into()),
1728        }
1729    }
1730}
1731
1732#[cfg(test)]
1733mod tests {
1734    use super::*;
1735    use crate::theme::Color;
1736
1737    fn appearance(stack: &str, weight: TextWeight) -> TextTheme {
1738        TextTheme::new(
1739            canonical::named_stack(&[stack]),
1740            Color::rgb(0, 0, 0),
1741            12.0,
1742            weight,
1743            1.2,
1744        )
1745        .unwrap()
1746    }
1747
1748    fn requirement(
1749        address: ComponentAddress,
1750        role: PreparedTextRole,
1751        index: u32,
1752        source: &str,
1753        generated: &[char],
1754        appearance: &TextTheme,
1755    ) -> PreparedTextRequirement {
1756        PreparedTextRequirement::new(address, role, index, source, generated, appearance).unwrap()
1757    }
1758
1759    #[test]
1760    fn census_resolves_each_pair_once_with_its_complete_scalar_union() {
1761        let normal = appearance("Test Sans", TextWeight::Normal);
1762        let bold = appearance("Test Sans", TextWeight::Bold);
1763        let mut census = PreparedTextCensus::materialize(
1764            vec![
1765                requirement(
1766                    ComponentAddress::root(),
1767                    PreparedTextRole::Title,
1768                    0,
1769                    "A",
1770                    &[],
1771                    &normal,
1772                ),
1773                requirement(
1774                    ComponentAddress::root(),
1775                    PreparedTextRole::SignificanceLabel,
1776                    0,
1777                    " ",
1778                    &[],
1779                    &bold,
1780                ),
1781            ],
1782            None,
1783            None,
1784        )
1785        .unwrap();
1786        let environment = PreparedFontEnvironment::synthetic();
1787        let mut presence = vec![0; SCALAR_MAP_WORDS];
1788
1789        crate::font::canonical::FONT_PAIR_RESOLUTION_CALLS.with(|calls| calls.set(0));
1790        census
1791            .prepare_fonts_in(&environment, &mut presence)
1792            .unwrap();
1793
1794        let stack = canonical::named_stack(&["Test Sans"]);
1795        assert_eq!(
1796            environment
1797                .prepared_pair(&stack, RequestedWeight::Normal)
1798                .unwrap()
1799                .unwrap()
1800                .selected_scalars
1801                .len(),
1802            1
1803        );
1804        assert_eq!(
1805            environment
1806                .prepared_pair(&stack, RequestedWeight::Bold)
1807                .unwrap()
1808                .unwrap()
1809                .provenance
1810                .pair_ordinal,
1811            1
1812        );
1813        crate::font::canonical::FONT_PAIR_RESOLUTION_CALLS.with(|calls| assert_eq!(calls.get(), 2));
1814
1815        environment
1816            .plan_text(crate::layout::TextPlanInput {
1817                size_trace: None,
1818                direction: crate::text::TextDirection::Auto,
1819                source: "A",
1820                stack: canonical::test_sans_stack(),
1821                weight: TextWeight::Normal,
1822                font_size: 10.0,
1823                line_height: crate::layout::TextLineHeight::Multiplier(1.2),
1824                maximum_width_quanta: i64::MAX,
1825                alignment: crate::layout::PhysicalTextAlignment::Start,
1826                paint: Color::rgb(0, 0, 0),
1827                provenance: crate::layout::TextPlanProvenance {
1828                    pair_ordinal: u32::MAX,
1829                    owner: "prepared census test".into(),
1830                },
1831                exact_override: false,
1832            })
1833            .unwrap();
1834        crate::font::canonical::FONT_PAIR_RESOLUTION_CALLS.with(|calls| assert_eq!(calls.get(), 2));
1835
1836        environment.operation().unwrap().seal_fonts().unwrap();
1837        let missing = environment
1838            .plan_text(crate::layout::TextPlanInput {
1839                size_trace: None,
1840                direction: crate::text::TextDirection::Auto,
1841                source: "B",
1842                stack: canonical::test_sans_stack(),
1843                weight: TextWeight::Normal,
1844                font_size: 10.0,
1845                line_height: crate::layout::TextLineHeight::Multiplier(1.2),
1846                maximum_width_quanta: i64::MAX,
1847                alignment: crate::layout::PhysicalTextAlignment::Start,
1848                paint: Color::rgb(0, 0, 0),
1849                provenance: crate::layout::TextPlanProvenance {
1850                    pair_ordinal: u32::MAX,
1851                    owner: "uncensused scalar test".into(),
1852                },
1853                exact_override: false,
1854            })
1855            .unwrap_err();
1856        assert!(matches!(
1857            missing,
1858            crate::layout::TextPlanError::Font(canonical::FontError::PreparedPairAfterSeal {
1859                pair_ordinal: 0
1860            })
1861        ));
1862        crate::font::canonical::FONT_PAIR_RESOLUTION_CALLS.with(|calls| assert_eq!(calls.get(), 2));
1863    }
1864}