Skip to main content

lichtung_plot/layout/
kernel.rs

1//! Bounded root requests, parent feedback and operation-scoped preparation resources.
2
3use std::cmp::Ordering;
4
5use super::RootSize;
6use crate::Error;
7
8const QUANTA_PER_CSS_PIXEL: i64 = 1024;
9
10pub(crate) fn nearest_spatial_quanta(value: f64) -> Result<i64, Error> {
11    LayoutScalar::from_css_pixels(value, SpatialRounding::NearestEven).map(|value| value.0)
12}
13
14pub(crate) fn ceil_spatial_quanta(value: f64) -> Result<i64, Error> {
15    LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil).map(|value| value.0)
16}
17
18#[cfg(test)]
19thread_local! {
20    static FORCED_RESERVATION_FAILURE: std::cell::Cell<Option<ReservationStage>> = const { std::cell::Cell::new(None) };
21}
22
23#[cfg(test)]
24pub(crate) fn force_reservation_failure(stage: ReservationStage) {
25    FORCED_RESERVATION_FAILURE.with(|forced| forced.set(Some(stage)));
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
29pub(crate) struct LayoutScalar(i64);
30
31#[derive(Debug, Clone, Copy)]
32pub(crate) enum SpatialRounding {
33    Floor,
34    Ceil,
35    NearestEven,
36}
37
38impl LayoutScalar {
39    pub(crate) const fn from_quanta(value: i64) -> Self {
40        Self(value)
41    }
42
43    pub(crate) const fn quanta(self) -> i64 {
44        self.0
45    }
46
47    fn is_nonnegative(self) -> bool {
48        self.0 >= 0
49    }
50
51    fn canonical_dimension(self) -> Option<u32> {
52        let value = u128::try_from(self.0).ok()?;
53        let quantum = QUANTA_PER_CSS_PIXEL as u128;
54        let rounded = value.checked_add(quantum - 1)? / quantum;
55        u32::try_from(rounded).ok()
56    }
57
58    pub(crate) fn from_css_pixels(value: f64, rounding: SpatialRounding) -> Result<Self, Error> {
59        let bits = value.to_bits();
60        let exponent_bits = ((bits >> 52) & 0x7ff) as u16;
61        if exponent_bits == 0x7ff {
62            return Err(Error::Render("layout spatial input must be finite".into()));
63        }
64        let fraction = bits & 0x000f_ffff_ffff_ffff;
65        if exponent_bits == 0 && fraction == 0 {
66            return Ok(Self(0));
67        }
68        let negative = bits >> 63 != 0;
69        let significand = if exponent_bits == 0 {
70            u128::from(fraction)
71        } else {
72            u128::from((1_u64 << 52) | fraction)
73        };
74        let shift = if exponent_bits == 0 {
75            -1064
76        } else {
77            i32::from(exponent_bits) - 1065
78        };
79        let (quotient, remainder_order) = if shift >= 0 {
80            let shift = u32::try_from(shift)
81                .map_err(|_| Error::Render("layout quantum shift overflowed".into()))?;
82            if shift >= u128::BITS || significand > (u128::MAX >> shift) {
83                return Err(Error::Render("layout quantum conversion overflowed".into()));
84            }
85            (significand << shift, None)
86        } else {
87            let denominator_shift = shift.unsigned_abs();
88            if denominator_shift >= 128 {
89                (0, Some(Ordering::Less))
90            } else {
91                let denominator = 1_u128 << denominator_shift;
92                let quotient = significand / denominator;
93                let remainder = significand % denominator;
94                (
95                    quotient,
96                    (remainder != 0).then(|| remainder.cmp(&(denominator / 2))),
97                )
98            }
99        };
100        let increment = match remainder_order {
101            None => false,
102            Some(order) => match rounding {
103                SpatialRounding::Floor => negative,
104                SpatialRounding::Ceil => !negative,
105                SpatialRounding::NearestEven => {
106                    order == Ordering::Greater || (order == Ordering::Equal && quotient % 2 != 0)
107                }
108            },
109        };
110        let magnitude = quotient
111            .checked_add(u128::from(increment))
112            .ok_or_else(|| Error::Render("layout quantum rounding overflowed".into()))?;
113        if negative {
114            if magnitude == 1_u128 << 63 {
115                Ok(Self(i64::MIN))
116            } else {
117                let magnitude = i64::try_from(magnitude)
118                    .map_err(|_| Error::Render("layout quantum conversion overflowed".into()))?;
119                Ok(Self(-magnitude))
120            }
121        } else {
122            i64::try_from(magnitude)
123                .map(Self)
124                .map_err(|_| Error::Render("layout quantum conversion overflowed".into()))
125        }
126    }
127}
128
129#[allow(
130    dead_code,
131    reason = "the closed role order is part of canonical structural identity"
132)]
133#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
134#[repr(u16)]
135/// Role of a component in the actual measured layout.
136#[non_exhaustive]
137pub enum AddressRole {
138    /// Root component.
139    Root,
140    /// Root title component.
141    RootTitle,
142    /// Root subtitle component.
143    RootSubtitle,
144    /// Root body component.
145    RootBody,
146    /// Root caption component.
147    RootCaption,
148    /// Plot body component.
149    PlotBody,
150    /// Canvas body component.
151    CanvasBody,
152    /// Canvas grid component.
153    CanvasGrid,
154    /// Facet grid component.
155    FacetGrid,
156    /// Canvas shared legend component.
157    CanvasSharedLegend,
158    /// Canvas header component.
159    CanvasHeader,
160    /// Canvas row title component.
161    CanvasRowTitle,
162    /// Canvas range group component.
163    CanvasRangeGroup,
164    /// Canvas cell component.
165    CanvasCell,
166    /// Facet header component.
167    FacetHeader,
168    /// Facet row title component.
169    FacetRowTitle,
170    /// Facet range group component.
171    FacetRangeGroup,
172    /// Facet cell component.
173    FacetCell,
174    /// Data panel component.
175    DataPanel,
176    /// Panel interior component.
177    PanelInterior,
178    /// Specialized interior component.
179    SpecializedInterior,
180    /// Mark layer component.
181    MarkLayer,
182    /// Mark item component.
183    MarkItem,
184    /// Heatmap cell component.
185    HeatmapCell,
186    /// Heatmap merged row component.
187    HeatmapMergedRow,
188    /// Heatmap value label component.
189    HeatmapValueLabel,
190    /// Heatmap highlight component.
191    HeatmapHighlight,
192    /// Beeswarm category component.
193    BeeswarmCategory,
194    /// Beeswarm point component.
195    BeeswarmPoint,
196    /// Marginal central component.
197    MarginalCentral,
198    /// Marginal top component.
199    MarginalTop,
200    /// Marginal right component.
201    MarginalRight,
202    /// Matrix cell component.
203    MatrixCell,
204    /// Matrix mark component.
205    MatrixMark,
206    /// Categorical category component.
207    CategoricalCategory,
208    /// Categorical series slot component.
209    CategoricalSeriesSlot,
210    /// Categorical body mark component.
211    CategoricalBodyMark,
212    /// Categorical interval component.
213    CategoricalInterval,
214    /// Categorical value label component.
215    CategoricalValueLabel,
216    /// Waterfall bar component.
217    WaterfallBar,
218    /// Waterfall connector component.
219    WaterfallConnector,
220    /// Waterfall base label component.
221    WaterfallBaseLabel,
222    /// Waterfall terminal label component.
223    WaterfallTerminalLabel,
224    /// Legend section component.
225    LegendSection,
226    /// Legend title component.
227    LegendTitle,
228    /// Legend entry component.
229    LegendEntry,
230    /// Legend key component.
231    LegendKey,
232    /// Legend label component.
233    LegendLabel,
234    /// Guide title component.
235    GuideTitle,
236    /// Guide gradient component.
237    GuideGradient,
238    /// Guide label component.
239    GuideLabel,
240    /// Guide missing block component.
241    GuideMissingBlock,
242    /// Surface component.
243    Surface,
244    /// Text panel content component.
245    TextPanelContent,
246    /// Text panel title component.
247    TextPanelTitle,
248    /// Text panel body component.
249    TextPanelBody,
250    /// Inside guide component.
251    InsideGuide,
252    /// Annotation component.
253    Annotation,
254    /// Annotation target component.
255    AnnotationTarget,
256    /// Other overlay component.
257    OtherOverlay,
258    /// Axis top component.
259    AxisTop,
260    /// Axis right component.
261    AxisRight,
262    /// Axis bottom component.
263    AxisBottom,
264    /// Axis left component.
265    AxisLeft,
266    /// Axis title component.
267    AxisTitle,
268    /// Outside guide top component.
269    OutsideGuideTop,
270    /// Outside guide right component.
271    OutsideGuideRight,
272    /// Outside guide bottom component.
273    OutsideGuideBottom,
274    /// Outside guide left component.
275    OutsideGuideLeft,
276    /// Outside guide auto component.
277    OutsideGuideAuto,
278    /// Preference metric component.
279    PreferenceMetric,
280    /// Text component.
281    Text,
282    /// Glyph component.
283    Glyph,
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
287/// One real structural address segment.
288pub struct AddressSegment {
289    /// Actual component role.
290    pub role: AddressRole,
291    /// Zero-based slot within that role.
292    pub slot_index: u32,
293}
294
295#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
296/// Address of a measured component within its native root.
297pub struct ComponentAddress {
298    root: AddressSegment,
299    descendants: Option<std::sync::Arc<Vec<AddressSegment>>>,
300}
301
302impl std::fmt::Debug for ComponentAddress {
303    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        formatter
305            .debug_struct("ComponentAddress")
306            .field("root", &self.root)
307            .field("descendants", &self.descendants())
308            .finish()
309    }
310}
311
312impl ComponentAddress {
313    /// Ordered structural address of this measured component, beginning at root.
314    pub fn segments(&self) -> impl Iterator<Item = AddressSegment> + '_ {
315        std::iter::once(self.root).chain(self.descendants().iter().copied())
316    }
317
318    fn descendants(&self) -> &[AddressSegment] {
319        self.descendants.as_deref().map_or(&[], Vec::as_slice)
320    }
321
322    pub(crate) fn leaf_role(&self) -> AddressRole {
323        self.descendants()
324            .last()
325            .map_or(self.root.role, |segment| segment.role)
326    }
327
328    pub(crate) fn leaf_slot_index(&self) -> u32 {
329        self.descendants().last().unwrap_or(&self.root).slot_index
330    }
331
332    pub(crate) fn under_grid(&self, grid: AddressRole) -> Result<Self, Error> {
333        let [leaf] = self.descendants() else {
334            return Err(Error::Render(
335                "child owner must be one root-local cell".into(),
336            ));
337        };
338        Self::root()
339            .child(grid, 0)?
340            .child(leaf.role, leaf.slot_index)
341    }
342    fn is_within(&self, owner: &Self) -> bool {
343        self.root == owner.root && self.descendants().starts_with(owner.descendants())
344    }
345    pub(crate) fn root() -> Self {
346        Self {
347            root: AddressSegment {
348                role: AddressRole::Root,
349                slot_index: 0,
350            },
351            descendants: None,
352        }
353    }
354
355    pub(crate) fn child(&self, role: AddressRole, slot_index: u32) -> Result<Self, Error> {
356        let count = self
357            .descendants()
358            .len()
359            .checked_add(1)
360            .ok_or_else(|| Error::Render("component address length overflowed".into()))?;
361
362        // The immutable path owns its Vec header and each actual segment. A
363        // scope, failure, or feedback clone only shares that admitted payload.
364
365        let mut descendants = Vec::new();
366        crate::operation::check()?;
367        descendants.try_reserve_exact(count).map_err(|error| {
368            Error::Render(
369                format!("layout could not reserve canonical component address: {error}").into(),
370            )
371        })?;
372        descendants.extend_from_slice(self.descendants());
373        descendants.push(AddressSegment { role, slot_index });
374        Ok(Self {
375            root: self.root,
376            descendants: Some(std::sync::Arc::new(descendants)),
377        })
378    }
379
380    pub(crate) fn canonical_text_cmp(&self, other: &Self) -> Ordering {
381        let root = (
382            self.root.role.text_traversal_ordinal(),
383            self.root.slot_index,
384        )
385            .cmp(&(
386                other.root.role.text_traversal_ordinal(),
387                other.root.slot_index,
388            ));
389        if root != Ordering::Equal {
390            return root;
391        }
392        self.descendants()
393            .iter()
394            .map(|segment| (segment.role.text_traversal_ordinal(), segment.slot_index))
395            .cmp(
396                other
397                    .descendants()
398                    .iter()
399                    .map(|segment| (segment.role.text_traversal_ordinal(), segment.slot_index)),
400            )
401    }
402}
403
404impl AddressRole {
405    const fn text_traversal_ordinal(self) -> u16 {
406        match self {
407            // Plot and Canvas preorder visit their frame/body before the caption.
408            Self::RootCaption => u16::MAX,
409            _ => self as u16,
410        }
411    }
412}
413
414pub(crate) struct PreparedStage<'a> {
415    resources: &'a mut crate::font::canonical::OperationContext,
416    reservations: &'a mut ReservationDriver,
417}
418
419impl PreparedStage<'_> {
420    pub(crate) fn reserve_scalar_presence_map(&mut self) -> Result<Vec<u64>, Error> {
421        const SCALAR_MAP_WORDS: usize = 0x11_0000 / u64::BITS as usize;
422        let mut presence = Vec::new();
423        self.reserve_prepared(
424            &mut presence,
425            SCALAR_MAP_WORDS,
426            "Unicode scalar presence map",
427        )?;
428        presence.resize(SCALAR_MAP_WORDS, 0);
429        Ok(presence)
430    }
431
432    pub(crate) fn reserve_prepared<T>(
433        &mut self,
434        values: &mut Vec<T>,
435        additional: usize,
436        payload: &str,
437    ) -> Result<(), Error> {
438        self.reservations.reserve_additional(
439            ReservationStage::Prepared,
440            values,
441            additional,
442            payload,
443        )
444    }
445
446    pub(crate) fn reserve_prepared_string(
447        &mut self,
448        value: &mut String,
449        additional: usize,
450        payload: &str,
451    ) -> Result<(), Error> {
452        self.reservations
453            .enter(ReservationStage::Prepared, payload)?;
454        crate::operation::check()?;
455        value
456            .try_reserve_exact(additional)
457            .map_err(|error| reservation_error(ReservationStage::Prepared, payload, error))
458    }
459
460    pub(crate) fn operation(&self) -> crate::font::canonical::OperationContext {
461        self.resources.clone()
462    }
463}
464
465pub(crate) struct FinalStage<'a> {
466    reservations: &'a mut ReservationDriver,
467}
468
469impl FinalStage<'_> {
470    pub(crate) fn reserve_capture<T>(
471        &mut self,
472        values: &mut Vec<T>,
473        additional: usize,
474        payload: &str,
475    ) -> Result<(), Error> {
476        let needed = values
477            .len()
478            .checked_add(additional)
479            .ok_or_else(|| Error::Render(format!("{payload}: capture length overflow").into()))?;
480        if needed <= values.capacity() {
481            return Ok(());
482        }
483        let capacity = needed.max(values.capacity().saturating_mul(2));
484
485        self.reserve_final(values, capacity - values.len(), payload)
486    }
487
488    pub(crate) fn reserve_final<T>(
489        &mut self,
490        values: &mut Vec<T>,
491        additional: usize,
492        payload: &str,
493    ) -> Result<(), Error> {
494        self.reservations
495            .reserve_additional(ReservationStage::Final, values, additional, payload)
496    }
497}
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
500pub(crate) enum ReservationStage {
501    Prepared,
502    Measured,
503    Final,
504}
505
506impl ReservationStage {
507    pub(crate) fn number(self) -> u8 {
508        match self {
509            Self::Prepared => 1,
510            Self::Measured => 2,
511            Self::Final => 3,
512        }
513    }
514}
515
516struct ReservationDriver {
517    phase: ReservationStage,
518}
519
520impl ReservationDriver {
521    fn new() -> Self {
522        Self {
523            phase: ReservationStage::Prepared,
524        }
525    }
526
527    fn reserve_additional<T>(
528        &mut self,
529        stage: ReservationStage,
530        values: &mut Vec<T>,
531        additional: usize,
532        payload: &str,
533    ) -> Result<(), Error> {
534        self.enter(stage, payload)?;
535        crate::operation::check()?;
536        values
537            .try_reserve_exact(additional)
538            .map_err(|error| reservation_error(stage, payload, error))
539    }
540
541    fn enter(&mut self, stage: ReservationStage, payload: &str) -> Result<(), Error> {
542        if self.phase != stage {
543            return Err(Error::Render(
544                format!(
545                    "layout reservation stage {} was requested out of order",
546                    stage.number()
547                )
548                .into(),
549            ));
550        }
551        #[cfg(test)]
552        if FORCED_RESERVATION_FAILURE.with(|forced| {
553            if forced.get() == Some(stage) {
554                forced.set(None);
555                true
556            } else {
557                false
558            }
559        }) {
560            return Err(reservation_error(stage, payload, "forced test refusal"));
561        }
562        let _ = payload;
563        Ok(())
564    }
565}
566
567fn reservation_error(
568    stage: ReservationStage,
569    payload: &str,
570    error: impl std::fmt::Display,
571) -> Error {
572    Error::Render(
573        format!(
574            "layout reservation stage {} could not reserve {payload}: {error}",
575            stage.number()
576        )
577        .into(),
578    )
579}
580
581/// One private root request; measurement resolves both dimensions before freeze.
582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
583pub(crate) enum RootRequest {
584    Natural,
585    ExactWidth(u64),
586    MaxWidth(u32),
587    ExactHeight(u64),
588    ExactSize(RootSize),
589}
590
591impl RootRequest {
592    pub(crate) const fn width(width: f64) -> Self {
593        Self::ExactWidth(width.to_bits())
594    }
595
596    pub(crate) fn height(height: f64) -> Self {
597        Self::ExactHeight(height.to_bits())
598    }
599
600    pub(crate) const fn size(width: f64, height: f64) -> Self {
601        Self::ExactSize(RootSize::css(width, height))
602    }
603
604    pub(crate) fn select_width(self, preference: f64) -> Result<f64, Error> {
605        self.validate()?;
606        if let Some(width) = self.exact_width() {
607            return Ok(width);
608        }
609        if !preference.is_finite() || preference <= 0.0 {
610            return Err(Error::Render(
611                "natural root width preference must be finite and positive".into(),
612            ));
613        }
614        Ok(f64::from(root_dimension(match self {
615            Self::MaxWidth(maximum) => preference.min(f64::from(maximum)),
616            _ => preference,
617        })?))
618    }
619
620    pub(crate) fn exact_width(self) -> Option<f64> {
621        match self {
622            Self::ExactWidth(width) => Some(f64::from_bits(width)),
623            Self::ExactSize(size) => size.dimensions().ok().map(|size| size.0),
624            _ => None,
625        }
626    }
627
628    pub(crate) const fn exact_height(self) -> Option<f64> {
629        match self {
630            Self::ExactHeight(height) => Some(f64::from_bits(height)),
631            _ => None,
632        }
633    }
634
635    pub(crate) const fn exact_size(self) -> Option<RootSize> {
636        match self {
637            Self::ExactSize(size) => Some(size),
638            _ => None,
639        }
640    }
641
642    pub(crate) const fn automatic_height(self) -> bool {
643        !matches!(self, Self::ExactSize(_) | Self::ExactHeight(_))
644    }
645
646    #[cfg(test)]
647    pub(crate) fn assigned_size(self) -> Result<RootSize, Error> {
648        let size = self.exact_size().ok_or_else(|| {
649            Error::Render("root content measurement must provide both finite dimensions".into())
650        })?;
651        size.dimensions()?;
652        Ok(size)
653    }
654
655    #[cfg(test)]
656    pub(crate) fn dimensions(self) -> Result<(f64, f64), Error> {
657        self.assigned_size()?.dimensions()
658    }
659
660    pub(crate) fn validate(self) -> Result<(), Error> {
661        if let Some(size) = self.exact_size() {
662            size.dimensions()?;
663        } else {
664            let width = self.exact_width().unwrap_or(1.);
665            let height = self.exact_height().unwrap_or(1.);
666            RootSize::new(width, height).dimensions()?;
667            if matches!(self, Self::MaxWidth(0)) {
668                return Err(Error::Render(
669                    "layout maximum width must be positive".into(),
670                ));
671            }
672        }
673        Ok(())
674    }
675
676    fn validate_size(self, size: RootSize) -> Result<(), Error> {
677        let (width, height) = size.dimensions()?;
678        if matches!(self, Self::MaxWidth(maximum) if width > f64::from(maximum)) {
679            return Err(Error::Render(
680                "measured root width exceeds its maximum-width sizing request".into(),
681            ));
682        }
683        if let Some(exact) = self.exact_size() {
684            if size != exact {
685                return Err(Error::Render(
686                    "measured root dimensions do not match the exact assignment".into(),
687                ));
688            }
689        } else if self.exact_width().map_or(width.fract() != 0., |exact| {
690            width.to_bits() != exact.to_bits()
691        }) || self.exact_height().map_or(height.fract() != 0., |exact| {
692            height.to_bits() != exact.to_bits()
693        }) {
694            return Err(Error::Render(
695                "measured root dimensions do not match the sizing request".into(),
696            ));
697        }
698        Ok(())
699    }
700}
701pub(crate) struct MeasuredLayout<Plan> {
702    size: RootSize,
703    plan: Plan,
704}
705
706impl<Plan> MeasuredLayout<Plan> {
707    pub(crate) fn new(size: RootSize, plan: Plan) -> Self {
708        Self { size, plan }
709    }
710}
711
712struct RootAllocation<Plan> {
713    request: RootRequest,
714    size: RootSize,
715    plan: Plan,
716}
717
718/// One result frozen after parent feedback. Final admission remains a separate stage.
719pub(crate) struct FrozenRoot<Plan> {
720    allocation: Box<[RootAllocation<Plan>; 1]>,
721}
722
723impl<Plan> FrozenRoot<Plan> {
724    pub(crate) fn size(&self) -> RootSize {
725        self.allocation[0]
726            .request
727            .validate_size(self.allocation[0].size)
728            .expect("frozen root satisfies its original sizing request");
729        self.allocation[0].size
730    }
731    pub(crate) fn plan(&self) -> &Plan {
732        &self.allocation[0].plan
733    }
734}
735
736mod feedback;
737mod tracks;
738pub(crate) use feedback::TrialOutcome;
739pub(crate) use feedback::{ChildFeedback, ChildFeedbackInputs};
740pub(crate) use feedback::{
741    FeedbackKind, FeedbackRequestId, FeedbackRound, FitKind, FrameRequirements,
742};
743pub(crate) use tracks::{allocate_grid_axis, allocate_tracks, GridRequirement, TrackSpec};
744
745pub(crate) fn required_length(value: f64) -> Result<f64, Error> {
746    let length = LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil)?;
747    if !length.is_nonnegative() {
748        return Err(Error::Render(
749            "required layout length must be nonnegative".into(),
750        ));
751    }
752    #[expect(
753        clippy::cast_precision_loss,
754        reason = "required guide lengths are subsequently checked against exact u32 root constraints"
755    )]
756    let value = length.0 as f64 / 1024.0;
757    Ok(value)
758}
759
760pub(crate) fn root_dimension(value: f64) -> Result<u32, Error> {
761    LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil)?
762        .canonical_dimension()
763        .filter(|value| *value > 0)
764        .ok_or_else(|| {
765            Error::Render(
766                "natural root dimension is not representable as positive CSS pixels".into(),
767            )
768        })
769}
770
771pub(crate) fn prepare_only<T>(
772    prepare: impl FnOnce(&mut PreparedStage<'_>) -> Result<T, Error>,
773) -> Result<T, Error> {
774    crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
775    let mut resources = crate::font::canonical::OperationContext::new();
776    let mut reservations = ReservationDriver::new();
777    prepare(&mut PreparedStage {
778        resources: &mut resources,
779        reservations: &mut reservations,
780    })
781}
782
783/// Prepare once, coordinate at most eight complete rounds, then freeze once.
784#[cfg(test)]
785pub(crate) fn plan_root<Plan, FinalPlan, Prepared>(
786    request: RootRequest,
787    prepare: impl FnOnce(&mut PreparedStage<'_>) -> Result<Prepared, Error>,
788    measure: impl FnMut(
789        &Prepared,
790        RootRequest,
791        &mut FeedbackRound,
792    ) -> Result<MeasuredLayout<Plan>, Error>,
793    finalize: impl FnOnce(&Prepared, RootSize, Plan, &mut FinalStage<'_>) -> Result<FinalPlan, Error>,
794) -> Result<FrozenRoot<FinalPlan>, Error> {
795    plan_root_with_results(request, false, prepare, measure, finalize)
796}
797
798#[expect(
799    clippy::too_many_lines,
800    reason = "the complete root prepare, feedback, seal and freeze lifecycle stays ordered"
801)]
802pub(crate) fn plan_root_with_results<Plan, FinalPlan, Prepared>(
803    request: RootRequest,
804    capture_results: bool,
805    prepare: impl FnOnce(&mut PreparedStage<'_>) -> Result<Prepared, Error>,
806    mut measure: impl FnMut(
807        &Prepared,
808        RootRequest,
809        &mut FeedbackRound,
810    ) -> Result<MeasuredLayout<Plan>, Error>,
811    finalize: impl FnOnce(&Prepared, RootSize, Plan, &mut FinalStage<'_>) -> Result<FinalPlan, Error>,
812) -> Result<FrozenRoot<FinalPlan>, Error> {
813    use crate::{errors::OperationPhase, operation};
814    request.validate()?;
815    operation::phase(OperationPhase::Prepare)?;
816    let mut assigned = request;
817    let mut resources = crate::font::canonical::OperationContext::with_results(capture_results);
818    let mut reservations = ReservationDriver::new();
819    let mut prepared_stage = PreparedStage {
820        resources: &mut resources,
821        reservations: &mut reservations,
822    };
823
824    let prepared = prepare(&mut prepared_stage)?;
825    operation::phase(OperationPhase::Layout)?;
826
827    reservations.phase = ReservationStage::Measured;
828    let mut history = Vec::new();
829    reservations.reserve_additional(
830        ReservationStage::Measured,
831        &mut history,
832        1,
833        "measured root plan",
834    )?;
835    let measured = loop {
836        operation::checkpoint()?;
837        let mut round = FeedbackRound::new(history.last(), history.len())?;
838        round.observe_root_request(request)?;
839        if let Some(size) = assigned.exact_size() {
840            let (width, height) = size.dimensions()?;
841            round.observe_number(width)?;
842            round.observe_number(height)?;
843        } else if let Some(width) = assigned.exact_width() {
844            round.observe_number(width)?;
845        }
846        let result = measure(&prepared, assigned, &mut round)?;
847        assigned.validate_size(result.size)?;
848        request.validate_size(result.size)?;
849        // Automatic width is chosen by initial bottom-up composition exactly once.
850        if assigned.automatic_height() {
851            assigned = RootRequest::width(result.size.dimensions()?.0);
852        } else if assigned.exact_height().is_some() {
853            assigned = RootRequest::ExactSize(result.size);
854        }
855        let state = round.finish();
856        if let Some(error) = state.terminal_error() {
857            return Err(error);
858        }
859        // Measure and validate the current assignment before accepting its plan.
860        // Observation equality would require an unconditional duplicate pass.
861        if state.feedback_unchanged() {
862            if let Some(error) = state.unchanged_error() {
863                return Err(error);
864            }
865            break result;
866        }
867        if state.repeats_history(&history) {
868            use crate::errors::{
869                Diagnostic, DiagnosticKind, ErrorContext, NonConvergenceReason, OperationPhase,
870            };
871            return Err(Error::Render(
872                Diagnostic::new(
873                    DiagnosticKind::NonConvergence {
874                        algorithm: "root layout feedback",
875                        iterations: history.len() + 1,
876                        reason: NonConvergenceReason::Cycle,
877                    },
878                    "layout root feedback cycle detected",
879                )
880                .with_context(ErrorContext::new().with_operation(OperationPhase::Layout)),
881            ));
882        }
883        if history.len() == 7 {
884            use crate::errors::{
885                BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, OperationPhase,
886            };
887            return Err(Error::Render(
888                Diagnostic::new(
889                    DiagnosticKind::BudgetExceeded {
890                        resource: BudgetResource::LayoutRounds,
891                        required: 9,
892                        limit: 8,
893                    },
894                    "layout root feedback exhausted eight rounds",
895                )
896                .with_context(ErrorContext::new().with_operation(OperationPhase::Layout)),
897            ));
898        }
899        reservations.reserve_additional(
900            ReservationStage::Measured,
901            &mut history,
902            1,
903            "root feedback state",
904        )?;
905        history.push(state);
906    };
907    let assigned = measured.size;
908
909    operation::phase(OperationPhase::Freeze)?;
910    resources
911        .seal_fonts()
912        .map_err(|error| Error::from(error).with_prefix("accepted root font sealing"))?;
913    reservations.phase = ReservationStage::Final;
914    let mut allocation = Vec::new();
915    let mut final_stage = FinalStage {
916        reservations: &mut reservations,
917    };
918    final_stage.reserve_final(&mut allocation, 1, "frozen root plan")?;
919    let plan = finalize(&prepared, assigned, measured.plan, &mut final_stage)?;
920    operation::checkpoint()?;
921    drop(prepared);
922    drop(history);
923    drop(resources);
924    allocation.push(RootAllocation {
925        request,
926        size: assigned,
927        plan,
928    });
929    let allocation = allocation
930        .into_boxed_slice()
931        .try_into()
932        .unwrap_or_else(|_| unreachable!("one frozen root allocation"));
933    Ok(FrozenRoot { allocation })
934}
935
936#[cfg(test)]
937#[path = "kernel/tests.rs"]
938mod tests;