1#![allow(dead_code)]
4
5use std::ops::Range;
6use std::str::FromStr;
7
8use unicode_bidi::{BidiDataSource, HardcodedBidiData, ParagraphBidiInfo};
9use unicode_script::{Script, UnicodeScript};
10use unicode_segmentation::UnicodeSegmentation;
11
12#[cfg(test)]
13use crate::font::canonical::RequestedWeight;
14use crate::font::canonical::{
15 self, DesignMetrics, FaceIdentity, FontError, FontStack, GlyphInk, PairProvenance,
16 PreparedFontEnvironment, ResolvedFontPair, ScalarFaceSelection,
17 ShapedRun as CanonicalShapedRun, ShapingDirection,
18};
19use crate::text::TextWeight;
20use crate::theme::Color;
21
22pub(crate) mod ellipsis;
23pub(crate) mod font_fit;
24pub(crate) mod placement;
25mod rational;
26pub(crate) mod request;
27mod requirements;
28pub(crate) mod visibility;
29use rational::ExactRational;
30#[cfg(test)]
31pub(crate) mod metric_tests;
32#[cfg(test)]
33mod shaping_tests;
34#[allow(unused_imports)]
35pub(crate) use requirements::{
36 foundational_plot_requirements, PreparedFontPairRequirement, PreparedTextCensus,
37 PreparedTextRequirement, PreparedTextRole,
38};
39
40pub(crate) const CSS_PIXEL_QUANTA: i64 = 1024;
41#[cfg(test)]
42thread_local! {
43 static TEXT_WORK: std::cell::Cell<TextWork> = const { std::cell::Cell::new(TextWork {
44 proposal_visits: 0, exact_trials: 0, shaping_scalars: 0, shaped_glyphs: 0,
45 }) };
46}
47
48#[cfg(test)]
49#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
50struct TextWork {
51 proposal_visits: usize,
52 exact_trials: usize,
53 shaping_scalars: usize,
54 shaped_glyphs: usize,
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub(crate) enum PhysicalTextAlignment {
59 Start,
60 Center,
61 End,
62}
63
64impl From<crate::text::TextAlignment> for PhysicalTextAlignment {
65 fn from(alignment: crate::text::TextAlignment) -> Self {
66 match alignment {
67 crate::text::TextAlignment::Start => Self::Start,
68 crate::text::TextAlignment::Center => Self::Center,
69 crate::text::TextAlignment::End => Self::End,
70 }
71 }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub(crate) enum TextLineHeight {
76 Multiplier(f64),
77 ResolvedQuanta(i64),
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub(crate) struct TextPlanProvenance {
82 pub(crate) pair_ordinal: u32,
83 pub(crate) owner: String,
84}
85
86#[derive(Debug, Clone)]
87pub(crate) struct TextPlanInput<'a> {
88 pub(crate) size_trace: Option<std::sync::Arc<font_fit::stability::Stability>>,
89 pub(crate) direction: crate::text::TextDirection,
90 pub(crate) source: &'a str,
91 pub(crate) stack: &'a FontStack,
92 pub(crate) weight: TextWeight,
93 pub(crate) font_size: f64,
94 pub(crate) line_height: TextLineHeight,
95 pub(crate) maximum_width_quanta: i64,
96 pub(crate) alignment: PhysicalTextAlignment,
97 pub(crate) paint: Color,
98 pub(crate) provenance: TextPlanProvenance,
99 pub(crate) exact_override: bool,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub(crate) struct TextSourceSpan {
104 pub(crate) start_byte: u32,
105 pub(crate) end_byte: u32,
106}
107
108impl TextSourceSpan {
109 fn new(start: usize, end: usize) -> Result<Self, TextPlanError> {
110 Ok(Self {
111 start_byte: u32::try_from(start).map_err(|_| TextPlanError::SourceTooLong)?,
112 end_byte: u32::try_from(end).map_err(|_| TextPlanError::SourceTooLong)?,
113 })
114 }
115
116 fn range(self) -> Range<usize> {
117 self.start_byte as usize..self.end_byte as usize
118 }
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub(crate) struct TextInkBounds {
123 pub(crate) left: i64,
124 pub(crate) bottom: i64,
125 pub(crate) right: i64,
126 pub(crate) top: i64,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub(crate) struct PlannedGlyph {
131 pub(crate) face: FaceIdentity,
132 pub(crate) glyph_id: u16,
133 pub(crate) cluster: u32,
134 pub(crate) design_x_advance: i32,
135 pub(crate) design_y_advance: i32,
136 pub(crate) design_x_offset: i32,
137 pub(crate) design_y_offset: i32,
138 pub(crate) design_ink: Option<GlyphInk>,
139 pub(crate) x_advance_quanta: i64,
140 pub(crate) y_advance_quanta: i64,
141 pub(crate) x_offset_quanta: i64,
142 pub(crate) y_offset_quanta: i64,
143 pub(crate) glyph_origin_x_quanta: i64,
145 pub(crate) glyph_origin_y_quanta: i64,
146 pub(crate) ink_quanta: Option<TextInkBounds>,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub(crate) struct ShapedTextRun {
151 pub(crate) source_span: TextSourceSpan,
152 pub(crate) face: FaceIdentity,
153 pub(crate) direction: ShapingDirection,
154 pub(crate) bidi_level: u8,
156 pub(crate) script: Script,
157 pub(crate) units_per_em: u16,
158 pub(crate) design_ascender: i16,
159 pub(crate) design_descender: i16,
160 pub(crate) metric_source: canonical::MetricSource,
161 pub(crate) ascender_quanta: i64,
162 pub(crate) descender_quanta: i64,
163 pub(crate) design_x_advance: i64,
164 pub(crate) design_y_advance: i64,
165 pub(crate) logical_advance_quanta: i64,
166 pub(crate) logical_y_advance_quanta: i64,
167 pub(crate) ink_quanta: Option<TextInkBounds>,
168 pub(crate) glyphs: Vec<PlannedGlyph>,
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub(crate) struct TextLinePlan {
173 pub(crate) source_span: TextSourceSpan,
174 pub(crate) selected_soft_hyphen: Option<TextSourceSpan>,
176 pub(crate) ending_grapheme_index: u32,
177 pub(crate) translation_x_quanta: i64,
178 pub(crate) translation_y_quanta: i64,
179 pub(crate) logical_advance_quanta: i64,
180 pub(crate) ink_quanta: Option<TextInkBounds>,
181 pub(crate) base_direction: ShapingDirection,
182 pub(crate) runs: Vec<ShapedTextRun>,
183}
184
185#[derive(Debug, Clone, PartialEq)]
186pub(crate) struct ResolvedTextStyle {
187 pub(crate) stack_source: String,
188 pub(crate) stack: FontStack,
189 pub(crate) weight: TextWeight,
190 pub(crate) font_size: f64,
191 pub(crate) line_height_quanta: i64,
192 pub(crate) alignment: PhysicalTextAlignment,
193 pub(crate) paint: Color,
194 pub(crate) provenance: TextPlanProvenance,
195 pub(crate) exact_override: bool,
196}
197impl Eq for ResolvedTextStyle {}
198
199#[derive(Debug, Clone)]
200pub(crate) struct ResolvedTextPlan(
201 std::sync::Arc<ResolvedTextPayload>,
202 Option<std::sync::Arc<TextAnalysis>>,
203);
204
205impl PartialEq for ResolvedTextPlan {
207 fn eq(&self, other: &Self) -> bool {
208 self.0 == other.0
209 }
210}
211impl Eq for ResolvedTextPlan {}
212
213#[derive(Debug)]
214struct TextAnalysis {
215 direction: crate::text::TextDirection,
216 environment: PreparedFontEnvironment,
217 original: std::sync::Arc<ResolvedTextPayload>,
218 paragraphs: Vec<AnalyzedParagraph>,
219}
220
221#[derive(Debug)]
222struct AnalyzedParagraph {
223 span: TextSourceSpan,
224 grapheme_start: usize,
225 grapheme_ends: Vec<usize>,
226 bidi: Option<ParagraphBidiData>,
227 items: Vec<ScalarItem>,
228 hyphen_face: Option<FaceIdentity>,
229 whole_width: i64,
230 whole: ParagraphWhole,
231 wrapping: std::sync::OnceLock<ParagraphWrapping>,
232 hard_width: std::sync::OnceLock<i64>,
233}
234
235#[derive(Debug)]
236enum ParagraphWhole {
237 Retained(BuiltLine),
238 OriginalLine {
239 index: usize,
240 advance: ExactRational,
241 ascent: i64,
242 descent: i64,
243 },
244}
245
246#[derive(Debug)]
247struct ParagraphWrapping {
248 boundaries: Vec<usize>,
249 prefixes: Vec<ExactRational>,
250}
251
252#[derive(Debug)]
253struct ParagraphBidiData {
254 original_classes: Vec<unicode_bidi::BidiClass>,
255 levels: Vec<unicode_bidi::Level>,
256 paragraph_level: unicode_bidi::Level,
257 is_pure_ltr: bool,
258}
259
260impl From<ParagraphBidiInfo<'_>> for ParagraphBidiData {
261 fn from(info: ParagraphBidiInfo<'_>) -> Self {
262 Self {
263 original_classes: info.original_classes,
264 levels: info.levels,
265 paragraph_level: info.paragraph_level,
266 is_pure_ltr: info.is_pure_ltr,
267 }
268 }
269}
270
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub(crate) struct ResolvedTextPayload {
273 pub(crate) fit_input: Option<std::sync::Arc<font_fit::FitInput>>,
274 pub(crate) fit_group:
275 Option<std::sync::Arc<(crate::layout::ComponentAddress, Vec<font_fit::GroupMember>)>>,
276 pub(crate) original_source: Option<std::sync::Arc<String>>,
277 pub(crate) display_map: Option<std::sync::Arc<Vec<DisplayFragment>>>,
278 pub(crate) selected_rotation: Option<crate::text::TextRotation>,
279 occupied_rotation: Option<(i64, i64)>,
280 content: std::sync::Arc<ResolvedTextContent>,
281 pub(crate) request: Option<crate::text::TextLayout>,
282 pub(crate) clip_size: Option<(i64, i64)>,
283 pub(crate) paint_region: Option<[u64; 4]>,
284}
285
286#[derive(Debug, Clone, PartialEq, Eq)]
288pub(crate) struct FrozenText {
289 content: std::sync::Arc<ResolvedTextContent>,
290 pub(crate) original_source: Option<std::sync::Arc<String>>,
291 pub(crate) display_map: Option<std::sync::Arc<Vec<DisplayFragment>>>,
292 pub(crate) request: Option<crate::text::TextLayout>,
293 pub(crate) fit_input: Option<std::sync::Arc<font_fit::FitInput>>,
294 pub(crate) fit_group:
295 Option<std::sync::Arc<(crate::layout::ComponentAddress, Vec<font_fit::GroupMember>)>>,
296 pub(crate) selected_rotation: Option<crate::text::TextRotation>,
297 pub(crate) clip_size: Option<(i64, i64)>,
298 pub(crate) paint_region: Option<[u64; 4]>,
299}
300
301impl std::ops::Deref for FrozenText {
302 type Target = ResolvedTextContent;
303
304 fn deref(&self) -> &Self::Target {
305 &self.content
306 }
307}
308
309impl FrozenText {
310 pub(crate) fn original_source(&self) -> &str {
311 self.original_source
312 .as_ref()
313 .map_or(&self.content.source, |source| source.as_str())
314 }
315
316 #[cfg(test)]
317 pub(crate) fn shares_content(&self, plan: &ResolvedTextPlan) -> bool {
318 std::sync::Arc::ptr_eq(&self.content, &plan.content)
319 }
320
321 #[cfg(test)]
322 pub(crate) fn line_texts(&self) -> Vec<&str> {
323 self.lines
324 .iter()
325 .map(|line| &self.source[line.source_span.range()])
326 .collect()
327 }
328}
329
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub(crate) struct DisplayFragment {
332 pub(crate) display: std::ops::Range<usize>,
333 pub(crate) original: Option<std::ops::Range<usize>>,
334}
335
336#[derive(Debug, PartialEq, Eq)]
337#[cfg_attr(test, derive(Clone))]
338pub(crate) struct ResolvedTextContent {
339 pub(crate) source: String,
340 pub(crate) style: ResolvedTextStyle,
341 pub(crate) pair_provenance: PairProvenance,
342 pub(crate) lines: Vec<TextLinePlan>,
343 pub(crate) line_pitch_quanta: i64,
344 pub(crate) first_baseline_quanta: Option<i64>,
345 pub(crate) last_baseline_quanta: Option<i64>,
346 pub(crate) width_quanta: i64,
347 pub(crate) height_quanta: i64,
348}
349
350impl std::ops::Deref for ResolvedTextPayload {
351 type Target = ResolvedTextContent;
352 fn deref(&self) -> &Self::Target {
353 &self.content
354 }
355}
356
357#[cfg(test)]
358impl std::ops::DerefMut for ResolvedTextPayload {
359 fn deref_mut(&mut self) -> &mut Self::Target {
360 std::sync::Arc::make_mut(&mut self.content)
361 }
362}
363
364impl std::ops::Deref for ResolvedTextPlan {
365 type Target = ResolvedTextPayload;
366
367 fn deref(&self) -> &Self::Target {
368 &self.0
369 }
370}
371
372impl ResolvedTextPlan {
373 #[cfg(test)]
374 pub(crate) fn analysis_liveness_probe(&self) -> impl Fn() -> bool + use<> {
375 let analysis = self.1.as_ref().map(std::sync::Arc::downgrade);
376 move || {
377 analysis
378 .as_ref()
379 .is_some_and(|analysis| analysis.strong_count() != 0)
380 }
381 }
382
383 pub(crate) fn freeze_selected(&self) -> FrozenText {
384 FrozenText {
385 content: std::sync::Arc::clone(&self.content),
386 original_source: self.original_source.clone(),
387 display_map: self.display_map.clone(),
388 request: self.request.clone(),
389 fit_input: self.fit_input.clone(),
390 fit_group: self.fit_group.clone(),
391 selected_rotation: self.selected_rotation,
392 clip_size: self.clip_size,
393 paint_region: self.paint_region,
394 }
395 }
396
397 pub(crate) fn original_source(&self) -> &str {
398 self.original_source
399 .as_ref()
400 .map_or(&self.source, |source| source.as_str())
401 }
402 pub(crate) fn with_display(
403 mut self,
404 source: &str,
405 map: Vec<DisplayFragment>,
406 ) -> Result<Self, crate::Error> {
407 self.payload_mut().original_source = Some(crate::data::source::source_arc(
408 crate::data::source::copy_source_string(source)?,
409 )?);
410 self.payload_mut().display_map = Some(crate::data::source::source_arc(map)?);
411 Ok(self)
412 }
413 #[expect(
414 clippy::cast_precision_loss,
415 reason = "canonical occupied lengths are converted before checked outward projection"
416 )]
417 pub(crate) fn freeze_orientation(mut self) -> Result<Self, crate::Error> {
418 self.payload_mut().occupied_rotation = None;
419 if let Some(angle) = self.selected_rotation {
420 let (sine, cosine) = crate::text::orientation::components(angle.0.get());
421 let width = self.occupied_width_quanta() as f64 / 1024.0;
422 let height = self.occupied_height_quanta() as f64 / 1024.0;
423 let dimensions = (
424 crate::layout::kernel::ceil_spatial_quanta(
425 width * cosine.abs() + height * sine.abs(),
426 )?,
427 crate::layout::kernel::ceil_spatial_quanta(
428 width * sine.abs() + height * cosine.abs(),
429 )?,
430 );
431 self.payload_mut().occupied_rotation = Some(dimensions);
432 }
433 Ok(self)
434 }
435 pub(crate) fn translate_paint_region(mut self, dx: f64, dy: f64) -> Self {
436 if let Some(region) = self.paint_region {
437 let [x0, x1, y0, y1] = region.map(f64::from_bits);
438 self.payload_mut().paint_region =
439 Some([x0 + dx, x1 + dx, y0 + dy, y1 + dy].map(f64::to_bits));
440 }
441 self
442 }
443 pub(crate) fn clear_paint_region(&mut self) {
444 if self.paint_region.is_some() {
445 self.payload_mut().paint_region = None;
446 }
447 }
448 pub(crate) fn occupied_width_quanta(&self) -> i64 {
449 self.occupied_rotation.map_or_else(
450 || {
451 self.clip_size
452 .map_or(self.width_quanta, |(width, _)| width.min(self.width_quanta))
453 },
454 |size| size.0,
455 )
456 }
457
458 pub(crate) fn occupied_height_quanta(&self) -> i64 {
459 self.occupied_rotation.map_or_else(
460 || {
461 self.clip_size.map_or(self.height_quanta, |(_, height)| {
462 height.min(self.height_quanta)
463 })
464 },
465 |size| size.1,
466 )
467 }
468
469 #[expect(
470 clippy::cast_precision_loss,
471 reason = "text extents are bounded canonical quanta"
472 )]
473 pub(crate) fn occupied_size(&self) -> (f64, f64) {
474 (
475 self.occupied_width_quanta() as f64 / 1024.0,
476 self.occupied_height_quanta() as f64 / 1024.0,
477 )
478 }
479 pub(crate) fn hidden_source(
480 source: &str,
481 appearance: crate::text::TextAppearance<'_>,
482 alignment: PhysicalTextAlignment,
483 owner: &str,
484 ) -> Result<Self, crate::Error> {
485 let theme = appearance.theme;
486 Ok(Self(
487 std::sync::Arc::new(ResolvedTextPayload {
488 fit_input: None,
489 fit_group: None,
490 original_source: None,
491 display_map: None,
492 selected_rotation: None,
493 occupied_rotation: None,
494 content: std::sync::Arc::new(ResolvedTextContent {
495 source: crate::data::source::copy_source_string(source)?,
496 style: ResolvedTextStyle {
497 stack_source: theme
498 .get_stack()
499 .css()
500 .map_err(|error| crate::Error::Render(error.to_string().into()))?,
501 stack: theme.get_stack().clone(),
502 weight: theme.get_weight(),
503 font_size: theme.get_font_size(),
504 line_height_quanta: 1,
505 alignment,
506 paint: theme.get_color(),
507 provenance: TextPlanProvenance {
508 pair_ordinal: 0,
509 owner: owner.into(),
510 },
511 exact_override: appearance.exact_override,
512 },
513 pair_provenance: PairProvenance {
514 pair_ordinal: 0,
515 weight: theme.get_weight().into(),
516 candidates: Vec::new(),
517 },
518 lines: Vec::new(),
519 line_pitch_quanta: 1,
520 first_baseline_quanta: None,
521 last_baseline_quanta: None,
522 width_quanta: 0,
523 height_quanta: 0,
524 }),
525 request: appearance.layout.cloned(),
526 clip_size: None,
527 paint_region: None,
528 }),
529 None,
530 ))
531 }
532 pub(crate) fn clip_region(mut self, region: crate::layout::PixelRect) -> Self {
533 self.payload_mut().paint_region =
534 Some([region.x0, region.x1, region.y0, region.y1].map(f64::to_bits));
535 self
536 }
537 fn payload_mut(&mut self) -> &mut ResolvedTextPayload {
538 std::sync::Arc::make_mut(&mut self.0)
539 }
540 pub(crate) fn with_request(mut self, request: Option<&crate::text::TextLayout>) -> Self {
541 if let Some(crate::text::orientation::Orientation::Fixed(angle)) = request
542 .and_then(|request| request.instructions().orientation.as_ref())
543 .map(|orientation| &orientation.0)
544 {
545 self.payload_mut().selected_rotation = Some(*angle);
546 }
547 self.payload_mut().request = request.cloned();
548 self
549 }
550 pub(crate) fn hide(mut self) -> Result<Self, crate::Error> {
551 if self.lines.is_empty() {
552 return Ok(self);
553 }
554 let original = &self.style;
555 let style = ResolvedTextStyle {
556 stack_source: crate::data::source::copy_source_string(&original.stack_source)?,
557 stack: crate::data::source::copy_font_stack(&original.stack)?,
558 provenance: TextPlanProvenance {
559 pair_ordinal: original.provenance.pair_ordinal,
560 owner: crate::data::source::copy_source_string(&original.provenance.owner)?,
561 },
562 weight: original.weight,
563 font_size: original.font_size,
564 line_height_quanta: original.line_height_quanta,
565 alignment: original.alignment,
566 paint: original.paint,
567 exact_override: original.exact_override,
568 };
569 let content = ResolvedTextContent {
570 source: crate::data::source::copy_source_string(&self.source)?,
571 style,
572 pair_provenance: PairProvenance {
573 pair_ordinal: self.pair_provenance.pair_ordinal,
574 weight: self.pair_provenance.weight,
575 candidates: crate::data::source::collect_source(
576 self.pair_provenance.candidates.iter().copied().map(Ok),
577 )?,
578 },
579 lines: Vec::new(),
580 width_quanta: 0,
581 height_quanta: 0,
582 first_baseline_quanta: None,
583 last_baseline_quanta: None,
584 line_pitch_quanta: self.line_pitch_quanta,
585 };
586 self.payload_mut().content = std::sync::Arc::new(content);
587 self.payload_mut().occupied_rotation = None;
588 Ok(self)
589 }
590 pub(crate) fn clip_to(mut self, width: i64, height: i64) -> Self {
591 self.payload_mut().clip_size = Some((width, height));
592 self
593 }
594 pub(crate) fn retained_handle_count(&self) -> usize {
595 1 + usize::from(self.1.is_some())
596 }
597 pub(crate) fn analysis_profile(&self) -> Result<(&str, &FontStack), TextPlanError> {
599 let original = &self
600 .1
601 .as_ref()
602 .ok_or(TextPlanError::Arithmetic("missing text analysis"))?
603 .original;
604 Ok((&original.source, &original.style.stack))
605 }
606
607 pub(crate) fn same_stack(&self, stack: &FontStack) -> bool {
608 self.style.stack.same(stack)
609 }
610 pub(crate) fn copy_stack(&self) -> Result<FontStack, TextPlanError> {
611 Ok(self.style.stack.try_copy()?)
612 }
613
614 pub(crate) fn intrinsic_from_analysis(
615 &self,
616 preferred_lines: usize,
617 ) -> Result<TextIntrinsicRequirements, TextPlanError> {
618 let analysis = self
619 .1
620 .as_ref()
621 .ok_or(TextPlanError::Arithmetic("missing text analysis"))?;
622 let environment = &analysis.environment;
623 let original = &analysis.original;
624 let mut result = TextIntrinsicRequirements {
625 hard_width_quanta: 0,
626 natural_width_quanta: 0,
627 preferred_width_quanta: 0,
628 };
629 for paragraph in &analysis.paragraphs {
630 if paragraph.span.start_byte == paragraph.span.end_byte {
631 continue;
632 }
633 let (whole, _, _, _) = paragraph.whole(original);
634 if let Some(ink) = whole.ink_quanta {
635 result.natural_width_quanta = result.natural_width_quanta.max(
636 ink.right
637 .checked_sub(ink.left)
638 .ok_or(TextPlanError::Arithmetic("intrinsic ink width"))?,
639 );
640 }
641 let wrapping = paragraph.wrapping(&original.source, whole, original.style.font_size)?;
642 let last = wrapping.boundaries.len() - 1;
643 if paragraph.hard_width.get().is_none() {
644 let mut hard = 0;
645 for start in 0..last {
646 let width = if last == 1 {
647 paragraph.whole_width
648 } else {
649 let end = wrapping.boundaries[start + 1];
650 let line = prepare_line(
651 environment,
652 &original.source,
653 paragraph.span,
654 TextSourceSpan::new(
655 paragraph.span.start_byte as usize + wrapping.boundaries[start],
656 paragraph.span.start_byte as usize + end,
657 )?,
658 ending_grapheme_index(
659 ¶graph.grapheme_ends,
660 end,
661 paragraph.grapheme_start,
662 )?,
663 original.style.font_size,
664 paragraph
665 .bidi
666 .as_ref()
667 .ok_or(TextPlanError::Arithmetic("empty intrinsic paragraph"))?,
668 ¶graph.items,
669 paragraph.hyphen_face,
670 )?;
671 exact_line_width(&line)?
672 };
673 hard = hard.max(width);
674 }
675
676 let _ = paragraph.hard_width.set(hard);
677 }
678 result.hard_width_quanta = result.hard_width_quanta.max(
679 *paragraph
680 .hard_width
681 .get()
682 .ok_or(TextPlanError::Arithmetic("intrinsic width initialization"))?,
683 );
684 let lines = (preferred_lines / analysis.paragraphs.len().max(1)).max(1);
685 let chunk = last.div_ceil(lines);
686 for start in (0..last).step_by(chunk) {
687 let end = start.saturating_add(chunk).min(last);
688 result.preferred_width_quanta = result.preferred_width_quanta.max(
689 prefix_difference(&wrapping.prefixes[end], &wrapping.prefixes[start])?
690 .ceil_i64("preferred width")?,
691 );
692 }
693 }
694 result.preferred_width_quanta = result.preferred_width_quanta.max(result.hard_width_quanta);
695 Ok(result)
696 }
697
698 pub(crate) fn reflow(&self, mut input: TextPlanInput<'_>) -> Result<Self, TextPlanError> {
699 let analysis = self
700 .1
701 .as_ref()
702 .ok_or(TextPlanError::Arithmetic("missing text analysis"))?;
703 let environment = &analysis.environment;
704 let original = &analysis.original;
705
706 if !canonical::same_bytes(input.source, &original.source)
707 || input.direction != analysis.direction
708 || !input.stack.same(&original.style.stack)
709 || input.weight != original.style.weight
710 || input.font_size.to_bits() != original.style.font_size.to_bits()
711 {
712 return Err(TextPlanError::Arithmetic("text analysis profile mismatch"));
713 }
714 if input.maximum_width_quanta < 0 {
715 return Err(TextPlanError::InvalidMaximumWidth);
716 }
717 let line_height = resolve_line_height(input.line_height, input.font_size)?;
718 let mut lines = Vec::new();
719 for paragraph in &analysis.paragraphs {
720 let (whole, advance, ascent, descent) = paragraph.whole(original);
721 if paragraph.whole_width <= input.maximum_width_quanta {
722 retain_line(&mut lines, copy_line(whole, advance, ascent, descent)?)?;
723 continue;
724 }
725 let wrapping = paragraph.wrapping(input.source, whole, input.font_size)?;
726 let boundaries = &wrapping.boundaries;
727 let bidi = paragraph
728 .bidi
729 .as_ref()
730 .ok_or(TextPlanError::Arithmetic("empty paragraph reflow"))?;
731 let mut start = 0;
732 while start + 1 < boundaries.len() {
733 let (end, line) = select_line(
734 &wrapping.prefixes,
735 start,
736 input.maximum_width_quanta,
737 (start == 0).then_some(paragraph.whole_width),
738 TextSourceSpan::new(
739 paragraph.span.start_byte as usize + boundaries[start],
740 paragraph.span.start_byte as usize + boundaries[start + 1],
741 )?,
742 |end| {
743 prepare_line(
744 environment,
745 input.source,
746 paragraph.span,
747 TextSourceSpan::new(
748 paragraph.span.start_byte as usize + boundaries[start],
749 paragraph.span.start_byte as usize + boundaries[end],
750 )?,
751 ending_grapheme_index(
752 ¶graph.grapheme_ends,
753 boundaries[end],
754 paragraph.grapheme_start,
755 )?,
756 input.font_size,
757 bidi,
758 ¶graph.items,
759 paragraph.hyphen_face,
760 )
761 },
762 )?;
763 retain_line(&mut lines, line)?;
764 start = end;
765 }
766 }
767 let mut candidates = Vec::new();
768 let provenance = &original.pair_provenance;
769
770 super::unicode16::reserve(&mut candidates, provenance.candidates.len())?;
771 candidates.extend_from_slice(&provenance.candidates);
772 input.provenance.pair_ordinal = provenance.pair_ordinal;
773 let stack = input.stack;
774 let mut plan = finalize_plan(
775 input,
776 stack,
777 PairProvenance {
778 pair_ordinal: provenance.pair_ordinal,
779 weight: provenance.weight,
780 candidates,
781 },
782 line_height,
783 lines,
784 )?;
785 plan.1 = Some(std::sync::Arc::clone(analysis));
786 Ok(plan)
787 }
788
789 pub(crate) fn unwrapped_fit_width(&self) -> Result<Option<i64>, TextPlanError> {
790 let mut previous_end = None;
791 let mut required = 0;
792 for line in &self.lines {
793 if let Some(end) = previous_end {
794 let separator = &self.source[end..line.source_span.start_byte as usize];
795 if separator.is_empty() {
796 return Ok(None);
797 }
798 for scalar in separator.chars() {
799 if !crate::text::is_nonrendering_mandatory_break(scalar) {
800 return Ok(None);
801 }
802 }
803 }
804 previous_end = Some(line.source_span.end_byte as usize);
805 let mut advance = ExactRational::ZERO;
806 for run in &line.runs {
807 advance = advance.add(
808 &scale_design(run.design_x_advance, self.style.font_size, run.units_per_em)?,
809 "cached paragraph advance",
810 )?;
811 }
812 let ink_width = line.ink_quanta.map_or(Ok(0), |ink| {
813 ink.right
814 .checked_sub(ink.left)
815 .ok_or(TextPlanError::Arithmetic("cached paragraph ink"))
816 })?;
817 required = required
818 .max(advance.ceil_i64("cached paragraph advance")?)
819 .max(ink_width);
820 }
821 Ok(Some(required))
822 }
823
824 pub(crate) fn shares_payload(&self, other: &Self) -> bool {
825 std::sync::Arc::ptr_eq(&self.0, &other.0)
826 }
827
828 #[cfg(test)]
829 pub(crate) fn shares_analysis(&self, other: &Self) -> bool {
830 match (&self.1, &other.1) {
831 (Some(left), Some(right)) => std::sync::Arc::ptr_eq(left, right),
832 _ => false,
833 }
834 }
835 #[expect(
836 clippy::cast_precision_loss,
837 reason = "immutable plans retain exact i64 quanta; layout adapters use pixels"
838 )]
839 pub(crate) fn width(&self) -> f64 {
840 self.width_quanta as f64 / CSS_PIXEL_QUANTA as f64
841 }
842
843 #[expect(
844 clippy::cast_precision_loss,
845 reason = "immutable plans retain exact i64 quanta; layout adapters use pixels"
846 )]
847 pub(crate) fn fit_width(&self) -> f64 {
848 let rounded_advance = self
849 .lines
850 .iter()
851 .map(|line| line.logical_advance_quanta)
852 .max()
853 .unwrap_or(0);
854 let conservative_ceil = rounded_advance.saturating_add(i64::from(rounded_advance > 0));
855 self.clip_size
856 .map_or(conservative_ceil, |(width, _)| width.min(conservative_ceil)) as f64
857 / CSS_PIXEL_QUANTA as f64
858 }
859
860 #[expect(
861 clippy::cast_precision_loss,
862 reason = "immutable plans retain exact i64 quanta; layout adapters use pixels"
863 )]
864 pub(crate) fn height(&self) -> f64 {
865 self.height_quanta as f64 / CSS_PIXEL_QUANTA as f64
866 }
867
868 #[expect(
869 clippy::cast_precision_loss,
870 reason = "immutable plans retain exact i64 quanta; layout adapters use pixels"
871 )]
872 pub(crate) fn line_height(&self) -> f64 {
873 self.line_pitch_quanta as f64 / CSS_PIXEL_QUANTA as f64
874 }
875
876 pub(crate) fn line_texts(&self) -> Vec<&str> {
877 self.lines
878 .iter()
879 .map(|line| &self.source[line.source_span.range()])
880 .collect()
881 }
882
883 pub(crate) fn into_line_texts(self) -> Result<Vec<String>, TextPlanError> {
886 let mut lines = Vec::new();
887
888 super::unicode16::reserve(&mut lines, self.lines.len())?;
889 for line in &self.lines {
890 let text = &self.source[line.source_span.range()];
891 let length = text.len() - usize::from(line.selected_soft_hyphen.is_some());
892
893 let mut retained = String::new();
894 crate::operation::string(&retained, length)?;
895 retained
896 .try_reserve_exact(length)
897 .map_err(|_| TextPlanError::Allocation("owned text line"))?;
898 if let Some(soft) = line.selected_soft_hyphen {
899 retained.push_str(
900 &self.source[line.source_span.start_byte as usize..soft.start_byte as usize],
901 );
902 retained.push('-');
903 retained.push_str(
904 &self.source[soft.end_byte as usize..line.source_span.end_byte as usize],
905 );
906 } else {
907 retained.push_str(text);
908 }
909 lines.push(retained);
910 }
911 Ok(lines)
912 }
913}
914
915impl AnalyzedParagraph {
916 fn whole<'a>(
917 &'a self,
918 original: &'a ResolvedTextPayload,
919 ) -> (&'a TextLinePlan, ExactRational, i64, i64) {
920 match &self.whole {
921 ParagraphWhole::Retained(line) => {
922 (&line.plan, line.advance.clone(), line.ascent, line.descent)
923 }
924 ParagraphWhole::OriginalLine {
925 index,
926 advance,
927 ascent,
928 descent,
929 } => (&original.lines[*index], advance.clone(), *ascent, *descent),
930 }
931 }
932
933 fn wrapping(
934 &self,
935
936 source: &str,
937 whole: &TextLinePlan,
938 font_size: f64,
939 ) -> Result<&ParagraphWrapping, TextPlanError> {
940 if self.wrapping.get().is_none() {
941 let mut boundaries =
942 legal_line_breaks_at_graphemes(&source[self.span.range()], &self.grapheme_ends)?;
943
944 super::unicode16::reserve(&mut boundaries, 1)?;
945 boundaries.insert(0, 0);
946 let prefixes = proposal_prefixes(whole, &boundaries, font_size)?;
947
948 let _ = self.wrapping.set(ParagraphWrapping {
949 boundaries,
950 prefixes,
951 });
952 }
953 self.wrapping.get().ok_or(TextPlanError::Arithmetic(
954 "paragraph wrapping initialization",
955 ))
956 }
957}
958
959fn copy_line(
960 line: &TextLinePlan,
961 advance: ExactRational,
962 ascent: i64,
963 descent: i64,
964) -> Result<BuiltLine, TextPlanError> {
965 let mut runs = Vec::new();
966
967 super::unicode16::reserve(&mut runs, line.runs.len())?;
968 for run in &line.runs {
969 let mut glyphs = Vec::new();
970
971 super::unicode16::reserve(&mut glyphs, run.glyphs.len())?;
972 glyphs.extend_from_slice(&run.glyphs);
973 runs.push(ShapedTextRun { glyphs, ..*run });
974 }
975 Ok(BuiltLine {
976 plan: TextLinePlan { runs, ..*line },
977 advance,
978 ascent,
979 descent,
980 })
981}
982
983#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
984#[error(
985 "text bytes {source_span:?} require {required_width_quanta} quanta but only {maximum_width_quanta} are available"
986)]
987pub(crate) struct TextFitMiss {
988 pub(crate) source_span: TextSourceSpan,
989 pub(crate) maximum_width_quanta: i64,
990 pub(crate) required_width_quanta: i64,
991}
992
993#[derive(Debug, thiserror::Error)]
994pub(crate) enum TextPlanError {
995 #[error(transparent)]
996 Spacing(#[from] crate::Error),
997 #[error(transparent)]
998 Font(#[from] FontError),
999 #[error(transparent)]
1000 Fit(#[from] TextFitMiss),
1001 #[error("font size must be positive")]
1002 InvalidFontSize,
1003 #[error("maximum text width must be nonnegative")]
1004 InvalidMaximumWidth,
1005 #[error("line height must be finite and positive")]
1006 InvalidLineHeight,
1007 #[error("text block {span:?} has zero checked layout height; selected faces {faces:?}")]
1008 NoTextHeight {
1009 span: TextSourceSpan,
1010 faces: Vec<FaceIdentity>,
1011 },
1012 #[error("text source exceeds the supported u32 byte range")]
1013 SourceTooLong,
1014 #[error("text planning arithmetic overflow while calculating {0}")]
1015 Arithmetic(&'static str),
1016 #[error("text planning could not reserve {0}")]
1017 Allocation(&'static str),
1018 #[error("cannot map Unicode script '{0}' into rustybuzz")]
1019 Script(String),
1020 #[error("resolved scalar U+{0:04X} is not backed by a rendering face")]
1021 InvalidScalarSelection(u32),
1022 #[error("prepared text census does not contain the requested font stack and weight")]
1023 MissingPreparedPair,
1024 #[error("prepared text census does not contain scalar U+{0:04X}")]
1025 MissingPreparedScalar(u32),
1026}
1027
1028impl From<TextPlanError> for crate::Error {
1029 fn from(error: TextPlanError) -> Self {
1030 match error {
1031 TextPlanError::Spacing(error) => error,
1032 TextPlanError::Font(error) => error.into(),
1033 error => crate::Error::Render(error.to_string().into()),
1034 }
1035 }
1036}
1037
1038#[derive(Debug, Clone, PartialEq, Eq)]
1039pub(crate) struct DeferredAnnotationTextPlan {
1040 pub(crate) plan: ResolvedTextPlan,
1041 pub(crate) exact_override: bool,
1042}
1043
1044impl DeferredAnnotationTextPlan {
1045 pub(crate) fn from_resolved(plan: ResolvedTextPlan) -> Self {
1046 let exact_override = plan.style.exact_override;
1047 Self {
1048 plan,
1049 exact_override,
1050 }
1051 }
1052}
1053
1054impl PreparedFontEnvironment {
1055 pub(crate) fn plan_text(
1056 &self,
1057 input: TextPlanInput<'_>,
1058 ) -> Result<ResolvedTextPlan, TextPlanError> {
1059 match measure_text(self, input, None)? {
1060 TextMeasurement::Assigned(plan) => Ok(plan),
1061 TextMeasurement::Intrinsic(_) => unreachable!("assigned text request"),
1062 }
1063 }
1064
1065 pub(crate) fn text_intrinsic_requirements(
1066 &self,
1067 input: TextPlanInput<'_>,
1068 preferred_lines: usize,
1069 ) -> Result<TextIntrinsicRequirements, TextPlanError> {
1070 match measure_text(self, input, Some(preferred_lines))? {
1071 TextMeasurement::Intrinsic(requirements) => Ok(requirements),
1072 TextMeasurement::Assigned(_) => unreachable!("intrinsic text request"),
1073 }
1074 }
1075}
1076
1077#[derive(Debug, Clone, Copy)]
1078#[expect(
1079 clippy::struct_field_names,
1080 reason = "explicit quantum units distinguish these widths from the pixel-space adapter lengths"
1081)]
1082pub(crate) struct TextIntrinsicRequirements {
1083 pub(crate) hard_width_quanta: i64,
1084 pub(crate) natural_width_quanta: i64,
1085 pub(crate) preferred_width_quanta: i64,
1086}
1087
1088enum TextMeasurement {
1089 Intrinsic(TextIntrinsicRequirements),
1090 Assigned(ResolvedTextPlan),
1091}
1092
1093#[expect(
1094 clippy::too_many_lines,
1095 reason = "constrained text planning keeps count, reservation, materialization, and freezing ordered"
1096)]
1097fn measure_text(
1098 environment: &PreparedFontEnvironment,
1099 mut input: TextPlanInput<'_>,
1100 intrinsic_lines: Option<usize>,
1101) -> Result<TextMeasurement, TextPlanError> {
1102 if !input.font_size.is_finite() || input.font_size <= 0.0 {
1103 return Err(TextPlanError::InvalidFontSize);
1104 }
1105 if input.maximum_width_quanta < 0 {
1106 return Err(TextPlanError::InvalidMaximumWidth);
1107 }
1108 let _ = u32::try_from(input.source.len()).map_err(|_| TextPlanError::SourceTooLong)?;
1109
1110 let stack = input.stack;
1111 let scale = FontScale {
1112 size: input.font_size,
1113 trace: input.size_trace.as_ref(),
1114 };
1115 let line_height_quanta = resolve_line_height(input.line_height, input.font_size)?;
1116 if let Some(trace) = scale.trace {
1117 trace.observe(line_height_quanta, |size| {
1118 resolve_line_height(input.line_height, size)
1119 })?;
1120 }
1121
1122 let weight = input.weight.into();
1123 environment.admit_text(stack, weight, input.source, None)?;
1124 let pair = environment
1125 .prepared_pair(stack, weight)?
1126 .ok_or(TextPlanError::MissingPreparedPair)?;
1127 input.provenance.pair_ordinal = pair.provenance.pair_ordinal;
1128
1129 let paragraph_seeds = mandatory_paragraph_seeds(input.source)?;
1130 let mut built_lines = Vec::new();
1131 let mut analyzed_paragraphs = Vec::new();
1132 let mut requirements = TextIntrinsicRequirements {
1133 hard_width_quanta: 0,
1134 natural_width_quanta: 0,
1135 preferred_width_quanta: 0,
1136 };
1137 let paragraph_count = paragraph_seeds.len();
1138 let mut grapheme_start = 0_usize;
1139
1140 for seed in paragraph_seeds {
1141 let paragraph = &input.source[seed.span.range()];
1142
1143 let mut grapheme_ends = Vec::new();
1144 for (start, grapheme) in paragraph.grapheme_indices(true) {
1145 super::unicode16::reserve(&mut grapheme_ends, 1)?;
1146 grapheme_ends.push(start + grapheme.len());
1147 }
1148 let next_grapheme = grapheme_start
1149 .checked_add(grapheme_ends.len())
1150 .ok_or(TextPlanError::Arithmetic("grapheme index"))?;
1151 let ending = u32::try_from(next_grapheme)
1152 .map_err(|_| TextPlanError::Arithmetic("grapheme index"))?;
1153 if paragraph.is_empty() {
1154 if intrinsic_lines.is_none() {
1155 let whole = empty_line(
1156 seed.span,
1157 ending,
1158 environment.face_metrics(pair.primary)?,
1159 scale,
1160 )?;
1161 retain_paragraph(
1162 &mut analyzed_paragraphs,
1163 AnalyzedParagraph {
1164 span: seed.span,
1165 grapheme_start,
1166 grapheme_ends,
1167 bidi: None,
1168 items: Vec::new(),
1169 hyphen_face: None,
1170 whole_width: 0,
1171 whole: ParagraphWhole::OriginalLine {
1172 index: built_lines.len(),
1173 advance: whole.advance.clone(),
1174 ascent: whole.ascent,
1175 descent: whole.descent,
1176 },
1177 wrapping: std::sync::OnceLock::new(),
1178 hard_width: std::sync::OnceLock::new(),
1179 },
1180 )?;
1181 retain_line(&mut built_lines, whole)?;
1182 }
1183 continue;
1184 }
1185
1186 let level = match input.direction {
1187 crate::text::TextDirection::Auto => None,
1188 crate::text::TextDirection::LeftToRight => Some(unicode_bidi::Level::ltr()),
1189 crate::text::TextDirection::RightToLeft => Some(unicode_bidi::Level::rtl()),
1190 };
1191 let bidi = ParagraphBidiData::from(ParagraphBidiInfo::new(paragraph, level));
1192 let items = selected_paragraph_items(&pair, paragraph)?;
1193 let hyphen_face = paragraph
1194 .contains('\u{ad}')
1195 .then(|| selected_face(&pair, "-", '-'))
1196 .transpose()?;
1197 let whole = prepare_line(
1198 environment,
1199 input.source,
1200 seed.span,
1201 seed.span,
1202 ending,
1203 scale,
1204 &bidi,
1205 &items,
1206 hyphen_face,
1207 )?;
1208 let whole_width = exact_line_width(&whole)?;
1209 if intrinsic_lines.is_none() && whole_width <= input.maximum_width_quanta {
1210 retain_paragraph(
1211 &mut analyzed_paragraphs,
1212 AnalyzedParagraph {
1213 span: seed.span,
1214 grapheme_start,
1215 grapheme_ends,
1216 bidi: Some(bidi),
1217 items,
1218 hyphen_face,
1219 whole_width,
1220 whole: ParagraphWhole::OriginalLine {
1221 index: built_lines.len(),
1222 advance: whole.advance.clone(),
1223 ascent: whole.ascent,
1224 descent: whole.descent,
1225 },
1226 wrapping: std::sync::OnceLock::new(),
1227 hard_width: std::sync::OnceLock::new(),
1228 },
1229 )?;
1230 retain_line(&mut built_lines, whole)?;
1231 grapheme_start = next_grapheme;
1232 continue;
1233 }
1234 let mut boundaries = legal_line_breaks_at_graphemes(paragraph, &grapheme_ends)?;
1235
1236 super::unicode16::reserve(&mut boundaries, 1)?;
1237 boundaries.insert(0, 0);
1238 let prefixes = proposal_prefixes(&whole.plan, &boundaries, scale)?;
1239 let last = boundaries.len() - 1;
1240 let shape = |start: usize, end: usize| {
1241 let span = TextSourceSpan::new(
1242 seed.span.start_byte as usize + boundaries[start],
1243 seed.span.start_byte as usize + boundaries[end],
1244 )?;
1245 prepare_line(
1246 environment,
1247 input.source,
1248 seed.span,
1249 span,
1250 ending_grapheme_index(&grapheme_ends, boundaries[end], grapheme_start)?,
1251 scale,
1252 &bidi,
1253 &items,
1254 hyphen_face,
1255 )
1256 };
1257 if let Some(preferred_lines) = intrinsic_lines {
1258 requirements.natural_width_quanta =
1259 requirements.natural_width_quanta.max(ink_width(&whole)?);
1260 for start in 0..last {
1261 let width = if last == 1 {
1262 whole_width
1263 } else {
1264 exact_line_width(&shape(start, start + 1)?)?
1265 };
1266 requirements.hard_width_quanta = requirements.hard_width_quanta.max(width);
1267 }
1268 let lines = (preferred_lines / paragraph_count.max(1)).max(1);
1269 let chunk = last.div_ceil(lines);
1270 for start in (0..last).step_by(chunk) {
1271 let end = start.saturating_add(chunk).min(last);
1272 let width = prefix_difference(&prefixes[end], &prefixes[start])?
1273 .ceil_i64("preferred width")?;
1274 requirements.preferred_width_quanta =
1275 requirements.preferred_width_quanta.max(width);
1276 }
1277 } else {
1278 let mut start = 0;
1281 while start < last {
1282 let (end, selected) = select_line(
1283 &prefixes,
1284 start,
1285 input.maximum_width_quanta,
1286 (start == 0).then_some(whole_width),
1287 TextSourceSpan::new(
1288 seed.span.start_byte as usize + boundaries[start],
1289 seed.span.start_byte as usize + boundaries[start + 1],
1290 )?,
1291 |end| shape(start, end),
1292 )?;
1293 retain_line(&mut built_lines, selected)?;
1294 start = end;
1295 }
1296
1297 retain_paragraph(
1298 &mut analyzed_paragraphs,
1299 AnalyzedParagraph {
1300 span: seed.span,
1301 grapheme_start,
1302 grapheme_ends,
1303 bidi: Some(bidi),
1304 items,
1305 hyphen_face,
1306 whole_width,
1307 whole: ParagraphWhole::Retained(whole),
1308 wrapping: std::sync::OnceLock::from(ParagraphWrapping {
1309 boundaries,
1310 prefixes,
1311 }),
1312 hard_width: std::sync::OnceLock::new(),
1313 },
1314 )?;
1315 }
1316 grapheme_start = next_grapheme;
1317 }
1318 if intrinsic_lines.is_some() {
1319 requirements.preferred_width_quanta = requirements
1320 .preferred_width_quanta
1321 .max(requirements.hard_width_quanta);
1322 return Ok(TextMeasurement::Intrinsic(requirements));
1323 }
1324 let direction = input.direction;
1325 let mut plan = finalize_plan(
1326 input,
1327 stack,
1328 pair.provenance,
1329 line_height_quanta,
1330 built_lines,
1331 )?;
1332
1333 plan.1 = Some(std::sync::Arc::new(TextAnalysis {
1334 direction,
1335 environment: environment.clone(),
1336 original: std::sync::Arc::clone(&plan.0),
1337 paragraphs: analyzed_paragraphs,
1338 }));
1339 Ok(TextMeasurement::Assigned(plan))
1340}
1341
1342fn retain_paragraph(
1343 paragraphs: &mut Vec<AnalyzedParagraph>,
1344 paragraph: AnalyzedParagraph,
1345) -> Result<(), TextPlanError> {
1346 super::unicode16::reserve(paragraphs, 1)?;
1347 paragraphs.push(paragraph);
1348 Ok(())
1349}
1350
1351#[derive(Debug, Clone, Copy)]
1352struct ParagraphSeed {
1353 span: TextSourceSpan,
1354 scalar_count: u128,
1355}
1356
1357fn select_line(
1358 prefixes: &[ExactRational],
1359 start: usize,
1360 maximum_width_quanta: i64,
1361 failed_paragraph_width: Option<i64>,
1362 first_span: TextSourceSpan,
1363 mut shape: impl FnMut(usize) -> Result<BuiltLine, TextPlanError>,
1364) -> Result<(usize, BuiltLine), TextPlanError> {
1365 let last = prefixes.len() - 1;
1366 let mut end = start + 1;
1367 for candidate in start + 1..=last {
1368 #[cfg(test)]
1369 TEXT_WORK.with(|work| {
1370 work.update(|mut work| {
1371 work.proposal_visits += 1;
1372 work
1373 });
1374 });
1375 if prefix_difference(&prefixes[candidate], &prefixes[start])?.ceil_i64("proposal width")?
1376 > maximum_width_quanta
1377 {
1378 end = candidate.saturating_sub(1).max(start + 1);
1379 break;
1380 }
1381 end = candidate;
1382 }
1383 let mut failed = failed_paragraph_width.map(|_| last);
1384 let mut selected = loop {
1385 let (trial, width) = if let Some(width) = failed_paragraph_width.filter(|_| end == last) {
1386 (None, width)
1387 } else {
1388 let trial = shape(end)?;
1389 let width = exact_line_width(&trial)?;
1390 (Some(trial), width)
1391 };
1392 if width <= maximum_width_quanta {
1393 break trial.ok_or(TextPlanError::Arithmetic("failed paragraph trial"))?;
1394 }
1395 failed = Some(end);
1396 if end == start + 1 {
1397 return Err(TextFitMiss {
1398 source_span: first_span,
1399 maximum_width_quanta,
1400 required_width_quanta: width,
1401 }
1402 .into());
1403 }
1404 end -= 1;
1405 };
1406 while end < last {
1407 if failed == Some(end + 1) {
1408 break;
1409 }
1410 let trial = shape(end + 1)?;
1411 if exact_line_width(&trial)? > maximum_width_quanta {
1412 break;
1413 }
1414 selected = trial;
1415 end += 1;
1416 }
1417 Ok((end, selected))
1418}
1419
1420fn retain_line(lines: &mut Vec<BuiltLine>, line: BuiltLine) -> Result<(), TextPlanError> {
1421 super::unicode16::reserve(lines, 1)?;
1422 lines.push(line);
1423 Ok(())
1424}
1425
1426fn ink_width(line: &BuiltLine) -> Result<i64, TextPlanError> {
1427 line.plan.ink_quanta.map_or(Ok(0), |ink| {
1428 ink.right
1429 .checked_sub(ink.left)
1430 .ok_or(TextPlanError::Arithmetic("line ink span"))
1431 })
1432}
1433
1434fn exact_line_width(line: &BuiltLine) -> Result<i64, TextPlanError> {
1435 #[cfg(test)]
1436 TEXT_WORK.with(|work| {
1437 work.update(|mut work| {
1438 work.exact_trials += 1;
1439 work
1440 });
1441 });
1442 Ok(line.advance.ceil_i64("wrap advance")?.max(ink_width(line)?))
1443}
1444
1445fn prefix_difference(
1446 end: &ExactRational,
1447 start: &ExactRational,
1448) -> Result<ExactRational, TextPlanError> {
1449 end.add(&start.negated()?, "proposal difference")
1450}
1451
1452fn proposal_prefixes<'a>(
1453 whole: &TextLinePlan,
1454 boundaries: &[usize],
1455 font_size: impl Into<FontScale<'a>>,
1456) -> Result<Vec<ExactRational>, TextPlanError> {
1457 let font_size = font_size.into();
1458 let mut prefixes = Vec::new();
1459 super::unicode16::reserve(&mut prefixes, boundaries.len())?;
1460 prefixes.resize(boundaries.len(), ExactRational::ZERO);
1461 let mut clusters = Vec::new();
1464 for (run_order, run) in whole.runs.iter().enumerate() {
1465 let mut cursor = if run.direction == ShapingDirection::RightToLeft {
1466 run.glyphs.len()
1467 } else {
1468 0
1469 };
1470 let rtl = run.direction == ShapingDirection::RightToLeft;
1471 while if rtl {
1472 cursor > 0
1473 } else {
1474 cursor < run.glyphs.len()
1475 } {
1476 let index = if rtl { cursor - 1 } else { cursor };
1477 let glyph_order = index;
1478 let cluster = run.glyphs[index].cluster;
1479 let mut total = 0_i64;
1480 loop {
1481 let index = if rtl { cursor - 1 } else { cursor };
1482
1483 total = total
1484 .checked_add(i64::from(run.glyphs[index].design_x_advance))
1485 .ok_or(TextPlanError::Arithmetic("cluster advance"))?;
1486 if rtl {
1487 cursor -= 1;
1488 } else {
1489 cursor += 1;
1490 }
1491 if (rtl && cursor == 0) || (!rtl && cursor == run.glyphs.len()) {
1492 break;
1493 }
1494 let next = if rtl { cursor - 1 } else { cursor };
1495 if run.glyphs[next].cluster != cluster {
1496 break;
1497 }
1498 }
1499 let end = if (rtl && cursor == 0) || (!rtl && cursor == run.glyphs.len()) {
1500 run.source_span.end_byte
1501 } else {
1502 run.glyphs[if rtl { cursor - 1 } else { cursor }].cluster
1503 };
1504 let magnitude = total
1505 .checked_abs()
1506 .ok_or(TextPlanError::Arithmetic("cluster magnitude"))?;
1507
1508 super::unicode16::reserve(&mut clusters, 1)?;
1509 clusters.push((
1510 end,
1511 run_order,
1512 glyph_order,
1513 cluster,
1514 scale_design(magnitude, font_size, run.units_per_em)?,
1515 ));
1516 }
1517 }
1518
1519 clusters.sort_unstable_by_key(|&(end, run, glyph, _, _)| (end, run, glyph));
1520 let mut boundary = 1;
1521 for (end, _, _, _, advance) in clusters {
1522 let end = (end - whole.source_span.start_byte) as usize;
1523 while boundaries[boundary] < end {
1524 boundary += 1;
1525 }
1526 prefixes[boundary] = prefixes[boundary].add(&advance, "cluster prefix")?;
1527 }
1528 for index in 1..prefixes.len() {
1529 prefixes[index] = prefixes[index].add(&prefixes[index - 1], "paragraph prefix")?;
1530 }
1531 Ok(prefixes)
1532}
1533
1534fn checked_multiply(
1535 value: u128,
1536 factor: u128,
1537 resource: &'static str,
1538) -> Result<u128, TextPlanError> {
1539 value
1540 .checked_mul(factor)
1541 .ok_or(TextPlanError::Arithmetic(resource))
1542}
1543
1544fn mandatory_paragraph_seeds(source: &str) -> Result<Vec<ParagraphSeed>, TextPlanError> {
1545 let mut paragraphs = Vec::new();
1546 let mut start = 0_usize;
1547 let mut scalar_count = 0_u128;
1548 let mut scalars = source.char_indices().peekable();
1549 while let Some((index, scalar)) = scalars.next() {
1550 if !crate::text::is_nonrendering_mandatory_break(scalar) {
1551 scalar_count = scalar_count
1552 .checked_add(1)
1553 .ok_or(TextPlanError::Arithmetic("paragraph scalar count"))?;
1554 continue;
1555 }
1556 super::unicode16::reserve(&mut paragraphs, 1)?;
1557 paragraphs.push(ParagraphSeed {
1558 span: TextSourceSpan::new(start, index)?,
1559 scalar_count,
1560 });
1561 let mut break_end = index + scalar.len_utf8();
1562 if scalar == '\r' && scalars.peek().is_some_and(|(_, next)| *next == '\n') {
1563 let (lf_index, lf) = scalars
1564 .next()
1565 .ok_or(TextPlanError::Arithmetic("CRLF segmentation"))?;
1566 break_end = lf_index + lf.len_utf8();
1567 }
1568 start = break_end;
1569 scalar_count = 0;
1570 }
1571 super::unicode16::reserve(&mut paragraphs, 1)?;
1572 paragraphs.push(ParagraphSeed {
1573 span: TextSourceSpan::new(start, source.len())?,
1574 scalar_count,
1575 });
1576 Ok(paragraphs)
1577}
1578
1579fn paragraph_linebreaks(
1580 paragraph: &str,
1581) -> Result<Vec<(usize, super::unicode16::BreakOpportunity)>, TextPlanError> {
1582 if paragraph.is_empty() {
1583 return Ok(Vec::new());
1584 }
1585 let mut reduced = String::new();
1590 crate::operation::string(&reduced, paragraph.len())?;
1591 reduced
1592 .try_reserve_exact(paragraph.len())
1593 .map_err(|_| TextPlanError::Allocation("line-break analysis source"))?;
1594 let mut offsets = Vec::new();
1595 let mut alphabetic = false;
1596 for (offset, scalar) in paragraph.char_indices() {
1597 let next_alphabetic = scalar.is_ascii_alphabetic();
1598 if !alphabetic || !next_alphabetic {
1599 super::unicode16::reserve(&mut offsets, 1)?;
1600 offsets.push((reduced.len(), offset));
1601 reduced.push(scalar);
1602 }
1603 alphabetic = next_alphabetic;
1604 }
1605 super::unicode16::reserve(&mut offsets, 1)?;
1606 offsets.push((reduced.len(), paragraph.len()));
1607 let mut opportunities = super::unicode16::linebreaks(&reduced)?;
1608 let mut mapped = 0;
1609 for (index, _) in &mut opportunities {
1610 loop {
1611 if offsets[mapped].0 >= *index {
1612 break;
1613 }
1614 mapped += 1;
1615 }
1616 *index = offsets[mapped].1;
1617 }
1618 Ok(opportunities)
1619}
1620
1621fn legal_line_breaks_at_graphemes(
1623 paragraph: &str,
1624 grapheme_ends: &[usize],
1625) -> Result<Vec<usize>, TextPlanError> {
1626 let opportunities = paragraph_linebreaks(paragraph)?;
1627 let mut breaks = Vec::new();
1628 let mut grapheme = 0;
1629 for (index, _) in opportunities {
1631 while grapheme < grapheme_ends.len() {
1632 if grapheme_ends[grapheme] >= index {
1633 break;
1634 }
1635 grapheme += 1;
1636 }
1637 if index > 0 && grapheme_ends.get(grapheme) == Some(&index) {
1638 super::unicode16::reserve(&mut breaks, 1)?;
1639 breaks.push(index);
1640 }
1641 }
1642 Ok(breaks)
1643}
1644
1645fn ending_grapheme_index(
1646 grapheme_ends: &[usize],
1647 end: usize,
1648 paragraph_start_index: usize,
1649) -> Result<u32, TextPlanError> {
1650 let local = grapheme_ends
1651 .binary_search(&end)
1652 .map_err(|_| TextPlanError::Arithmetic("ending grapheme boundary"))?
1653 .checked_add(1)
1654 .ok_or(TextPlanError::Arithmetic("ending grapheme index"))?;
1655 u32::try_from(
1656 paragraph_start_index
1657 .checked_add(local)
1658 .ok_or(TextPlanError::Arithmetic("ending grapheme index"))?,
1659 )
1660 .map_err(|_| TextPlanError::Arithmetic("ending grapheme index"))
1661}
1662
1663#[derive(Debug)]
1664struct BuiltLine {
1665 plan: TextLinePlan,
1666 advance: ExactRational,
1667 ascent: i64,
1668 descent: i64,
1669}
1670
1671fn empty_line<'a>(
1672 span: TextSourceSpan,
1673 ending_grapheme_index: u32,
1674 primary_metrics: DesignMetrics,
1675 font_size: impl Into<FontScale<'a>>,
1676) -> Result<BuiltLine, TextPlanError> {
1677 let font_size = font_size.into();
1678 let (ascent, descent) = scaled_metrics(primary_metrics, font_size)?;
1679 let descent = descent
1680 .checked_neg()
1681 .ok_or(TextPlanError::Arithmetic("primary face descender"))?;
1682 Ok(BuiltLine {
1683 plan: TextLinePlan {
1684 source_span: span,
1685 selected_soft_hyphen: None,
1686 ending_grapheme_index,
1687 translation_x_quanta: 0,
1688 translation_y_quanta: 0,
1689 logical_advance_quanta: 0,
1690 ink_quanta: None,
1691 base_direction: ShapingDirection::LeftToRight,
1692 runs: Vec::new(),
1693 },
1694 advance: ExactRational::ZERO,
1695 ascent,
1696 descent,
1697 })
1698}
1699
1700#[expect(
1701 clippy::too_many_arguments,
1702 reason = "selected-line shaping retains exact paragraph and line identities"
1703)]
1704#[expect(
1705 clippy::too_many_lines,
1706 reason = "contextual shaping keeps glyph retention and exact line geometry ordered"
1707)]
1708fn prepare_line<'a>(
1709 environment: &PreparedFontEnvironment,
1710 source: &str,
1711 paragraph_span: TextSourceSpan,
1712 line_span: TextSourceSpan,
1713 ending_grapheme_index: u32,
1714 font_size: impl Into<FontScale<'a>>,
1715 bidi: &ParagraphBidiData,
1716 items: &[ScalarItem],
1717 hyphen_face: Option<FaceIdentity>,
1718) -> Result<BuiltLine, TextPlanError> {
1719 let font_size = font_size.into();
1720 let selected_soft_hyphen = (line_span.end_byte < paragraph_span.end_byte
1721 && source[line_span.range()].ends_with('\u{ad}'))
1722 .then(|| {
1723 TextSourceSpan::new(
1724 line_span.end_byte as usize - '\u{ad}'.len_utf8(),
1725 line_span.end_byte as usize,
1726 )
1727 })
1728 .transpose()?;
1729 let line_local_start = (line_span.start_byte - paragraph_span.start_byte) as usize;
1730 let line_local_end = (line_span.end_byte - paragraph_span.start_byte) as usize;
1731
1732 let (levels, bidi_runs) = line_visual_runs(
1733 bidi,
1734 &source[paragraph_span.range()],
1735 line_local_start..line_local_end,
1736 )?;
1737
1738 let mut runs = Vec::new();
1739 let mut exact_ink: Option<ExactInk> = None;
1740 let mut pen_x = ExactRational::ZERO;
1741 let mut pen_y = ExactRational::ZERO;
1742 let mut ascent = 0_i64;
1743 let mut descent = 0_i64;
1744
1745 for bidi_run in bidi_runs {
1746 let direction = if levels[bidi_run.start].is_rtl() {
1747 ShapingDirection::RightToLeft
1748 } else {
1749 ShapingDirection::LeftToRight
1750 };
1751 let mut groups = itemize_bidi_run(
1752 items,
1753 paragraph_span.start_byte,
1754 bidi_run.start + line_local_start..bidi_run.end + line_local_start,
1755 )?;
1756 if let Some(soft) = selected_soft_hyphen {
1757 if let Some(index) = groups
1758 .iter()
1759 .position(|group| group.span.range().contains(&(soft.start_byte as usize)))
1760 {
1761 let hyphen = ItemGroup {
1762 span: soft,
1763 face: hyphen_face.ok_or(TextPlanError::MissingPreparedScalar('-' as u32))?,
1764 script: groups[index].script,
1765 };
1766 if groups[index].face != hyphen.face {
1768 if groups[index].span.start_byte == soft.start_byte {
1769 groups[index] = hyphen;
1770 } else {
1771 super::unicode16::reserve(&mut groups, 1)?;
1772 groups[index].span.end_byte = soft.start_byte;
1773 groups.insert(index + 1, hyphen);
1774 }
1775 }
1776 }
1777 }
1778 if direction == ShapingDirection::RightToLeft {
1779 groups.reverse();
1780 }
1781 for group in groups {
1782 let text = &source[group.span.range()];
1783 #[cfg(test)]
1784 TEXT_WORK.with(|work| {
1785 work.update(|mut work| {
1786 work.shaping_scalars += text.chars().count();
1787 work
1788 });
1789 });
1790 let shaped = environment.shape_run_with_context(
1791 group.face,
1792 text,
1793 direction,
1794 rustybuzz_script(group.script)?,
1795 canonical::ShapingContext {
1796 pre: &source[line_span.start_byte as usize..group.span.start_byte as usize],
1797 post: if selected_soft_hyphen
1798 .is_some_and(|soft| soft.start_byte == group.span.end_byte)
1799 {
1800 "-"
1801 } else {
1802 &source[group.span.end_byte as usize..line_span.end_byte as usize]
1803 },
1804 soft_hyphen: selected_soft_hyphen
1805 .filter(|soft| group.span.range().contains(&(soft.start_byte as usize)))
1806 .map(|soft| (soft.start_byte - group.span.start_byte) as usize),
1807 },
1808 )?;
1809 #[cfg(test)]
1810 TEXT_WORK.with(|work| {
1811 work.update(|mut work| {
1812 work.shaped_glyphs += shaped.glyphs.len();
1813 work
1814 });
1815 });
1816
1817 super::unicode16::reserve(&mut runs, 1)?;
1818 let built = scale_run(
1819 shaped,
1820 group.span,
1821 group.script,
1822 font_size,
1823 &pen_x,
1824 &pen_y,
1825 levels[bidi_run.start].number(),
1826 )?;
1827 ascent = ascent.max(built.plan.ascender_quanta);
1828 descent = descent.max(
1829 built
1830 .plan
1831 .descender_quanta
1832 .checked_neg()
1833 .ok_or(TextPlanError::Arithmetic("face descender"))?,
1834 );
1835 if let Some(ink) = built.ink {
1836 exact_ink = Some(match exact_ink {
1837 Some(current) => current.union(ink),
1838 None => ink,
1839 });
1840 }
1841 pen_x = pen_x.add(&built.advance_x, "line advance")?;
1842 pen_y = pen_y.add(&built.advance_y, "line advance")?;
1843 runs.push(built.plan);
1844 }
1845 }
1846
1847 let ink_quanta = exact_ink.as_ref().map(ExactInk::outward).transpose()?;
1848 if let Some(ink) = ink_quanta {
1849 ascent = ascent.max(ink.top.max(0));
1850 descent = descent.max(
1851 ink.bottom
1852 .min(0)
1853 .checked_neg()
1854 .ok_or(TextPlanError::Arithmetic("line ink below baseline"))?,
1855 );
1856 }
1857 let logical_advance_quanta = pen_x.nearest_even_i64("line logical advance")?;
1858 if logical_advance_quanta < 0 {
1859 return Err(TextPlanError::Arithmetic("negative line logical advance"));
1860 }
1861
1862 Ok(BuiltLine {
1863 plan: TextLinePlan {
1864 source_span: line_span,
1865 selected_soft_hyphen,
1866 ending_grapheme_index,
1867 translation_x_quanta: 0,
1868 translation_y_quanta: 0,
1869 logical_advance_quanta,
1870 ink_quanta,
1871 base_direction: if bidi.paragraph_level.is_rtl() {
1872 ShapingDirection::RightToLeft
1873 } else {
1874 ShapingDirection::LeftToRight
1875 },
1876 runs,
1877 },
1878 advance: pen_x,
1879 ascent,
1880 descent,
1881 })
1882}
1883
1884#[derive(Debug, Clone, Copy)]
1885struct ItemGroup {
1886 span: TextSourceSpan,
1887 face: FaceIdentity,
1888 script: Script,
1889}
1890
1891#[derive(Debug, Clone, Copy)]
1892struct ScalarItem {
1893 start: usize,
1894 end: usize,
1895 face: FaceIdentity,
1896 script: Script,
1897}
1898
1899fn line_visual_runs(
1902 bidi: &ParagraphBidiData,
1903 paragraph: &str,
1904 line: Range<usize>,
1905) -> Result<(Vec<unicode_bidi::Level>, Vec<Range<usize>>), TextPlanError> {
1906 let mut original_classes = Vec::new();
1907 let mut levels = Vec::new();
1908 crate::operation::vector(&original_classes, line.len())?;
1909 original_classes
1910 .try_reserve_exact(line.len())
1911 .map_err(|_| TextPlanError::Allocation("line bidi classes"))?;
1912 crate::operation::vector(&levels, line.len())?;
1913 levels
1914 .try_reserve_exact(line.len())
1915 .map_err(|_| TextPlanError::Allocation("line bidi levels"))?;
1916 original_classes.extend_from_slice(&bidi.original_classes[line.clone()]);
1917 levels.extend_from_slice(&bidi.levels[line.clone()]);
1918 let selected = ParagraphBidiInfo {
1919 text: ¶graph[line.clone()],
1920 original_classes,
1921 levels,
1922 paragraph_level: bidi.paragraph_level,
1923 is_pure_ltr: bidi.is_pure_ltr,
1924 };
1925 Ok(selected.visual_runs(0..selected.text.len()))
1926}
1927
1928fn selected_paragraph_items(
1929 pair: &ResolvedFontPair,
1930 paragraph: &str,
1931) -> Result<Vec<ScalarItem>, TextPlanError> {
1932 let mut units = canonical::selection_units(paragraph);
1933 let mut unit = "";
1934 let mut unit_end = 0;
1935 let mut items = paragraph_items(paragraph, |start, scalar| {
1936 if start == unit_end {
1937 unit = units
1938 .next()
1939 .ok_or(TextPlanError::Arithmetic("source unit boundary"))?;
1940 unit_end += unit.len();
1941 }
1942 selected_face(pair, unit, scalar)
1943 })?;
1944 let mut following_face = pair.primary;
1947 for item in items.iter_mut().rev() {
1948 let scalar = paragraph[item.start..item.end]
1949 .chars()
1950 .next()
1951 .ok_or(TextPlanError::Arithmetic("source scalar boundary"))?;
1952 if crate::text::is_nonpainting_control(scalar) {
1953 item.face = following_face;
1954 } else {
1955 following_face = item.face;
1956 }
1957 }
1958 let mut preceding_face = None;
1959 for item in &mut items {
1960 let scalar = paragraph[item.start..item.end]
1961 .chars()
1962 .next()
1963 .ok_or(TextPlanError::Arithmetic("source scalar boundary"))?;
1964 if crate::text::is_nonpainting_control(scalar) {
1965 if let Some(face) = preceding_face {
1966 item.face = face;
1967 }
1968 } else {
1969 preceding_face = Some(item.face);
1970 }
1971 }
1972 Ok(items)
1973}
1974
1975fn paragraph_items(
1976 paragraph: &str,
1977 mut face_for: impl FnMut(usize, char) -> Result<FaceIdentity, TextPlanError>,
1978) -> Result<Vec<ScalarItem>, TextPlanError> {
1979 let mut items: Vec<ScalarItem> = Vec::new();
1980 let mut extensions = unicode_script::ScriptExtension::default();
1981 let mut segment_start = 0;
1982 let mut segment_script = None;
1983 for (start, scalar) in paragraph.char_indices() {
1984 super::unicode16::reserve(&mut items, 1)?;
1985
1986 let next = extensions.intersection(scalar.script_extension());
1987 if next.is_empty() {
1988 let script = segment_script.unwrap_or(Script::Common);
1989 for item in &mut items[segment_start..] {
1990 item.script = script;
1991 }
1992 segment_start = items.len();
1993 extensions = scalar.script_extension();
1994 segment_script = None;
1995 } else {
1996 extensions = next;
1997 }
1998 if !matches!(
1999 scalar.script(),
2000 Script::Common | Script::Inherited | Script::Unknown
2001 ) {
2002 segment_script = Some(scalar.script());
2003 }
2004 items.push(ScalarItem {
2005 start,
2006 end: start + scalar.len_utf8(),
2007 face: face_for(start, scalar)?,
2008 script: scalar.script(),
2009 });
2010 }
2011 let script = segment_script.unwrap_or(Script::Common);
2012 for item in &mut items[segment_start..] {
2013 item.script = script;
2014 }
2015
2016 let mut openings: Vec<(char, Vec<usize>)> = Vec::new();
2019 let mut stack: Vec<(usize, usize)> = Vec::new();
2020 for (index, scalar) in paragraph.chars().enumerate() {
2021 let Some(bracket) = HardcodedBidiData.bidi_matched_opening_bracket(scalar) else {
2022 if index > 0
2027 && (scalar.script() == Script::Inherited || scalar.script_extension().is_common())
2028 {
2029 items[index].script = items[index - 1].script;
2030 }
2031 continue;
2032 };
2033 let mut key = None;
2034 for (candidate, (opening, _)) in openings.iter().enumerate() {
2035 if *opening == bracket.opening {
2036 key = Some(candidate);
2037 break;
2038 }
2039 }
2040 if bracket.is_open {
2041 let key = if let Some(key) = key {
2042 key
2043 } else {
2044 super::unicode16::reserve(&mut openings, 1)?;
2045 openings.push((bracket.opening, Vec::new()));
2046 openings.len() - 1
2047 };
2048 let indices = &mut openings[key].1;
2049 super::unicode16::reserve(indices, 1)?;
2050 super::unicode16::reserve(&mut stack, 1)?;
2051 indices.push(stack.len());
2052 stack.push((key, index));
2053 } else if let Some(position) = key.and_then(|key| openings[key].1.last()).copied() {
2054 items[index].script = items[stack[position].1].script;
2055 while stack.len() > position {
2056 let (key, _) = stack.pop().expect("matched bracket stack");
2057 openings[key].1.pop();
2058 }
2059 }
2060 }
2061 Ok(items)
2062}
2063
2064fn itemize_bidi_run(
2065 items: &[ScalarItem],
2066 paragraph_source_start: u32,
2067 bidi_run: Range<usize>,
2068) -> Result<Vec<ItemGroup>, TextPlanError> {
2069 let mut limits = [0; 2];
2070 for (limit, boundary) in limits.iter_mut().zip([bidi_run.start, bidi_run.end]) {
2071 let (mut low, mut high) = (0, items.len());
2072 while low < high {
2073 let middle = low + (high - low) / 2;
2074 if items[middle].start < boundary {
2075 low = middle + 1;
2076 } else {
2077 high = middle;
2078 }
2079 }
2080 *limit = low;
2081 }
2082 let [first, last] = limits;
2083 let mut groups: Vec<ItemGroup> = Vec::new();
2084 for item in &items[first..last] {
2085 let absolute_start = (paragraph_source_start as usize)
2086 .checked_add(item.start)
2087 .ok_or(TextPlanError::Arithmetic("run source span"))?;
2088 let absolute_end = (paragraph_source_start as usize)
2089 .checked_add(item.end)
2090 .ok_or(TextPlanError::Arithmetic("run source span"))?;
2091 if let Some(previous) = groups.last_mut() {
2092 if previous.face == item.face
2093 && previous.script == item.script
2094 && previous.span.end_byte as usize == absolute_start
2095 {
2096 previous.span.end_byte =
2097 u32::try_from(absolute_end).map_err(|_| TextPlanError::SourceTooLong)?;
2098 continue;
2099 }
2100 }
2101 super::unicode16::reserve(&mut groups, 1)?;
2102 groups.push(ItemGroup {
2103 span: TextSourceSpan::new(absolute_start, absolute_end)?,
2104 face: item.face,
2105 script: item.script,
2106 });
2107 }
2108 Ok(groups)
2109}
2110
2111fn selected_face(
2112 pair: &ResolvedFontPair,
2113 unit: &str,
2114 scalar: char,
2115) -> Result<FaceIdentity, TextPlanError> {
2116 if crate::text::is_nonpainting_control(scalar) {
2117 return Ok(pair.primary);
2118 }
2119 let selection = pair
2120 .selection_for_unit(unit, scalar)
2121 .map_err(|error| match error {
2122 FontError::MissingGlyph { .. } => TextPlanError::MissingPreparedScalar(scalar as u32),
2123 error => TextPlanError::Font(error),
2124 })?;
2125 match selection {
2126 ScalarFaceSelection::Face(identity) => Ok(identity),
2127 ScalarFaceSelection::NonRenderingMandatoryBreak => {
2128 Err(TextPlanError::InvalidScalarSelection(scalar as u32))
2129 }
2130 }
2131}
2132
2133fn rustybuzz_script(script: Script) -> Result<rustybuzz::Script, TextPlanError> {
2134 rustybuzz::Script::from_str(script.short_name())
2135 .map_err(|_| TextPlanError::Script(script.short_name().to_owned()))
2136}
2137
2138#[derive(Debug)]
2139struct BuiltRun {
2140 plan: ShapedTextRun,
2141 advance_x: ExactRational,
2142 advance_y: ExactRational,
2143 ink: Option<ExactInk>,
2144}
2145
2146#[expect(
2147 clippy::too_many_lines,
2148 reason = "freeze origins and ink in one pass while retaining exact advances for wrapping"
2149)]
2150fn scale_run<'a>(
2151 shaped: CanonicalShapedRun,
2152 source_span: TextSourceSpan,
2153 script: Script,
2154 font_size: impl Into<FontScale<'a>>,
2155 line_pen_x: &ExactRational,
2156 line_pen_y: &ExactRational,
2157 bidi_level: u8,
2158) -> Result<BuiltRun, TextPlanError> {
2159 let font_size = font_size.into();
2160 let mut glyphs = Vec::new();
2161
2162 super::unicode16::reserve(&mut glyphs, shaped.glyphs.len())?;
2163 let mut pen_x = ExactRational::ZERO;
2164 let mut pen_y = ExactRational::ZERO;
2165 let mut exact_ink: Option<ExactInk> = None;
2166 let mut design_horizontal_advance = 0_i64;
2167 let mut design_vertical_advance = 0_i64;
2168
2169 for glyph in shaped.glyphs {
2170 let x_advance = scale_design(
2171 glyph.x_advance.into(),
2172 font_size,
2173 shaped.metrics.units_per_em,
2174 )?;
2175 let y_advance = scale_design(
2176 glyph.y_advance.into(),
2177 font_size,
2178 shaped.metrics.units_per_em,
2179 )?;
2180 let x_offset = scale_design(
2181 glyph.x_offset.into(),
2182 font_size,
2183 shaped.metrics.units_per_em,
2184 )?;
2185 let y_offset = scale_design(
2186 glyph.y_offset.into(),
2187 font_size,
2188 shaped.metrics.units_per_em,
2189 )?;
2190 let origin_x = line_pen_x
2191 .add(&pen_x, "glyph origin")?
2192 .add(&x_offset, "glyph origin")?
2193 .nearest_even_i64("glyph origin")?;
2194 let origin_y = line_pen_y
2195 .add(&pen_y, "glyph origin")?
2196 .add(&y_offset, "glyph origin")?
2197 .nearest_even_i64("glyph origin")?;
2198 let glyph_exact_ink = glyph
2199 .ink
2200 .map(|ink| {
2201 exact_glyph_ink(ink, 0, 0, font_size, shaped.metrics.units_per_em)?.translated(
2202 &ExactRational::new(i128::from(origin_x), 1)?,
2203 &ExactRational::new(i128::from(origin_y), 1)?,
2204 )
2205 })
2206 .transpose()?;
2207 if let Some(ink) = &glyph_exact_ink {
2208 exact_ink = Some(match exact_ink {
2209 Some(current) => current.union(ink.clone()),
2210 None => ink.clone(),
2211 });
2212 }
2213 let cluster = source_span
2214 .start_byte
2215 .checked_add(glyph.cluster)
2216 .ok_or(TextPlanError::Arithmetic("glyph cluster"))?;
2217 glyphs.push(PlannedGlyph {
2218 face: shaped.identity,
2219 glyph_id: glyph.glyph_id,
2220 cluster,
2221 design_x_advance: glyph.x_advance,
2222 design_y_advance: glyph.y_advance,
2223 design_x_offset: glyph.x_offset,
2224 design_y_offset: glyph.y_offset,
2225 design_ink: glyph.ink,
2226 x_advance_quanta: x_advance.nearest_even_i64("glyph x advance")?,
2227 y_advance_quanta: y_advance.nearest_even_i64("glyph y advance")?,
2228 x_offset_quanta: x_offset.nearest_even_i64("glyph x offset")?,
2229 y_offset_quanta: y_offset.nearest_even_i64("glyph y offset")?,
2230 glyph_origin_x_quanta: origin_x,
2231 glyph_origin_y_quanta: origin_y,
2232 ink_quanta: glyph_exact_ink
2233 .as_ref()
2234 .map(ExactInk::outward)
2235 .transpose()?,
2236 });
2237 pen_x = pen_x.add(&x_advance, "run x advance")?;
2238 pen_y = pen_y.add(&y_advance, "run y advance")?;
2239 design_horizontal_advance = design_horizontal_advance
2240 .checked_add(i64::from(glyph.x_advance))
2241 .ok_or(TextPlanError::Arithmetic("design run x advance"))?;
2242 design_vertical_advance = design_vertical_advance
2243 .checked_add(i64::from(glyph.y_advance))
2244 .ok_or(TextPlanError::Arithmetic("design run y advance"))?;
2245 }
2246
2247 let (ascender_quanta, descender_quanta) = scaled_metrics(shaped.metrics, font_size)?;
2248 Ok(BuiltRun {
2249 plan: ShapedTextRun {
2250 source_span,
2251 face: shaped.identity,
2252 direction: shaped.direction,
2253 bidi_level,
2254 script,
2255 units_per_em: shaped.metrics.units_per_em,
2256 design_ascender: shaped.metrics.ascender,
2257 design_descender: shaped.metrics.descender,
2258 metric_source: shaped.metrics.source,
2259 ascender_quanta,
2260 descender_quanta,
2261 design_x_advance: design_horizontal_advance,
2262 design_y_advance: design_vertical_advance,
2263 logical_advance_quanta: pen_x.nearest_even_i64("run logical advance")?,
2264 logical_y_advance_quanta: pen_y.nearest_even_i64("run logical y advance")?,
2265 ink_quanta: exact_ink.as_ref().map(ExactInk::outward).transpose()?,
2266 glyphs,
2267 },
2268 advance_x: pen_x,
2269 advance_y: pen_y,
2270 ink: exact_ink,
2271 })
2272}
2273
2274fn exact_glyph_ink(
2275 ink: GlyphInk,
2276 x_offset: i32,
2277 y_offset: i32,
2278 font_size: FontScale<'_>,
2279 units_per_em: u16,
2280) -> Result<ExactInk, TextPlanError> {
2281 Ok(ExactInk {
2282 left: scale_design(
2283 i64::from(x_offset)
2284 .checked_add(i64::from(ink.x_min))
2285 .ok_or(TextPlanError::Arithmetic("glyph ink left"))?,
2286 font_size,
2287 units_per_em,
2288 )?,
2289 bottom: scale_design(
2290 i64::from(y_offset)
2291 .checked_add(i64::from(ink.y_min))
2292 .ok_or(TextPlanError::Arithmetic("glyph ink bottom"))?,
2293 font_size,
2294 units_per_em,
2295 )?,
2296 right: scale_design(
2297 i64::from(x_offset)
2298 .checked_add(i64::from(ink.x_max))
2299 .ok_or(TextPlanError::Arithmetic("glyph ink right"))?,
2300 font_size,
2301 units_per_em,
2302 )?,
2303 top: scale_design(
2304 i64::from(y_offset)
2305 .checked_add(i64::from(ink.y_max))
2306 .ok_or(TextPlanError::Arithmetic("glyph ink top"))?,
2307 font_size,
2308 units_per_em,
2309 )?,
2310 })
2311}
2312
2313fn scaled_metrics<'a>(
2314 metrics: DesignMetrics,
2315 font_size: impl Into<FontScale<'a>>,
2316) -> Result<(i64, i64), TextPlanError> {
2317 let font_size = font_size.into();
2318 let ascender = scale_design(
2319 i64::from(metrics.ascender).max(0),
2320 font_size,
2321 metrics.units_per_em,
2322 )?
2323 .ceil_i64("face ascender")?;
2324 let descender = scale_design(
2325 i64::from(metrics.descender).min(0),
2326 font_size,
2327 metrics.units_per_em,
2328 )?
2329 .floor_i64("face descender")?;
2330 if ascender < 0 || descender > 0 {
2331 return Err(TextPlanError::Arithmetic("scaled face metrics"));
2332 }
2333 Ok((ascender, descender))
2334}
2335
2336fn require_block_height(
2337 span: TextSourceSpan,
2338 height: i64,
2339 identities: impl Iterator<Item = FaceIdentity>,
2340) -> Result<(), TextPlanError> {
2341 if height == 0 {
2342 let mut faces = Vec::new();
2343 for identity in identities {
2344 super::unicode16::reserve(&mut faces, 1)?;
2345 faces.push(identity);
2346 }
2347 return Err(TextPlanError::NoTextHeight { span, faces });
2348 }
2349 Ok(())
2350}
2351
2352#[expect(
2353 clippy::too_many_lines,
2354 reason = "final geometry and root-admitted payload freezing remain ordered"
2355)]
2356fn finalize_plan(
2357 input: TextPlanInput<'_>,
2358 stack: &FontStack,
2359 pair_provenance: PairProvenance,
2360 line_height_quanta: i64,
2361 mut built_lines: Vec<BuiltLine>,
2362) -> Result<ResolvedTextPlan, TextPlanError> {
2363 let ascent = built_lines
2364 .iter()
2365 .map(|line| line.ascent)
2366 .max()
2367 .unwrap_or(0);
2368 let descent = built_lines
2369 .iter()
2370 .map(|line| line.descent)
2371 .max()
2372 .unwrap_or(0);
2373 let metric_height = ascent
2374 .checked_add(descent)
2375 .ok_or(TextPlanError::Arithmetic("text metric height"))?;
2376 let line_pitch_quanta = metric_height.max(line_height_quanta);
2377
2378 let width_quanta = built_lines.iter().try_fold(0_i64, |width, line| {
2379 let span = line.plan.ink_quanta.map_or(Ok(0), |ink| {
2380 ink.right
2381 .checked_sub(ink.left)
2382 .ok_or(TextPlanError::Arithmetic("line ink span"))
2383 })?;
2384 Ok::<_, TextPlanError>(width.max(span))
2385 })?;
2386
2387 for (line_index, line) in built_lines.iter_mut().enumerate() {
2388 let (line_left, line_span) = line.plan.ink_quanta.map_or(Ok((0, 0)), |ink| {
2389 Ok::<_, TextPlanError>((
2390 ink.left,
2391 ink.right
2392 .checked_sub(ink.left)
2393 .ok_or(TextPlanError::Arithmetic("line ink span"))?,
2394 ))
2395 })?;
2396 let alignment_space = width_quanta
2397 .checked_sub(line_span)
2398 .ok_or(TextPlanError::Arithmetic("line alignment slack"))?;
2399 let alignment_offset = match input.alignment {
2400 PhysicalTextAlignment::Start => 0,
2401 PhysicalTextAlignment::Center => ExactRational::new(i128::from(alignment_space), 2)?
2402 .nearest_even_i64("center line alignment")?,
2403 PhysicalTextAlignment::End => alignment_space,
2404 };
2405 line.plan.translation_x_quanta = alignment_offset
2406 .checked_sub(line_left)
2407 .ok_or(TextPlanError::Arithmetic("line x translation"))?;
2408 let line_index =
2409 i64::try_from(line_index).map_err(|_| TextPlanError::Arithmetic("line index"))?;
2410 line.plan.translation_y_quanta = line_pitch_quanta
2411 .checked_mul(line_index)
2412 .and_then(|offset| ascent.checked_add(offset))
2413 .ok_or(TextPlanError::Arithmetic("line baseline"))?;
2414 }
2415
2416 let line_count =
2417 i64::try_from(built_lines.len()).map_err(|_| TextPlanError::Arithmetic("line count"))?;
2418 let height_quanta = if line_count == 0 {
2419 0
2420 } else {
2421 line_pitch_quanta
2422 .checked_mul(line_count - 1)
2423 .and_then(|pitch| metric_height.checked_add(pitch))
2424 .ok_or(TextPlanError::Arithmetic("text height"))?
2425 };
2426 if line_count > 0 {
2429 require_block_height(
2430 TextSourceSpan::new(0, input.source.len())?,
2431 height_quanta,
2432 built_lines
2433 .iter()
2434 .flat_map(|line| &line.plan.runs)
2435 .map(|run| run.face)
2436 .chain(
2437 pair_provenance
2438 .candidates
2439 .first()
2440 .copied()
2441 .filter(|_| built_lines.iter().any(|line| line.plan.runs.is_empty())),
2442 ),
2443 )?;
2444 }
2445 let first_baseline_quanta = (line_count > 0).then_some(ascent);
2446 let last_baseline_quanta = if line_count == 0 {
2447 None
2448 } else {
2449 Some(
2450 line_pitch_quanta
2451 .checked_mul(line_count - 1)
2452 .and_then(|pitch| ascent.checked_add(pitch))
2453 .ok_or(TextPlanError::Arithmetic("last baseline"))?,
2454 )
2455 };
2456
2457 let mut source = String::new();
2458 let stack_source = stack.css()?;
2459 let stack = stack.copy_with_stage(None)?;
2460 let mut lines = Vec::new();
2461
2462 crate::operation::string(&source, input.source.len())?;
2463 source
2464 .try_reserve_exact(input.source.len())
2465 .map_err(|_| TextPlanError::Allocation("text source"))?;
2466 super::unicode16::reserve(&mut lines, built_lines.len())?;
2467 source.push_str(input.source);
2468 lines.extend(built_lines.into_iter().map(|line| line.plan));
2469 Ok(ResolvedTextPlan(
2470 std::sync::Arc::new(ResolvedTextPayload {
2471 fit_input: None,
2472 fit_group: None,
2473 original_source: None,
2474 display_map: None,
2475 selected_rotation: None,
2476 occupied_rotation: None,
2477 content: std::sync::Arc::new(ResolvedTextContent {
2478 source,
2479 style: ResolvedTextStyle {
2480 stack_source,
2481 stack,
2482 weight: input.weight,
2483 font_size: input.font_size,
2484 line_height_quanta,
2485 alignment: input.alignment,
2486 paint: input.paint,
2487 provenance: input.provenance,
2488 exact_override: input.exact_override,
2489 },
2490 pair_provenance,
2491 lines,
2492 line_pitch_quanta,
2493 first_baseline_quanta,
2494 last_baseline_quanta,
2495 width_quanta,
2496 height_quanta,
2497 }),
2498 request: None,
2499 clip_size: None,
2500 paint_region: None,
2501 }),
2502 None,
2503 ))
2504}
2505
2506#[derive(Debug, Clone)]
2507struct ExactInk {
2508 left: ExactRational,
2509 bottom: ExactRational,
2510 right: ExactRational,
2511 top: ExactRational,
2512}
2513
2514impl ExactInk {
2515 fn translated(self, x: &ExactRational, y: &ExactRational) -> Result<Self, TextPlanError> {
2516 Ok(Self {
2517 left: self.left.add(x, "ink translation")?,
2518 bottom: self.bottom.add(y, "ink translation")?,
2519 right: self.right.add(x, "ink translation")?,
2520 top: self.top.add(y, "ink translation")?,
2521 })
2522 }
2523
2524 fn union(self, other: Self) -> Self {
2525 Self {
2526 left: self.left.min(other.left),
2527 bottom: self.bottom.min(other.bottom),
2528 right: self.right.max(other.right),
2529 top: self.top.max(other.top),
2530 }
2531 }
2532
2533 fn outward(&self) -> Result<TextInkBounds, TextPlanError> {
2534 Ok(TextInkBounds {
2535 left: self.left.floor_i64("ink left")?,
2536 bottom: self.bottom.floor_i64("ink bottom")?,
2537 right: self.right.ceil_i64("ink right")?,
2538 top: self.top.ceil_i64("ink top")?,
2539 })
2540 }
2541}
2542
2543#[derive(Clone, Copy)]
2544struct FontScale<'a> {
2545 size: f64,
2546 trace: Option<&'a std::sync::Arc<font_fit::stability::Stability>>,
2547}
2548impl From<f64> for FontScale<'_> {
2549 fn from(size: f64) -> Self {
2550 Self { size, trace: None }
2551 }
2552}
2553
2554fn scale_design<'a>(
2555 design: i64,
2556 font_size: impl Into<FontScale<'a>>,
2557 units_per_em: u16,
2558) -> Result<ExactRational, TextPlanError> {
2559 let scale = font_size.into();
2560 scale.trace.map_or_else(
2561 || ExactRational::design(design, scale.size, units_per_em),
2562 |trace| ExactRational::tracked_design(design, scale.size, units_per_em, trace),
2563 )
2564}
2565
2566fn resolve_line_height(line_height: TextLineHeight, font_size: f64) -> Result<i64, TextPlanError> {
2567 match line_height {
2568 TextLineHeight::Multiplier(multiplier) => {
2569 if !multiplier.is_finite() || multiplier <= 0.0 {
2570 return Err(TextPlanError::InvalidLineHeight);
2571 }
2572 Ok(crate::theme::RelativeSpacing::new(multiplier)?
2573 .product(crate::theme::LocalMetric::css_pixels(font_size)?)
2574 .round(super::kernel::SpatialRounding::Ceil)?
2575 .quanta())
2576 }
2577 TextLineHeight::ResolvedQuanta(height) if height > 0 => Ok(height),
2578 TextLineHeight::ResolvedQuanta(_) => Err(TextPlanError::InvalidLineHeight),
2579 }
2580}
2581
2582pub(crate) fn maximum_width_quanta(maximum_width: f64) -> Result<i64, TextPlanError> {
2583 Ok(super::kernel::LayoutScalar::from_css_pixels(
2584 maximum_width,
2585 super::kernel::SpatialRounding::Floor,
2586 )?
2587 .quanta())
2588}
2589
2590#[derive(Debug, Clone, PartialEq, Eq)]
2592pub(crate) struct TextBlock {
2593 plan: ResolvedTextPlan,
2594}
2595
2596impl TextBlock {
2597 pub(crate) const fn plan(&self) -> &ResolvedTextPlan {
2598 &self.plan
2599 }
2600 pub(crate) const fn from_resolved(plan: ResolvedTextPlan) -> Self {
2601 Self { plan }
2602 }
2603
2604 pub(crate) fn lines(&self) -> Vec<&str> {
2605 self.plan.line_texts()
2606 }
2607
2608 pub(crate) fn width(&self) -> f64 {
2609 self.plan.occupied_size().0
2610 }
2611
2612 pub(crate) fn height(&self) -> f64 {
2613 self.plan.occupied_size().1
2614 }
2615
2616 pub(crate) fn line_height(&self) -> f64 {
2617 self.plan.line_height()
2618 }
2619}
2620
2621#[cfg(test)]
2622mod tests {
2623 use super::*;
2624
2625 pub(super) fn input(
2626 source: &str,
2627 maximum_width_quanta: i64,
2628 alignment: PhysicalTextAlignment,
2629 ) -> TextPlanInput<'_> {
2630 TextPlanInput {
2631 size_trace: None,
2632 direction: crate::text::TextDirection::Auto,
2633 source,
2634 stack: canonical::test_sans_stack(),
2635 weight: TextWeight::Normal,
2636 font_size: 10.0,
2637 line_height: TextLineHeight::Multiplier(1.2),
2638 maximum_width_quanta,
2639 alignment,
2640 paint: Color::rgb(1, 2, 3),
2641 provenance: TextPlanProvenance {
2642 pair_ordinal: 0,
2643 owner: "test".into(),
2644 },
2645 exact_override: false,
2646 }
2647 }
2648
2649 pub(super) fn plan(
2650 source: &str,
2651 maximum_width_quanta: i64,
2652 alignment: PhysicalTextAlignment,
2653 ) -> ResolvedTextPlan {
2654 PreparedFontEnvironment::synthetic()
2655 .plan_text(input(source, maximum_width_quanta, alignment))
2656 .unwrap()
2657 }
2658
2659 fn line_texts(plan: &ResolvedTextPlan) -> Vec<&str> {
2660 plan.lines
2661 .iter()
2662 .map(|line| &plan.source[line.source_span.range()])
2663 .collect()
2664 }
2665
2666 #[test]
2667 fn mandatory_breaks_preserve_crlf_and_all_blank_paragraphs() {
2668 let plan = plan("\r\nA\n\n", i64::MAX, PhysicalTextAlignment::Start);
2669
2670 assert_eq!(line_texts(&plan), ["", "A", "", ""]);
2671 assert_eq!(
2672 plan.lines
2673 .iter()
2674 .map(|line| line.ending_grapheme_index)
2675 .collect::<Vec<_>>(),
2676 [0, 1, 1, 1]
2677 );
2678 }
2679}