#![allow(dead_code)]
use std::ops::Range;
use std::str::FromStr;
use unicode_bidi::{BidiDataSource, HardcodedBidiData, ParagraphBidiInfo};
use unicode_script::{Script, UnicodeScript};
use unicode_segmentation::UnicodeSegmentation;
#[cfg(test)]
use crate::font::canonical::RequestedWeight;
use crate::font::canonical::{
self, DesignMetrics, FaceIdentity, FontError, FontStack, GlyphInk, PairProvenance,
PreparedFontEnvironment, ResolvedFontPair, ScalarFaceSelection,
ShapedRun as CanonicalShapedRun, ShapingDirection,
};
use crate::theme::Color;
use crate::TextWeight;
pub(crate) mod ellipsis;
pub(crate) mod font_fit;
pub(crate) mod placement;
mod rational;
pub(crate) mod request;
mod requirements;
pub(crate) mod visibility;
use rational::ExactRational;
#[cfg(test)]
pub(crate) mod metric_tests;
#[cfg(test)]
mod shaping_tests;
#[allow(unused_imports)]
pub(crate) use requirements::{
foundational_plot_requirements, PreparedFontPairRequirement, PreparedTextCensus,
PreparedTextRequirement, PreparedTextRole,
};
pub(crate) const CSS_PIXEL_QUANTA: i64 = 1024;
#[cfg(test)]
thread_local! {
static TEXT_WORK: std::cell::Cell<TextWork> = const { std::cell::Cell::new(TextWork {
proposal_visits: 0, exact_trials: 0, shaping_scalars: 0, shaped_glyphs: 0,
}) };
}
#[cfg(test)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct TextWork {
proposal_visits: usize,
exact_trials: usize,
shaping_scalars: usize,
shaped_glyphs: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PhysicalTextAlignment {
Start,
Center,
End,
}
impl From<crate::TextAlignment> for PhysicalTextAlignment {
fn from(alignment: crate::TextAlignment) -> Self {
match alignment {
crate::TextAlignment::Start => Self::Start,
crate::TextAlignment::Center => Self::Center,
crate::TextAlignment::End => Self::End,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum TextLineHeight {
Multiplier(f64),
ResolvedQuanta(i64),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TextPlanProvenance {
pub(crate) pair_ordinal: u32,
pub(crate) owner: String,
}
#[derive(Debug, Clone)]
pub(crate) struct TextPlanInput<'a> {
pub(crate) size_trace: Option<std::sync::Arc<font_fit::stability::Stability>>,
pub(crate) direction: crate::TextDirection,
pub(crate) source: &'a str,
pub(crate) stack: &'a FontStack,
pub(crate) weight: TextWeight,
pub(crate) font_size: f64,
pub(crate) line_height: TextLineHeight,
pub(crate) maximum_width_quanta: i64,
pub(crate) alignment: PhysicalTextAlignment,
pub(crate) paint: Color,
pub(crate) provenance: TextPlanProvenance,
pub(crate) exact_override: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct TextSourceSpan {
pub(crate) start_byte: u32,
pub(crate) end_byte: u32,
}
impl TextSourceSpan {
fn new(start: usize, end: usize) -> Result<Self, TextPlanError> {
Ok(Self {
start_byte: u32::try_from(start).map_err(|_| TextPlanError::SourceTooLong)?,
end_byte: u32::try_from(end).map_err(|_| TextPlanError::SourceTooLong)?,
})
}
fn range(self) -> Range<usize> {
self.start_byte as usize..self.end_byte as usize
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct TextInkBounds {
pub(crate) left: i64,
pub(crate) bottom: i64,
pub(crate) right: i64,
pub(crate) top: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PlannedGlyph {
pub(crate) face: FaceIdentity,
pub(crate) glyph_id: u16,
pub(crate) cluster: u32,
pub(crate) design_x_advance: i32,
pub(crate) design_y_advance: i32,
pub(crate) design_x_offset: i32,
pub(crate) design_y_offset: i32,
pub(crate) design_ink: Option<GlyphInk>,
pub(crate) x_advance_quanta: i64,
pub(crate) y_advance_quanta: i64,
pub(crate) x_offset_quanta: i64,
pub(crate) y_offset_quanta: i64,
pub(crate) glyph_origin_x_quanta: i64,
pub(crate) glyph_origin_y_quanta: i64,
pub(crate) ink_quanta: Option<TextInkBounds>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ShapedTextRun {
pub(crate) source_span: TextSourceSpan,
pub(crate) face: FaceIdentity,
pub(crate) direction: ShapingDirection,
pub(crate) bidi_level: u8,
pub(crate) script: Script,
pub(crate) units_per_em: u16,
pub(crate) design_ascender: i16,
pub(crate) design_descender: i16,
pub(crate) metric_source: canonical::MetricSource,
pub(crate) ascender_quanta: i64,
pub(crate) descender_quanta: i64,
pub(crate) design_x_advance: i64,
pub(crate) design_y_advance: i64,
pub(crate) logical_advance_quanta: i64,
pub(crate) logical_y_advance_quanta: i64,
pub(crate) ink_quanta: Option<TextInkBounds>,
pub(crate) glyphs: Vec<PlannedGlyph>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TextLinePlan {
pub(crate) source_span: TextSourceSpan,
pub(crate) selected_soft_hyphen: Option<TextSourceSpan>,
pub(crate) ending_grapheme_index: u32,
pub(crate) translation_x_quanta: i64,
pub(crate) translation_y_quanta: i64,
pub(crate) logical_advance_quanta: i64,
pub(crate) ink_quanta: Option<TextInkBounds>,
pub(crate) base_direction: ShapingDirection,
pub(crate) runs: Vec<ShapedTextRun>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ResolvedTextStyle {
pub(crate) stack_source: String,
pub(crate) stack: FontStack,
pub(crate) weight: TextWeight,
pub(crate) font_size: f64,
pub(crate) line_height_quanta: i64,
pub(crate) alignment: PhysicalTextAlignment,
pub(crate) paint: Color,
pub(crate) provenance: TextPlanProvenance,
pub(crate) exact_override: bool,
}
impl Eq for ResolvedTextStyle {}
#[derive(Debug, Clone)]
pub(crate) struct ResolvedTextPlan(
std::sync::Arc<ResolvedTextPayload>,
Option<std::sync::Arc<TextAnalysis>>,
);
impl PartialEq for ResolvedTextPlan {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl Eq for ResolvedTextPlan {}
#[derive(Debug)]
struct TextAnalysis {
direction: crate::TextDirection,
environment: PreparedFontEnvironment,
original: std::sync::Arc<ResolvedTextPayload>,
paragraphs: Vec<AnalyzedParagraph>,
}
#[derive(Debug)]
struct AnalyzedParagraph {
span: TextSourceSpan,
grapheme_start: usize,
grapheme_ends: Vec<usize>,
bidi: Option<ParagraphBidiData>,
items: Vec<ScalarItem>,
hyphen_face: Option<FaceIdentity>,
whole_width: i64,
whole: ParagraphWhole,
wrapping: std::sync::OnceLock<ParagraphWrapping>,
hard_width: std::sync::OnceLock<i64>,
}
#[derive(Debug)]
enum ParagraphWhole {
Retained(BuiltLine),
OriginalLine {
index: usize,
advance: ExactRational,
ascent: i64,
descent: i64,
},
}
#[derive(Debug)]
struct ParagraphWrapping {
boundaries: Vec<usize>,
prefixes: Vec<ExactRational>,
}
#[derive(Debug)]
struct ParagraphBidiData {
original_classes: Vec<unicode_bidi::BidiClass>,
levels: Vec<unicode_bidi::Level>,
paragraph_level: unicode_bidi::Level,
is_pure_ltr: bool,
}
impl From<ParagraphBidiInfo<'_>> for ParagraphBidiData {
fn from(info: ParagraphBidiInfo<'_>) -> Self {
Self {
original_classes: info.original_classes,
levels: info.levels,
paragraph_level: info.paragraph_level,
is_pure_ltr: info.is_pure_ltr,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ResolvedTextPayload {
pub(crate) fit_input: Option<std::sync::Arc<font_fit::FitInput>>,
pub(crate) fit_group:
Option<std::sync::Arc<(crate::layout::ComponentAddress, Vec<font_fit::GroupMember>)>>,
pub(crate) original_source: Option<std::sync::Arc<String>>,
pub(crate) display_map: Option<std::sync::Arc<Vec<DisplayFragment>>>,
pub(crate) selected_rotation: Option<crate::TextRotation>,
occupied_rotation: Option<(i64, i64)>,
content: std::sync::Arc<ResolvedTextContent>,
pub(crate) request: Option<crate::TextLayout>,
pub(crate) clip_size: Option<(i64, i64)>,
pub(crate) paint_region: Option<[u64; 4]>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FrozenText {
content: std::sync::Arc<ResolvedTextContent>,
pub(crate) original_source: Option<std::sync::Arc<String>>,
pub(crate) display_map: Option<std::sync::Arc<Vec<DisplayFragment>>>,
pub(crate) request: Option<crate::TextLayout>,
pub(crate) fit_input: Option<std::sync::Arc<font_fit::FitInput>>,
pub(crate) fit_group:
Option<std::sync::Arc<(crate::layout::ComponentAddress, Vec<font_fit::GroupMember>)>>,
pub(crate) selected_rotation: Option<crate::TextRotation>,
pub(crate) clip_size: Option<(i64, i64)>,
pub(crate) paint_region: Option<[u64; 4]>,
}
impl std::ops::Deref for FrozenText {
type Target = ResolvedTextContent;
fn deref(&self) -> &Self::Target {
&self.content
}
}
impl FrozenText {
pub(crate) fn original_source(&self) -> &str {
self.original_source
.as_ref()
.map_or(&self.content.source, |source| source.as_str())
}
#[cfg(test)]
pub(crate) fn shares_content(&self, plan: &ResolvedTextPlan) -> bool {
std::sync::Arc::ptr_eq(&self.content, &plan.content)
}
#[cfg(test)]
pub(crate) fn line_texts(&self) -> Vec<&str> {
self.lines
.iter()
.map(|line| &self.source[line.source_span.range()])
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DisplayFragment {
pub(crate) display: std::ops::Range<usize>,
pub(crate) original: Option<std::ops::Range<usize>>,
}
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(test, derive(Clone))]
pub(crate) struct ResolvedTextContent {
pub(crate) source: String,
pub(crate) style: ResolvedTextStyle,
pub(crate) pair_provenance: PairProvenance,
pub(crate) lines: Vec<TextLinePlan>,
pub(crate) line_pitch_quanta: i64,
pub(crate) first_baseline_quanta: Option<i64>,
pub(crate) last_baseline_quanta: Option<i64>,
pub(crate) width_quanta: i64,
pub(crate) height_quanta: i64,
}
impl std::ops::Deref for ResolvedTextPayload {
type Target = ResolvedTextContent;
fn deref(&self) -> &Self::Target {
&self.content
}
}
#[cfg(test)]
impl std::ops::DerefMut for ResolvedTextPayload {
fn deref_mut(&mut self) -> &mut Self::Target {
std::sync::Arc::make_mut(&mut self.content)
}
}
impl std::ops::Deref for ResolvedTextPlan {
type Target = ResolvedTextPayload;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ResolvedTextPlan {
#[cfg(test)]
pub(crate) fn analysis_liveness_probe(&self) -> impl Fn() -> bool + use<> {
let analysis = self.1.as_ref().map(std::sync::Arc::downgrade);
move || {
analysis
.as_ref()
.is_some_and(|analysis| analysis.strong_count() != 0)
}
}
pub(crate) fn freeze_selected(&self) -> FrozenText {
FrozenText {
content: std::sync::Arc::clone(&self.content),
original_source: self.original_source.clone(),
display_map: self.display_map.clone(),
request: self.request.clone(),
fit_input: self.fit_input.clone(),
fit_group: self.fit_group.clone(),
selected_rotation: self.selected_rotation,
clip_size: self.clip_size,
paint_region: self.paint_region,
}
}
pub(crate) fn original_source(&self) -> &str {
self.original_source
.as_ref()
.map_or(&self.source, |source| source.as_str())
}
pub(crate) fn with_display(
mut self,
source: &str,
map: Vec<DisplayFragment>,
) -> Result<Self, crate::Error> {
self.payload_mut().original_source = Some(crate::data::source::source_arc(
crate::data::source::copy_source_string(source)?,
)?);
self.payload_mut().display_map = Some(crate::data::source::source_arc(map)?);
Ok(self)
}
#[expect(
clippy::cast_precision_loss,
reason = "canonical occupied lengths are converted before checked outward projection"
)]
pub(crate) fn freeze_orientation(mut self) -> Result<Self, crate::Error> {
self.payload_mut().occupied_rotation = None;
if let Some(angle) = self.selected_rotation {
let (sine, cosine) = crate::text::orientation::components(angle.0.get());
let width = self.occupied_width_quanta() as f64 / 1024.0;
let height = self.occupied_height_quanta() as f64 / 1024.0;
let dimensions = (
crate::layout::kernel::ceil_spatial_quanta(
width * cosine.abs() + height * sine.abs(),
)?,
crate::layout::kernel::ceil_spatial_quanta(
width * sine.abs() + height * cosine.abs(),
)?,
);
self.payload_mut().occupied_rotation = Some(dimensions);
}
Ok(self)
}
pub(crate) fn translate_paint_region(mut self, dx: f64, dy: f64) -> Self {
if let Some(region) = self.paint_region {
let [x0, x1, y0, y1] = region.map(f64::from_bits);
self.payload_mut().paint_region =
Some([x0 + dx, x1 + dx, y0 + dy, y1 + dy].map(f64::to_bits));
}
self
}
pub(crate) fn clear_paint_region(&mut self) {
if self.paint_region.is_some() {
self.payload_mut().paint_region = None;
}
}
pub(crate) fn occupied_width_quanta(&self) -> i64 {
self.occupied_rotation.map_or_else(
|| {
self.clip_size
.map_or(self.width_quanta, |(width, _)| width.min(self.width_quanta))
},
|size| size.0,
)
}
pub(crate) fn occupied_height_quanta(&self) -> i64 {
self.occupied_rotation.map_or_else(
|| {
self.clip_size.map_or(self.height_quanta, |(_, height)| {
height.min(self.height_quanta)
})
},
|size| size.1,
)
}
#[expect(
clippy::cast_precision_loss,
reason = "text extents are bounded canonical quanta"
)]
pub(crate) fn occupied_size(&self) -> (f64, f64) {
(
self.occupied_width_quanta() as f64 / 1024.0,
self.occupied_height_quanta() as f64 / 1024.0,
)
}
pub(crate) fn hidden_source(
source: &str,
appearance: crate::text::TextAppearance<'_>,
alignment: PhysicalTextAlignment,
owner: &str,
) -> Result<Self, crate::Error> {
let theme = appearance.theme;
Ok(Self(
std::sync::Arc::new(ResolvedTextPayload {
fit_input: None,
fit_group: None,
original_source: None,
display_map: None,
selected_rotation: None,
occupied_rotation: None,
content: std::sync::Arc::new(ResolvedTextContent {
source: crate::data::source::copy_source_string(source)?,
style: ResolvedTextStyle {
stack_source: theme
.get_stack()
.css()
.map_err(|error| crate::Error::Render(error.to_string()))?,
stack: theme.get_stack().clone(),
weight: theme.get_weight(),
font_size: theme.get_font_size(),
line_height_quanta: 1,
alignment,
paint: theme.get_color(),
provenance: TextPlanProvenance {
pair_ordinal: 0,
owner: owner.into(),
},
exact_override: appearance.exact_override,
},
pair_provenance: PairProvenance {
pair_ordinal: 0,
weight: theme.get_weight().into(),
candidates: Vec::new(),
},
lines: Vec::new(),
line_pitch_quanta: 1,
first_baseline_quanta: None,
last_baseline_quanta: None,
width_quanta: 0,
height_quanta: 0,
}),
request: appearance.layout.cloned(),
clip_size: None,
paint_region: None,
}),
None,
))
}
pub(crate) fn clip_region(mut self, region: crate::layout::PixelRect) -> Self {
self.payload_mut().paint_region =
Some([region.x0, region.x1, region.y0, region.y1].map(f64::to_bits));
self
}
fn payload_mut(&mut self) -> &mut ResolvedTextPayload {
std::sync::Arc::make_mut(&mut self.0)
}
pub(crate) fn with_request(mut self, request: Option<&crate::TextLayout>) -> Self {
if let Some(crate::text::orientation::Orientation::Fixed(angle)) = request
.and_then(|request| request.instructions().orientation.as_ref())
.map(|orientation| &orientation.0)
{
self.payload_mut().selected_rotation = Some(*angle);
}
self.payload_mut().request = request.cloned();
self
}
pub(crate) fn hide(mut self) -> Result<Self, crate::Error> {
if self.lines.is_empty() {
return Ok(self);
}
let original = &self.style;
let style = ResolvedTextStyle {
stack_source: crate::data::source::copy_source_string(&original.stack_source)?,
stack: crate::data::source::copy_font_stack(&original.stack)?,
provenance: TextPlanProvenance {
pair_ordinal: original.provenance.pair_ordinal,
owner: crate::data::source::copy_source_string(&original.provenance.owner)?,
},
weight: original.weight,
font_size: original.font_size,
line_height_quanta: original.line_height_quanta,
alignment: original.alignment,
paint: original.paint,
exact_override: original.exact_override,
};
let content = ResolvedTextContent {
source: crate::data::source::copy_source_string(&self.source)?,
style,
pair_provenance: PairProvenance {
pair_ordinal: self.pair_provenance.pair_ordinal,
weight: self.pair_provenance.weight,
candidates: crate::data::source::collect_source(
self.pair_provenance.candidates.iter().copied().map(Ok),
)?,
},
lines: Vec::new(),
width_quanta: 0,
height_quanta: 0,
first_baseline_quanta: None,
last_baseline_quanta: None,
line_pitch_quanta: self.line_pitch_quanta,
};
self.payload_mut().content = std::sync::Arc::new(content);
self.payload_mut().occupied_rotation = None;
Ok(self)
}
pub(crate) fn clip_to(mut self, width: i64, height: i64) -> Self {
self.payload_mut().clip_size = Some((width, height));
self
}
pub(crate) fn retained_handle_count(&self) -> usize {
1 + usize::from(self.1.is_some())
}
pub(crate) fn analysis_profile(&self) -> Result<(&str, &FontStack), TextPlanError> {
let original = &self
.1
.as_ref()
.ok_or(TextPlanError::Arithmetic("missing text analysis"))?
.original;
Ok((&original.source, &original.style.stack))
}
pub(crate) fn same_stack(&self, stack: &FontStack) -> bool {
self.style.stack.same(stack)
}
pub(crate) fn copy_stack(&self) -> Result<FontStack, TextPlanError> {
Ok(self.style.stack.try_copy()?)
}
pub(crate) fn intrinsic_from_analysis(
&self,
preferred_lines: usize,
) -> Result<TextIntrinsicRequirements, TextPlanError> {
let analysis = self
.1
.as_ref()
.ok_or(TextPlanError::Arithmetic("missing text analysis"))?;
let environment = &analysis.environment;
let original = &analysis.original;
let mut result = TextIntrinsicRequirements {
hard_width_quanta: 0,
natural_width_quanta: 0,
preferred_width_quanta: 0,
};
for paragraph in &analysis.paragraphs {
if paragraph.span.start_byte == paragraph.span.end_byte {
continue;
}
let (whole, _, _, _) = paragraph.whole(original);
if let Some(ink) = whole.ink_quanta {
result.natural_width_quanta = result.natural_width_quanta.max(
ink.right
.checked_sub(ink.left)
.ok_or(TextPlanError::Arithmetic("intrinsic ink width"))?,
);
}
let wrapping = paragraph.wrapping(&original.source, whole, original.style.font_size)?;
let last = wrapping.boundaries.len() - 1;
if paragraph.hard_width.get().is_none() {
let mut hard = 0;
for start in 0..last {
let width = if last == 1 {
paragraph.whole_width
} else {
let end = wrapping.boundaries[start + 1];
let line = prepare_line(
environment,
&original.source,
paragraph.span,
TextSourceSpan::new(
paragraph.span.start_byte as usize + wrapping.boundaries[start],
paragraph.span.start_byte as usize + end,
)?,
ending_grapheme_index(
¶graph.grapheme_ends,
end,
paragraph.grapheme_start,
)?,
original.style.font_size,
paragraph
.bidi
.as_ref()
.ok_or(TextPlanError::Arithmetic("empty intrinsic paragraph"))?,
¶graph.items,
paragraph.hyphen_face,
)?;
exact_line_width(&line)?
};
hard = hard.max(width);
}
let _ = paragraph.hard_width.set(hard);
}
result.hard_width_quanta = result.hard_width_quanta.max(
*paragraph
.hard_width
.get()
.ok_or(TextPlanError::Arithmetic("intrinsic width initialization"))?,
);
let lines = (preferred_lines / analysis.paragraphs.len().max(1)).max(1);
let chunk = last.div_ceil(lines);
for start in (0..last).step_by(chunk) {
let end = start.saturating_add(chunk).min(last);
result.preferred_width_quanta = result.preferred_width_quanta.max(
prefix_difference(&wrapping.prefixes[end], &wrapping.prefixes[start])?
.ceil_i64("preferred width")?,
);
}
}
result.preferred_width_quanta = result.preferred_width_quanta.max(result.hard_width_quanta);
Ok(result)
}
pub(crate) fn reflow(&self, mut input: TextPlanInput<'_>) -> Result<Self, TextPlanError> {
let analysis = self
.1
.as_ref()
.ok_or(TextPlanError::Arithmetic("missing text analysis"))?;
let environment = &analysis.environment;
let original = &analysis.original;
if !canonical::same_bytes(input.source, &original.source)
|| input.direction != analysis.direction
|| !input.stack.same(&original.style.stack)
|| input.weight != original.style.weight
|| input.font_size.to_bits() != original.style.font_size.to_bits()
{
return Err(TextPlanError::Arithmetic("text analysis profile mismatch"));
}
if input.maximum_width_quanta < 0 {
return Err(TextPlanError::InvalidMaximumWidth);
}
let line_height = resolve_line_height(input.line_height, input.font_size)?;
let mut lines = Vec::new();
for paragraph in &analysis.paragraphs {
let (whole, advance, ascent, descent) = paragraph.whole(original);
if paragraph.whole_width <= input.maximum_width_quanta {
retain_line(&mut lines, copy_line(whole, advance, ascent, descent)?)?;
continue;
}
let wrapping = paragraph.wrapping(input.source, whole, input.font_size)?;
let boundaries = &wrapping.boundaries;
let bidi = paragraph
.bidi
.as_ref()
.ok_or(TextPlanError::Arithmetic("empty paragraph reflow"))?;
let mut start = 0;
while start + 1 < boundaries.len() {
let (end, line) = select_line(
&wrapping.prefixes,
start,
input.maximum_width_quanta,
(start == 0).then_some(paragraph.whole_width),
TextSourceSpan::new(
paragraph.span.start_byte as usize + boundaries[start],
paragraph.span.start_byte as usize + boundaries[start + 1],
)?,
|end| {
prepare_line(
environment,
input.source,
paragraph.span,
TextSourceSpan::new(
paragraph.span.start_byte as usize + boundaries[start],
paragraph.span.start_byte as usize + boundaries[end],
)?,
ending_grapheme_index(
¶graph.grapheme_ends,
boundaries[end],
paragraph.grapheme_start,
)?,
input.font_size,
bidi,
¶graph.items,
paragraph.hyphen_face,
)
},
)?;
retain_line(&mut lines, line)?;
start = end;
}
}
let mut candidates = Vec::new();
let provenance = &original.pair_provenance;
super::unicode16::reserve(&mut candidates, provenance.candidates.len())?;
candidates.extend_from_slice(&provenance.candidates);
input.provenance.pair_ordinal = provenance.pair_ordinal;
let stack = input.stack;
let mut plan = finalize_plan(
input,
stack,
PairProvenance {
pair_ordinal: provenance.pair_ordinal,
weight: provenance.weight,
candidates,
},
line_height,
lines,
)?;
plan.1 = Some(std::sync::Arc::clone(analysis));
Ok(plan)
}
pub(crate) fn unwrapped_fit_width(&self) -> Result<Option<i64>, TextPlanError> {
let mut previous_end = None;
let mut required = 0;
for line in &self.lines {
if let Some(end) = previous_end {
let separator = &self.source[end..line.source_span.start_byte as usize];
if separator.is_empty() {
return Ok(None);
}
for scalar in separator.chars() {
if !crate::text::is_nonrendering_mandatory_break(scalar) {
return Ok(None);
}
}
}
previous_end = Some(line.source_span.end_byte as usize);
let mut advance = ExactRational::ZERO;
for run in &line.runs {
advance = advance.add(
&scale_design(run.design_x_advance, self.style.font_size, run.units_per_em)?,
"cached paragraph advance",
)?;
}
let ink_width = line.ink_quanta.map_or(Ok(0), |ink| {
ink.right
.checked_sub(ink.left)
.ok_or(TextPlanError::Arithmetic("cached paragraph ink"))
})?;
required = required
.max(advance.ceil_i64("cached paragraph advance")?)
.max(ink_width);
}
Ok(Some(required))
}
pub(crate) fn shares_payload(&self, other: &Self) -> bool {
std::sync::Arc::ptr_eq(&self.0, &other.0)
}
#[cfg(test)]
pub(crate) fn shares_analysis(&self, other: &Self) -> bool {
match (&self.1, &other.1) {
(Some(left), Some(right)) => std::sync::Arc::ptr_eq(left, right),
_ => false,
}
}
#[expect(
clippy::cast_precision_loss,
reason = "immutable plans retain exact i64 quanta; layout adapters use pixels"
)]
pub(crate) fn width(&self) -> f64 {
self.width_quanta as f64 / CSS_PIXEL_QUANTA as f64
}
#[expect(
clippy::cast_precision_loss,
reason = "immutable plans retain exact i64 quanta; layout adapters use pixels"
)]
pub(crate) fn fit_width(&self) -> f64 {
let rounded_advance = self
.lines
.iter()
.map(|line| line.logical_advance_quanta)
.max()
.unwrap_or(0);
let conservative_ceil = rounded_advance.saturating_add(i64::from(rounded_advance > 0));
self.clip_size
.map_or(conservative_ceil, |(width, _)| width.min(conservative_ceil)) as f64
/ CSS_PIXEL_QUANTA as f64
}
#[expect(
clippy::cast_precision_loss,
reason = "immutable plans retain exact i64 quanta; layout adapters use pixels"
)]
pub(crate) fn height(&self) -> f64 {
self.height_quanta as f64 / CSS_PIXEL_QUANTA as f64
}
#[expect(
clippy::cast_precision_loss,
reason = "immutable plans retain exact i64 quanta; layout adapters use pixels"
)]
pub(crate) fn line_height(&self) -> f64 {
self.line_pitch_quanta as f64 / CSS_PIXEL_QUANTA as f64
}
pub(crate) fn line_texts(&self) -> Vec<&str> {
self.lines
.iter()
.map(|line| &self.source[line.source_span.range()])
.collect()
}
pub(crate) fn into_line_texts(self) -> Result<Vec<String>, TextPlanError> {
let mut lines = Vec::new();
super::unicode16::reserve(&mut lines, self.lines.len())?;
for line in &self.lines {
let text = &self.source[line.source_span.range()];
let length = text.len() - usize::from(line.selected_soft_hyphen.is_some());
let mut retained = String::new();
retained
.try_reserve_exact(length)
.map_err(|_| TextPlanError::Allocation("owned text line"))?;
if let Some(soft) = line.selected_soft_hyphen {
retained.push_str(
&self.source[line.source_span.start_byte as usize..soft.start_byte as usize],
);
retained.push('-');
retained.push_str(
&self.source[soft.end_byte as usize..line.source_span.end_byte as usize],
);
} else {
retained.push_str(text);
}
lines.push(retained);
}
Ok(lines)
}
}
impl AnalyzedParagraph {
fn whole<'a>(
&'a self,
original: &'a ResolvedTextPayload,
) -> (&'a TextLinePlan, ExactRational, i64, i64) {
match &self.whole {
ParagraphWhole::Retained(line) => {
(&line.plan, line.advance.clone(), line.ascent, line.descent)
}
ParagraphWhole::OriginalLine {
index,
advance,
ascent,
descent,
} => (&original.lines[*index], advance.clone(), *ascent, *descent),
}
}
fn wrapping(
&self,
source: &str,
whole: &TextLinePlan,
font_size: f64,
) -> Result<&ParagraphWrapping, TextPlanError> {
if self.wrapping.get().is_none() {
let mut boundaries =
legal_line_breaks_at_graphemes(&source[self.span.range()], &self.grapheme_ends)?;
super::unicode16::reserve(&mut boundaries, 1)?;
boundaries.insert(0, 0);
let prefixes = proposal_prefixes(whole, &boundaries, font_size)?;
let _ = self.wrapping.set(ParagraphWrapping {
boundaries,
prefixes,
});
}
self.wrapping.get().ok_or(TextPlanError::Arithmetic(
"paragraph wrapping initialization",
))
}
}
fn copy_line(
line: &TextLinePlan,
advance: ExactRational,
ascent: i64,
descent: i64,
) -> Result<BuiltLine, TextPlanError> {
let mut runs = Vec::new();
super::unicode16::reserve(&mut runs, line.runs.len())?;
for run in &line.runs {
let mut glyphs = Vec::new();
super::unicode16::reserve(&mut glyphs, run.glyphs.len())?;
glyphs.extend_from_slice(&run.glyphs);
runs.push(ShapedTextRun { glyphs, ..*run });
}
Ok(BuiltLine {
plan: TextLinePlan { runs, ..*line },
advance,
ascent,
descent,
})
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
"text bytes {source_span:?} require {required_width_quanta} quanta but only {maximum_width_quanta} are available"
)]
pub(crate) struct TextFitMiss {
pub(crate) source_span: TextSourceSpan,
pub(crate) maximum_width_quanta: i64,
pub(crate) required_width_quanta: i64,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum TextPlanError {
#[error(transparent)]
Spacing(#[from] crate::Error),
#[error(transparent)]
Font(#[from] FontError),
#[error(transparent)]
Fit(#[from] TextFitMiss),
#[error("font size must be positive")]
InvalidFontSize,
#[error("maximum text width must be nonnegative")]
InvalidMaximumWidth,
#[error("line height must be finite and positive")]
InvalidLineHeight,
#[error("text block {span:?} has zero checked layout height; selected faces {faces:?}")]
NoTextHeight {
span: TextSourceSpan,
faces: Vec<FaceIdentity>,
},
#[error("text source exceeds the supported u32 byte range")]
SourceTooLong,
#[error("text planning arithmetic overflow while calculating {0}")]
Arithmetic(&'static str),
#[error("text planning could not reserve {0}")]
Allocation(&'static str),
#[error("cannot map Unicode script '{0}' into rustybuzz")]
Script(String),
#[error("resolved scalar U+{0:04X} is not backed by a rendering face")]
InvalidScalarSelection(u32),
#[error("prepared text census does not contain the requested font stack and weight")]
MissingPreparedPair,
#[error("prepared text census does not contain scalar U+{0:04X}")]
MissingPreparedScalar(u32),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DeferredAnnotationTextPlan {
pub(crate) plan: ResolvedTextPlan,
pub(crate) exact_override: bool,
}
impl DeferredAnnotationTextPlan {
pub(crate) fn from_resolved(plan: ResolvedTextPlan) -> Self {
let exact_override = plan.style.exact_override;
Self {
plan,
exact_override,
}
}
}
impl PreparedFontEnvironment {
pub(crate) fn plan_text(
&self,
input: TextPlanInput<'_>,
) -> Result<ResolvedTextPlan, TextPlanError> {
match measure_text(self, input, None)? {
TextMeasurement::Assigned(plan) => Ok(plan),
TextMeasurement::Intrinsic(_) => unreachable!("assigned text request"),
}
}
pub(crate) fn text_intrinsic_requirements(
&self,
input: TextPlanInput<'_>,
preferred_lines: usize,
) -> Result<TextIntrinsicRequirements, TextPlanError> {
match measure_text(self, input, Some(preferred_lines))? {
TextMeasurement::Intrinsic(requirements) => Ok(requirements),
TextMeasurement::Assigned(_) => unreachable!("intrinsic text request"),
}
}
}
#[derive(Debug, Clone, Copy)]
#[expect(
clippy::struct_field_names,
reason = "explicit quantum units distinguish these widths from the pixel-space adapter lengths"
)]
pub(crate) struct TextIntrinsicRequirements {
pub(crate) hard_width_quanta: i64,
pub(crate) natural_width_quanta: i64,
pub(crate) preferred_width_quanta: i64,
}
enum TextMeasurement {
Intrinsic(TextIntrinsicRequirements),
Assigned(ResolvedTextPlan),
}
#[expect(
clippy::too_many_lines,
reason = "constrained text planning keeps count, reservation, materialization, and freezing ordered"
)]
fn measure_text(
environment: &PreparedFontEnvironment,
mut input: TextPlanInput<'_>,
intrinsic_lines: Option<usize>,
) -> Result<TextMeasurement, TextPlanError> {
if !input.font_size.is_finite() || input.font_size <= 0.0 {
return Err(TextPlanError::InvalidFontSize);
}
if input.maximum_width_quanta < 0 {
return Err(TextPlanError::InvalidMaximumWidth);
}
let _ = u32::try_from(input.source.len()).map_err(|_| TextPlanError::SourceTooLong)?;
let stack = input.stack;
let scale = FontScale {
size: input.font_size,
trace: input.size_trace.as_ref(),
};
let line_height_quanta = resolve_line_height(input.line_height, input.font_size)?;
if let Some(trace) = scale.trace {
trace.observe(line_height_quanta, |size| {
resolve_line_height(input.line_height, size)
})?;
}
let weight = input.weight.into();
environment.admit_text(stack, weight, input.source, None)?;
let pair = environment
.prepared_pair(stack, weight)?
.ok_or(TextPlanError::MissingPreparedPair)?;
input.provenance.pair_ordinal = pair.provenance.pair_ordinal;
let paragraph_seeds = mandatory_paragraph_seeds(input.source)?;
let mut built_lines = Vec::new();
let mut analyzed_paragraphs = Vec::new();
let mut requirements = TextIntrinsicRequirements {
hard_width_quanta: 0,
natural_width_quanta: 0,
preferred_width_quanta: 0,
};
let paragraph_count = paragraph_seeds.len();
let mut grapheme_start = 0_usize;
for seed in paragraph_seeds {
let paragraph = &input.source[seed.span.range()];
let mut grapheme_ends = Vec::new();
for (start, grapheme) in paragraph.grapheme_indices(true) {
super::unicode16::reserve(&mut grapheme_ends, 1)?;
grapheme_ends.push(start + grapheme.len());
}
let next_grapheme = grapheme_start
.checked_add(grapheme_ends.len())
.ok_or(TextPlanError::Arithmetic("grapheme index"))?;
let ending = u32::try_from(next_grapheme)
.map_err(|_| TextPlanError::Arithmetic("grapheme index"))?;
if paragraph.is_empty() {
if intrinsic_lines.is_none() {
let whole = empty_line(
seed.span,
ending,
environment.face_metrics(pair.primary)?,
scale,
)?;
retain_paragraph(
&mut analyzed_paragraphs,
AnalyzedParagraph {
span: seed.span,
grapheme_start,
grapheme_ends,
bidi: None,
items: Vec::new(),
hyphen_face: None,
whole_width: 0,
whole: ParagraphWhole::OriginalLine {
index: built_lines.len(),
advance: whole.advance.clone(),
ascent: whole.ascent,
descent: whole.descent,
},
wrapping: std::sync::OnceLock::new(),
hard_width: std::sync::OnceLock::new(),
},
)?;
retain_line(&mut built_lines, whole)?;
}
continue;
}
let level = match input.direction {
crate::TextDirection::Auto => None,
crate::TextDirection::LeftToRight => Some(unicode_bidi::Level::ltr()),
crate::TextDirection::RightToLeft => Some(unicode_bidi::Level::rtl()),
};
let bidi = ParagraphBidiData::from(ParagraphBidiInfo::new(paragraph, level));
let items = selected_paragraph_items(&pair, paragraph)?;
let hyphen_face = paragraph
.contains('\u{ad}')
.then(|| selected_face(&pair, "-", '-'))
.transpose()?;
let whole = prepare_line(
environment,
input.source,
seed.span,
seed.span,
ending,
scale,
&bidi,
&items,
hyphen_face,
)?;
let whole_width = exact_line_width(&whole)?;
if intrinsic_lines.is_none() && whole_width <= input.maximum_width_quanta {
retain_paragraph(
&mut analyzed_paragraphs,
AnalyzedParagraph {
span: seed.span,
grapheme_start,
grapheme_ends,
bidi: Some(bidi),
items,
hyphen_face,
whole_width,
whole: ParagraphWhole::OriginalLine {
index: built_lines.len(),
advance: whole.advance.clone(),
ascent: whole.ascent,
descent: whole.descent,
},
wrapping: std::sync::OnceLock::new(),
hard_width: std::sync::OnceLock::new(),
},
)?;
retain_line(&mut built_lines, whole)?;
grapheme_start = next_grapheme;
continue;
}
let mut boundaries = legal_line_breaks_at_graphemes(paragraph, &grapheme_ends)?;
super::unicode16::reserve(&mut boundaries, 1)?;
boundaries.insert(0, 0);
let prefixes = proposal_prefixes(&whole.plan, &boundaries, scale)?;
let last = boundaries.len() - 1;
let shape = |start: usize, end: usize| {
let span = TextSourceSpan::new(
seed.span.start_byte as usize + boundaries[start],
seed.span.start_byte as usize + boundaries[end],
)?;
prepare_line(
environment,
input.source,
seed.span,
span,
ending_grapheme_index(&grapheme_ends, boundaries[end], grapheme_start)?,
scale,
&bidi,
&items,
hyphen_face,
)
};
if let Some(preferred_lines) = intrinsic_lines {
requirements.natural_width_quanta =
requirements.natural_width_quanta.max(ink_width(&whole)?);
for start in 0..last {
let width = if last == 1 {
whole_width
} else {
exact_line_width(&shape(start, start + 1)?)?
};
requirements.hard_width_quanta = requirements.hard_width_quanta.max(width);
}
let lines = (preferred_lines / paragraph_count.max(1)).max(1);
let chunk = last.div_ceil(lines);
for start in (0..last).step_by(chunk) {
let end = start.saturating_add(chunk).min(last);
let width = prefix_difference(&prefixes[end], &prefixes[start])?
.ceil_i64("preferred width")?;
requirements.preferred_width_quanta =
requirements.preferred_width_quanta.max(width);
}
} else {
let mut start = 0;
while start < last {
let (end, selected) = select_line(
&prefixes,
start,
input.maximum_width_quanta,
(start == 0).then_some(whole_width),
TextSourceSpan::new(
seed.span.start_byte as usize + boundaries[start],
seed.span.start_byte as usize + boundaries[start + 1],
)?,
|end| shape(start, end),
)?;
retain_line(&mut built_lines, selected)?;
start = end;
}
retain_paragraph(
&mut analyzed_paragraphs,
AnalyzedParagraph {
span: seed.span,
grapheme_start,
grapheme_ends,
bidi: Some(bidi),
items,
hyphen_face,
whole_width,
whole: ParagraphWhole::Retained(whole),
wrapping: std::sync::OnceLock::from(ParagraphWrapping {
boundaries,
prefixes,
}),
hard_width: std::sync::OnceLock::new(),
},
)?;
}
grapheme_start = next_grapheme;
}
if intrinsic_lines.is_some() {
requirements.preferred_width_quanta = requirements
.preferred_width_quanta
.max(requirements.hard_width_quanta);
return Ok(TextMeasurement::Intrinsic(requirements));
}
let direction = input.direction;
let mut plan = finalize_plan(
input,
stack,
pair.provenance,
line_height_quanta,
built_lines,
)?;
plan.1 = Some(std::sync::Arc::new(TextAnalysis {
direction,
environment: environment.clone(),
original: std::sync::Arc::clone(&plan.0),
paragraphs: analyzed_paragraphs,
}));
Ok(TextMeasurement::Assigned(plan))
}
fn retain_paragraph(
paragraphs: &mut Vec<AnalyzedParagraph>,
paragraph: AnalyzedParagraph,
) -> Result<(), TextPlanError> {
super::unicode16::reserve(paragraphs, 1)?;
paragraphs.push(paragraph);
Ok(())
}
#[derive(Debug, Clone, Copy)]
struct ParagraphSeed {
span: TextSourceSpan,
scalar_count: u128,
}
fn select_line(
prefixes: &[ExactRational],
start: usize,
maximum_width_quanta: i64,
failed_paragraph_width: Option<i64>,
first_span: TextSourceSpan,
mut shape: impl FnMut(usize) -> Result<BuiltLine, TextPlanError>,
) -> Result<(usize, BuiltLine), TextPlanError> {
let last = prefixes.len() - 1;
let mut end = start + 1;
for candidate in start + 1..=last {
#[cfg(test)]
TEXT_WORK.with(|work| {
work.update(|mut work| {
work.proposal_visits += 1;
work
});
});
if prefix_difference(&prefixes[candidate], &prefixes[start])?.ceil_i64("proposal width")?
> maximum_width_quanta
{
end = candidate.saturating_sub(1).max(start + 1);
break;
}
end = candidate;
}
let mut failed = failed_paragraph_width.map(|_| last);
let mut selected = loop {
let (trial, width) = if let Some(width) = failed_paragraph_width.filter(|_| end == last) {
(None, width)
} else {
let trial = shape(end)?;
let width = exact_line_width(&trial)?;
(Some(trial), width)
};
if width <= maximum_width_quanta {
break trial.ok_or(TextPlanError::Arithmetic("failed paragraph trial"))?;
}
failed = Some(end);
if end == start + 1 {
return Err(TextFitMiss {
source_span: first_span,
maximum_width_quanta,
required_width_quanta: width,
}
.into());
}
end -= 1;
};
while end < last {
if failed == Some(end + 1) {
break;
}
let trial = shape(end + 1)?;
if exact_line_width(&trial)? > maximum_width_quanta {
break;
}
selected = trial;
end += 1;
}
Ok((end, selected))
}
fn retain_line(lines: &mut Vec<BuiltLine>, line: BuiltLine) -> Result<(), TextPlanError> {
super::unicode16::reserve(lines, 1)?;
lines.push(line);
Ok(())
}
fn ink_width(line: &BuiltLine) -> Result<i64, TextPlanError> {
line.plan.ink_quanta.map_or(Ok(0), |ink| {
ink.right
.checked_sub(ink.left)
.ok_or(TextPlanError::Arithmetic("line ink span"))
})
}
fn exact_line_width(line: &BuiltLine) -> Result<i64, TextPlanError> {
#[cfg(test)]
TEXT_WORK.with(|work| {
work.update(|mut work| {
work.exact_trials += 1;
work
});
});
Ok(line.advance.ceil_i64("wrap advance")?.max(ink_width(line)?))
}
fn prefix_difference(
end: &ExactRational,
start: &ExactRational,
) -> Result<ExactRational, TextPlanError> {
end.add(&start.negated()?, "proposal difference")
}
fn proposal_prefixes<'a>(
whole: &TextLinePlan,
boundaries: &[usize],
font_size: impl Into<FontScale<'a>>,
) -> Result<Vec<ExactRational>, TextPlanError> {
let font_size = font_size.into();
let mut prefixes = Vec::new();
super::unicode16::reserve(&mut prefixes, boundaries.len())?;
prefixes.resize(boundaries.len(), ExactRational::ZERO);
let mut clusters = Vec::new();
for (run_order, run) in whole.runs.iter().enumerate() {
let mut cursor = if run.direction == ShapingDirection::RightToLeft {
run.glyphs.len()
} else {
0
};
let rtl = run.direction == ShapingDirection::RightToLeft;
while if rtl {
cursor > 0
} else {
cursor < run.glyphs.len()
} {
let index = if rtl { cursor - 1 } else { cursor };
let glyph_order = index;
let cluster = run.glyphs[index].cluster;
let mut total = 0_i64;
loop {
let index = if rtl { cursor - 1 } else { cursor };
total = total
.checked_add(i64::from(run.glyphs[index].design_x_advance))
.ok_or(TextPlanError::Arithmetic("cluster advance"))?;
if rtl {
cursor -= 1;
} else {
cursor += 1;
}
if (rtl && cursor == 0) || (!rtl && cursor == run.glyphs.len()) {
break;
}
let next = if rtl { cursor - 1 } else { cursor };
if run.glyphs[next].cluster != cluster {
break;
}
}
let end = if (rtl && cursor == 0) || (!rtl && cursor == run.glyphs.len()) {
run.source_span.end_byte
} else {
run.glyphs[if rtl { cursor - 1 } else { cursor }].cluster
};
let magnitude = total
.checked_abs()
.ok_or(TextPlanError::Arithmetic("cluster magnitude"))?;
super::unicode16::reserve(&mut clusters, 1)?;
clusters.push((
end,
run_order,
glyph_order,
cluster,
scale_design(magnitude, font_size, run.units_per_em)?,
));
}
}
clusters.sort_unstable_by_key(|&(end, run, glyph, _, _)| (end, run, glyph));
let mut boundary = 1;
for (end, _, _, _, advance) in clusters {
let end = (end - whole.source_span.start_byte) as usize;
while boundaries[boundary] < end {
boundary += 1;
}
prefixes[boundary] = prefixes[boundary].add(&advance, "cluster prefix")?;
}
for index in 1..prefixes.len() {
prefixes[index] = prefixes[index].add(&prefixes[index - 1], "paragraph prefix")?;
}
Ok(prefixes)
}
fn checked_multiply(
value: u128,
factor: u128,
resource: &'static str,
) -> Result<u128, TextPlanError> {
value
.checked_mul(factor)
.ok_or(TextPlanError::Arithmetic(resource))
}
fn mandatory_paragraph_seeds(source: &str) -> Result<Vec<ParagraphSeed>, TextPlanError> {
let mut paragraphs = Vec::new();
let mut start = 0_usize;
let mut scalar_count = 0_u128;
let mut scalars = source.char_indices().peekable();
while let Some((index, scalar)) = scalars.next() {
if !crate::text::is_nonrendering_mandatory_break(scalar) {
scalar_count = scalar_count
.checked_add(1)
.ok_or(TextPlanError::Arithmetic("paragraph scalar count"))?;
continue;
}
super::unicode16::reserve(&mut paragraphs, 1)?;
paragraphs.push(ParagraphSeed {
span: TextSourceSpan::new(start, index)?,
scalar_count,
});
let mut break_end = index + scalar.len_utf8();
if scalar == '\r' && scalars.peek().is_some_and(|(_, next)| *next == '\n') {
let (lf_index, lf) = scalars
.next()
.ok_or(TextPlanError::Arithmetic("CRLF segmentation"))?;
break_end = lf_index + lf.len_utf8();
}
start = break_end;
scalar_count = 0;
}
super::unicode16::reserve(&mut paragraphs, 1)?;
paragraphs.push(ParagraphSeed {
span: TextSourceSpan::new(start, source.len())?,
scalar_count,
});
Ok(paragraphs)
}
fn paragraph_linebreaks(
paragraph: &str,
) -> Result<Vec<(usize, super::unicode16::BreakOpportunity)>, TextPlanError> {
if paragraph.is_empty() {
return Ok(Vec::new());
}
let mut reduced = String::new();
reduced
.try_reserve_exact(paragraph.len())
.map_err(|_| TextPlanError::Allocation("line-break analysis source"))?;
let mut offsets = Vec::new();
let mut alphabetic = false;
for (offset, scalar) in paragraph.char_indices() {
let next_alphabetic = scalar.is_ascii_alphabetic();
if !alphabetic || !next_alphabetic {
super::unicode16::reserve(&mut offsets, 1)?;
offsets.push((reduced.len(), offset));
reduced.push(scalar);
}
alphabetic = next_alphabetic;
}
super::unicode16::reserve(&mut offsets, 1)?;
offsets.push((reduced.len(), paragraph.len()));
let mut opportunities = super::unicode16::linebreaks(&reduced)?;
let mut mapped = 0;
for (index, _) in &mut opportunities {
loop {
if offsets[mapped].0 >= *index {
break;
}
mapped += 1;
}
*index = offsets[mapped].1;
}
Ok(opportunities)
}
fn legal_line_breaks_at_graphemes(
paragraph: &str,
grapheme_ends: &[usize],
) -> Result<Vec<usize>, TextPlanError> {
let opportunities = paragraph_linebreaks(paragraph)?;
let mut breaks = Vec::new();
let mut grapheme = 0;
for (index, _) in opportunities {
while grapheme < grapheme_ends.len() {
if grapheme_ends[grapheme] >= index {
break;
}
grapheme += 1;
}
if index > 0 && grapheme_ends.get(grapheme) == Some(&index) {
super::unicode16::reserve(&mut breaks, 1)?;
breaks.push(index);
}
}
Ok(breaks)
}
fn ending_grapheme_index(
grapheme_ends: &[usize],
end: usize,
paragraph_start_index: usize,
) -> Result<u32, TextPlanError> {
let local = grapheme_ends
.binary_search(&end)
.map_err(|_| TextPlanError::Arithmetic("ending grapheme boundary"))?
.checked_add(1)
.ok_or(TextPlanError::Arithmetic("ending grapheme index"))?;
u32::try_from(
paragraph_start_index
.checked_add(local)
.ok_or(TextPlanError::Arithmetic("ending grapheme index"))?,
)
.map_err(|_| TextPlanError::Arithmetic("ending grapheme index"))
}
#[derive(Debug)]
struct BuiltLine {
plan: TextLinePlan,
advance: ExactRational,
ascent: i64,
descent: i64,
}
fn empty_line<'a>(
span: TextSourceSpan,
ending_grapheme_index: u32,
primary_metrics: DesignMetrics,
font_size: impl Into<FontScale<'a>>,
) -> Result<BuiltLine, TextPlanError> {
let font_size = font_size.into();
let (ascent, descent) = scaled_metrics(primary_metrics, font_size)?;
let descent = descent
.checked_neg()
.ok_or(TextPlanError::Arithmetic("primary face descender"))?;
Ok(BuiltLine {
plan: TextLinePlan {
source_span: span,
selected_soft_hyphen: None,
ending_grapheme_index,
translation_x_quanta: 0,
translation_y_quanta: 0,
logical_advance_quanta: 0,
ink_quanta: None,
base_direction: ShapingDirection::LeftToRight,
runs: Vec::new(),
},
advance: ExactRational::ZERO,
ascent,
descent,
})
}
#[expect(
clippy::too_many_arguments,
reason = "selected-line shaping retains exact paragraph and line identities"
)]
#[expect(
clippy::too_many_lines,
reason = "contextual shaping keeps glyph retention and exact line geometry ordered"
)]
fn prepare_line<'a>(
environment: &PreparedFontEnvironment,
source: &str,
paragraph_span: TextSourceSpan,
line_span: TextSourceSpan,
ending_grapheme_index: u32,
font_size: impl Into<FontScale<'a>>,
bidi: &ParagraphBidiData,
items: &[ScalarItem],
hyphen_face: Option<FaceIdentity>,
) -> Result<BuiltLine, TextPlanError> {
let font_size = font_size.into();
let selected_soft_hyphen = (line_span.end_byte < paragraph_span.end_byte
&& source[line_span.range()].ends_with('\u{ad}'))
.then(|| {
TextSourceSpan::new(
line_span.end_byte as usize - '\u{ad}'.len_utf8(),
line_span.end_byte as usize,
)
})
.transpose()?;
let line_local_start = (line_span.start_byte - paragraph_span.start_byte) as usize;
let line_local_end = (line_span.end_byte - paragraph_span.start_byte) as usize;
let (levels, bidi_runs) = line_visual_runs(
bidi,
&source[paragraph_span.range()],
line_local_start..line_local_end,
)?;
let mut runs = Vec::new();
let mut exact_ink: Option<ExactInk> = None;
let mut pen_x = ExactRational::ZERO;
let mut pen_y = ExactRational::ZERO;
let mut ascent = 0_i64;
let mut descent = 0_i64;
for bidi_run in bidi_runs {
let direction = if levels[bidi_run.start].is_rtl() {
ShapingDirection::RightToLeft
} else {
ShapingDirection::LeftToRight
};
let mut groups = itemize_bidi_run(
items,
paragraph_span.start_byte,
bidi_run.start + line_local_start..bidi_run.end + line_local_start,
)?;
if let Some(soft) = selected_soft_hyphen {
if let Some(index) = groups
.iter()
.position(|group| group.span.range().contains(&(soft.start_byte as usize)))
{
let hyphen = ItemGroup {
span: soft,
face: hyphen_face.ok_or(TextPlanError::MissingPreparedScalar('-' as u32))?,
script: groups[index].script,
};
if groups[index].face != hyphen.face {
if groups[index].span.start_byte == soft.start_byte {
groups[index] = hyphen;
} else {
super::unicode16::reserve(&mut groups, 1)?;
groups[index].span.end_byte = soft.start_byte;
groups.insert(index + 1, hyphen);
}
}
}
}
if direction == ShapingDirection::RightToLeft {
groups.reverse();
}
for group in groups {
let text = &source[group.span.range()];
#[cfg(test)]
TEXT_WORK.with(|work| {
work.update(|mut work| {
work.shaping_scalars += text.chars().count();
work
});
});
let shaped = environment.shape_run_with_context(
group.face,
text,
direction,
rustybuzz_script(group.script)?,
canonical::ShapingContext {
pre: &source[line_span.start_byte as usize..group.span.start_byte as usize],
post: if selected_soft_hyphen
.is_some_and(|soft| soft.start_byte == group.span.end_byte)
{
"-"
} else {
&source[group.span.end_byte as usize..line_span.end_byte as usize]
},
soft_hyphen: selected_soft_hyphen
.filter(|soft| group.span.range().contains(&(soft.start_byte as usize)))
.map(|soft| (soft.start_byte - group.span.start_byte) as usize),
},
)?;
#[cfg(test)]
TEXT_WORK.with(|work| {
work.update(|mut work| {
work.shaped_glyphs += shaped.glyphs.len();
work
});
});
super::unicode16::reserve(&mut runs, 1)?;
let built = scale_run(
shaped,
group.span,
group.script,
font_size,
&pen_x,
&pen_y,
levels[bidi_run.start].number(),
)?;
ascent = ascent.max(built.plan.ascender_quanta);
descent = descent.max(
built
.plan
.descender_quanta
.checked_neg()
.ok_or(TextPlanError::Arithmetic("face descender"))?,
);
if let Some(ink) = built.ink {
exact_ink = Some(match exact_ink {
Some(current) => current.union(ink),
None => ink,
});
}
pen_x = pen_x.add(&built.advance_x, "line advance")?;
pen_y = pen_y.add(&built.advance_y, "line advance")?;
runs.push(built.plan);
}
}
let ink_quanta = exact_ink.as_ref().map(ExactInk::outward).transpose()?;
if let Some(ink) = ink_quanta {
ascent = ascent.max(ink.top.max(0));
descent = descent.max(
ink.bottom
.min(0)
.checked_neg()
.ok_or(TextPlanError::Arithmetic("line ink below baseline"))?,
);
}
let logical_advance_quanta = pen_x.nearest_even_i64("line logical advance")?;
if logical_advance_quanta < 0 {
return Err(TextPlanError::Arithmetic("negative line logical advance"));
}
Ok(BuiltLine {
plan: TextLinePlan {
source_span: line_span,
selected_soft_hyphen,
ending_grapheme_index,
translation_x_quanta: 0,
translation_y_quanta: 0,
logical_advance_quanta,
ink_quanta,
base_direction: if bidi.paragraph_level.is_rtl() {
ShapingDirection::RightToLeft
} else {
ShapingDirection::LeftToRight
},
runs,
},
advance: pen_x,
ascent,
descent,
})
}
#[derive(Debug, Clone, Copy)]
struct ItemGroup {
span: TextSourceSpan,
face: FaceIdentity,
script: Script,
}
#[derive(Debug, Clone, Copy)]
struct ScalarItem {
start: usize,
end: usize,
face: FaceIdentity,
script: Script,
}
fn line_visual_runs(
bidi: &ParagraphBidiData,
paragraph: &str,
line: Range<usize>,
) -> Result<(Vec<unicode_bidi::Level>, Vec<Range<usize>>), TextPlanError> {
let mut original_classes = Vec::new();
let mut levels = Vec::new();
original_classes
.try_reserve_exact(line.len())
.map_err(|_| TextPlanError::Allocation("line bidi classes"))?;
levels
.try_reserve_exact(line.len())
.map_err(|_| TextPlanError::Allocation("line bidi levels"))?;
original_classes.extend_from_slice(&bidi.original_classes[line.clone()]);
levels.extend_from_slice(&bidi.levels[line.clone()]);
let selected = ParagraphBidiInfo {
text: ¶graph[line.clone()],
original_classes,
levels,
paragraph_level: bidi.paragraph_level,
is_pure_ltr: bidi.is_pure_ltr,
};
Ok(selected.visual_runs(0..selected.text.len()))
}
fn selected_paragraph_items(
pair: &ResolvedFontPair,
paragraph: &str,
) -> Result<Vec<ScalarItem>, TextPlanError> {
let mut units = canonical::selection_units(paragraph);
let mut unit = "";
let mut unit_end = 0;
let mut items = paragraph_items(paragraph, |start, scalar| {
if start == unit_end {
unit = units
.next()
.ok_or(TextPlanError::Arithmetic("source unit boundary"))?;
unit_end += unit.len();
}
selected_face(pair, unit, scalar)
})?;
let mut following_face = pair.primary;
for item in items.iter_mut().rev() {
let scalar = paragraph[item.start..item.end]
.chars()
.next()
.ok_or(TextPlanError::Arithmetic("source scalar boundary"))?;
if crate::text::is_nonpainting_control(scalar) {
item.face = following_face;
} else {
following_face = item.face;
}
}
let mut preceding_face = None;
for item in &mut items {
let scalar = paragraph[item.start..item.end]
.chars()
.next()
.ok_or(TextPlanError::Arithmetic("source scalar boundary"))?;
if crate::text::is_nonpainting_control(scalar) {
if let Some(face) = preceding_face {
item.face = face;
}
} else {
preceding_face = Some(item.face);
}
}
Ok(items)
}
fn paragraph_items(
paragraph: &str,
mut face_for: impl FnMut(usize, char) -> Result<FaceIdentity, TextPlanError>,
) -> Result<Vec<ScalarItem>, TextPlanError> {
let mut items: Vec<ScalarItem> = Vec::new();
let mut extensions = unicode_script::ScriptExtension::default();
let mut segment_start = 0;
let mut segment_script = None;
for (start, scalar) in paragraph.char_indices() {
super::unicode16::reserve(&mut items, 1)?;
let next = extensions.intersection(scalar.script_extension());
if next.is_empty() {
let script = segment_script.unwrap_or(Script::Common);
for item in &mut items[segment_start..] {
item.script = script;
}
segment_start = items.len();
extensions = scalar.script_extension();
segment_script = None;
} else {
extensions = next;
}
if !matches!(
scalar.script(),
Script::Common | Script::Inherited | Script::Unknown
) {
segment_script = Some(scalar.script());
}
items.push(ScalarItem {
start,
end: start + scalar.len_utf8(),
face: face_for(start, scalar)?,
script: scalar.script(),
});
}
let script = segment_script.unwrap_or(Script::Common);
for item in &mut items[segment_start..] {
item.script = script;
}
let mut openings: Vec<(char, Vec<usize>)> = Vec::new();
let mut stack: Vec<(usize, usize)> = Vec::new();
for (index, scalar) in paragraph.chars().enumerate() {
let Some(bracket) = HardcodedBidiData.bidi_matched_opening_bracket(scalar) else {
if index > 0
&& (scalar.script() == Script::Inherited || scalar.script_extension().is_common())
{
items[index].script = items[index - 1].script;
}
continue;
};
let mut key = None;
for (candidate, (opening, _)) in openings.iter().enumerate() {
if *opening == bracket.opening {
key = Some(candidate);
break;
}
}
if bracket.is_open {
let key = if let Some(key) = key {
key
} else {
super::unicode16::reserve(&mut openings, 1)?;
openings.push((bracket.opening, Vec::new()));
openings.len() - 1
};
let indices = &mut openings[key].1;
super::unicode16::reserve(indices, 1)?;
super::unicode16::reserve(&mut stack, 1)?;
indices.push(stack.len());
stack.push((key, index));
} else if let Some(position) = key.and_then(|key| openings[key].1.last()).copied() {
items[index].script = items[stack[position].1].script;
while stack.len() > position {
let (key, _) = stack.pop().expect("matched bracket stack");
openings[key].1.pop();
}
}
}
Ok(items)
}
fn itemize_bidi_run(
items: &[ScalarItem],
paragraph_source_start: u32,
bidi_run: Range<usize>,
) -> Result<Vec<ItemGroup>, TextPlanError> {
let mut limits = [0; 2];
for (limit, boundary) in limits.iter_mut().zip([bidi_run.start, bidi_run.end]) {
let (mut low, mut high) = (0, items.len());
while low < high {
let middle = low + (high - low) / 2;
if items[middle].start < boundary {
low = middle + 1;
} else {
high = middle;
}
}
*limit = low;
}
let [first, last] = limits;
let mut groups: Vec<ItemGroup> = Vec::new();
for item in &items[first..last] {
let absolute_start = (paragraph_source_start as usize)
.checked_add(item.start)
.ok_or(TextPlanError::Arithmetic("run source span"))?;
let absolute_end = (paragraph_source_start as usize)
.checked_add(item.end)
.ok_or(TextPlanError::Arithmetic("run source span"))?;
if let Some(previous) = groups.last_mut() {
if previous.face == item.face
&& previous.script == item.script
&& previous.span.end_byte as usize == absolute_start
{
previous.span.end_byte =
u32::try_from(absolute_end).map_err(|_| TextPlanError::SourceTooLong)?;
continue;
}
}
super::unicode16::reserve(&mut groups, 1)?;
groups.push(ItemGroup {
span: TextSourceSpan::new(absolute_start, absolute_end)?,
face: item.face,
script: item.script,
});
}
Ok(groups)
}
fn selected_face(
pair: &ResolvedFontPair,
unit: &str,
scalar: char,
) -> Result<FaceIdentity, TextPlanError> {
if crate::text::is_nonpainting_control(scalar) {
return Ok(pair.primary);
}
let selection = pair
.selection_for_unit(unit, scalar)
.map_err(|error| match error {
FontError::MissingGlyph { .. } => TextPlanError::MissingPreparedScalar(scalar as u32),
error => TextPlanError::Font(error),
})?;
match selection {
ScalarFaceSelection::Face(identity) => Ok(identity),
ScalarFaceSelection::NonRenderingMandatoryBreak => {
Err(TextPlanError::InvalidScalarSelection(scalar as u32))
}
}
}
fn rustybuzz_script(script: Script) -> Result<rustybuzz::Script, TextPlanError> {
rustybuzz::Script::from_str(script.short_name())
.map_err(|_| TextPlanError::Script(script.short_name().to_owned()))
}
#[derive(Debug)]
struct BuiltRun {
plan: ShapedTextRun,
advance_x: ExactRational,
advance_y: ExactRational,
ink: Option<ExactInk>,
}
#[expect(
clippy::too_many_lines,
reason = "freeze origins and ink in one pass while retaining exact advances for wrapping"
)]
fn scale_run<'a>(
shaped: CanonicalShapedRun,
source_span: TextSourceSpan,
script: Script,
font_size: impl Into<FontScale<'a>>,
line_pen_x: &ExactRational,
line_pen_y: &ExactRational,
bidi_level: u8,
) -> Result<BuiltRun, TextPlanError> {
let font_size = font_size.into();
let mut glyphs = Vec::new();
super::unicode16::reserve(&mut glyphs, shaped.glyphs.len())?;
let mut pen_x = ExactRational::ZERO;
let mut pen_y = ExactRational::ZERO;
let mut exact_ink: Option<ExactInk> = None;
let mut design_horizontal_advance = 0_i64;
let mut design_vertical_advance = 0_i64;
for glyph in shaped.glyphs {
let x_advance = scale_design(
glyph.x_advance.into(),
font_size,
shaped.metrics.units_per_em,
)?;
let y_advance = scale_design(
glyph.y_advance.into(),
font_size,
shaped.metrics.units_per_em,
)?;
let x_offset = scale_design(
glyph.x_offset.into(),
font_size,
shaped.metrics.units_per_em,
)?;
let y_offset = scale_design(
glyph.y_offset.into(),
font_size,
shaped.metrics.units_per_em,
)?;
let origin_x = line_pen_x
.add(&pen_x, "glyph origin")?
.add(&x_offset, "glyph origin")?
.nearest_even_i64("glyph origin")?;
let origin_y = line_pen_y
.add(&pen_y, "glyph origin")?
.add(&y_offset, "glyph origin")?
.nearest_even_i64("glyph origin")?;
let glyph_exact_ink = glyph
.ink
.map(|ink| {
exact_glyph_ink(ink, 0, 0, font_size, shaped.metrics.units_per_em)?.translated(
&ExactRational::new(i128::from(origin_x), 1)?,
&ExactRational::new(i128::from(origin_y), 1)?,
)
})
.transpose()?;
if let Some(ink) = &glyph_exact_ink {
exact_ink = Some(match exact_ink {
Some(current) => current.union(ink.clone()),
None => ink.clone(),
});
}
let cluster = source_span
.start_byte
.checked_add(glyph.cluster)
.ok_or(TextPlanError::Arithmetic("glyph cluster"))?;
glyphs.push(PlannedGlyph {
face: shaped.identity,
glyph_id: glyph.glyph_id,
cluster,
design_x_advance: glyph.x_advance,
design_y_advance: glyph.y_advance,
design_x_offset: glyph.x_offset,
design_y_offset: glyph.y_offset,
design_ink: glyph.ink,
x_advance_quanta: x_advance.nearest_even_i64("glyph x advance")?,
y_advance_quanta: y_advance.nearest_even_i64("glyph y advance")?,
x_offset_quanta: x_offset.nearest_even_i64("glyph x offset")?,
y_offset_quanta: y_offset.nearest_even_i64("glyph y offset")?,
glyph_origin_x_quanta: origin_x,
glyph_origin_y_quanta: origin_y,
ink_quanta: glyph_exact_ink
.as_ref()
.map(ExactInk::outward)
.transpose()?,
});
pen_x = pen_x.add(&x_advance, "run x advance")?;
pen_y = pen_y.add(&y_advance, "run y advance")?;
design_horizontal_advance = design_horizontal_advance
.checked_add(i64::from(glyph.x_advance))
.ok_or(TextPlanError::Arithmetic("design run x advance"))?;
design_vertical_advance = design_vertical_advance
.checked_add(i64::from(glyph.y_advance))
.ok_or(TextPlanError::Arithmetic("design run y advance"))?;
}
let (ascender_quanta, descender_quanta) = scaled_metrics(shaped.metrics, font_size)?;
Ok(BuiltRun {
plan: ShapedTextRun {
source_span,
face: shaped.identity,
direction: shaped.direction,
bidi_level,
script,
units_per_em: shaped.metrics.units_per_em,
design_ascender: shaped.metrics.ascender,
design_descender: shaped.metrics.descender,
metric_source: shaped.metrics.source,
ascender_quanta,
descender_quanta,
design_x_advance: design_horizontal_advance,
design_y_advance: design_vertical_advance,
logical_advance_quanta: pen_x.nearest_even_i64("run logical advance")?,
logical_y_advance_quanta: pen_y.nearest_even_i64("run logical y advance")?,
ink_quanta: exact_ink.as_ref().map(ExactInk::outward).transpose()?,
glyphs,
},
advance_x: pen_x,
advance_y: pen_y,
ink: exact_ink,
})
}
fn exact_glyph_ink(
ink: GlyphInk,
x_offset: i32,
y_offset: i32,
font_size: FontScale<'_>,
units_per_em: u16,
) -> Result<ExactInk, TextPlanError> {
Ok(ExactInk {
left: scale_design(
i64::from(x_offset)
.checked_add(i64::from(ink.x_min))
.ok_or(TextPlanError::Arithmetic("glyph ink left"))?,
font_size,
units_per_em,
)?,
bottom: scale_design(
i64::from(y_offset)
.checked_add(i64::from(ink.y_min))
.ok_or(TextPlanError::Arithmetic("glyph ink bottom"))?,
font_size,
units_per_em,
)?,
right: scale_design(
i64::from(x_offset)
.checked_add(i64::from(ink.x_max))
.ok_or(TextPlanError::Arithmetic("glyph ink right"))?,
font_size,
units_per_em,
)?,
top: scale_design(
i64::from(y_offset)
.checked_add(i64::from(ink.y_max))
.ok_or(TextPlanError::Arithmetic("glyph ink top"))?,
font_size,
units_per_em,
)?,
})
}
fn scaled_metrics<'a>(
metrics: DesignMetrics,
font_size: impl Into<FontScale<'a>>,
) -> Result<(i64, i64), TextPlanError> {
let font_size = font_size.into();
let ascender = scale_design(
i64::from(metrics.ascender).max(0),
font_size,
metrics.units_per_em,
)?
.ceil_i64("face ascender")?;
let descender = scale_design(
i64::from(metrics.descender).min(0),
font_size,
metrics.units_per_em,
)?
.floor_i64("face descender")?;
if ascender < 0 || descender > 0 {
return Err(TextPlanError::Arithmetic("scaled face metrics"));
}
Ok((ascender, descender))
}
fn require_block_height(
span: TextSourceSpan,
height: i64,
identities: impl Iterator<Item = FaceIdentity>,
) -> Result<(), TextPlanError> {
if height == 0 {
let mut faces = Vec::new();
for identity in identities {
super::unicode16::reserve(&mut faces, 1)?;
faces.push(identity);
}
return Err(TextPlanError::NoTextHeight { span, faces });
}
Ok(())
}
#[expect(
clippy::too_many_lines,
reason = "final geometry and root-admitted payload freezing remain ordered"
)]
fn finalize_plan(
input: TextPlanInput<'_>,
stack: &FontStack,
pair_provenance: PairProvenance,
line_height_quanta: i64,
mut built_lines: Vec<BuiltLine>,
) -> Result<ResolvedTextPlan, TextPlanError> {
let ascent = built_lines
.iter()
.map(|line| line.ascent)
.max()
.unwrap_or(0);
let descent = built_lines
.iter()
.map(|line| line.descent)
.max()
.unwrap_or(0);
let metric_height = ascent
.checked_add(descent)
.ok_or(TextPlanError::Arithmetic("text metric height"))?;
let line_pitch_quanta = metric_height.max(line_height_quanta);
let width_quanta = built_lines.iter().try_fold(0_i64, |width, line| {
let span = line.plan.ink_quanta.map_or(Ok(0), |ink| {
ink.right
.checked_sub(ink.left)
.ok_or(TextPlanError::Arithmetic("line ink span"))
})?;
Ok::<_, TextPlanError>(width.max(span))
})?;
for (line_index, line) in built_lines.iter_mut().enumerate() {
let (line_left, line_span) = line.plan.ink_quanta.map_or(Ok((0, 0)), |ink| {
Ok::<_, TextPlanError>((
ink.left,
ink.right
.checked_sub(ink.left)
.ok_or(TextPlanError::Arithmetic("line ink span"))?,
))
})?;
let alignment_space = width_quanta
.checked_sub(line_span)
.ok_or(TextPlanError::Arithmetic("line alignment slack"))?;
let alignment_offset = match input.alignment {
PhysicalTextAlignment::Start => 0,
PhysicalTextAlignment::Center => ExactRational::new(i128::from(alignment_space), 2)?
.nearest_even_i64("center line alignment")?,
PhysicalTextAlignment::End => alignment_space,
};
line.plan.translation_x_quanta = alignment_offset
.checked_sub(line_left)
.ok_or(TextPlanError::Arithmetic("line x translation"))?;
let line_index =
i64::try_from(line_index).map_err(|_| TextPlanError::Arithmetic("line index"))?;
line.plan.translation_y_quanta = line_pitch_quanta
.checked_mul(line_index)
.and_then(|offset| ascent.checked_add(offset))
.ok_or(TextPlanError::Arithmetic("line baseline"))?;
}
let line_count =
i64::try_from(built_lines.len()).map_err(|_| TextPlanError::Arithmetic("line count"))?;
let height_quanta = if line_count == 0 {
0
} else {
line_pitch_quanta
.checked_mul(line_count - 1)
.and_then(|pitch| metric_height.checked_add(pitch))
.ok_or(TextPlanError::Arithmetic("text height"))?
};
if line_count > 0 {
require_block_height(
TextSourceSpan::new(0, input.source.len())?,
height_quanta,
built_lines
.iter()
.flat_map(|line| &line.plan.runs)
.map(|run| run.face)
.chain(
pair_provenance
.candidates
.first()
.copied()
.filter(|_| built_lines.iter().any(|line| line.plan.runs.is_empty())),
),
)?;
}
let first_baseline_quanta = (line_count > 0).then_some(ascent);
let last_baseline_quanta = if line_count == 0 {
None
} else {
Some(
line_pitch_quanta
.checked_mul(line_count - 1)
.and_then(|pitch| ascent.checked_add(pitch))
.ok_or(TextPlanError::Arithmetic("last baseline"))?,
)
};
let mut source = String::new();
let stack_source = stack.css()?;
let stack = stack.copy_with_stage(None)?;
let mut lines = Vec::new();
source
.try_reserve_exact(input.source.len())
.map_err(|_| TextPlanError::Allocation("text source"))?;
super::unicode16::reserve(&mut lines, built_lines.len())?;
source.push_str(input.source);
lines.extend(built_lines.into_iter().map(|line| line.plan));
Ok(ResolvedTextPlan(
std::sync::Arc::new(ResolvedTextPayload {
fit_input: None,
fit_group: None,
original_source: None,
display_map: None,
selected_rotation: None,
occupied_rotation: None,
content: std::sync::Arc::new(ResolvedTextContent {
source,
style: ResolvedTextStyle {
stack_source,
stack,
weight: input.weight,
font_size: input.font_size,
line_height_quanta,
alignment: input.alignment,
paint: input.paint,
provenance: input.provenance,
exact_override: input.exact_override,
},
pair_provenance,
lines,
line_pitch_quanta,
first_baseline_quanta,
last_baseline_quanta,
width_quanta,
height_quanta,
}),
request: None,
clip_size: None,
paint_region: None,
}),
None,
))
}
#[derive(Debug, Clone)]
struct ExactInk {
left: ExactRational,
bottom: ExactRational,
right: ExactRational,
top: ExactRational,
}
impl ExactInk {
fn translated(self, x: &ExactRational, y: &ExactRational) -> Result<Self, TextPlanError> {
Ok(Self {
left: self.left.add(x, "ink translation")?,
bottom: self.bottom.add(y, "ink translation")?,
right: self.right.add(x, "ink translation")?,
top: self.top.add(y, "ink translation")?,
})
}
fn union(self, other: Self) -> Self {
Self {
left: self.left.min(other.left),
bottom: self.bottom.min(other.bottom),
right: self.right.max(other.right),
top: self.top.max(other.top),
}
}
fn outward(&self) -> Result<TextInkBounds, TextPlanError> {
Ok(TextInkBounds {
left: self.left.floor_i64("ink left")?,
bottom: self.bottom.floor_i64("ink bottom")?,
right: self.right.ceil_i64("ink right")?,
top: self.top.ceil_i64("ink top")?,
})
}
}
#[derive(Clone, Copy)]
struct FontScale<'a> {
size: f64,
trace: Option<&'a std::sync::Arc<font_fit::stability::Stability>>,
}
impl From<f64> for FontScale<'_> {
fn from(size: f64) -> Self {
Self { size, trace: None }
}
}
fn scale_design<'a>(
design: i64,
font_size: impl Into<FontScale<'a>>,
units_per_em: u16,
) -> Result<ExactRational, TextPlanError> {
let scale = font_size.into();
scale.trace.map_or_else(
|| ExactRational::design(design, scale.size, units_per_em),
|trace| ExactRational::tracked_design(design, scale.size, units_per_em, trace),
)
}
fn resolve_line_height(line_height: TextLineHeight, font_size: f64) -> Result<i64, TextPlanError> {
match line_height {
TextLineHeight::Multiplier(multiplier) => {
if !multiplier.is_finite() || multiplier <= 0.0 {
return Err(TextPlanError::InvalidLineHeight);
}
Ok(crate::theme::RelativeSpacing::new(multiplier)?
.product(crate::theme::LocalMetric::css_pixels(font_size)?)
.round(super::kernel::SpatialRounding::Ceil)?
.quanta())
}
TextLineHeight::ResolvedQuanta(height) if height > 0 => Ok(height),
TextLineHeight::ResolvedQuanta(_) => Err(TextPlanError::InvalidLineHeight),
}
}
pub(crate) fn maximum_width_quanta(maximum_width: f64) -> Result<i64, TextPlanError> {
Ok(super::kernel::LayoutScalar::from_css_pixels(
maximum_width,
super::kernel::SpatialRounding::Floor,
)?
.quanta())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TextBlock {
plan: ResolvedTextPlan,
}
impl TextBlock {
pub(crate) const fn plan(&self) -> &ResolvedTextPlan {
&self.plan
}
pub(crate) const fn from_resolved(plan: ResolvedTextPlan) -> Self {
Self { plan }
}
pub(crate) fn lines(&self) -> Vec<&str> {
self.plan.line_texts()
}
pub(crate) fn width(&self) -> f64 {
self.plan.occupied_size().0
}
pub(crate) fn height(&self) -> f64 {
self.plan.occupied_size().1
}
pub(crate) fn line_height(&self) -> f64 {
self.plan.line_height()
}
}
#[cfg(test)]
mod tests {
use super::*;
pub(super) fn input(
source: &str,
maximum_width_quanta: i64,
alignment: PhysicalTextAlignment,
) -> TextPlanInput<'_> {
TextPlanInput {
size_trace: None,
direction: crate::TextDirection::Auto,
source,
stack: canonical::test_sans_stack(),
weight: TextWeight::Normal,
font_size: 10.0,
line_height: TextLineHeight::Multiplier(1.2),
maximum_width_quanta,
alignment,
paint: Color::rgb(1, 2, 3),
provenance: TextPlanProvenance {
pair_ordinal: 0,
owner: "test".into(),
},
exact_override: false,
}
}
pub(super) fn plan(
source: &str,
maximum_width_quanta: i64,
alignment: PhysicalTextAlignment,
) -> ResolvedTextPlan {
PreparedFontEnvironment::synthetic()
.plan_text(input(source, maximum_width_quanta, alignment))
.unwrap()
}
fn line_texts(plan: &ResolvedTextPlan) -> Vec<&str> {
plan.lines
.iter()
.map(|line| &plan.source[line.source_span.range()])
.collect()
}
#[test]
fn mandatory_breaks_preserve_crlf_and_all_blank_paragraphs() {
let plan = plan("\r\nA\n\n", i64::MAX, PhysicalTextAlignment::Start);
assert_eq!(line_texts(&plan), ["", "A", "", ""]);
assert_eq!(
plan.lines
.iter()
.map(|line| line.ending_grapheme_index)
.collect::<Vec<_>>(),
[0, 1, 1, 1]
);
}
}