1use std::cell::OnceCell;
9use std::cmp::Ordering;
10use std::collections::{BTreeMap, BTreeSet, HashMap};
11use std::fmt;
12use std::ops::Range;
13use std::sync::Arc;
14
15use ab_glyph_rasterizer::{Point, Rasterizer, point};
16use alpha2_media::{
17 EmojiPolicy, HostTexture, HostTexturePixels, Premultiplication, RasterColorSpace, TextAlign,
18 TextTexture,
19};
20use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder};
21use rustybuzz::{Direction, UnicodeBuffer};
22use unicode_bidi::ParagraphBidiInfo;
23use unicode_linebreak::BreakOpportunity;
24use unicode_script::{Script, UnicodeScript};
25use unicode_segmentation::UnicodeSegmentation;
26
27mod animated;
28mod boxes;
29mod color;
30mod font_check;
31mod gradient;
32mod highlight;
33mod paint;
34mod runs;
35mod unicode_tables;
36
37pub use animated::{
38 ClusterGrouping, ClusterInfo, ClusterState, ColorMix, LineInfo, MAX_CLUSTER_SCALE,
39 MAX_REVEAL_EDGES, RevealEdge, TextLayout,
40};
41pub use gradient::{TextGradient, TextGradientKind, TextGradientStop, TextSpread};
42
43const MAX_TEXT_BYTES: usize = 64 * 1024;
44const MAX_FONT_SIZE: f32 = 2_048.0;
45const MAX_LINE_HEIGHT: f32 = 10.0;
46const MAX_STROKE_EXTENT: f32 = 64.0;
48const MAX_STROKES: usize = 8;
49pub const MAX_TEXT_SPANS: usize = 512;
51const MAX_BACKGROUND_PADDING: f32 = 256.0;
52pub const MAX_TEXT_BOX: u32 = 16_384;
54#[allow(clippy::cast_precision_loss)]
55const MAX_TEXT_BOX_PIXELS: f32 = MAX_TEXT_BOX as f32;
56const LETTER_SPACING_RANGE: std::ops::RangeInclusive<f32> = -0.5..=1.0;
58const MAX_RASTER_BYTES: u64 = 1 << 30;
60
61fn raster_pixels(width: u32, height: u32, bytes_per_pixel: u64) -> Result<usize, TextRasterError> {
65 let pixels = u64::from(width) * u64::from(height);
66 if width > MAX_TEXT_BOX
67 || height > MAX_TEXT_BOX
68 || pixels > alpha2_media::MAX_FRAME_PIXELS
69 || pixels.saturating_mul(bytes_per_pixel) > MAX_RASTER_BYTES
70 {
71 return Err(TextRasterError::TooLarge);
72 }
73 usize::try_from(pixels).map_err(|_| TextRasterError::TooLarge)
74}
75
76fn raster_bytes_per_pixel(request: &TextRasterRequest, strokes: usize, colors: bool) -> u64 {
79 let split = request.split_background
80 && (request.background.is_some()
81 || request
82 .spans
83 .iter()
84 .any(|span| span.background_color.is_some()));
85 let strokes = strokes as u64;
86 1 + 4
87 + if split { 4 } else { 0 }
88 + if colors {
89 4 + u64::from(strokes > 0)
90 } else {
91 0
92 }
93 + strokes
94}
95
96#[derive(Clone, Debug)]
98pub struct TextFont {
99 pub family: String,
101 pub bytes: Arc<[u8]>,
103 pub face_index: u32,
105}
106
107#[derive(Clone, Debug, PartialEq)]
109pub struct TextRasterRequest {
110 pub text: String,
112 pub font_size: f32,
114 pub max_width: f32,
116 pub line_height: f32,
119 pub align: TextAlign,
121 pub fill: TextFill,
124 pub emoji_policy: EmojiPolicy,
126 pub content_version: u64,
128 pub strokes: Vec<TextStroke>,
131 pub background: Option<TextBackground>,
133 pub split_background: bool,
136 pub font_family: Option<String>,
140 pub letter_spacing: f32,
144 pub font_weight: u16,
147 pub clamp: Option<TextClamp>,
149 pub spans: Vec<TextSpan>,
153 pub advance_headroom: f32,
157 pub animator_grouping: ClusterGrouping,
159 pub highlight: Option<TextHighlightRequest>,
162 pub animator_pivot: [f32; 2],
165}
166
167impl TextRasterRequest {
168 #[must_use]
171 pub fn wrap_width(&self) -> f32 {
172 wrap_width(self.max_width, self.advance_headroom)
173 }
174}
175
176#[must_use]
180pub fn wrap_width(max_width: f32, advance_headroom: f32) -> f32 {
181 if max_width > 0.0 && advance_headroom > 1.0 {
182 max_width / advance_headroom
183 } else {
184 max_width
185 }
186}
187
188#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)]
190pub enum FontStyle {
191 #[default]
193 Normal,
194 Italic,
196 Oblique,
198}
199
200#[derive(Clone, Debug, PartialEq)]
206pub struct TextSpan {
207 pub bytes: Range<usize>,
209 pub font_family: Option<String>,
211 pub font_weight: u16,
213 pub font_style: FontStyle,
215 pub font_size: f32,
217 pub letter_spacing: f32,
219 pub fill: TextFill,
221 pub strokes: Vec<TextStroke>,
223 pub background_color: Option<[u8; 4]>,
226 pub underline: bool,
228 pub line_through: bool,
230}
231
232pub const MAX_ELLIPSIS_BYTES: usize = 256;
234
235#[derive(Clone, Debug, PartialEq)]
238pub struct TextClamp {
239 pub max_lines: Option<u32>,
241 pub max_height: f32,
244 pub ellipsis: Option<String>,
247}
248
249#[must_use]
253#[allow(
254 clippy::cast_possible_truncation,
255 clippy::cast_precision_loss,
256 clippy::cast_sign_loss
257)]
258pub fn line_limit(
259 font_size: f32,
260 line_height: f32,
261 max_lines: Option<u32>,
262 max_height: f32,
263) -> Option<u32> {
264 let advance = font_size * line_height;
265 let by_height = (max_height > 0.0).then(|| {
266 let first = advance.max(font_size);
268 let estimate = ((max_height - first) / advance).floor() + 1.0;
269 let mut lines = if estimate.is_finite() {
270 estimate.clamp(1.0, 1.0e9) as u32
271 } else {
272 1
273 };
274 while lines > 1 && box_height(lines, advance, font_size) > max_height {
275 lines -= 1;
276 }
277 while lines < 1_000_000_000 && box_height(lines + 1, advance, font_size) <= max_height {
278 lines += 1;
279 }
280 lines
281 });
282 match (max_lines.map(|lines| lines.max(1)), by_height) {
283 (Some(count), Some(height)) => Some(count.min(height)),
284 (count, height) => count.or(height),
285 }
286}
287
288#[derive(Clone, Debug, PartialEq)]
290pub enum TextFill {
291 Solid([u8; 4]),
293 Gradient(TextGradient),
295}
296
297impl TextFill {
298 #[must_use]
300 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
301 pub fn foreground(&self) -> [u8; 4] {
302 match self {
303 Self::Solid(color) => *color,
304 Self::Gradient(gradient) => gradient.stops.first().map_or([0; 4], |stop| {
305 stop.color
306 .map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8)
307 }),
308 }
309 }
310
311 pub(crate) fn is_valid(&self) -> bool {
312 match self {
313 Self::Solid(_) => true,
314 Self::Gradient(gradient) => gradient.is_valid(),
315 }
316 }
317}
318
319#[derive(Copy, Clone, Debug, PartialEq)]
324pub struct TextStroke {
325 pub color: [u8; 4],
327 pub width: f32,
329}
330
331#[derive(Clone, Debug, PartialEq)]
334pub struct TextBackground {
335 pub color: [u8; 4],
337 pub padding: [f32; 4],
340 pub radius: f32,
342 pub border: Option<TextBoxBorder>,
344 pub extent: BoxExtent,
346}
347
348#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
350pub enum BoxExtent {
351 #[default]
354 Line,
355 Revealed,
359 Block,
361}
362
363#[derive(Clone, Debug, PartialEq)]
366pub struct TextHighlightRequest {
367 pub look: TextBackground,
369 pub steps: Vec<(Range<usize>, f32)>,
375}
376
377pub const MAX_HIGHLIGHT_STEPS: usize = 512;
379
380#[derive(Clone, Debug, PartialEq)]
382pub struct TextBoxBorder {
383 pub width: f32,
385 pub color: [u8; 4],
387 pub dash: Option<TextBoxDash>,
389}
390
391#[derive(Clone, Debug, PartialEq)]
394pub struct TextBoxDash {
395 pub pattern: Vec<f32>,
398 pub offset: f32,
400}
401
402impl TextBackground {
403 #[must_use]
405 pub const fn padded(color: [u8; 4], padding: f32) -> Self {
406 Self {
407 color,
408 padding: [padding; 4],
409 radius: 0.0,
410 border: None,
411 extent: BoxExtent::Line,
412 }
413 }
414
415 fn is_valid(&self) -> bool {
416 let length = |value: f32| value.is_finite() && value >= 0.0;
417 self.padding
418 .iter()
419 .all(|side| length(*side) && *side <= MAX_BACKGROUND_PADDING)
420 && length(self.radius)
421 && self.radius <= MAX_TEXT_BOX_PIXELS
422 && self.border.as_ref().is_none_or(|border| {
423 border.width.is_finite()
424 && border.width > 0.0
425 && border.width <= MAX_TEXT_BOX_PIXELS
426 && border.dash.as_ref().is_none_or(|dash| {
427 (1..=16).contains(&dash.pattern.len())
428 && dash
429 .pattern
430 .iter()
431 .all(|entry| length(*entry) && *entry <= MAX_TEXT_BOX_PIXELS)
432 && dash.pattern.iter().any(|entry| *entry > 0.0)
433 && dash.offset.is_finite()
434 })
435 })
436 }
437
438 pub(crate) fn is_plain(&self) -> bool {
440 self.radius == 0.0 && self.border.is_none()
441 }
442}
443
444#[derive(Clone, Debug, PartialEq)]
446pub struct TextRasterResult {
447 pub descriptor: TextTexture,
449 pub pixels: HostTexturePixels,
451 pub background: Option<Vec<u8>>,
454}
455
456#[derive(Clone, Debug, PartialEq)]
460pub struct TextMeasure {
461 pub box_width: u32,
463 pub box_height: u32,
465 pub decoration_margin: [u32; 2],
467 pub content: [f32; 4],
470 pub ink: Option<[f32; 4]>,
473 pub line_count: u32,
475 pub first_baseline: f32,
477 pub last_baseline: f32,
479 pub truncated: bool,
481}
482
483#[derive(Clone, Debug)]
486pub struct ShapedText {
487 paragraphs: Vec<Vec<Cluster>>,
488 font_size: f32,
489 line_height: f32,
490}
491
492#[derive(Copy, Clone, Debug, PartialEq)]
494pub struct LineMetrics {
495 pub line_count: u32,
497 pub widest: f32,
499 pub height: f32,
501 pub first_baseline: f32,
503 pub last_baseline: f32,
505}
506
507impl ShapedText {
508 #[must_use]
510 pub fn min_content_width(&self) -> f32 {
511 let mut widest = 0.0_f32;
512 for clusters in &self.paragraphs {
513 let mut start = 0;
514 for index in 1..=clusters.len() {
515 if index == clusters.len() || clusters[index].break_before {
516 widest = widest.max(advance(&clusters[start..index]));
517 start = index;
518 }
519 }
520 }
521 widest
522 }
523
524 #[must_use]
526 pub fn max_content_width(&self) -> f32 {
527 self.paragraphs
528 .iter()
529 .map(|clusters| advance(clusters))
530 .fold(0.0, f32::max)
531 }
532
533 #[must_use]
535 pub fn lines_at(&self, max_width: f32) -> LineMetrics {
536 self.lines_within(max_width, None).lines
537 }
538
539 #[must_use]
542 pub fn line_limit(
543 &self,
544 max_width: f32,
545 max_lines: Option<u32>,
546 max_height: f32,
547 ) -> Option<u32> {
548 if self.is_uniform() {
549 return line_limit(self.font_size, self.line_height, max_lines, max_height);
550 }
551 let sizes = self
552 .paragraphs
553 .iter()
554 .flat_map(|clusters| {
555 break_lines(clusters, max_width)
556 .into_iter()
557 .map(|range| line_size(&clusters[range], self.font_size))
558 })
559 .collect::<Vec<_>>();
560 mixed_line_limit(&sizes, self.line_height, max_lines, max_height)
561 }
562
563 fn is_uniform(&self) -> bool {
564 self.paragraphs
565 .iter()
566 .flatten()
567 .all(|cluster| cluster.size <= self.font_size)
568 }
569
570 #[must_use]
573 pub fn lines_within(&self, max_width: f32, limit: Option<u32>) -> ClampedLines {
574 let limit = limit.map_or(u32::MAX, |limit| limit.max(1));
575 let (mut count, mut kept, mut widest) = (0_u32, 1_u32, 0.0_f32);
576 let mut sizes = Vec::new();
577 let (mut truncated, mut emergency) = (false, false);
578 'paragraphs: for (index, clusters) in self.paragraphs.iter().enumerate() {
579 let ranges = break_lines(clusters, max_width);
580 for (at, range) in ranges.iter().enumerate() {
581 count = count.saturating_add(1);
582 sizes.push(line_size(&clusters[range.clone()], self.font_size));
583 if !range.is_empty() {
584 kept = count;
585 }
586 widest = widest.max(advance(&clusters[range.clone()]));
587 emergency |= !range.is_empty()
588 && range.end < clusters.len()
589 && !clusters[range.end].break_before;
590 if count == limit {
591 truncated = ranges[at + 1..].iter().any(|range| !range.is_empty())
592 || self.paragraphs[index + 1..]
593 .iter()
594 .any(|clusters| !clusters.is_empty());
595 break 'paragraphs;
596 }
597 }
598 }
599 sizes.truncate(kept as usize);
600 let boxes = LineBoxes::of(&sizes, self.font_size, self.line_height);
601 let last = sizes.len().saturating_sub(1);
602 ClampedLines {
603 lines: LineMetrics {
604 line_count: kept,
605 widest,
606 height: boxes.height,
607 first_baseline: boxes.tops[0] + boxes.ascents[0],
608 last_baseline: boxes.tops[last] + boxes.ascents[last],
609 },
610 truncated,
611 splits_word: if truncated {
612 emergency
613 } else {
614 max_width > 0.0 && self.min_content_width() > max_width
615 },
616 }
617 }
618}
619
620#[derive(Copy, Clone, Debug, PartialEq)]
622pub struct ClampedLines {
623 pub lines: LineMetrics,
625 pub truncated: bool,
627 pub splits_word: bool,
630}
631
632fn advance(clusters: &[Cluster]) -> f32 {
635 let Some(last) = clusters.iter().rposition(|cluster| !cluster.hangs) else {
636 return 0.0;
637 };
638 clusters[..=last]
639 .iter()
640 .fold(0.0, |width, cluster| width + cluster.width)
641 - clusters[last].spacing
642}
643
644#[must_use]
646pub fn half_leading(font_size: f32, line_height: f32) -> f32 {
647 (font_size * line_height - font_size).max(0.0) * 0.5
648}
649
650#[allow(clippy::cast_precision_loss)]
652fn box_height(line_count: u32, line_advance: f32, font_size: f32) -> f32 {
653 line_count.saturating_sub(1) as f32 * line_advance + line_advance.max(font_size)
654}
655
656#[derive(Clone, Debug, Eq, PartialEq)]
658#[non_exhaustive]
659pub enum TextRasterError {
660 NoFonts,
662 InvalidFont(String),
664 InvalidRequest,
666 TooLarge,
668}
669
670impl fmt::Display for TextRasterError {
671 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
672 match self {
673 Self::NoFonts => formatter.write_str("text rasterizer requires at least one font"),
674 Self::InvalidFont(error) => write!(formatter, "invalid text font: {error}"),
675 Self::InvalidRequest => formatter.write_str("invalid text raster request"),
676 Self::TooLarge => formatter.write_str("text raster result is too large"),
677 }
678 }
679}
680
681impl std::error::Error for TextRasterError {}
682
683#[derive(Clone, Debug)]
684struct LoadedFont {
685 source: TextFont,
686 family: Option<String>,
688 aliases: Vec<String>,
690 weight: u16,
692 wght: Option<(f32, f32, f32)>,
694 ital: Option<(f32, f32, f32)>,
696 italic: bool,
698 oblique: bool,
700}
701
702const WGHT: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"wght");
703const ITAL: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"ital");
704
705impl LoadedFont {
706 fn parse(source: TextFont) -> Result<Self, TextRasterError> {
708 let face = parse_checked(&source.bytes, source.face_index)?;
709 let weight = face.weight().to_number().clamp(1, 1000);
710 let axis = |tag| {
711 face.variation_axes()
712 .into_iter()
713 .find(|axis| axis.tag == tag)
714 .map(|axis| (axis.min_value, axis.def_value, axis.max_value))
715 };
716 let (wght, ital) = (axis(WGHT), axis(ITAL));
717 let family = font_family(&source.bytes, source.face_index).map(|name| fold_family(&name));
718 let mut aliases = font_family_names(&source.bytes, source.face_index)
719 .iter()
720 .map(|name| fold_family(name))
721 .collect::<Vec<_>>();
722 aliases.extend(family.clone());
723 aliases.sort();
724 aliases.dedup();
725 Ok(Self {
726 italic: face.is_italic(),
727 oblique: face.is_oblique(),
728 source,
729 family,
730 aliases,
731 weight,
732 wght,
733 ital,
734 })
735 }
736
737 fn ital_reaches_one(&self) -> bool {
738 self.ital.is_some_and(|(_, _, max)| max >= 1.0)
739 }
740
741 fn style_rank(&self, style: FontStyle) -> u8 {
743 let italic = self.italic || self.ital_reaches_one();
744 let (first, second) = match style {
745 FontStyle::Normal => (!self.italic && !self.oblique, self.oblique && !self.italic),
746 FontStyle::Italic => (italic, self.oblique),
747 FontStyle::Oblique => (self.oblique, italic),
748 };
749 u8::from(!first) + u8::from(!first && !second)
750 }
751
752 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
754 fn weights(&self) -> (u16, u16) {
755 self.wght
756 .map_or((self.weight, self.weight), |(min, _, max)| {
757 let whole = |value: f32| value.clamp(1.0, 1000.0) as u16;
758 (whole(min.ceil()), whole(max.floor()).max(whole(min.ceil())))
759 })
760 }
761}
762
763fn weight_order(weights: &[(u16, u16)], desired: u16) -> Vec<usize> {
766 let key = |&(min, max): &(u16, u16)| -> (u8, u16) {
767 if (min..=max).contains(&desired) {
768 return (0, 0);
769 }
770 let weight = if desired < min { min } else { max };
771 let (above, distance) = (weight > desired, weight.abs_diff(desired));
772 if (400..=500).contains(&desired) {
773 match (above, weight <= 500) {
774 (true, true) => (1, distance),
775 (false, _) => (2, distance),
776 (true, false) => (3, distance),
777 }
778 } else if (desired < 400) != above {
779 (1, distance)
780 } else {
781 (2, distance)
782 }
783 };
784 let mut order = (0..weights.len()).collect::<Vec<_>>();
785 order.sort_by_key(|&index| key(&weights[index]));
786 order
787}
788
789pub fn check_font(bytes: &[u8], face_index: u32) -> Result<(), TextRasterError> {
798 parse_checked(bytes, face_index).map(drop)
799}
800
801fn parse_checked(bytes: &[u8], face_index: u32) -> Result<ttf_parser::Face<'_>, TextRasterError> {
802 if ttf_parser::fonts_in_collection(bytes)
803 .is_some_and(|faces| faces > font_check::MAX_COLLECTION_FACES)
804 {
805 return Err(TextRasterError::InvalidFont(format!(
806 "the font collection holds more than {} faces",
807 font_check::MAX_COLLECTION_FACES
808 )));
809 }
810 let face = ttf_parser::Face::parse(bytes, face_index)
811 .map_err(|error| TextRasterError::InvalidFont(error.to_string()))?;
812 font_check::check_face(&face).map_err(TextRasterError::InvalidFont)?;
813 Ok(face)
814}
815
816#[must_use]
818pub fn face_count(bytes: &[u8]) -> u32 {
819 ttf_parser::fonts_in_collection(bytes).unwrap_or(1)
820}
821
822#[must_use]
825pub fn font_family(bytes: &[u8], face_index: u32) -> Option<String> {
826 use rustybuzz::ttf_parser::{Language, name_id};
827 let face = rustybuzz::ttf_parser::Face::parse(bytes, face_index).ok()?;
828 let names = face.names();
829 [name_id::TYPOGRAPHIC_FAMILY, name_id::FAMILY]
830 .into_iter()
831 .find_map(|id| {
832 let decoded = || {
833 names
834 .into_iter()
835 .filter(move |name| name.name_id == id)
836 .filter_map(|name| {
837 let text = name.to_string()?;
838 (!text.trim().is_empty()).then_some((name.language(), text))
839 })
840 };
841 decoded()
842 .find(|(language, _)| *language == Language::English_UnitedStates)
843 .or_else(|| decoded().next())
844 .map(|(_, text)| text)
845 })
846}
847
848#[must_use]
851pub fn font_family_names(bytes: &[u8], face_index: u32) -> Vec<String> {
852 use rustybuzz::ttf_parser::name_id;
853 let Ok(face) = rustybuzz::ttf_parser::Face::parse(bytes, face_index) else {
854 return Vec::new();
855 };
856 let mut names = Vec::new();
857 for name in face.names() {
858 if name.name_id != name_id::TYPOGRAPHIC_FAMILY && name.name_id != name_id::FAMILY {
859 continue;
860 }
861 if let Some(text) = name.to_string().map(|text| text.trim().to_owned())
862 && !text.is_empty()
863 && !names.contains(&text)
864 {
865 names.push(text);
866 }
867 }
868 names
869}
870
871#[must_use]
873pub fn fold_family(name: &str) -> String {
874 use unicode_normalization::UnicodeNormalization;
875 name.trim().nfc().collect::<String>().to_lowercase()
876}
877
878pub const DEFAULT_TEXT_CACHE_BYTES: usize = 64 << 20;
880
881const CACHE_ENTRY_OVERHEAD: usize = 256;
883
884#[derive(Debug)]
889pub struct TextRasterizer {
890 fonts: Vec<LoadedFont>,
891 cache: ResultCache,
892 tiles: animated::TileCache,
893 unmatched: std::sync::Mutex<BTreeSet<String>>,
894}
895
896#[derive(Debug)]
897struct ResultCache {
898 entries: HashMap<u64, CacheEntry>,
899 by_use: BTreeMap<u64, u64>,
901 next_use: u64,
902 bytes: usize,
903 budget: usize,
904}
905
906#[derive(Debug)]
907struct CacheEntry {
908 result: Arc<TextRasterResult>,
909 last_use: u64,
910 bytes: usize,
911}
912
913impl ResultCache {
914 fn new(budget: usize) -> Self {
915 Self {
916 entries: HashMap::new(),
917 by_use: BTreeMap::new(),
918 next_use: 0,
919 bytes: 0,
920 budget,
921 }
922 }
923
924 fn get(&mut self, version: u64) -> Option<Arc<TextRasterResult>> {
925 let entry = self.entries.get_mut(&version)?;
926 self.by_use.remove(&entry.last_use);
927 entry.last_use = self.next_use;
928 self.by_use.insert(self.next_use, version);
929 self.next_use += 1;
930 Some(Arc::clone(&entry.result))
931 }
932
933 fn insert(&mut self, version: u64, result: &Arc<TextRasterResult>) {
934 self.remove(version);
935 let bytes = result
936 .pixels
937 .rgba8
938 .len()
939 .saturating_add(CACHE_ENTRY_OVERHEAD);
940 if bytes > self.budget {
941 return;
942 }
943 self.bytes += bytes;
944 self.entries.insert(
945 version,
946 CacheEntry {
947 result: Arc::clone(result),
948 last_use: self.next_use,
949 bytes,
950 },
951 );
952 self.by_use.insert(self.next_use, version);
953 self.next_use += 1;
954 self.evict();
955 }
956
957 fn remove(&mut self, version: u64) {
958 if let Some(entry) = self.entries.remove(&version) {
959 self.by_use.remove(&entry.last_use);
960 self.bytes -= entry.bytes;
961 }
962 }
963
964 fn clear(&mut self) {
965 self.entries.clear();
966 self.by_use.clear();
967 self.bytes = 0;
968 }
969
970 fn set_budget(&mut self, budget: usize) {
971 self.budget = budget;
972 self.evict();
973 }
974
975 fn evict(&mut self) {
976 while self.bytes > self.budget {
977 let Some((_, version)) = self.by_use.pop_first() else {
978 break;
979 };
980 if let Some(entry) = self.entries.remove(&version) {
981 self.bytes -= entry.bytes;
982 }
983 }
984 }
985}
986
987impl TextRasterizer {
988 #[must_use]
990 pub fn empty() -> Self {
991 Self {
992 fonts: Vec::new(),
993 cache: ResultCache::new(DEFAULT_TEXT_CACHE_BYTES),
994 tiles: animated::TileCache::default(),
995 unmatched: std::sync::Mutex::default(),
996 }
997 }
998
999 pub fn new(fonts: Vec<TextFont>) -> Result<Self, TextRasterError> {
1004 if fonts.is_empty() {
1005 return Err(TextRasterError::NoFonts);
1006 }
1007 let loaded = fonts
1008 .into_iter()
1009 .map(LoadedFont::parse)
1010 .collect::<Result<Vec<_>, _>>()?;
1011 Ok(Self {
1012 fonts: loaded,
1013 cache: ResultCache::new(DEFAULT_TEXT_CACHE_BYTES),
1014 tiles: animated::TileCache::default(),
1015 unmatched: std::sync::Mutex::default(),
1016 })
1017 }
1018
1019 pub fn add_font(&mut self, source: TextFont) -> Result<(), TextRasterError> {
1026 self.fonts.push(LoadedFont::parse(source)?);
1027 self.cache.clear();
1028 self.tiles.clear();
1029 Ok(())
1030 }
1031
1032 #[must_use]
1034 pub fn font_count(&self) -> usize {
1035 self.fonts.len()
1036 }
1037
1038 #[must_use]
1041 pub fn unmatched_families(&self) -> Vec<String> {
1042 self.unmatched
1043 .lock()
1044 .unwrap_or_else(std::sync::PoisonError::into_inner)
1045 .iter()
1046 .cloned()
1047 .collect()
1048 }
1049
1050 pub fn rasterize(
1055 &mut self,
1056 request: &TextRasterRequest,
1057 ) -> Result<Arc<TextRasterResult>, TextRasterError> {
1058 validate_request(request)?;
1059 if self.fonts.is_empty() {
1060 return Err(TextRasterError::NoFonts);
1061 }
1062 if let Some(cached) = self.cache.get(request.content_version) {
1063 return Ok(cached);
1064 }
1065 let result = if runs::paints_per_cluster(request) {
1066 let states = vec![ClusterState::IDENTITY; self.layout(request)?.clusters.len()];
1067 let mut tiles = std::mem::take(&mut self.tiles);
1068 let result = self.rasterize_states(request, &states, &mut tiles);
1069 self.tiles = tiles;
1070 result?
1071 } else {
1072 self.rasterize_uncached(request)?
1073 };
1074 let result = Arc::new(result);
1075 self.cache.insert(request.content_version, &result);
1076 Ok(result)
1077 }
1078
1079 pub fn invalidate(&mut self, content_version: u64) {
1081 self.cache.remove(content_version);
1082 }
1083
1084 pub fn set_cache_budget(&mut self, bytes: usize) {
1087 self.cache.set_budget(bytes);
1088 }
1089
1090 #[must_use]
1092 pub fn cache_bytes(&self) -> usize {
1093 self.cache.bytes
1094 }
1095
1096 pub fn clear(&mut self) {
1098 self.cache.clear();
1099 self.tiles.clear();
1100 }
1101
1102 #[must_use]
1104 pub fn cache_len(&self) -> usize {
1105 self.cache.entries.len()
1106 }
1107
1108 #[allow(clippy::cast_precision_loss)]
1113 pub fn measure(&self, request: &TextRasterRequest) -> Result<TextMeasure, TextRasterError> {
1114 validate_request(request)?;
1115 if self.fonts.is_empty() {
1116 return Err(TextRasterError::NoFonts);
1117 }
1118 let (faces, shaping) = self.prepare(request)?;
1119 let layout = Self::lay_out(&faces, &shaping, request)?;
1120 let mut inks = vec![None; shaping.looks.len()];
1121 layout.each_glyph(
1122 &faces,
1123 &shaping,
1124 request,
1125 &mut HashMap::new(),
1126 |drawing, origin, scale, glyph| {
1127 if let Some([x_min, y_min, x_max, y_max]) = drawing.ink_bounds() {
1128 include(
1129 &mut inks[usize::from(glyph.look)],
1130 [
1131 origin[0] + x_min * scale,
1132 origin[1] - y_max * scale,
1133 origin[0] + x_max * scale,
1134 origin[1] - y_min * scale,
1135 ],
1136 );
1137 }
1138 },
1139 );
1140 let paint = layout.paint(&faces, &shaping, request.align);
1141 for decoration in &paint.decorations {
1142 let look = layout.clusters[decoration.owner].look;
1143 include(&mut inks[usize::from(look)], decoration.rect);
1144 }
1145 let mut ink = None;
1146 for (look, bounds) in shaping.looks.iter().zip(inks) {
1147 let band = stroke_radius(&look.strokes).map_or(0.0, |radius| radius + 1.0);
1149 if let Some(bounds) = bounds {
1150 include(&mut ink, grown(bounds, band));
1151 }
1152 }
1153 for run in &paint.boxes {
1154 include(&mut ink, [run.left, run.top, run.right, run.bottom]);
1155 }
1156 let mut content = None;
1157 for (index, line) in layout.lines.iter().enumerate() {
1158 let left = layout.line_offset(line, request.align);
1159 let top = layout.line_top(index);
1160 include(&mut content, [left, 0.0, left + line.width, layout.height]);
1161 if let (Some(background), true) = (
1162 request
1163 .background
1164 .as_ref()
1165 .filter(|background| background.extent != BoxExtent::Block),
1166 line.width > 0.0,
1167 ) {
1168 let [pad_top, pad_right, pad_bottom, pad_left] = background.padding;
1169 include(
1170 &mut ink,
1171 [
1172 left - pad_left,
1173 top - pad_top,
1174 left + line.width + pad_right,
1175 top + layout.line_size(index) + pad_bottom,
1176 ],
1177 );
1178 }
1179 }
1180 if let Some((background, (left, width, top, height))) = request
1181 .background
1182 .as_ref()
1183 .filter(|background| background.extent == BoxExtent::Block)
1184 .zip(layout.block_box())
1185 {
1186 let [pad_top, pad_right, pad_bottom, pad_left] = background.padding;
1187 include(
1188 &mut ink,
1189 [
1190 left - pad_left,
1191 top - pad_top,
1192 left + width + pad_right,
1193 top + height + pad_bottom,
1194 ],
1195 );
1196 }
1197 let content = content.unwrap_or([0.0, 0.0, 0.0, layout.height]);
1198 let last = layout.lines.len().saturating_sub(1);
1199 Ok(TextMeasure {
1200 first_baseline: layout.baseline(0),
1201 last_baseline: layout.baseline(last),
1202 box_width: layout.box_width,
1203 box_height: layout.box_height,
1204 decoration_margin: request.decoration_margin(),
1205 content: grown_by(content, request.decoration_margin().map(|side| side as f32)),
1206 ink,
1207 line_count: layout.line_count,
1208 truncated: layout.truncated,
1209 })
1210 }
1211
1212 pub fn shape(&self, request: &TextRasterRequest) -> Result<ShapedText, TextRasterError> {
1219 validate_request(&TextRasterRequest {
1220 text: String::new(),
1221 max_width: 0.0,
1222 content_version: 1,
1223 fill: TextFill::Solid([0; 4]),
1224 strokes: Vec::new(),
1225 background: None,
1226 spans: Vec::new(),
1227 ..request.clone()
1228 })?;
1229 if request.text.len() > MAX_TEXT_BYTES || !runs::valid_spans(request) {
1230 return Err(TextRasterError::InvalidRequest);
1231 }
1232 if self.fonts.is_empty() {
1233 return Err(TextRasterError::NoFonts);
1234 }
1235 let (faces, shaping) = self.prepare(request)?;
1236 let mut start = 0;
1237 let paragraphs = normalize(&request.text, request.emoji_policy)
1238 .split('\n')
1239 .map(|paragraph| {
1240 let shaped = ShapedParagraph::new(
1241 &faces,
1242 paragraph,
1243 None,
1244 &shaping,
1245 Some(start),
1246 request.emoji_policy,
1247 );
1248 start += paragraph.len() + 1;
1249 shaped.clusters
1250 })
1251 .collect();
1252 Ok(ShapedText {
1253 paragraphs,
1254 font_size: request.font_size,
1255 line_height: request.line_height,
1256 })
1257 }
1258
1259 fn prepare(
1260 &self,
1261 request: &TextRasterRequest,
1262 ) -> Result<(Faces<'_>, runs::Shaping), TextRasterError> {
1263 let mut faces = Faces::new(&self.fonts, request.font_weight)?;
1264 let mut map = Vec::new();
1265 if !request.spans.is_empty() {
1266 normalize_mapped(&request.text, request.emoji_policy, Some(&mut map));
1267 }
1268 let (looks, at) = runs::Shaping::looks(request, &map);
1269 let mut orders = Vec::<Vec<usize>>::with_capacity(looks.len());
1270 for (index, look) in looks.iter().enumerate() {
1271 if let Some(same) = looks[..index].iter().position(|held| {
1272 held.family == look.family && held.weight == look.weight && held.style == look.style
1273 }) {
1274 orders.push(orders[same].clone());
1275 continue;
1276 }
1277 let fonts = self.font_order(look.family.as_deref(), look.style, look.weight);
1278 let italic = look.style != FontStyle::Normal;
1279 orders.push(
1280 fonts
1281 .into_iter()
1282 .map(|font| faces.instance(font, look.weight, italic))
1283 .collect::<Result<_, _>>()?,
1284 );
1285 }
1286 Ok((faces, runs::Shaping::new(looks, orders, at)))
1287 }
1288
1289 #[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1290 fn lay_out(
1291 faces: &Faces<'_>,
1292 shaping: &runs::Shaping,
1293 request: &TextRasterRequest,
1294 ) -> Result<Layout, TextRasterError> {
1295 let strut = request.font_size;
1296 let clamp = request.clamp.as_ref();
1297 let normalized = normalize(&request.text, request.emoji_policy);
1298 let paragraphs = normalized.split('\n').collect::<Vec<_>>();
1299 let starts = paragraphs
1300 .iter()
1301 .scan(0, |start, paragraph| {
1302 let at = *start;
1303 *start += paragraph.len() + 1;
1304 Some(at)
1305 })
1306 .collect::<Vec<_>>();
1307 let shape = |index: usize| {
1308 ShapedParagraph::new(
1309 faces,
1310 paragraphs[index],
1311 None,
1312 shaping,
1313 Some(starts[index]),
1314 request.emoji_policy,
1315 )
1316 };
1317 let mut shaped_ahead = Vec::new();
1318 let limit = clamp.and_then(|clamp| {
1319 if shaping.uniform() {
1320 return line_limit(
1321 strut,
1322 request.line_height,
1323 clamp.max_lines,
1324 clamp.max_height,
1325 );
1326 }
1327 shaped_ahead = (0..paragraphs.len())
1328 .map(|index| Some(shape(index)))
1329 .collect();
1330 let sizes = shaped_ahead
1331 .iter()
1332 .flatten()
1333 .flat_map(|shaped: &ShapedParagraph<'_>| {
1334 break_lines(&shaped.clusters, request.wrap_width())
1335 .into_iter()
1336 .map(|range| line_size(&shaped.clusters[range], strut))
1337 })
1338 .collect::<Vec<_>>();
1339 mixed_line_limit(
1340 &sizes,
1341 request.line_height,
1342 clamp.max_lines,
1343 clamp.max_height,
1344 )
1345 });
1346 let limit = limit.map_or(usize::MAX, |limit| limit as usize);
1347 let mut lines = Vec::new();
1348 let mut kept = 1;
1350 let mut clusters = Vec::new();
1351 let mut truncated = false;
1352 for index in 0..paragraphs.len() {
1353 let first = clusters.len();
1354 let shaped = shaped_ahead
1355 .get_mut(index)
1356 .and_then(Option::take)
1357 .unwrap_or_else(|| shape(index));
1358 let ranges = break_lines(&shaped.clusters, request.wrap_width());
1359 let mut clamped = false;
1360 for (at, range) in ranges.iter().enumerate() {
1361 let at_line = (first, lines.len());
1362 clamped = lines.len() + 1 >= limit;
1363 let cut = clamped
1364 && (ranges[at + 1..].iter().any(|range| !range.is_empty())
1365 || paragraphs[index + 1..]
1366 .iter()
1367 .any(|paragraph| !paragraph.is_empty()));
1368 truncated |= cut;
1369 let ellipsis = clamp
1370 .and_then(|clamp| clamp.ellipsis.as_deref())
1371 .filter(|_| cut);
1372 let size = line_size(&shaped.clusters[range.clone()], strut);
1373 let mut line = match ellipsis {
1374 Some(ellipsis) => {
1375 let level = shaped.bidi.paragraph_level;
1376 let mark = ShapedParagraph::new(
1377 faces,
1378 ellipsis,
1379 Some(level),
1380 shaping,
1381 None,
1382 request.emoji_policy,
1383 );
1384 shaped.place_cut(
1385 range.clone(),
1386 &mark,
1387 request.wrap_width(),
1388 at_line,
1389 &mut clusters,
1390 )
1391 }
1392 None => shaped.place(range.clone(), at_line, &mut clusters),
1393 };
1394 line.size = size;
1395 if line.has_glyphs {
1396 kept = lines.len() + 1;
1397 }
1398 lines.push(line);
1399 if clamped {
1400 break;
1401 }
1402 }
1403 for span in &mut clusters[first..] {
1404 span.bytes = span.bytes.start + starts[index]..span.bytes.end + starts[index];
1405 }
1406 if clamped {
1407 break;
1408 }
1409 }
1410 lines.truncate(kept);
1411 let line_count = u32::try_from(lines.len()).map_err(|_| TextRasterError::TooLarge)?;
1412 let width = if request.max_width > 0.0 {
1413 request.max_width
1414 } else {
1415 lines.iter().map(|line| line.width).fold(0.0, f32::max)
1416 }
1417 .max(1.0);
1418 let sizes = lines.iter().map(|line| line.size).collect::<Vec<_>>();
1419 let metrics = LineBoxes::of(&sizes, strut, request.line_height);
1420 let height = metrics.height.max(1.0);
1421 Ok(Layout {
1422 box_width: checked_dimension(width)?,
1423 box_height: checked_dimension(height)?,
1424 lines,
1425 clusters,
1426 line_count,
1427 boxes: metrics,
1428 ascent: strut * 0.8,
1429 descent: strut * 0.2,
1430 width,
1431 height,
1432 truncated,
1433 })
1434 }
1435
1436 #[allow(
1437 clippy::cast_possible_truncation,
1438 clippy::cast_precision_loss,
1439 clippy::too_many_lines
1440 )]
1441 fn rasterize_uncached(
1442 &self,
1443 request: &TextRasterRequest,
1444 ) -> Result<TextRasterResult, TextRasterError> {
1445 let (faces, shaping) = self.prepare(request)?;
1446 let layout = Self::lay_out(&faces, &shaping, request)?;
1447 let (box_width, box_height) = (layout.box_width, layout.box_height);
1448 let mut drawings = HashMap::<DrawingKey, Drawing>::new();
1449 let mut placed = Vec::new();
1450 let (mut overflow_x, mut overflow_y) = (0_i64, 0_i64);
1451 let (mut ink_ascent, mut ink_descent) = (layout.ascent, layout.descent);
1452 layout.each_glyph(
1453 &faces,
1454 &shaping,
1455 request,
1456 &mut drawings,
1457 |drawing, origin, scale, glyph| {
1458 let Some(bounds) = drawing.bounds() else {
1459 return;
1460 };
1461 let pixels = PixelBox::of(bounds, origin, scale);
1462 overflow_x = overflow_x
1463 .max(pixels.left.saturating_neg())
1464 .max(pixels.right.saturating_sub(i64::from(box_width)));
1465 overflow_y = overflow_y
1466 .max(pixels.top.saturating_neg())
1467 .max(pixels.bottom.saturating_sub(i64::from(box_height)));
1468 ink_ascent = ink_ascent.max(bounds[3] * scale + glyph.y_offset);
1469 ink_descent = ink_descent.max(-(bounds[1] * scale + glyph.y_offset));
1470 placed.push((drawing_key(&shaping, glyph), origin, scale, pixels));
1471 },
1472 );
1473 let (outline, padding) = decoration_extents(request);
1475 let margin = |overflow: i64, padding: u32| -> Result<u32, TextRasterError> {
1476 u32::try_from(overflow)
1477 .map_err(|_| TextRasterError::TooLarge)?
1478 .checked_add(outline)
1479 .map(|margin| margin.max(outline.max(padding)))
1480 .ok_or(TextRasterError::TooLarge)
1481 };
1482 let (margin_x, margin_y) = (
1483 margin(overflow_x, padding[0])?,
1484 margin(overflow_y, padding[1])?,
1485 );
1486 let width = margin_x
1487 .checked_mul(2)
1488 .and_then(|margins| box_width.checked_add(margins))
1489 .ok_or(TextRasterError::TooLarge)?;
1490 let height = margin_y
1491 .checked_mul(2)
1492 .and_then(|margins| box_height.checked_add(margins))
1493 .ok_or(TextRasterError::TooLarge)?;
1494 let colors = placed
1495 .iter()
1496 .any(|(key, ..)| !matches!(drawings[key], Drawing::Outline(_)));
1497 let pixel_count = raster_pixels(
1498 width,
1499 height,
1500 raster_bytes_per_pixel(request, request.strokes.len(), colors),
1501 )?;
1502 let mut coverage = vec![0_u8; pixel_count];
1503 let mut colors: Option<Vec<u8>> = None;
1505 let line_boxes = layout.background_boxes(request.align, request.background.as_ref());
1506 let highlight = request
1507 .highlight
1508 .as_ref()
1509 .map_or_else(Vec::new, |highlight| {
1510 let clusters = animated::text_layout(&layout, &shaping, request).clusters;
1511 highlight::boxes(
1512 &layout,
1513 &clusters,
1514 &layout.static_extents(request.align),
1515 highlight,
1516 )
1517 });
1518 for (key, origin, scale, pixels) in placed {
1519 let (origin_x, origin_y) = (
1520 pixels.left + i64::from(margin_x),
1521 pixels.top + i64::from(margin_y),
1522 );
1523 let glyph_width = usize::try_from(pixels.right - pixels.left).unwrap_or(0);
1524 match &drawings[&key] {
1525 Drawing::Outline(outline) => place_glyph(
1526 &mut coverage,
1527 width,
1528 height,
1529 origin_x,
1530 origin_y,
1531 glyph_width,
1532 &outline.draw(origin, scale, pixels),
1533 ),
1534 drawing => place_color_glyph(
1535 colors.get_or_insert_with(|| vec![0; pixel_count * 4]),
1536 width,
1537 height,
1538 origin_x,
1539 origin_y,
1540 glyph_width,
1541 &drawing.draw_color(origin, scale, pixels),
1542 ),
1543 }
1544 }
1545 let bands = stroke_bands(request, &coverage, colors.as_deref(), width);
1546 let (rgba8, background) = compose(
1547 request,
1548 &coverage,
1549 colors.as_deref(),
1550 width,
1551 [margin_x, margin_y],
1552 &line_boxes,
1553 &[],
1554 &highlight,
1555 &bands,
1556 &RequestLook::of(request, [layout.width, layout.height]),
1557 );
1558 let texture = HostTexture {
1559 content_version: request.content_version,
1560 width,
1561 height,
1562 premultiplication: Premultiplication::Premultiplied,
1563 color_space: RasterColorSpace::Srgb,
1564 };
1565 Ok(TextRasterResult {
1566 descriptor: TextTexture {
1567 texture: texture.clone(),
1568 layout_x: margin_x as f32,
1569 layout_y: margin_y as f32,
1570 layout_width: layout.width,
1571 layout_height: layout.height,
1572 first_baseline: layout.baseline(0),
1573 ascent: ink_ascent,
1574 descent: ink_descent,
1575 line_count: layout.line_count,
1576 },
1577 pixels: HostTexturePixels { texture, rgba8 },
1578 background,
1579 })
1580 }
1581
1582 fn font_order(&self, family: Option<&str>, style: FontStyle, weight: u16) -> Vec<usize> {
1585 let mut groups: Vec<(Option<&str>, Vec<usize>)> = Vec::new();
1587 for (index, font) in self.fonts.iter().enumerate() {
1588 let name = font.family.as_deref();
1589 match groups
1590 .iter_mut()
1591 .find(|(held, _)| name.is_some() && *held == name)
1592 {
1593 Some((_, faces)) => faces.push(index),
1594 None => groups.push((name, vec![index])),
1595 }
1596 }
1597 if let Some(requested) = family {
1598 let wanted = fold_family(requested);
1599 match groups.iter().position(|(_, faces)| {
1600 faces
1601 .iter()
1602 .any(|&index| self.fonts[index].aliases.contains(&wanted))
1603 }) {
1604 Some(at) => {
1605 let preferred = groups.remove(at);
1606 groups.insert(0, preferred);
1607 }
1608 None if !self.fonts.is_empty() => {
1609 self.unmatched
1610 .lock()
1611 .unwrap_or_else(std::sync::PoisonError::into_inner)
1612 .insert(requested.to_owned());
1613 }
1614 None => {}
1615 }
1616 }
1617 groups
1618 .into_iter()
1619 .flat_map(|(_, faces)| {
1620 let weights = faces
1621 .iter()
1622 .map(|&index| self.fonts[index].weights())
1623 .collect::<Vec<_>>();
1624 let mut order = weight_order(&weights, weight);
1625 order.sort_by_key(|&at| self.fonts[faces[at]].style_rank(style));
1626 order.into_iter().map(move |at| faces[at])
1627 })
1628 .collect()
1629 }
1630}
1631
1632struct Faces<'a> {
1634 fonts: &'a [LoadedFont],
1635 parsed: Vec<ttf_parser::Face<'a>>,
1636 shapers: Vec<OnceCell<rustybuzz::Face<'a>>>,
1637 color: Vec<bool>,
1639 of: Vec<(usize, u16, bool)>,
1640}
1641
1642impl<'a> Faces<'a> {
1643 fn new(fonts: &'a [LoadedFont], weight: u16) -> Result<Self, TextRasterError> {
1645 let mut faces = Self {
1646 fonts,
1647 parsed: Vec::with_capacity(fonts.len()),
1648 shapers: Vec::with_capacity(fonts.len()),
1649 color: Vec::with_capacity(fonts.len()),
1650 of: Vec::with_capacity(fonts.len()),
1651 };
1652 for font in 0..fonts.len() {
1653 faces.push(font, weight, false)?;
1654 }
1655 Ok(faces)
1656 }
1657
1658 fn push(&mut self, font: usize, weight: u16, italic: bool) -> Result<usize, TextRasterError> {
1659 let loaded = &self.fonts[font];
1660 let mut face = ttf_parser::Face::parse(&loaded.source.bytes, loaded.source.face_index)
1661 .ok()
1662 .filter(|face| face.units_per_em() > 0)
1663 .ok_or_else(|| TextRasterError::InvalidFont(loaded.source.family.clone()))?;
1664 if let Some((min, _, max)) = loaded.wght {
1665 face.set_variation(WGHT, f32::from(weight).clamp(min, max));
1666 }
1667 if italic && let Some((min, _, max)) = loaded.ital {
1668 face.set_variation(ITAL, 1.0_f32.clamp(min, max));
1669 }
1670 let tables = face.tables();
1671 self.color
1672 .push(tables.colr.is_some() || tables.cbdt.is_some() || tables.sbix.is_some());
1673 self.of
1674 .push((font, if loaded.wght.is_some() { weight } else { 0 }, italic));
1675 self.parsed.push(face);
1676 self.shapers.push(OnceCell::new());
1677 Ok(self.parsed.len() - 1)
1678 }
1679
1680 fn instance(
1681 &mut self,
1682 font: usize,
1683 weight: u16,
1684 italic: bool,
1685 ) -> Result<usize, TextRasterError> {
1686 let loaded = &self.fonts[font];
1687 let italic = italic && loaded.ital_reaches_one();
1688 let weight = if loaded.wght.is_some() { weight } else { 0 };
1689 let (_, base_weight, _) = self.of[font];
1690 if weight == base_weight && !italic {
1691 return Ok(font);
1692 }
1693 if let Some(found) = self
1694 .of
1695 .iter()
1696 .position(|held| *held == (font, weight, italic))
1697 {
1698 return Ok(found);
1699 }
1700 self.push(font, weight.max(1), italic)
1701 }
1702
1703 fn slanted(&self, face: usize) -> bool {
1704 let (font, _, italic) = self.of[face];
1705 italic || self.fonts[font].italic || self.fonts[font].oblique
1706 }
1707
1708 fn shaper(&self, font: usize) -> &rustybuzz::Face<'a> {
1709 self.shapers[font].get_or_init(|| rustybuzz::Face::from_face(self.parsed[font].clone()))
1710 }
1711
1712 #[allow(clippy::cast_precision_loss)]
1713 fn units_per_em(&self, font: usize) -> f32 {
1714 f32::from(self.parsed[font].units_per_em())
1715 }
1716
1717 fn has(&self, font: usize, character: char) -> bool {
1718 self.parsed[font]
1719 .glyph_index(character)
1720 .is_some_and(|glyph| glyph.0 != 0)
1721 }
1722
1723 fn covers(&self, font: usize, grapheme: &str) -> bool {
1725 grapheme
1726 .chars()
1727 .filter(|&character| !is_default_ignorable(character))
1728 .all(|character| self.has(font, character))
1729 }
1730}
1731
1732fn normalize(text: &str, policy: EmojiPolicy) -> String {
1735 normalize_mapped(text, policy, None)
1736}
1737
1738fn normalize_mapped(text: &str, policy: EmojiPolicy, mut map: Option<&mut Vec<usize>>) -> String {
1741 let mut normalized = String::with_capacity(text.len());
1742 for (start, grapheme) in text.grapheme_indices(true) {
1743 let before = normalized.len();
1744 if policy == EmojiPolicy::Replace && is_emoji(grapheme) {
1745 normalized.push('\u{fffd}');
1746 } else if grapheme == "\r\n" {
1747 normalized.push('\n');
1748 } else {
1749 normalized.extend(grapheme.chars().map(|character| match character {
1750 '\r'
1751 | '\u{b}'
1752 | '\u{c}'
1753 | '\u{1c}'..='\u{1e}'
1754 | '\u{85}'
1755 | '\u{2028}'
1756 | '\u{2029}' => '\n',
1757 '\t' => ' ',
1758 other => other,
1759 }));
1760 }
1761 if let Some(map) = map.as_deref_mut() {
1762 let written = normalized.len() - before;
1764 if written == grapheme.len() {
1765 map.extend(start..start + written);
1766 } else {
1767 map.extend(std::iter::repeat_n(start, written));
1768 }
1769 }
1770 }
1771 if let Some(map) = map {
1772 map.push(text.len());
1773 }
1774 normalized
1775}
1776
1777fn is_emoji(grapheme: &str) -> bool {
1780 if grapheme.contains('\u{fe0e}') {
1781 return false;
1782 }
1783 let selected = grapheme.contains('\u{fe0f}');
1784 grapheme.chars().any(|character| {
1785 in_table(unicode_tables::EMOJI_PRESENTATION, character)
1786 || (selected
1787 && (character == '\u{20e3}'
1788 || in_table(unicode_tables::EXTENDED_PICTOGRAPHIC, character)))
1789 })
1790}
1791
1792fn is_cursive(text: &str) -> bool {
1794 text.chars()
1795 .map(|character| character.script())
1796 .find(|script| !matches!(script, Script::Common | Script::Inherited | Script::Unknown))
1797 .is_some_and(|script| {
1798 matches!(
1799 script,
1800 Script::Adlam
1801 | Script::Arabic
1802 | Script::Hanifi_Rohingya
1803 | Script::Mandaic
1804 | Script::Mongolian
1805 | Script::Nko
1806 | Script::Phags_Pa
1807 | Script::Syriac
1808 )
1809 })
1810}
1811
1812fn is_default_ignorable(character: char) -> bool {
1813 in_table(unicode_tables::DEFAULT_IGNORABLE, character)
1814}
1815
1816fn in_table(table: &[(u32, u32)], character: char) -> bool {
1817 let code = u32::from(character);
1818 table
1819 .binary_search_by(|&(first, last)| {
1820 if last < code {
1821 Ordering::Less
1822 } else if first > code {
1823 Ordering::Greater
1824 } else {
1825 Ordering::Equal
1826 }
1827 })
1828 .is_ok()
1829}
1830
1831fn hangs(character: char) -> bool {
1833 character.is_whitespace()
1834 && !matches!(character, '\u{a0}' | '\u{2007}' | '\u{202f}' | '\u{1680}')
1835}
1836
1837fn is_hangul(character: char) -> bool {
1838 matches!(
1839 character,
1840 '\u{1100}'..='\u{11ff}'
1841 | '\u{3130}'..='\u{318f}'
1842 | '\u{a960}'..='\u{a97f}'
1843 | '\u{ac00}'..='\u{d7a3}'
1844 | '\u{d7b0}'..='\u{d7ff}'
1845 )
1846}
1847
1848#[derive(Clone, Debug, PartialEq)]
1852struct LineBoxes {
1853 tops: Vec<f32>,
1854 ascents: Vec<f32>,
1855 sizes: Vec<f32>,
1856 height: f32,
1857}
1858
1859impl LineBoxes {
1860 #[allow(clippy::cast_precision_loss)]
1861 fn of(sizes: &[f32], strut: f32, line_height: f32) -> Self {
1862 let count = u32::try_from(sizes.len()).unwrap_or(u32::MAX);
1863 if sizes.iter().all(|size| size.to_bits() == strut.to_bits()) {
1864 let advance = strut * line_height;
1865 let leading = half_leading(strut, line_height);
1866 return Self {
1867 tops: (0..sizes.len())
1868 .map(|index| index as f32 * advance + leading)
1869 .collect(),
1870 ascents: vec![strut * 0.8; sizes.len()],
1871 sizes: sizes.to_vec(),
1872 height: box_height(count, advance, strut),
1873 };
1874 }
1875 let mut tops = Vec::with_capacity(sizes.len());
1876 let mut top = 0.0_f32;
1877 for &size in sizes {
1878 tops.push(top + half_leading(size, line_height));
1879 top += size * line_height;
1880 }
1881 Self {
1882 tops,
1883 ascents: sizes.iter().map(|size| size * 0.8).collect(),
1884 sizes: sizes.to_vec(),
1885 height: mixed_height(sizes, line_height),
1886 }
1887 }
1888}
1889
1890fn mixed_height(sizes: &[f32], line_height: f32) -> f32 {
1891 let Some((last, before)) = sizes.split_last() else {
1892 return 0.0;
1893 };
1894 before
1895 .iter()
1896 .fold(0.0_f32, |height, size| height + size * line_height)
1897 + (last * line_height).max(*last)
1898}
1899
1900fn line_size(clusters: &[Cluster], strut: f32) -> f32 {
1901 clusters
1902 .iter()
1903 .fold(strut, |largest, cluster| largest.max(cluster.size))
1904}
1905
1906fn mixed_line_limit(
1907 sizes: &[f32],
1908 line_height: f32,
1909 max_lines: Option<u32>,
1910 max_height: f32,
1911) -> Option<u32> {
1912 let by_height = (max_height > 0.0).then(|| {
1913 let fitting = (1..=sizes.len())
1914 .take_while(|&count| mixed_height(&sizes[..count], line_height) <= max_height)
1915 .last()
1916 .unwrap_or(1);
1917 u32::try_from(fitting).unwrap_or(u32::MAX)
1918 });
1919 match (max_lines.map(|lines| lines.max(1)), by_height) {
1920 (Some(count), Some(height)) => Some(count.min(height)),
1921 (count, height) => count.or(height),
1922 }
1923}
1924
1925struct Layout {
1927 lines: Vec<LaidLine>,
1928 clusters: Vec<ClusterSpan>,
1930 line_count: u32,
1931 boxes: LineBoxes,
1932 ascent: f32,
1933 descent: f32,
1934 width: f32,
1936 height: f32,
1937 box_width: u32,
1938 box_height: u32,
1939 truncated: bool,
1941}
1942
1943impl Layout {
1944 fn line_boxes(&self, align: TextAlign) -> Vec<(f32, f32, f32, f32)> {
1945 self.lines
1946 .iter()
1947 .enumerate()
1948 .filter(|(_, line)| line.width > 0.0)
1949 .map(|(index, line)| {
1950 (
1951 self.line_offset(line, align),
1952 line.width,
1953 self.line_top(index),
1954 self.line_size(index),
1955 )
1956 })
1957 .collect()
1958 }
1959
1960 fn background_boxes(
1963 &self,
1964 align: TextAlign,
1965 background: Option<&TextBackground>,
1966 ) -> Vec<(f32, f32, f32, f32)> {
1967 match background.map(|background| background.extent) {
1968 Some(BoxExtent::Block) => self.block_box().into_iter().collect(),
1969 _ => self.line_boxes(align),
1970 }
1971 }
1972
1973 fn block_box(&self) -> Option<(f32, f32, f32, f32)> {
1975 let last = self.lines.len().checked_sub(1)?;
1976 let top = self.line_top(0);
1977 Some((
1978 0.0,
1979 self.width,
1980 top,
1981 self.line_top(last) + self.line_size(last) - top,
1982 ))
1983 }
1984
1985 fn static_extents(&self, align: TextAlign) -> Vec<Option<(f32, f32)>> {
1987 let mut extents = vec![None; self.clusters.len()];
1988 for index in 0..self.lines.len() {
1989 for (cluster, extent) in self.cluster_extents(index, align) {
1990 extents[cluster] = Some(extent);
1991 }
1992 }
1993 extents
1994 }
1995
1996 fn cluster_extents(&self, index: usize, align: TextAlign) -> HashMap<usize, (f32, f32)> {
1997 let line = &self.lines[index];
1998 let offset = self.line_offset(line, align);
1999 let mut extents = HashMap::<usize, (f32, f32)>::new();
2000 for glyph in &line.glyphs {
2001 let left = glyph.x + offset;
2002 let extent = extents.entry(glyph.cluster).or_insert((left, left));
2003 *extent = (extent.0.min(left), extent.1.max(left + glyph.advance));
2004 }
2005 extents
2006 }
2007
2008 fn paint(
2009 &self,
2010 faces: &Faces<'_>,
2011 shaping: &runs::Shaping,
2012 align: TextAlign,
2013 ) -> paint::LinePaint {
2014 let mut paint = paint::LinePaint::default();
2015 for index in 0..self.lines.len() {
2016 let extents = self.cluster_extents(index, align);
2017 paint.add_line(
2018 faces,
2019 shaping,
2020 self,
2021 index,
2022 (
2023 |cluster| extents[&cluster],
2024 |cluster| extents.get(&cluster).copied(),
2025 ),
2026 |_| animated::IDENTITY_AFFINE,
2027 );
2028 }
2029 paint
2030 }
2031
2032 fn line_offset(&self, line: &LaidLine, align: TextAlign) -> f32 {
2034 match (align, line.rtl) {
2035 (TextAlign::Center, _) => (self.width - line.width) * 0.5,
2036 (TextAlign::Start, false) | (TextAlign::End, true) => 0.0,
2037 (TextAlign::End, false) | (TextAlign::Start, true) => self.width - line.width,
2038 }
2039 }
2040
2041 fn line_top(&self, index: usize) -> f32 {
2042 self.boxes.tops[index]
2043 }
2044
2045 fn baseline(&self, index: usize) -> f32 {
2046 self.boxes.tops[index] + self.boxes.ascents[index]
2047 }
2048
2049 fn line_size(&self, index: usize) -> f32 {
2050 self.boxes.sizes[index]
2051 }
2052
2053 #[allow(clippy::cast_precision_loss)]
2056 fn each_glyph(
2057 &self,
2058 faces: &Faces<'_>,
2059 shaping: &runs::Shaping,
2060 request: &TextRasterRequest,
2061 drawings: &mut HashMap<DrawingKey, Drawing>,
2062 mut place: impl FnMut(&Drawing, [f32; 2], f32, &PositionedGlyph),
2063 ) {
2064 for (index, line) in self.lines.iter().enumerate() {
2065 let offset = self.line_offset(line, request.align);
2066 let baseline = self.baseline(index);
2067 for glyph in &line.glyphs {
2068 let key = drawing_key(shaping, glyph);
2069 let drawing = drawings
2070 .entry(key)
2071 .or_insert_with(|| Drawing::of(faces, key, request.emoji_policy));
2072 let scale = glyph.size / faces.units_per_em(glyph.font);
2073 let origin = [glyph.x + glyph.x_offset + offset, baseline - glyph.y_offset];
2074 place(drawing, origin, scale, glyph);
2075 }
2076 }
2077 }
2078}
2079
2080fn include(bounds: &mut Option<[f32; 4]>, [left, top, right, bottom]: [f32; 4]) {
2081 let held = bounds.get_or_insert([left, top, right, bottom]);
2082 *held = [
2083 held[0].min(left),
2084 held[1].min(top),
2085 held[2].max(right),
2086 held[3].max(bottom),
2087 ];
2088}
2089
2090fn grown([left, top, right, bottom]: [f32; 4], by: f32) -> [f32; 4] {
2091 [left - by, top - by, right + by, bottom + by]
2092}
2093
2094fn grown_by([left, top, right, bottom]: [f32; 4], [x, y]: [f32; 2]) -> [f32; 4] {
2095 [left - x, top - y, right + x, bottom + y]
2096}
2097
2098#[derive(Clone, Debug)]
2100struct ClusterSpan {
2101 bytes: Range<usize>,
2102 line: usize,
2103 look: u16,
2104 ellipsis: bool,
2106}
2107
2108struct LaidLine {
2109 glyphs: Vec<PositionedGlyph>,
2111 width: f32,
2113 rtl: bool,
2114 has_glyphs: bool,
2116 size: f32,
2117}
2118
2119struct ShapedParagraph<'a> {
2121 text: &'a str,
2122 bidi: ParagraphBidiInfo<'a>,
2123 glyphs: Vec<ShapedGlyph>,
2124 clusters: Vec<Cluster>,
2125}
2126
2127impl<'a> ShapedParagraph<'a> {
2128 fn new(
2130 faces: &Faces<'_>,
2131 text: &'a str,
2132 level: Option<unicode_bidi::Level>,
2133 shaping: &runs::Shaping,
2134 start: Option<usize>,
2135 policy: EmojiPolicy,
2136 ) -> Self {
2137 let look_of = |byte: usize| start.map_or(0, |start| shaping.at(start + byte));
2138 let bidi = ParagraphBidiInfo::new(text, level);
2139 let segments = segments(text, shaping, look_of);
2140 let glyphs = shape_paragraph(faces, text, &bidi, shaping, &segments, policy);
2141 let clusters = clusters(&glyphs, text, shaping, look_of);
2142 Self {
2143 text,
2144 bidi,
2145 glyphs,
2146 clusters,
2147 }
2148 }
2149
2150 fn place(
2153 &self,
2154 range: Range<usize>,
2155 (cluster_base, line): (usize, usize),
2156 spans: &mut Vec<ClusterSpan>,
2157 ) -> LaidLine {
2158 self.push_spans(range.clone(), cluster_base, line, spans);
2159 self.position(range, cluster_base)
2160 }
2161
2162 fn place_cut(
2165 &self,
2166 range: Range<usize>,
2167 mark: &ShapedParagraph<'_>,
2168 max_width: f32,
2169 (cluster_base, line): (usize, usize),
2170 spans: &mut Vec<ClusterSpan>,
2171 ) -> LaidLine {
2172 let mark_width = advance(&mark.clusters);
2173 let mut end = self.cut_end(range.clone(), mark_width, max_width);
2174 while end > range.start && self.clusters[end - 1].hangs {
2176 end -= 1;
2177 }
2178 self.push_spans(range.start..end, cluster_base, line, spans);
2179 let at = self
2180 .clusters
2181 .get(end)
2182 .map_or(self.text.len(), |next| next.start);
2183 spans.push(ClusterSpan {
2184 bytes: at..at,
2185 line,
2186 look: 0,
2187 ellipsis: true,
2188 });
2189 let mut laid = self.position(range.start..end, cluster_base);
2190 let gap = self.clusters[range.start..end]
2192 .last()
2193 .map_or(0.0, |cluster| cluster.spacing);
2194 let mut glyphs = mark.position(0..mark.clusters.len(), 0).glyphs;
2195 let shift = if laid.rtl { 0.0 } else { laid.width + gap };
2196 for glyph in &mut glyphs {
2197 glyph.cluster = cluster_base + end;
2198 glyph.x += shift;
2199 }
2200 if laid.rtl {
2201 for glyph in &mut laid.glyphs {
2202 glyph.x += mark_width + gap;
2203 }
2204 glyphs.append(&mut laid.glyphs);
2205 laid.glyphs = glyphs;
2206 } else {
2207 laid.glyphs.append(&mut glyphs);
2208 }
2209 laid.width += mark_width + gap;
2210 laid.has_glyphs = true;
2211 laid
2212 }
2213
2214 fn cut_end(&self, range: Range<usize>, mark_width: f32, max_width: f32) -> usize {
2218 if max_width <= 0.0 {
2219 return range.end;
2220 }
2221 let fits = |end: usize| {
2222 let kept = &self.clusters[range.start..end];
2223 let width = kept
2224 .iter()
2225 .rposition(|cluster| !cluster.hangs)
2226 .map_or(0.0, |last| {
2227 kept[..=last]
2228 .iter()
2229 .fold(0.0, |width, cluster| width + cluster.width)
2230 });
2231 width + mark_width <= max_width
2232 };
2233 let soft = |end: usize| end == self.clusters.len() || self.clusters[end].break_before;
2234 let ends = || (range.start + 1..=range.end).rev();
2235 ends()
2236 .find(|&end| soft(end) && fits(end))
2237 .or_else(|| ends().find(|&end| fits(end)))
2238 .unwrap_or(range.start)
2239 }
2240
2241 fn push_spans(
2242 &self,
2243 range: Range<usize>,
2244 cluster_base: usize,
2245 line: usize,
2246 spans: &mut Vec<ClusterSpan>,
2247 ) {
2248 debug_assert_eq!(spans.len(), cluster_base + range.start);
2249 for index in range {
2250 let end = self
2251 .clusters
2252 .get(index + 1)
2253 .map_or(self.text.len(), |next| next.start);
2254 spans.push(ClusterSpan {
2255 bytes: self.clusters[index].start..end.max(self.clusters[index].start),
2256 line,
2257 look: self.clusters[index].look,
2258 ellipsis: false,
2259 });
2260 }
2261 }
2262
2263 fn position(&self, range: Range<usize>, cluster_base: usize) -> LaidLine {
2266 let clusters = &self.clusters;
2267 let glyphs = &self.glyphs;
2268 let has_glyphs = !range.is_empty();
2269 let mut end = range.end;
2270 while end > range.start && clusters[end - 1].hangs {
2271 end -= 1;
2272 }
2273 let mut line = LaidLine {
2274 glyphs: Vec::new(),
2275 width: 0.0,
2276 rtl: self.bidi.paragraph_level.is_rtl(),
2277 has_glyphs,
2278 size: 0.0,
2279 };
2280 if end == range.start {
2281 return line;
2282 }
2283 let bytes = clusters[range.start].start
2284 ..clusters
2285 .get(range.end)
2286 .map_or(self.text.len(), |next| next.start);
2287 let levels = self.bidi.reordered_levels(bytes);
2288 let mut cluster_of = vec![0; clusters[end - 1].glyphs.end];
2290 for (index, cluster) in clusters[range.start..end].iter().enumerate() {
2291 cluster_of[cluster.glyphs.clone()].fill(range.start + index);
2292 }
2293 let mut x = 0.0_f32;
2294 let mut previous: Option<usize> = None;
2295 for index in visual_order(
2296 clusters[range.start].glyphs.start..clusters[end - 1].glyphs.end,
2297 |index| levels[glyphs[index].cluster].number(),
2298 ) {
2299 let glyph = &glyphs[index];
2300 let cluster = cluster_of[index];
2301 if let Some(before) = previous.filter(|&before| before != cluster) {
2302 x += clusters[before].spacing;
2303 }
2304 previous = Some(cluster);
2305 line.glyphs.push(PositionedGlyph {
2306 font: glyph.font,
2307 glyph_index: glyph.glyph_index,
2308 cluster: cluster_base + cluster,
2309 advance: glyph.advance,
2310 x,
2311 x_offset: glyph.x_offset,
2312 y_offset: glyph.y_offset,
2313 size: glyph.size,
2314 shear: glyph.shear,
2315 look: clusters[cluster].look,
2316 });
2317 x += glyph.advance;
2318 }
2319 line.width = x;
2320 line
2321 }
2322}
2323
2324fn visual_order(range: Range<usize>, level: impl Fn(usize) -> u8) -> Vec<usize> {
2326 let mut order = range.collect::<Vec<_>>();
2327 let levels = order.iter().map(|&index| level(index)).collect::<Vec<_>>();
2328 let highest = levels.iter().copied().max().unwrap_or(0);
2329 let Some(lowest_odd) = levels.iter().copied().filter(|level| level % 2 == 1).min() else {
2330 return order;
2331 };
2332 let mut current = levels;
2333 for at_least in (lowest_odd..=highest).rev() {
2334 let mut start = 0;
2335 while start < order.len() {
2336 if current[start] < at_least {
2337 start += 1;
2338 continue;
2339 }
2340 let end = (start..order.len())
2341 .find(|&index| current[index] < at_least)
2342 .unwrap_or(order.len());
2343 order[start..end].reverse();
2344 current[start..end].reverse();
2345 start = end;
2346 }
2347 }
2348 order
2349}
2350
2351#[derive(Clone, Debug, PartialEq)]
2353struct Run {
2354 range: Range<usize>,
2355 font: usize,
2356 script: Option<Script>,
2357 rtl: bool,
2358 segment: usize,
2359}
2360
2361#[derive(Clone, Debug, PartialEq)]
2362struct ShapeSegment {
2363 range: Range<usize>,
2364 look: u16,
2365}
2366
2367fn segments(
2368 paragraph: &str,
2369 shaping: &runs::Shaping,
2370 look_of: impl Fn(usize) -> u16,
2371) -> Vec<ShapeSegment> {
2372 let mut segments = Vec::<ShapeSegment>::new();
2373 for (start, grapheme) in paragraph.grapheme_indices(true) {
2374 let look = look_of(start);
2375 let end = start + grapheme.len();
2376 match segments.last_mut() {
2377 Some(segment)
2378 if shaping.looks[usize::from(segment.look)]
2379 .shapes_like(&shaping.looks[usize::from(look)]) =>
2380 {
2381 segment.range.end = end;
2382 }
2383 _ => segments.push(ShapeSegment {
2384 range: start..end,
2385 look,
2386 }),
2387 }
2388 }
2389 segments
2390}
2391
2392struct SegmentOrders<'o> {
2393 order: &'o [usize],
2394 color_first: Vec<usize>,
2395 text_first: Vec<usize>,
2396 color: bool,
2397 text: bool,
2398}
2399
2400impl<'o> SegmentOrders<'o> {
2401 fn of(faces: &Faces<'_>, order: &'o [usize]) -> Self {
2402 let (color, text): (Vec<usize>, Vec<usize>) =
2403 order.iter().partition(|&&font| faces.color[font]);
2404 Self {
2405 order,
2406 color_first: color.iter().chain(&text).copied().collect(),
2407 text_first: text.iter().chain(&color).copied().collect(),
2408 color: !color.is_empty(),
2409 text: !text.is_empty(),
2410 }
2411 }
2412}
2413
2414fn itemize(
2422 faces: &Faces<'_>,
2423 paragraph: &str,
2424 bidi: &ParagraphBidiInfo<'_>,
2425 segments: &[ShapeSegment],
2426 orders: &[Vec<usize>],
2427 policy: EmojiPolicy,
2428) -> Vec<Run> {
2429 let prepared = segments
2430 .iter()
2431 .map(|segment| SegmentOrders::of(faces, &orders[usize::from(segment.look)]))
2432 .collect::<Vec<_>>();
2433 let mut graphemes = Vec::<(usize, usize, Option<Script>, bool, usize)>::new();
2434 let mut current = None;
2435 let mut segment = 0;
2436 for (start, grapheme) in paragraph.grapheme_indices(true) {
2437 while segment + 1 < segments.len() && start >= segments[segment].range.end {
2438 segment += 1;
2439 current = None;
2440 }
2441 let orders = &prepared[segment];
2442 let first = orders.order.first().copied().unwrap_or(0);
2443 let fits = |font: usize, color_wanted: bool| {
2444 faces.color[font] == color_wanted
2445 || if color_wanted {
2446 !orders.color
2447 } else {
2448 !orders.text
2449 }
2450 };
2451 let script = grapheme
2452 .chars()
2453 .map(|character| character.script())
2454 .find(|script| !matches!(script, Script::Common | Script::Inherited | Script::Unknown));
2455 let wants_color = if grapheme.contains('\u{fe0e}') {
2456 Some(false)
2457 } else if is_emoji(grapheme) {
2458 Some(policy == EmojiPolicy::Color)
2459 } else {
2460 None
2461 };
2462 let order = match wants_color {
2463 Some(true) => orders.color_first.as_slice(),
2464 Some(false) => orders.text_first.as_slice(),
2465 None => orders.order,
2466 };
2467 let stays = current.filter(|&font| {
2468 script.is_none()
2469 && wants_color.is_none_or(|wanted| fits(font, wanted))
2470 && faces.covers(font, grapheme)
2471 });
2472 let font = stays
2473 .or_else(|| {
2474 order
2475 .iter()
2476 .copied()
2477 .find(|&font| faces.covers(font, grapheme))
2478 })
2479 .or_else(|| {
2480 let base = grapheme
2481 .chars()
2482 .find(|&character| !is_default_ignorable(character))?;
2483 order.iter().copied().find(|&font| faces.has(font, base))
2484 })
2485 .or(current)
2486 .unwrap_or(first);
2487 current = Some(font);
2488 graphemes.push((start, font, script, bidi.levels[start].is_rtl(), segment));
2489 }
2490 let leading = graphemes.iter().find_map(|grapheme| grapheme.2);
2491 let mut before = leading;
2492 for grapheme in &mut graphemes {
2493 match grapheme.2 {
2494 Some(script) => before = Some(script),
2495 None => grapheme.2 = before,
2496 }
2497 }
2498 let mut runs = Vec::<Run>::new();
2499 for (index, &(start, font, script, rtl, segment)) in graphemes.iter().enumerate() {
2500 let end = graphemes
2501 .get(index + 1)
2502 .map_or(paragraph.len(), |next| next.0);
2503 match runs.last_mut() {
2504 Some(run)
2505 if run.font == font
2506 && run.script == script
2507 && run.rtl == rtl
2508 && run.segment == segment =>
2509 {
2510 run.range.end = end;
2511 }
2512 _ => runs.push(Run {
2513 range: start..end,
2514 font,
2515 script,
2516 rtl,
2517 segment,
2518 }),
2519 }
2520 }
2521 runs
2522}
2523
2524fn shaping_script(script: Script) -> Option<rustybuzz::Script> {
2525 let code: [u8; 4] = script.short_name().as_bytes().try_into().ok()?;
2526 rustybuzz::Script::from_iso15924_tag(ttf_parser::Tag::from_bytes(&code))
2527}
2528
2529fn shape_paragraph(
2531 faces: &Faces<'_>,
2532 paragraph: &str,
2533 bidi: &ParagraphBidiInfo<'_>,
2534 shaping: &runs::Shaping,
2535 segments: &[ShapeSegment],
2536 policy: EmojiPolicy,
2537) -> Vec<ShapedGlyph> {
2538 let mut glyphs = Vec::new();
2539 for run in itemize(faces, paragraph, bidi, segments, &shaping.orders, policy) {
2540 let look = &shaping.looks[usize::from(segments[run.segment].look)];
2541 let font_size = look.size;
2542 let features = if look.spacing == 0.0 {
2544 Vec::new()
2545 } else {
2546 [b"liga", b"clig", b"dlig", b"hlig"]
2547 .map(|tag| rustybuzz::Feature::new(ttf_parser::Tag::from_bytes(tag), 0, ..))
2548 .to_vec()
2549 };
2550 let shear = look.style != FontStyle::Normal && !faces.slanted(run.font);
2551 let face = faces.shaper(run.font);
2552 let units = faces.units_per_em(run.font);
2553 let mut buffer = UnicodeBuffer::new();
2554 buffer.push_str(¶graph[run.range.clone()]);
2555 buffer.set_pre_context(¶graph[..run.range.start]);
2556 buffer.set_post_context(¶graph[run.range.end..]);
2557 buffer.set_direction(if run.rtl {
2558 Direction::RightToLeft
2559 } else {
2560 Direction::LeftToRight
2561 });
2562 match run.script.and_then(shaping_script) {
2563 Some(script) => buffer.set_script(script),
2564 None => buffer.guess_segment_properties(),
2565 }
2566 let shaped = rustybuzz::shape(face, &features, buffer);
2567 let first = glyphs.len();
2568 for (info, position) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
2569 #[allow(clippy::cast_precision_loss)]
2570 glyphs.push(ShapedGlyph {
2571 font: run.font,
2572 glyph_index: u16::try_from(info.glyph_id)
2574 .ok()
2575 .filter(|&glyph| glyph < face.number_of_glyphs())
2576 .unwrap_or(0),
2577 cluster: run.range.start + usize::try_from(info.cluster).unwrap_or(0),
2578 advance: position.x_advance as f32 * font_size / units,
2579 x_offset: position.x_offset as f32 * font_size / units,
2580 y_offset: position.y_offset as f32 * font_size / units,
2581 size: font_size,
2582 shear,
2583 });
2584 }
2585 if run.rtl {
2587 glyphs[first..].reverse();
2588 }
2589 }
2590 glyphs
2591}
2592
2593#[derive(Copy, Clone, Debug)]
2594struct ShapedGlyph {
2595 font: usize,
2596 glyph_index: u16,
2597 cluster: usize,
2599 advance: f32,
2600 x_offset: f32,
2602 y_offset: f32,
2603 size: f32,
2604 shear: bool,
2605}
2606
2607#[derive(Clone, Debug, PartialEq)]
2609struct Cluster {
2610 glyphs: Range<usize>,
2611 start: usize,
2613 width: f32,
2615 spacing: f32,
2617 hangs: bool,
2619 break_before: bool,
2621 size: f32,
2622 look: u16,
2623}
2624
2625fn clusters(
2628 glyphs: &[ShapedGlyph],
2629 paragraph: &str,
2630 shaping: &runs::Shaping,
2631 look_of: impl Fn(usize) -> u16,
2632) -> Vec<Cluster> {
2633 let mut opportunities = unicode_linebreak::linebreaks(paragraph)
2634 .filter(|&(at, kind)| {
2635 kind == BreakOpportunity::Allowed
2636 && !(paragraph[..at].chars().next_back().is_some_and(is_hangul)
2637 && paragraph[at..].chars().next().is_some_and(is_hangul))
2638 })
2639 .map(|(at, _)| at)
2640 .peekable();
2641 let mut clusters = Vec::<Cluster>::new();
2642 for (index, glyph) in glyphs.iter().enumerate() {
2643 match clusters.last_mut() {
2644 Some(cluster) if cluster.start == glyph.cluster => {
2645 cluster.glyphs.end = index + 1;
2646 cluster.width += glyph.advance;
2647 }
2648 _ => clusters.push(Cluster {
2649 glyphs: index..index + 1,
2650 start: glyph.cluster,
2651 width: glyph.advance,
2652 spacing: 0.0,
2653 hangs: false,
2654 break_before: false,
2655 size: glyph.size,
2656 look: look_of(glyph.cluster),
2657 }),
2658 }
2659 }
2660 for index in 0..clusters.len() {
2661 let start = clusters[index].start;
2662 let end = clusters
2663 .get(index + 1)
2664 .map(|next| next.start)
2665 .filter(|&end| end > start)
2666 .unwrap_or_else(|| {
2667 paragraph[start..]
2668 .chars()
2669 .next()
2670 .map_or(start, |character| start + character.len_utf8())
2671 });
2672 clusters[index].hangs = paragraph[start..end].chars().all(hangs);
2673 let letter_spacing = shaping.looks[usize::from(clusters[index].look)].spacing;
2674 if letter_spacing != 0.0 && !is_cursive(¶graph[start..end]) {
2675 clusters[index].spacing = letter_spacing;
2676 clusters[index].width += letter_spacing;
2677 }
2678 let mut found = false;
2679 while let Some(&at) = opportunities.peek() {
2680 if at > start {
2681 break;
2682 }
2683 opportunities.next();
2684 found = true;
2685 }
2686 clusters[index].break_before = index > 0 && found;
2687 }
2688 clusters
2689}
2690
2691fn break_lines(clusters: &[Cluster], max_width: f32) -> Vec<Range<usize>> {
2694 let mut lines = Vec::new();
2695 let mut start = 0;
2696 let mut x = 0.0_f32;
2697 let mut opportunity: Option<(usize, f32)> = None;
2699 for (index, cluster) in clusters.iter().enumerate() {
2700 if cluster.break_before && index > start {
2701 opportunity = Some((index, x));
2702 }
2703 let fits = |x: f32| x + cluster.width - cluster.spacing <= max_width;
2704 if max_width > 0.0 && !cluster.hangs && index > start && !fits(x) {
2705 let (end, width) = opportunity.unwrap_or((index, x));
2706 lines.push(start..end);
2707 start = end;
2708 x -= width;
2709 opportunity = None;
2710 if index > start && !fits(x) {
2712 lines.push(start..index);
2713 start = index;
2714 x = 0.0;
2715 }
2716 }
2717 x += cluster.width;
2718 }
2719 lines.push(start..clusters.len());
2720 lines
2721}
2722
2723#[derive(Copy, Clone, Debug)]
2724struct PositionedGlyph {
2725 font: usize,
2726 glyph_index: u16,
2727 cluster: usize,
2729 advance: f32,
2731 x: f32,
2733 x_offset: f32,
2735 y_offset: f32,
2736 size: f32,
2737 shear: bool,
2738 look: u16,
2739}
2740
2741#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
2742struct DrawingKey {
2743 face: usize,
2744 glyph: u16,
2745 shear: bool,
2746 size: u32,
2747 foreground: [u8; 4],
2748}
2749
2750fn drawing_key(shaping: &runs::Shaping, glyph: &PositionedGlyph) -> DrawingKey {
2751 DrawingKey {
2752 face: glyph.font,
2753 glyph: glyph.glyph_index,
2754 shear: glyph.shear,
2755 size: glyph.size.to_bits(),
2756 foreground: shaping.looks[usize::from(glyph.look)].fill.foreground(),
2757 }
2758}
2759
2760const OBLIQUE_SHEAR: f32 = 0.25;
2763
2764enum Drawing {
2766 Outline(Outline),
2767 Painting(color::Painting),
2768 Bitmap(color::Bitmap),
2769}
2770
2771impl Drawing {
2772 fn of(faces: &Faces<'_>, key: DrawingKey, policy: EmojiPolicy) -> Self {
2775 let face = &faces.parsed[key.face];
2776 if policy == EmojiPolicy::Color && faces.color[key.face] {
2777 let [red, green, blue, _] = key.foreground;
2778 let shear = if key.shear { OBLIQUE_SHEAR } else { 0.0 };
2779 if let Some(painting) =
2780 color::Painting::of(face, key.glyph, [red, green, blue, 255], shear)
2781 {
2782 return Self::Painting(painting);
2783 }
2784 if let Some(bitmap) = color::Bitmap::of(face, key.glyph, f32::from_bits(key.size)) {
2785 return Self::Bitmap(bitmap);
2786 }
2787 }
2788 let outline = Outline::of(face, key.glyph);
2789 Self::Outline(if key.shear {
2790 outline.sheared(OBLIQUE_SHEAR)
2791 } else {
2792 outline
2793 })
2794 }
2795
2796 fn bounds(&self) -> Option<[f32; 4]> {
2798 match self {
2799 Self::Outline(outline) => outline.bounds,
2800 Self::Painting(painting) => painting.bounds(),
2801 Self::Bitmap(bitmap) => Some(bitmap.bounds()),
2802 }
2803 }
2804
2805 fn ink_bounds(&self) -> Option<[f32; 4]> {
2807 match self {
2808 Self::Outline(outline) => outline.curve_bounds(),
2809 Self::Painting(painting) => painting.bounds(),
2810 Self::Bitmap(bitmap) => bitmap.ink_bounds(),
2811 }
2812 }
2813
2814 fn draw_color(&self, origin: [f32; 2], scale: f32, pixels: PixelBox) -> Vec<u8> {
2816 match self {
2817 Self::Outline(_) => Vec::new(),
2818 Self::Painting(painting) => painting.draw(origin, scale, pixels),
2819 Self::Bitmap(bitmap) => bitmap.draw(origin, scale, pixels),
2820 }
2821 }
2822}
2823
2824#[derive(Default)]
2826struct Outline {
2827 segments: Vec<Segment>,
2828 bounds: Option<[f32; 4]>,
2830}
2831
2832enum Segment {
2833 Line([f32; 2], [f32; 2]),
2834 Quad([f32; 2], [f32; 2], [f32; 2]),
2835 Cubic([f32; 2], [f32; 2], [f32; 2], [f32; 2]),
2836}
2837
2838#[derive(Copy, Clone, Debug)]
2840struct PixelBox {
2841 left: i64,
2842 top: i64,
2843 right: i64,
2844 bottom: i64,
2845}
2846
2847impl PixelBox {
2848 #[allow(clippy::cast_possible_truncation)]
2849 fn of(bounds: [f32; 4], origin: [f32; 2], scale: f32) -> Self {
2850 let [x_min, y_min, x_max, y_max] = bounds;
2851 Self {
2853 left: (origin[0] + x_min * scale).floor() as i64,
2854 top: (origin[1] - y_max * scale).floor() as i64,
2855 right: (origin[0] + x_max * scale).ceil() as i64,
2856 bottom: (origin[1] - y_min * scale).ceil() as i64,
2857 }
2858 }
2859}
2860
2861#[cfg(test)]
2862thread_local! {
2863 #[allow(clippy::missing_const_for_thread_local)]
2865 static OUTLINES_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2866}
2867
2868impl Outline {
2869 fn of(face: &ttf_parser::Face<'_>, glyph: u16) -> Self {
2870 #[cfg(test)]
2871 OUTLINES_READ.with(|read| read.set(read.get() + 1));
2872 let mut sink = OutlineSink::default();
2873 face.outline_glyph(GlyphId(glyph), &mut sink);
2874 sink.close();
2875 if sink.overflow {
2876 return Self::default();
2877 }
2878 sink.outline
2879 }
2880
2881 #[allow(
2882 clippy::cast_possible_truncation,
2883 clippy::cast_sign_loss,
2884 clippy::cast_precision_loss
2885 )]
2886 fn draw(&self, origin: [f32; 2], scale: f32, pixels: PixelBox) -> Vec<u8> {
2887 let width = usize::try_from(pixels.right - pixels.left).unwrap_or(0);
2888 let height = usize::try_from(pixels.bottom - pixels.top).unwrap_or(0);
2889 let (left, top) = (pixels.left as f32, pixels.top as f32);
2890 let raster = self.raster(width, height, |[x, y]| {
2891 point(origin[0] + x * scale - left, (origin[1] - y * scale) - top)
2892 });
2893 let mut alpha = vec![0_u8; width * height];
2894 raster.for_each_pixel(|index, coverage| {
2895 alpha[index] = (coverage.min(1.0) * 255.0).round() as u8;
2896 });
2897 alpha
2898 }
2899}
2900
2901impl Outline {
2902 fn sheared(self, shear: f32) -> Self {
2903 let map = |[x, y]: [f32; 2]| [x + shear * y, y];
2904 let segments = self
2905 .segments
2906 .into_iter()
2907 .map(|segment| match segment {
2908 Segment::Line(from, to) => Segment::Line(map(from), map(to)),
2909 Segment::Quad(from, control, to) => Segment::Quad(map(from), map(control), map(to)),
2910 Segment::Cubic(from, first, second, to) => {
2911 Segment::Cubic(map(from), map(first), map(second), map(to))
2912 }
2913 })
2914 .collect::<Vec<_>>();
2915 let mut bounds = None;
2916 for segment in &segments {
2917 let points: &[[f32; 2]] = match segment {
2918 Segment::Line(from, to) => &[*from, *to],
2919 Segment::Quad(from, control, to) => &[*from, *control, *to],
2920 Segment::Cubic(from, first, second, to) => &[*from, *first, *second, *to],
2921 };
2922 for &[x, y] in points {
2923 include(&mut bounds, [x, y, x, y]);
2924 }
2925 }
2926 Self { segments, bounds }
2927 }
2928
2929 fn curve_bounds(&self) -> Option<[f32; 4]> {
2931 let mut bounds = None;
2932 let mut hold = |[x, y]: [f32; 2]| include(&mut bounds, [x, y, x, y]);
2933 for segment in &self.segments {
2934 match *segment {
2935 Segment::Line(from, to) => {
2936 hold(from);
2937 hold(to);
2938 }
2939 Segment::Quad(from, control, to) => {
2940 hold(from);
2941 hold(to);
2942 for axis in 0..2 {
2943 let curvature = from[axis] - 2.0 * control[axis] + to[axis];
2944 let t = (from[axis] - control[axis]) / curvature;
2945 if t > 0.0 && t < 1.0 {
2946 hold(std::array::from_fn(|axis| {
2947 let u = 1.0 - t;
2948 u * u * from[axis] + 2.0 * u * t * control[axis] + t * t * to[axis]
2949 }));
2950 }
2951 }
2952 }
2953 Segment::Cubic(from, first, second, to) => {
2954 hold(from);
2955 hold(to);
2956 for axis in 0..2 {
2957 let [p0, p1, p2, p3] = [from[axis], first[axis], second[axis], to[axis]];
2958 for t in quadratic_roots(
2959 -p0 + 3.0 * (p1 - p2) + p3,
2960 2.0 * (p0 - 2.0 * p1 + p2),
2961 p1 - p0,
2962 )
2963 .into_iter()
2964 .flatten()
2965 .filter(|t| *t > 0.0 && *t < 1.0)
2966 {
2967 hold(std::array::from_fn(|axis| {
2968 let u = 1.0 - t;
2969 u * u * u * from[axis]
2970 + 3.0 * u * u * t * first[axis]
2971 + 3.0 * u * t * t * second[axis]
2972 + t * t * t * to[axis]
2973 }));
2974 }
2975 }
2976 }
2977 }
2978 }
2979 bounds
2980 }
2981
2982 fn raster(&self, width: usize, height: usize, at: impl Fn([f32; 2]) -> Point) -> Rasterizer {
2983 let mut raster = Rasterizer::new(width, height);
2984 for segment in &self.segments {
2985 match *segment {
2986 Segment::Line(from, to) => raster.draw_line(at(from), at(to)),
2987 Segment::Quad(from, control, to) => raster.draw_quad(at(from), at(control), at(to)),
2988 Segment::Cubic(from, first, second, to) => {
2989 raster.draw_cubic(at(from), at(first), at(second), at(to));
2990 }
2991 }
2992 }
2993 raster
2994 }
2995}
2996
2997fn quadratic_roots(a: f32, b: f32, c: f32) -> [Option<f32>; 2] {
2999 let finite = |t: f32| t.is_finite().then_some(t);
3000 if a.abs() <= f32::EPSILON * (b.abs() + c.abs()) {
3001 return [finite(-c / b), None];
3002 }
3003 let discriminant = b * b - 4.0 * a * c;
3004 if discriminant < 0.0 {
3005 return [None, None];
3006 }
3007 let root = discriminant.sqrt();
3008 [
3009 finite((-b + root) / (2.0 * a)),
3010 finite((-b - root) / (2.0 * a)),
3011 ]
3012}
3013
3014const MAX_GLYPH_SEGMENTS: usize = 65_536;
3016
3017#[derive(Default)]
3018struct OutlineSink {
3019 outline: Outline,
3020 start: [f32; 2],
3021 pen: [f32; 2],
3022 overflow: bool,
3023}
3024
3025impl OutlineSink {
3026 fn room(&mut self) -> bool {
3029 self.overflow |= self.outline.segments.len() >= MAX_GLYPH_SEGMENTS;
3030 !self.overflow
3031 }
3032
3033 fn include(&mut self, points: &[[f32; 2]]) {
3034 for &[x, y] in points {
3035 let bounds = self.outline.bounds.get_or_insert([x, y, x, y]);
3036 *bounds = [
3037 bounds[0].min(x),
3038 bounds[1].min(y),
3039 bounds[2].max(x),
3040 bounds[3].max(y),
3041 ];
3042 }
3043 }
3044}
3045
3046impl OutlineBuilder for OutlineSink {
3047 fn move_to(&mut self, x: f32, y: f32) {
3048 self.close();
3049 self.start = [x, y];
3050 self.pen = [x, y];
3051 }
3052
3053 fn line_to(&mut self, x: f32, y: f32) {
3054 if !self.room() {
3055 return;
3056 }
3057 let to = [x, y];
3058 self.include(&[self.pen, to]);
3059 self.outline.segments.push(Segment::Line(self.pen, to));
3060 self.pen = to;
3061 }
3062
3063 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
3064 if !self.room() {
3065 return;
3066 }
3067 let (control, to) = ([x1, y1], [x, y]);
3068 self.include(&[self.pen, control, to]);
3069 self.outline
3070 .segments
3071 .push(Segment::Quad(self.pen, control, to));
3072 self.pen = to;
3073 }
3074
3075 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
3076 if !self.room() {
3077 return;
3078 }
3079 let (first, second, to) = ([x1, y1], [x2, y2], [x, y]);
3080 self.include(&[self.pen, first, second, to]);
3081 self.outline
3082 .segments
3083 .push(Segment::Cubic(self.pen, first, second, to));
3084 self.pen = to;
3085 }
3086
3087 fn close(&mut self) {
3088 if self.pen.map(f32::to_bits) != self.start.map(f32::to_bits) {
3090 self.line_to(self.start[0], self.start[1]);
3091 }
3092 }
3093}
3094
3095fn validate_request(request: &TextRasterRequest) -> Result<(), TextRasterError> {
3096 if request.font_size.is_finite()
3097 && request.font_size > 0.0
3098 && request.font_size <= MAX_FONT_SIZE
3099 && request.text.len() <= MAX_TEXT_BYTES
3100 && request.max_width.is_finite()
3101 && request.max_width <= MAX_TEXT_BOX_PIXELS
3102 && request.line_height.is_finite()
3103 && request.line_height > 0.0
3104 && request.line_height <= MAX_LINE_HEIGHT
3105 && request.letter_spacing.is_finite()
3106 && request.letter_spacing >= LETTER_SPACING_RANGE.start() * request.font_size
3107 && request.letter_spacing <= LETTER_SPACING_RANGE.end() * request.font_size
3108 && (1..=1000).contains(&request.font_weight)
3109 && request.content_version > 0
3110 && request.fill.is_valid()
3111 && valid_strokes(&request.strokes)
3112 && request
3113 .background
3114 .as_ref()
3115 .is_none_or(TextBackground::is_valid)
3116 && request.clamp.as_ref().is_none_or(|clamp| {
3117 clamp.max_lines != Some(0)
3118 && clamp.max_height.is_finite()
3119 && clamp.ellipsis.as_ref().is_none_or(|ellipsis| {
3120 ellipsis.len() <= MAX_ELLIPSIS_BYTES && !ellipsis.contains('\n')
3121 })
3122 })
3123 && runs::valid_spans(request)
3124 && (1.0..=MAX_CLUSTER_SCALE).contains(&request.advance_headroom)
3125 && request.highlight.as_ref().is_none_or(|highlight| {
3126 highlight.look.is_valid()
3127 && highlight.steps.len() <= MAX_HIGHLIGHT_STEPS
3128 && highlight.steps.iter().all(|(bytes, progress)| {
3129 bytes.start <= bytes.end
3130 && bytes.end <= request.text.len()
3131 && (0.0..=1.0).contains(progress)
3132 })
3133 })
3134 && request
3135 .animator_pivot
3136 .iter()
3137 .all(|fraction| (0.0..=1.0).contains(fraction))
3138 {
3139 Ok(())
3140 } else {
3141 Err(TextRasterError::InvalidRequest)
3142 }
3143}
3144
3145fn valid_strokes(strokes: &[TextStroke]) -> bool {
3146 strokes.len() <= MAX_STROKES
3147 && strokes
3148 .iter()
3149 .all(|stroke| stroke.width.is_finite() && stroke.width > 0.0)
3150 && stroke_radius(strokes).is_none_or(|radius| radius <= MAX_STROKE_EXTENT)
3151}
3152
3153fn checked_dimension(value: f32) -> Result<u32, TextRasterError> {
3154 if value.is_finite() && value > 0.0 && value.ceil() <= MAX_TEXT_BOX_PIXELS {
3155 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3156 Ok(value.ceil() as u32)
3157 } else {
3158 Err(TextRasterError::TooLarge)
3159 }
3160}
3161
3162fn place_glyph(
3164 mask: &mut [u8],
3165 width: u32,
3166 height: u32,
3167 origin_x: i64,
3168 origin_y: i64,
3169 glyph_width: usize,
3170 alpha: &[u8],
3171) {
3172 for (index, coverage) in alpha.iter().copied().enumerate() {
3173 let x = origin_x + i64::try_from(index % glyph_width.max(1)).unwrap_or(0);
3174 let y = origin_y + i64::try_from(index / glyph_width.max(1)).unwrap_or(0);
3175 if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) {
3176 continue;
3177 }
3178 let pixel =
3179 u64::try_from(y).unwrap_or(0) * u64::from(width) + u64::try_from(x).unwrap_or(0);
3180 let slot = &mut mask[usize::try_from(pixel).unwrap_or(0)];
3181 *slot = (*slot).max(coverage);
3182 }
3183}
3184
3185fn place_color_glyph(
3187 colors: &mut [u8],
3188 width: u32,
3189 height: u32,
3190 origin_x: i64,
3191 origin_y: i64,
3192 glyph_width: usize,
3193 rgba8: &[u8],
3194) {
3195 for (index, source) in rgba8.as_chunks::<4>().0.iter().enumerate() {
3196 let x = origin_x + i64::try_from(index % glyph_width.max(1)).unwrap_or(0);
3197 let y = origin_y + i64::try_from(index / glyph_width.max(1)).unwrap_or(0);
3198 if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) || source[3] == 0 {
3199 continue;
3200 }
3201 let pixel =
3202 u64::try_from(y).unwrap_or(0) * u64::from(width) + u64::try_from(x).unwrap_or(0);
3203 let slot = &mut colors[usize::try_from(pixel).unwrap_or(0) * 4..][..4];
3204 let blended = over(
3205 std::array::from_fn(|channel| u32::from(source[channel])),
3206 std::array::from_fn(|channel| u32::from(slot[channel])),
3207 );
3208 for (byte, value) in slot.iter_mut().zip(blended) {
3209 *byte = u8::try_from(value.min(255)).unwrap_or(u8::MAX);
3210 }
3211 }
3212}
3213
3214impl TextRasterRequest {
3215 #[must_use]
3219 pub fn decoration_margin(&self) -> [u32; 2] {
3220 let (outline, padding) = decoration_extents(self);
3221 padding.map(|padding| outline.max(padding))
3222 }
3223}
3224
3225fn decoration_extents(request: &TextRasterRequest) -> (u32, [u32; 2]) {
3228 let outline = stroke_radius(&request.strokes).map_or(0, disc_extent);
3229 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3230 let padding = request
3231 .background
3232 .iter()
3233 .chain(request.highlight.as_ref().map(|highlight| &highlight.look))
3234 .fold([0; 2], |held, background| {
3235 let [top, right, bottom, left] = background.padding;
3236 let reach = [right.max(left), top.max(bottom)].map(|side| side.ceil() as u32);
3237 [held[0].max(reach[0]), held[1].max(reach[1])]
3238 });
3239 (outline, padding)
3240}
3241
3242fn stroke_radius(strokes: &[TextStroke]) -> Option<f32> {
3244 let mut radius = None;
3245 for stroke in strokes {
3246 radius = Some(radius.unwrap_or(0.0) + stroke.width);
3247 }
3248 radius
3249}
3250
3251#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3253fn disc_extent(width: f32) -> u32 {
3254 (width + 0.5).ceil() as u32
3255}
3256
3257fn premultiplied(color: [u8; 4], coverage: u8) -> [u32; 4] {
3260 let alpha = u32::from(coverage) * u32::from(color[3]) / 255;
3261 [
3262 u32::from(color[0]) * alpha / 255,
3263 u32::from(color[1]) * alpha / 255,
3264 u32::from(color[2]) * alpha / 255,
3265 alpha,
3266 ]
3267}
3268
3269fn over(source: [u32; 4], destination: [u32; 4]) -> [u32; 4] {
3270 let keep = 255 - source[3];
3271 std::array::from_fn(|channel| source[channel] + (destination[channel] * keep + 127) / 255)
3272}
3273
3274trait PixelLook {
3275 fn fill(&self, index: usize, point: [f32; 2]) -> [u8; 4];
3277 fn band(&self, stroke: usize, index: usize) -> [u8; 4];
3278 fn fade(&self, _index: usize) -> Option<u32> {
3280 None
3281 }
3282 fn color_alpha(&self, index: usize) -> u32;
3283}
3284
3285struct RequestLook<'a> {
3286 foreground: [u8; 4],
3287 gradient: Option<gradient::PreparedGradient<'a>>,
3288 strokes: &'a [TextStroke],
3289}
3290
3291impl<'a> RequestLook<'a> {
3292 fn of(request: &'a TextRasterRequest, layout_size: [f32; 2]) -> Self {
3293 Self::painting(&request.fill, &request.strokes, layout_size)
3294 }
3295
3296 fn painting(fill: &'a TextFill, strokes: &'a [TextStroke], layout_size: [f32; 2]) -> Self {
3297 Self {
3298 foreground: fill.foreground(),
3299 gradient: match fill {
3300 TextFill::Solid(_) => None,
3301 TextFill::Gradient(gradient) => Some(gradient.prepared(layout_size)),
3302 },
3303 strokes,
3304 }
3305 }
3306}
3307
3308impl PixelLook for RequestLook<'_> {
3309 #[inline]
3310 fn fill(&self, _: usize, point: [f32; 2]) -> [u8; 4] {
3311 self.gradient
3312 .as_ref()
3313 .map_or(self.foreground, |gradient| gradient.rgba8_at(point))
3314 }
3315
3316 #[inline]
3317 fn band(&self, stroke: usize, _: usize) -> [u8; 4] {
3318 self.strokes
3319 .get(stroke)
3320 .map_or([0; 4], |stroke| stroke.color)
3321 }
3322
3323 fn color_alpha(&self, _: usize) -> u32 {
3324 u32::from(self.foreground[3])
3325 }
3326}
3327
3328fn stroke_bands(
3330 request: &TextRasterRequest,
3331 coverage: &[u8],
3332 colors: Option<&[u8]>,
3333 width: u32,
3334) -> Vec<Vec<u8>> {
3335 if request.strokes.is_empty() {
3336 return Vec::new();
3337 }
3338 let height = u32::try_from(coverage.len() / width.max(1) as usize).unwrap_or(0);
3339 let ink = colors.map(|colors| {
3340 coverage
3341 .iter()
3342 .zip(colors.as_chunks::<4>().0)
3343 .map(|(&text, color)| text.max(color[3]))
3344 .collect::<Vec<_>>()
3345 });
3346 let ink = ink.as_deref().unwrap_or(coverage);
3347 let mut radius = 0.0;
3348 request
3349 .strokes
3350 .iter()
3351 .map(|stroke| {
3352 radius += stroke.width;
3353 dilate(ink, width, height, radius)
3354 })
3355 .collect()
3356}
3357
3358type BoxLayer<'a> = (&'a TextBackground, Vec<boxes::LineBox>);
3360
3361#[expect(clippy::cast_precision_loss, reason = "margins are far below 2^24")]
3364fn box_layers<'a>(
3365 request: &'a TextRasterRequest,
3366 margin: [u32; 2],
3367 line_boxes: &[(f32, f32, f32, f32)],
3368 highlight: &[[f32; 4]],
3369) -> (Option<BoxLayer<'a>>, Option<BoxLayer<'a>>) {
3370 let [margin_x, margin_y] = margin.map(|margin| margin as f32);
3371 let background = request.background.as_ref().map(|background| {
3372 let boxes = line_boxes
3373 .iter()
3374 .map(|&(left, width, top, height)| {
3375 boxes::LineBox::padded(
3376 background,
3377 [
3378 margin_x + left,
3379 margin_x + left + width,
3380 margin_y + top,
3381 margin_y + top + height,
3382 ],
3383 )
3384 })
3385 .collect::<Vec<_>>();
3386 (background, boxes)
3387 });
3388 let highlight = request
3389 .highlight
3390 .as_ref()
3391 .filter(|_| !highlight.is_empty())
3392 .map(|request| {
3393 let boxes = highlight
3394 .iter()
3395 .map(|&[left, right, top, bottom]| {
3396 boxes::LineBox::padded(
3397 &request.look,
3398 [
3399 margin_x + left,
3400 margin_x + right,
3401 margin_y + top,
3402 margin_y + bottom,
3403 ],
3404 )
3405 })
3406 .collect::<Vec<_>>();
3407 (&request.look, boxes)
3408 });
3409 (background, highlight)
3410}
3411
3412#[allow(
3416 clippy::cast_possible_truncation,
3417 clippy::cast_sign_loss,
3418 clippy::cast_precision_loss,
3419 clippy::too_many_arguments
3420)]
3421fn compose(
3422 request: &TextRasterRequest,
3423 coverage: &[u8],
3424 colors: Option<&[u8]>,
3425 width: u32,
3426 margin: [u32; 2],
3427 line_boxes: &[(f32, f32, f32, f32)],
3428 run_boxes: &[paint::RunBox],
3429 highlight: &[[f32; 4]],
3430 bands: &[Vec<u8>],
3431 look: &impl PixelLook,
3432) -> (Vec<u8>, Option<Vec<u8>>) {
3433 let (background, highlight) = box_layers(request, margin, line_boxes, highlight);
3434 let split = request.split_background
3435 && (background.is_some() || !run_boxes.is_empty() || highlight.is_some());
3436 let mut split_plane = split.then(|| vec![0_u8; coverage.len() * 4]);
3437 let [margin_x, margin_y] = margin.map(|margin| margin as f32);
3438 let mut row_runs = Vec::<&paint::RunBox>::new();
3439 let mut rgba8 = vec![0_u8; coverage.len() * 4];
3440 let (mut first, mut last) = (0, 0);
3442 for (index, text) in coverage.iter().copied().enumerate() {
3443 let mut pixel = [0_u32; 4];
3444 let x = (index % width as usize) as f32;
3445 let y = (index / width as usize) as f32;
3446 if !run_boxes.is_empty() && index % width as usize == 0 {
3447 row_runs.clear();
3448 row_runs.extend(
3449 run_boxes
3450 .iter()
3451 .filter(|run| margin_y + run.top < y + 1.0 && margin_y + run.bottom > y),
3452 );
3453 }
3454 if let Some((background, boxes)) = &background {
3455 if index % width as usize == 0 {
3456 while first < boxes.len() && boxes[first].bottom <= y {
3457 first += 1;
3458 }
3459 last = last.max(first);
3460 while last < boxes.len() && boxes[last].top < y + 1.0 {
3461 last += 1;
3462 }
3463 }
3464 pixel = boxes::paint(background, &boxes[first..last], [x, y]);
3465 }
3466 if let Some(run) = run_cover(&row_runs, [margin_x, margin_y], [x, y]) {
3467 pixel = over(run, pixel);
3468 }
3469 if let Some((look, boxes)) = &highlight {
3470 let lit = boxes::paint(look, boxes, [x, y]);
3471 if lit[3] > 0 {
3472 pixel = over(lit, pixel);
3473 }
3474 }
3475 if let Some(plane) = &mut split_plane {
3476 for (channel, value) in pixel.iter().enumerate() {
3477 plane[index * 4 + channel] = (*value).min(255) as u8;
3478 }
3479 pixel = [0; 4];
3480 }
3481 let fade = look.fade(index);
3483 let boxes = pixel;
3484 if fade.is_some() {
3485 pixel = [0; 4];
3486 }
3487 for (stroke, band) in bands.iter().enumerate().rev() {
3488 if band[index] > 0 {
3489 pixel = over(premultiplied(look.band(stroke, index), band[index]), pixel);
3490 }
3491 }
3492 if text > 0 {
3493 let fill = look.fill(index, [x + 0.5 - margin_x, y + 0.5 - margin_y]);
3494 pixel = over(premultiplied(fill, text), pixel);
3495 }
3496 if let Some(colors) = colors {
3497 let color = &colors[index * 4..][..4];
3498 if color[3] > 0 {
3499 let opacity = look.color_alpha(index);
3500 pixel = over(
3501 std::array::from_fn(|channel| u32::from(color[channel]) * opacity / 255),
3502 pixel,
3503 );
3504 }
3505 }
3506 if let Some(fade) = fade {
3507 pixel = over(pixel.map(|value| (value * fade + 127) / 255), boxes);
3508 }
3509 for (channel, value) in pixel.iter().enumerate() {
3510 rgba8[index * 4 + channel] = (*value).min(255) as u8;
3511 }
3512 }
3513 (rgba8, split_plane)
3514}
3515
3516#[expect(
3517 clippy::cast_possible_truncation,
3518 clippy::cast_sign_loss,
3519 reason = "coverage in [0, 1] to a byte"
3520)]
3521fn run_cover(
3522 runs: &[&paint::RunBox],
3523 [margin_x, margin_y]: [f32; 2],
3524 [x, y]: [f32; 2],
3525) -> Option<[u32; 4]> {
3526 let (mut best, mut color) = (0.0_f32, [0; 4]);
3527 for run in runs {
3528 let across =
3529 ((margin_x + run.right).min(x + 1.0) - (margin_x + run.left).max(x)).clamp(0.0, 1.0);
3530 let down =
3531 ((margin_y + run.bottom).min(y + 1.0) - (margin_y + run.top).max(y)).clamp(0.0, 1.0);
3532 let covered = across * down;
3533 if covered > 0.0 && covered >= best {
3534 (best, color) = (covered, run.color);
3535 }
3536 }
3537 (best > 0.0).then(|| premultiplied(color, (best * 255.0).round() as u8))
3538}
3539
3540#[allow(
3546 clippy::cast_possible_truncation,
3547 clippy::cast_sign_loss,
3548 clippy::cast_precision_loss,
3549 clippy::cast_possible_wrap
3550)]
3551fn dilate(coverage: &[u8], width: u32, height: u32, radius: f32) -> Vec<u8> {
3552 let (width, height) = (width as usize, height as usize);
3553 let mut band = vec![0_u8; coverage.len()];
3554 let Some(ink) = ink_bounds(coverage, width, height) else {
3555 return band;
3556 };
3557 let disc = Disc::new(radius);
3558 let extent = disc.extent;
3559 let reach = Bounds {
3560 left: ink.left.saturating_sub(extent),
3561 top: ink.top.saturating_sub(extent),
3562 right: (ink.right + extent).min(width),
3563 bottom: (ink.bottom + extent).min(height),
3564 };
3565 let span = reach.right - reach.left;
3567 let mut window = WindowMax::default();
3568 let mut maxima = vec![0_u8; span];
3569 for (half, offsets) in &disc.runs {
3570 for source_y in ink.top..ink.bottom {
3571 let row = &coverage[source_y * width..(source_y + 1) * width];
3572 window.of(row, reach.left, span, *half, &mut maxima);
3573 for &offset in offsets {
3574 let Some(y) = source_y.checked_add_signed(-offset) else {
3575 continue;
3576 };
3577 if y < reach.top || y >= reach.bottom {
3578 continue;
3579 }
3580 let out = &mut band[y * width + reach.left..y * width + reach.right];
3581 for (pixel, highest) in out.iter_mut().zip(&maxima) {
3582 *pixel = (*pixel).max(*highest);
3583 }
3584 }
3585 }
3586 }
3587 for &(dx, dy, weight) in &disc.rim {
3588 for source_y in ink.top..ink.bottom {
3589 let Some(y) = source_y.checked_add_signed(-dy) else {
3590 continue;
3591 };
3592 if y >= height {
3593 continue;
3594 }
3595 let first = ink.left.max(usize::try_from(dx).unwrap_or(0));
3597 let last = ink
3598 .right
3599 .min(usize::try_from(width as isize + dx.min(0)).unwrap_or(0));
3600 if first >= last {
3601 continue;
3602 }
3603 let source = &coverage[source_y * width + first..source_y * width + last];
3604 let start = y * width + (first as isize - dx) as usize;
3605 let out = &mut band[start..start + source.len()];
3606 for (pixel, value) in out.iter_mut().zip(source) {
3607 *pixel = (*pixel).max((u32::from(*value) * weight / 255) as u8);
3608 }
3609 }
3610 }
3611 band
3612}
3613
3614#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3616struct Bounds {
3617 left: usize,
3618 top: usize,
3619 right: usize,
3620 bottom: usize,
3621}
3622
3623fn ink_bounds(coverage: &[u8], width: usize, height: usize) -> Option<Bounds> {
3624 let mut bounds: Option<Bounds> = None;
3625 for y in 0..height {
3626 let row = &coverage[y * width..(y + 1) * width];
3627 let Some(left) = row.iter().position(|&value| value > 0) else {
3628 continue;
3629 };
3630 let right = row.iter().rposition(|&value| value > 0).unwrap_or(left) + 1;
3631 bounds = Some(bounds.map_or(
3632 Bounds {
3633 left,
3634 top: y,
3635 right,
3636 bottom: y + 1,
3637 },
3638 |bounds| Bounds {
3639 left: bounds.left.min(left),
3640 top: bounds.top,
3641 right: bounds.right.max(right),
3642 bottom: y + 1,
3643 },
3644 ));
3645 }
3646 bounds
3647}
3648
3649struct Disc {
3651 extent: usize,
3652 runs: Vec<(usize, Vec<isize>)>,
3654 rim: Vec<(isize, isize, u32)>,
3656}
3657
3658impl Disc {
3659 #[allow(
3661 clippy::cast_possible_truncation,
3662 clippy::cast_sign_loss,
3663 clippy::cast_precision_loss,
3664 clippy::cast_possible_wrap
3665 )]
3666 fn new(radius: f32) -> Self {
3667 let extent = disc_extent(radius) as isize;
3668 let mut runs: Vec<(usize, Vec<isize>)> = Vec::new();
3669 let mut rim = Vec::new();
3670 for dy in -extent..=extent {
3671 let mut half = None;
3672 for dx in -extent..=extent {
3673 let distance = ((dx * dx + dy * dy) as f32).sqrt();
3674 let weight = ((radius + 0.5 - distance).clamp(0.0, 1.0) * 255.0).round() as u32;
3675 match weight {
3676 0 => {}
3677 255 => half = Some(dx.unsigned_abs()),
3679 _ => rim.push((dx, dy, weight)),
3680 }
3681 }
3682 if let Some(half) = half {
3683 match runs.iter_mut().find(|(run, _)| *run == half) {
3684 Some((_, offsets)) => offsets.push(dy),
3685 None => runs.push((half, vec![dy])),
3686 }
3687 }
3688 }
3689 Self {
3690 extent: extent as usize,
3691 runs,
3692 rim,
3693 }
3694 }
3695}
3696
3697#[derive(Default)]
3699struct WindowMax {
3700 padded: Vec<u8>,
3701 from_start: Vec<u8>,
3702 to_end: Vec<u8>,
3703}
3704
3705impl WindowMax {
3706 fn of(&mut self, row: &[u8], left: usize, count: usize, half: usize, out: &mut [u8]) {
3708 let window = 2 * half + 1;
3709 let length = count + 2 * half;
3710 self.padded.clear();
3711 self.padded.resize(length, 0);
3712 let first_column = left.saturating_sub(half);
3714 let last_column = (left + count + half).min(row.len());
3715 if first_column < last_column {
3716 let at = first_column + half - left;
3717 self.padded[at..at + last_column - first_column]
3718 .copy_from_slice(&row[first_column..last_column]);
3719 }
3720 self.from_start.clear();
3721 self.from_start.resize(length, 0);
3722 self.to_end.clear();
3723 self.to_end.resize(length, 0);
3724 for block in (0..length).step_by(window) {
3725 let end = (block + window).min(length);
3726 let mut highest = 0;
3727 for index in block..end {
3728 highest = highest.max(self.padded[index]);
3729 self.from_start[index] = highest;
3730 }
3731 highest = 0;
3732 for index in (block..end).rev() {
3733 highest = highest.max(self.padded[index]);
3734 self.to_end[index] = highest;
3735 }
3736 }
3737 for (index, value) in out[..count].iter_mut().enumerate() {
3738 *value = self.to_end[index].max(self.from_start[index + window - 1]);
3739 }
3740 }
3741}
3742
3743#[cfg(test)]
3744mod tests;
3745
3746#[cfg(test)]
3747#[path = "clamp_tests.rs"]
3748mod clamp_tests;
3749
3750#[cfg(test)]
3751#[path = "runs_tests.rs"]
3752mod runs_tests;
3753
3754#[cfg(test)]
3755#[path = "box_tests.rs"]
3756mod box_tests;