use std::cmp::Ordering;
use super::RootSize;
use crate::Error;
const QUANTA_PER_CSS_PIXEL: i64 = 1024;
pub(crate) fn nearest_spatial_quanta(value: f64) -> Result<i64, Error> {
LayoutScalar::from_css_pixels(value, SpatialRounding::NearestEven).map(|value| value.0)
}
pub(crate) fn ceil_spatial_quanta(value: f64) -> Result<i64, Error> {
LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil).map(|value| value.0)
}
#[cfg(test)]
thread_local! {
static FORCED_RESERVATION_FAILURE: std::cell::Cell<Option<ReservationStage>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
pub(crate) fn force_reservation_failure(stage: ReservationStage) {
FORCED_RESERVATION_FAILURE.with(|forced| forced.set(Some(stage)));
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct LayoutScalar(i64);
#[derive(Debug, Clone, Copy)]
pub(crate) enum SpatialRounding {
Floor,
Ceil,
NearestEven,
}
impl LayoutScalar {
pub(crate) const fn from_quanta(value: i64) -> Self {
Self(value)
}
pub(crate) const fn quanta(self) -> i64 {
self.0
}
fn is_nonnegative(self) -> bool {
self.0 >= 0
}
fn canonical_dimension(self) -> Option<u32> {
let value = u128::try_from(self.0).ok()?;
let quantum = QUANTA_PER_CSS_PIXEL as u128;
let rounded = value.checked_add(quantum - 1)? / quantum;
u32::try_from(rounded).ok()
}
pub(crate) fn from_css_pixels(value: f64, rounding: SpatialRounding) -> Result<Self, Error> {
let bits = value.to_bits();
let exponent_bits = ((bits >> 52) & 0x7ff) as u16;
if exponent_bits == 0x7ff {
return Err(Error::Render("layout spatial input must be finite".into()));
}
let fraction = bits & 0x000f_ffff_ffff_ffff;
if exponent_bits == 0 && fraction == 0 {
return Ok(Self(0));
}
let negative = bits >> 63 != 0;
let significand = if exponent_bits == 0 {
u128::from(fraction)
} else {
u128::from((1_u64 << 52) | fraction)
};
let shift = if exponent_bits == 0 {
-1064
} else {
i32::from(exponent_bits) - 1065
};
let (quotient, remainder_order) = if shift >= 0 {
let shift = u32::try_from(shift)
.map_err(|_| Error::Render("layout quantum shift overflowed".into()))?;
if shift >= u128::BITS || significand > (u128::MAX >> shift) {
return Err(Error::Render("layout quantum conversion overflowed".into()));
}
(significand << shift, None)
} else {
let denominator_shift = shift.unsigned_abs();
if denominator_shift >= 128 {
(0, Some(Ordering::Less))
} else {
let denominator = 1_u128 << denominator_shift;
let quotient = significand / denominator;
let remainder = significand % denominator;
(
quotient,
(remainder != 0).then(|| remainder.cmp(&(denominator / 2))),
)
}
};
let increment = match remainder_order {
None => false,
Some(order) => match rounding {
SpatialRounding::Floor => negative,
SpatialRounding::Ceil => !negative,
SpatialRounding::NearestEven => {
order == Ordering::Greater || (order == Ordering::Equal && quotient % 2 != 0)
}
},
};
let magnitude = quotient
.checked_add(u128::from(increment))
.ok_or_else(|| Error::Render("layout quantum rounding overflowed".into()))?;
if negative {
if magnitude == 1_u128 << 63 {
Ok(Self(i64::MIN))
} else {
let magnitude = i64::try_from(magnitude)
.map_err(|_| Error::Render("layout quantum conversion overflowed".into()))?;
Ok(Self(-magnitude))
}
} else {
i64::try_from(magnitude)
.map(Self)
.map_err(|_| Error::Render("layout quantum conversion overflowed".into()))
}
}
}
#[allow(
dead_code,
reason = "the closed role order is part of canonical structural identity"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u16)]
#[non_exhaustive]
pub enum AddressRole {
Root,
RootTitle,
RootSubtitle,
RootBody,
RootCaption,
PlotBody,
CanvasBody,
CanvasGrid,
FacetGrid,
CanvasSharedLegend,
CanvasHeader,
CanvasRowTitle,
CanvasRangeGroup,
CanvasCell,
FacetHeader,
FacetRowTitle,
FacetRangeGroup,
FacetCell,
DataPanel,
PanelInterior,
SpecializedInterior,
MarkLayer,
MarkItem,
HeatmapCell,
HeatmapMergedRow,
HeatmapValueLabel,
HeatmapHighlight,
BeeswarmCategory,
BeeswarmPoint,
MarginalCentral,
MarginalTop,
MarginalRight,
MatrixCell,
MatrixMark,
CategoricalCategory,
CategoricalSeriesSlot,
CategoricalBodyMark,
CategoricalInterval,
CategoricalValueLabel,
WaterfallBar,
WaterfallConnector,
WaterfallBaseLabel,
WaterfallTerminalLabel,
LegendSection,
LegendTitle,
LegendEntry,
LegendKey,
LegendLabel,
GuideTitle,
GuideGradient,
GuideLabel,
GuideMissingBlock,
Surface,
TextPanelContent,
TextPanelTitle,
TextPanelBody,
InsideGuide,
Annotation,
AnnotationTarget,
OtherOverlay,
AxisTop,
AxisRight,
AxisBottom,
AxisLeft,
AxisTitle,
OutsideGuideTop,
OutsideGuideRight,
OutsideGuideBottom,
OutsideGuideLeft,
OutsideGuideAuto,
PreferenceMetric,
Text,
Glyph,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct AddressSegment {
pub role: AddressRole,
pub slot_index: u32,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ComponentAddress {
root: AddressSegment,
descendants: Option<std::sync::Arc<Vec<AddressSegment>>>,
}
impl std::fmt::Debug for ComponentAddress {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ComponentAddress")
.field("root", &self.root)
.field("descendants", &self.descendants())
.finish()
}
}
impl ComponentAddress {
pub fn segments(&self) -> impl Iterator<Item = AddressSegment> + '_ {
std::iter::once(self.root).chain(self.descendants().iter().copied())
}
fn descendants(&self) -> &[AddressSegment] {
self.descendants.as_deref().map_or(&[], Vec::as_slice)
}
pub(crate) fn leaf_role(&self) -> AddressRole {
self.descendants()
.last()
.map_or(self.root.role, |segment| segment.role)
}
pub(crate) fn leaf_slot_index(&self) -> u32 {
self.descendants().last().unwrap_or(&self.root).slot_index
}
pub(crate) fn under_grid(&self, grid: AddressRole) -> Result<Self, Error> {
let [leaf] = self.descendants() else {
return Err(Error::Render(
"child owner must be one root-local cell".into(),
));
};
Self::root()
.child(grid, 0)?
.child(leaf.role, leaf.slot_index)
}
fn is_within(&self, owner: &Self) -> bool {
self.root == owner.root && self.descendants().starts_with(owner.descendants())
}
pub(crate) fn root() -> Self {
Self {
root: AddressSegment {
role: AddressRole::Root,
slot_index: 0,
},
descendants: None,
}
}
pub(crate) fn child(&self, role: AddressRole, slot_index: u32) -> Result<Self, Error> {
let count = self
.descendants()
.len()
.checked_add(1)
.ok_or_else(|| Error::Render("component address length overflowed".into()))?;
let mut descendants = Vec::new();
crate::operation::capacity::<AddressSegment>(0, 0, count)?;
descendants.try_reserve_exact(count).map_err(|error| {
Error::Render(
format!("layout could not reserve canonical component address: {error}").into(),
)
})?;
descendants.extend_from_slice(self.descendants());
descendants.push(AddressSegment { role, slot_index });
Ok(Self {
root: self.root,
descendants: Some(std::sync::Arc::new(descendants)),
})
}
pub(crate) fn canonical_text_cmp(&self, other: &Self) -> Ordering {
let root = (
self.root.role.text_traversal_ordinal(),
self.root.slot_index,
)
.cmp(&(
other.root.role.text_traversal_ordinal(),
other.root.slot_index,
));
if root != Ordering::Equal {
return root;
}
self.descendants()
.iter()
.map(|segment| (segment.role.text_traversal_ordinal(), segment.slot_index))
.cmp(
other
.descendants()
.iter()
.map(|segment| (segment.role.text_traversal_ordinal(), segment.slot_index)),
)
}
}
impl AddressRole {
const fn text_traversal_ordinal(self) -> u16 {
match self {
Self::RootCaption => u16::MAX,
_ => self as u16,
}
}
}
pub(crate) struct PreparedStage<'a> {
resources: &'a mut crate::font::canonical::OperationContext,
reservations: &'a mut ReservationDriver,
}
impl PreparedStage<'_> {
pub(crate) fn reserve_scalar_presence_map(&mut self) -> Result<Vec<u64>, Error> {
const SCALAR_MAP_WORDS: usize = 0x11_0000 / u64::BITS as usize;
let mut presence = Vec::new();
self.reserve_prepared(
&mut presence,
SCALAR_MAP_WORDS,
"Unicode scalar presence map",
)?;
presence.resize(SCALAR_MAP_WORDS, 0);
Ok(presence)
}
pub(crate) fn reserve_prepared<T>(
&mut self,
values: &mut Vec<T>,
additional: usize,
payload: &str,
) -> Result<(), Error> {
self.reservations.reserve_additional(
ReservationStage::Prepared,
values,
additional,
payload,
)
}
pub(crate) fn reserve_prepared_string(
&mut self,
value: &mut String,
additional: usize,
payload: &str,
) -> Result<(), Error> {
self.reservations
.enter(ReservationStage::Prepared, payload)?;
crate::operation::capacity::<u8>(value.capacity(), value.len(), additional)?;
value
.try_reserve_exact(additional)
.map_err(|error| reservation_error(ReservationStage::Prepared, payload, error))
}
pub(crate) fn operation(&self) -> crate::font::canonical::OperationContext {
self.resources.clone()
}
}
pub(crate) struct FinalStage<'a> {
reservations: &'a mut ReservationDriver,
}
impl FinalStage<'_> {
pub(crate) fn reserve_capture<T>(
&mut self,
values: &mut Vec<T>,
additional: usize,
payload: &str,
) -> Result<(), Error> {
let needed = values
.len()
.checked_add(additional)
.ok_or_else(|| Error::Render(format!("{payload}: capture length overflow").into()))?;
if needed <= values.capacity() {
return Ok(());
}
let capacity = needed.max(values.capacity().saturating_mul(2));
self.reserve_final(values, capacity - values.len(), payload)
}
pub(crate) fn reserve_final<T>(
&mut self,
values: &mut Vec<T>,
additional: usize,
payload: &str,
) -> Result<(), Error> {
self.reservations
.reserve_additional(ReservationStage::Final, values, additional, payload)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReservationStage {
Prepared,
Measured,
Final,
}
impl ReservationStage {
pub(crate) fn number(self) -> u8 {
match self {
Self::Prepared => 1,
Self::Measured => 2,
Self::Final => 3,
}
}
}
struct ReservationDriver {
phase: ReservationStage,
}
impl ReservationDriver {
fn new() -> Self {
Self {
phase: ReservationStage::Prepared,
}
}
fn reserve_additional<T>(
&mut self,
stage: ReservationStage,
values: &mut Vec<T>,
additional: usize,
payload: &str,
) -> Result<(), Error> {
self.enter(stage, payload)?;
crate::operation::capacity::<T>(values.capacity(), values.len(), additional)?;
values
.try_reserve_exact(additional)
.map_err(|error| reservation_error(stage, payload, error))
}
fn enter(&mut self, stage: ReservationStage, payload: &str) -> Result<(), Error> {
if self.phase != stage {
return Err(Error::Render(
format!(
"layout reservation stage {} was requested out of order",
stage.number()
)
.into(),
));
}
#[cfg(test)]
if FORCED_RESERVATION_FAILURE.with(|forced| {
if forced.get() == Some(stage) {
forced.set(None);
true
} else {
false
}
}) {
return Err(reservation_error(stage, payload, "forced test refusal"));
}
let _ = payload;
Ok(())
}
}
fn reservation_error(
stage: ReservationStage,
payload: &str,
error: impl std::fmt::Display,
) -> Error {
Error::Render(
format!(
"layout reservation stage {} could not reserve {payload}: {error}",
stage.number()
)
.into(),
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RootRequest {
Natural,
ExactWidth(u32),
MaxWidth(u32),
ExactSize { width: u32, height: u32 },
Physical(RootSize),
}
impl RootRequest {
pub(crate) fn select_width(self, preference: f64) -> Result<u32, Error> {
self.validate()?;
if let Some(width) = self.exact_width() {
return Ok(width);
}
if !preference.is_finite() || preference <= 0.0 {
return Err(Error::Render(
"natural root width preference must be finite and positive".into(),
));
}
root_dimension(match self {
Self::MaxWidth(maximum) => preference.min(f64::from(maximum)),
_ => preference,
})
}
pub(crate) const fn exact_width(self) -> Option<u32> {
match self {
Self::Natural | Self::MaxWidth(_) | Self::Physical(_) => None,
Self::ExactWidth(width) | Self::ExactSize { width, .. } => Some(width),
}
}
pub(crate) fn exact_size(self) -> Option<RootSize> {
match self {
Self::ExactSize { width, height } => Some(RootSize::new(width, height)),
Self::Physical(size) => Some(size),
_ => None,
}
}
pub(crate) const fn automatic_height(self) -> bool {
!matches!(self, Self::ExactSize { .. } | Self::Physical(_))
}
#[cfg(test)]
pub(crate) fn assigned_size(self) -> Result<RootSize, Error> {
let size = self.exact_size().ok_or_else(|| {
Error::Render("root content measurement must provide both finite dimensions".into())
})?;
size.dimensions()?;
Ok(size)
}
#[cfg(test)]
pub(crate) fn dimensions(self) -> Result<(f64, f64), Error> {
self.assigned_size()?.dimensions()
}
fn validate(self) -> Result<(), Error> {
if let Some(size) = self.exact_size() {
size.dimensions()?;
} else if self.exact_width() == Some(0) || matches!(self, Self::MaxWidth(0)) {
return Err(Error::Render(
"layout root dimensions must be finite and positive".into(),
));
}
Ok(())
}
fn validate_size(self, size: RootSize) -> Result<(), Error> {
let (width, height) = size.dimensions()?;
if matches!(self, Self::MaxWidth(maximum) if width > f64::from(maximum)) {
return Err(Error::Render(
"measured root width exceeds its maximum-width sizing request".into(),
));
}
if let Some(exact) = self.exact_size() {
if size != exact {
return Err(Error::Render(
"measured root dimensions do not match the exact assignment".into(),
));
}
} else if width.fract() != 0.0
|| height.fract() != 0.0
|| self
.exact_width()
.is_some_and(|exact| width.to_bits() != f64::from(exact).to_bits())
{
return Err(Error::Render(
"measured root dimensions do not match the sizing request".into(),
));
}
Ok(())
}
}
pub(crate) struct MeasuredLayout<Plan> {
size: RootSize,
plan: Plan,
}
impl<Plan> MeasuredLayout<Plan> {
pub(crate) fn new(size: RootSize, plan: Plan) -> Self {
Self { size, plan }
}
}
struct RootAllocation<Plan> {
request: RootRequest,
size: RootSize,
plan: Plan,
}
pub(crate) struct FrozenRoot<Plan> {
allocation: Box<[RootAllocation<Plan>; 1]>,
}
impl<Plan> FrozenRoot<Plan> {
pub(crate) fn size(&self) -> RootSize {
self.allocation[0]
.request
.validate_size(self.allocation[0].size)
.expect("frozen root satisfies its original sizing request");
self.allocation[0].size
}
pub(crate) fn plan(&self) -> &Plan {
&self.allocation[0].plan
}
}
mod feedback;
mod tracks;
pub(crate) use feedback::TrialOutcome;
pub(crate) use feedback::{ChildFeedback, ChildFeedbackInputs};
pub(crate) use feedback::{
FeedbackKind, FeedbackRequestId, FeedbackRound, FitKind, FrameRequirements,
};
pub(crate) use tracks::{allocate_grid_axis, allocate_tracks, GridRequirement, TrackSpec};
pub(crate) fn required_length(value: f64) -> Result<f64, Error> {
let length = LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil)?;
if !length.is_nonnegative() {
return Err(Error::Render(
"required layout length must be nonnegative".into(),
));
}
#[expect(
clippy::cast_precision_loss,
reason = "required guide lengths are subsequently checked against exact u32 root constraints"
)]
let value = length.0 as f64 / 1024.0;
Ok(value)
}
pub(crate) fn root_dimension(value: f64) -> Result<u32, Error> {
LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil)?
.canonical_dimension()
.filter(|value| *value > 0)
.ok_or_else(|| {
Error::Render(
"natural root dimension is not representable as positive CSS pixels".into(),
)
})
}
#[cfg(test)]
pub(crate) fn plan_root<Plan, FinalPlan, Prepared>(
request: RootRequest,
prepare: impl FnOnce(&mut PreparedStage<'_>) -> Result<Prepared, Error>,
measure: impl FnMut(
&Prepared,
RootRequest,
&mut FeedbackRound,
) -> Result<MeasuredLayout<Plan>, Error>,
finalize: impl FnOnce(&Prepared, RootSize, Plan, &mut FinalStage<'_>) -> Result<FinalPlan, Error>,
) -> Result<FrozenRoot<FinalPlan>, Error> {
plan_root_with_results(request, false, prepare, measure, finalize)
}
#[expect(
clippy::too_many_lines,
reason = "the complete root prepare, feedback, seal and freeze lifecycle stays ordered"
)]
pub(crate) fn plan_root_with_results<Plan, FinalPlan, Prepared>(
request: RootRequest,
capture_results: bool,
prepare: impl FnOnce(&mut PreparedStage<'_>) -> Result<Prepared, Error>,
mut measure: impl FnMut(
&Prepared,
RootRequest,
&mut FeedbackRound,
) -> Result<MeasuredLayout<Plan>, Error>,
finalize: impl FnOnce(&Prepared, RootSize, Plan, &mut FinalStage<'_>) -> Result<FinalPlan, Error>,
) -> Result<FrozenRoot<FinalPlan>, Error> {
use crate::{errors::OperationPhase, operation};
request.validate()?;
operation::phase(OperationPhase::Prepare)?;
let mut assigned = request;
let mut resources = crate::font::canonical::OperationContext::with_results(capture_results);
let mut reservations = ReservationDriver::new();
let mut prepared_stage = PreparedStage {
resources: &mut resources,
reservations: &mut reservations,
};
let prepared = prepare(&mut prepared_stage)?;
operation::phase(OperationPhase::Layout)?;
reservations.phase = ReservationStage::Measured;
let mut history = Vec::new();
reservations.reserve_additional(
ReservationStage::Measured,
&mut history,
1,
"measured root plan",
)?;
let measured = loop {
operation::checkpoint()?;
operation::work(1)?;
let mut round = FeedbackRound::new(history.last(), history.len())?;
round.observe_root_request(request)?;
if let Some(size) = assigned.exact_size() {
let (width, height) = size.dimensions()?;
round.observe_number(width)?;
round.observe_number(height)?;
} else if let Some(width) = assigned.exact_width() {
round.observe_number(f64::from(width))?;
}
let result = measure(&prepared, assigned, &mut round)?;
assigned.validate_size(result.size)?;
request.validate_size(result.size)?;
if assigned.automatic_height() {
assigned = RootRequest::ExactWidth(root_dimension(result.size.dimensions()?.0)?);
}
let state = round.finish();
if let Some(error) = state.terminal_error() {
return Err(error);
}
if state.feedback_unchanged() {
if let Some(error) = state.unchanged_error() {
return Err(error);
}
break result;
}
if state.repeats_history(&history) {
use crate::errors::{
Diagnostic, DiagnosticKind, ErrorContext, NonConvergenceReason, OperationPhase,
};
return Err(Error::Render(
Diagnostic::new(
DiagnosticKind::NonConvergence {
algorithm: "root layout feedback",
iterations: history.len() + 1,
reason: NonConvergenceReason::Cycle,
},
"layout root feedback cycle detected",
)
.with_context(ErrorContext::new().with_operation(OperationPhase::Layout)),
));
}
if history.len() == 7 {
use crate::errors::{
BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, OperationPhase,
};
return Err(Error::Render(
Diagnostic::new(
DiagnosticKind::BudgetExceeded {
resource: BudgetResource::LayoutRounds,
required: 9,
limit: 8,
},
"layout root feedback exhausted eight rounds",
)
.with_context(ErrorContext::new().with_operation(OperationPhase::Layout)),
));
}
reservations.reserve_additional(
ReservationStage::Measured,
&mut history,
1,
"root feedback state",
)?;
history.push(state);
};
let assigned = measured.size;
operation::phase(OperationPhase::Freeze)?;
resources
.seal_fonts()
.map_err(|error| Error::from(error).with_prefix("accepted root font sealing"))?;
reservations.phase = ReservationStage::Final;
let mut allocation = Vec::new();
let mut final_stage = FinalStage {
reservations: &mut reservations,
};
final_stage.reserve_final(&mut allocation, 1, "frozen root plan")?;
let plan = finalize(&prepared, assigned, measured.plan, &mut final_stage)?;
operation::checkpoint()?;
drop(prepared);
drop(history);
drop(resources);
allocation.push(RootAllocation {
request,
size: assigned,
plan,
});
let allocation = allocation
.into_boxed_slice()
.try_into()
.unwrap_or_else(|_| unreachable!("one frozen root allocation"));
Ok(FrozenRoot { allocation })
}
#[cfg(test)]
#[path = "kernel/tests.rs"]
mod tests;