1use alloc::string::String;
61use alloc::vec;
62use alloc::vec::Vec;
63
64use font_model::{Font, GlyphId};
65
66use crate::error::ShapeError;
67use crate::glyph::DeviceMetrics;
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71pub enum LayoutDirection {
72 #[default]
74 LeftToRight,
75 RightToLeft,
77 Auto,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum BidiClass {
90 L,
92 R,
94 Al,
96 En,
98 An,
100 Nsm,
102 Et,
105 Other,
107}
108
109impl BidiClass {
110 #[must_use]
112 pub const fn is_strong(self) -> bool {
113 matches!(self, BidiClass::L | BidiClass::R | BidiClass::Al)
114 }
115
116 #[must_use]
118 pub const fn is_rtl(self) -> bool {
119 matches!(self, BidiClass::R | BidiClass::Al)
120 }
121}
122
123#[must_use]
136pub fn bidi_class(ch: char) -> BidiClass {
137 let c = ch as u32;
138 match c {
139 0x0300..=0x036F
146 | 0x0483..=0x0489
147 | 0x0591..=0x05C7
148 | 0x0610..=0x061A
149 | 0x064B..=0x065F
150 | 0x0670
151 | 0x06D6..=0x06DC => BidiClass::Nsm,
152 0x0590..=0x05FF => BidiClass::R, 0x0600..=0x07BF => {
154 match c {
157 0x0660..=0x0669 | 0x06F0..=0x06F9 | 0x066B | 0x066C | 0x06DD => BidiClass::An,
158 _ => BidiClass::Al,
159 }
160 }
161 0xFB1D..=0xFB4F => BidiClass::R, 0xFB50..=0xFDFF => BidiClass::Al, 0xFE70..=0xFEFF => BidiClass::Al, 0x200B..=0x200D => BidiClass::Other, 0x2010..=0x2027 => BidiClass::Other, 0x2000..=0x200A | 0x2028 | 0x2029 | 0x205F | 0x3000 => BidiClass::Other,
167 0x30FB => BidiClass::Other, 0x20A0..=0x20CF => BidiClass::Et, 0x00A2..=0x00A5 | 0x00B0 | 0x00B1 => BidiClass::Et, 0x0030..=0x0039 => BidiClass::En,
171 0x00B2 | 0x00B3 | 0x00B9 => BidiClass::En, 0x2070 | 0x2074..=0x2079 => BidiClass::En,
173 0xFF10..=0xFF19 => BidiClass::En, 0x0000..=0x002F | 0x003A..=0x0040 | 0x005B..=0x0060 | 0x007B..=0x007E => BidiClass::Other,
179 0x00A0..=0x00BF => match c {
180 0x00A2..=0x00A5 | 0x00B0 | 0x00B1 => BidiClass::Et,
181 _ => BidiClass::Other,
182 },
183 0x2030..=0x205E => BidiClass::Other, 0x2100..=0x214F => BidiClass::Other, 0x2190..=0x2BFF => BidiClass::Other, 0xFB00..=0xFB17 => BidiClass::Other, _ => BidiClass::L,
188 }
189}
190
191#[must_use]
194pub const fn is_rtl_level(level: u8) -> bool {
195 level % 2 == 1
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct BidiLevels {
201 pub levels: Vec<u8>,
203 pub paragraph_level: u8,
205}
206
207impl BidiLevels {
208 #[must_use]
210 pub fn level(&self, index: usize) -> u8 {
211 self.levels
212 .get(index)
213 .copied()
214 .unwrap_or(self.paragraph_level)
215 }
216
217 #[must_use]
223 pub fn visual_order(&self) -> Vec<usize> {
224 reorder_indices(&self.levels)
225 }
226}
227
228#[must_use]
241pub fn reorder_indices(levels: &[u8]) -> Vec<usize> {
242 let n = levels.len();
243 let mut order: Vec<usize> = (0..n).collect();
244 if n == 0 {
245 return order;
246 }
247 let mut lowest_odd = u8::MAX;
249 for &l in levels {
250 if l % 2 == 1 && l < lowest_odd {
251 lowest_odd = l;
252 }
253 }
254 if lowest_odd == u8::MAX {
255 return order;
256 }
257 let highest = levels.iter().copied().fold(0u8, |a, b| a.max(b));
262 let level_of = |slot: usize, order: &[usize]| -> Option<u8> {
263 order.get(slot).and_then(|&j| levels.get(j)).copied()
264 };
265 let mut level = highest;
266 while level >= lowest_odd {
267 let at_level = |slot: usize, order: &[usize]| -> bool {
268 level_of(slot, order).is_some_and(|l| l >= level)
269 };
270 let mut i = 0usize;
271 while i < n {
272 if at_level(i, &order) {
273 let start = i;
274 while i < n && at_level(i, &order) {
275 i += 1;
276 }
277 if let Some(run) = order.get_mut(start..i) {
278 run.reverse();
279 }
280 } else {
281 i += 1;
282 }
283 }
284 if level == 0 {
285 break;
286 }
287 level -= 1;
288 }
289 order
290}
291
292#[must_use]
336pub fn resolve_bidi(text: &str) -> BidiLevels {
337 let chars: Vec<char> = text.chars().collect();
338 resolve_bidi_chars(&chars)
339}
340
341#[must_use]
344pub fn resolve_bidi_chars(chars: &[char]) -> BidiLevels {
345 let paragraph_level = paragraph_level_for(chars);
346 let mut classes: Vec<BidiClass> = chars.iter().copied().map(bidi_class).collect();
347 apply_w_rules(chars, &mut classes);
348
349 let base_rtl = is_rtl_level(paragraph_level);
354 let resolved: Vec<BidiClass> = classes
355 .iter()
356 .enumerate()
357 .map(|(i, &cls)| {
358 if matches!(
359 cls,
360 BidiClass::L | BidiClass::R | BidiClass::En | BidiClass::An
361 ) {
362 cls
363 } else {
364 neutral_direction(
365 cls,
366 i.checked_sub(1).and_then(|k| classes.get(k).copied()),
367 classes.get(i + 1).copied(),
368 base_rtl,
369 )
370 }
371 })
372 .collect();
373
374 let mut levels: Vec<u8> = resolved
376 .iter()
377 .map(|&cls| implicit_level(cls, base_rtl, paragraph_level))
378 .collect();
379 for (level, ch) in levels.iter_mut().rev().zip(chars.iter().rev()) {
383 if is_separator(*ch) || ch.is_whitespace() {
384 *level = paragraph_level;
385 } else {
386 break;
387 }
388 }
389 BidiLevels {
390 levels,
391 paragraph_level,
392 }
393}
394
395fn is_separator(ch: char) -> bool {
397 matches!(ch, '\u{2029}' | '\u{2028}' | '\r' | '\n')
398}
399
400fn paragraph_level_for(chars: &[char]) -> u8 {
403 for &ch in chars {
404 match bidi_class(ch) {
405 BidiClass::L => return 0,
406 BidiClass::R | BidiClass::Al => return 1,
407 _ => {}
408 }
409 }
410 0
411}
412
413fn apply_w_rules(chars: &[char], classes: &mut [BidiClass]) {
415 let mut prev = BidiClass::Other;
417 for cls in classes.iter_mut() {
418 if *cls == BidiClass::Nsm {
419 *cls = prev;
420 }
421 prev = *cls;
422 }
423 let mut last_strong: Option<BidiClass> = None;
426 for cls in classes.iter_mut() {
427 if cls.is_strong() {
428 last_strong = Some(*cls);
429 }
430 if *cls == BidiClass::En && last_strong == Some(BidiClass::Al) {
431 *cls = BidiClass::An;
432 }
433 }
434 for cls in classes.iter_mut() {
436 if *cls == BidiClass::Al {
437 *cls = BidiClass::R;
438 }
439 }
440 let snapshot: Vec<BidiClass> = classes.to_vec();
445 let is_number = |c: BidiClass| matches!(c, BidiClass::En | BidiClass::An);
446 for i in 1..snapshot.len().saturating_sub(1) {
449 let (Some(&before), Some(&after), Some(&ch)) =
450 (snapshot.get(i - 1), snapshot.get(i + 1), chars.get(i))
451 else {
452 continue;
453 };
454 if !is_common_separator(ch) || !is_number(before) || before != after {
455 continue;
456 }
457 if let Some(slot) = classes.get_mut(i) {
458 *slot = before;
459 }
460 }
461 let snapshot: Vec<BidiClass> = classes.to_vec();
463 let is_et = |i: usize| snapshot.get(i) == Some(&BidiClass::Et);
464 let mut i = 0usize;
465 while i < snapshot.len() {
466 if !is_et(i) {
467 i += 1;
468 continue;
469 }
470 let start = i;
471 while i < snapshot.len() && is_et(i) {
472 i += 1;
473 }
474 let before_en = start > 0 && snapshot.get(start - 1) == Some(&BidiClass::En);
475 let after_en = snapshot.get(i) == Some(&BidiClass::En);
476 if before_en || after_en {
477 for slot in classes.iter_mut().take(i).skip(start) {
478 if *slot == BidiClass::Et {
479 *slot = BidiClass::En;
480 }
481 }
482 }
483 }
484 for cls in classes.iter_mut() {
486 if *cls == BidiClass::Et {
487 *cls = BidiClass::Other;
488 }
489 }
490 let mut last_strong = None;
492 for cls in classes.iter_mut() {
493 if cls.is_strong() {
494 last_strong = Some(*cls);
495 }
496 if *cls == BidiClass::En && last_strong == Some(BidiClass::L) {
497 *cls = BidiClass::L;
498 }
499 }
500}
501
502fn is_common_separator(ch: char) -> bool {
505 matches!(
506 ch,
507 ',' | '.'
508 | '/'
509 | ':'
510 | '\u{060C}'
511 | '\u{202F}'
512 | '\u{2044}'
513 | '\u{FF0C}'
514 | '\u{FF0E}'
515 | '\u{FF1A}'
516 )
517}
518
519fn neutral_direction(
527 _cls: BidiClass,
528 prev: Option<BidiClass>,
529 next: Option<BidiClass>,
530 base_rtl: bool,
531) -> BidiClass {
532 let side = |c: Option<BidiClass>| -> Option<BidiClass> {
533 match c {
534 Some(BidiClass::En) | Some(BidiClass::An) => {
535 Some(if base_rtl { BidiClass::R } else { BidiClass::L })
536 }
537 Some(BidiClass::L) | Some(BidiClass::R) => c,
538 _ => None,
539 }
540 };
541 let base = if base_rtl { BidiClass::R } else { BidiClass::L };
542 match (side(prev), side(next)) {
543 (Some(b), Some(a)) if b == a => b,
544 _ => base,
545 }
546}
547
548fn implicit_level(cls: BidiClass, base_rtl: bool, paragraph_level: u8) -> u8 {
556 let number = matches!(cls, BidiClass::En | BidiClass::An);
557 if base_rtl {
558 if cls.is_rtl() && !number {
559 paragraph_level
560 } else {
561 paragraph_level + 1
562 }
563 } else if cls.is_rtl() {
564 paragraph_level + 1
565 } else if number {
566 paragraph_level + 2
567 } else {
568 paragraph_level
569 }
570}
571
572#[derive(Debug, Clone, PartialEq)]
574pub struct GlyphPlacement {
575 pub glyph: GlyphId,
577 pub cluster: u32,
582 pub level: u8,
584 pub x: f32,
586 pub y: f32,
588 pub x_offset: f32,
591 pub advance_px: f32,
593}
594
595impl GlyphPlacement {
596 #[must_use]
598 pub fn origin_px(&self) -> (f32, f32) {
599 (self.x + self.x_offset, self.y)
600 }
601
602 #[must_use]
604 pub const fn is_rtl(&self) -> bool {
605 is_rtl_level(self.level)
606 }
607}
608
609#[derive(Debug, Clone, PartialEq, Default)]
611pub struct ShapedLine {
612 placements: Vec<GlyphPlacement>,
613 advance_px: f32,
614 ascent_px: f32,
615 descent_px: f32,
616 line_height_px: f32,
617 ink_left_px: Option<f32>,
618 ink_right_px: Option<f32>,
619 paragraph_level: u8,
620}
621
622impl ShapedLine {
623 #[must_use]
625 pub const fn empty() -> Self {
626 ShapedLine {
627 placements: Vec::new(),
628 advance_px: 0.0,
629 ascent_px: 0.0,
630 descent_px: 0.0,
631 line_height_px: 0.0,
632 ink_left_px: None,
633 ink_right_px: None,
634 paragraph_level: 0,
635 }
636 }
637
638 #[must_use]
641 pub fn placements(&self) -> &[GlyphPlacement] {
642 &self.placements
643 }
644
645 #[must_use]
647 pub fn into_placements(self) -> Vec<GlyphPlacement> {
648 self.placements
649 }
650
651 #[must_use]
653 pub fn len(&self) -> usize {
654 self.placements.len()
655 }
656
657 #[must_use]
659 pub fn is_empty(&self) -> bool {
660 self.placements.is_empty()
661 }
662
663 #[must_use]
665 pub fn get(&self, index: usize) -> Option<&GlyphPlacement> {
666 self.placements.get(index)
667 }
668
669 #[must_use]
671 pub const fn advance_px(&self) -> f32 {
672 self.advance_px
673 }
674
675 #[must_use]
677 pub const fn ascent_px(&self) -> f32 {
678 self.ascent_px
679 }
680
681 #[must_use]
683 pub const fn descent_px(&self) -> f32 {
684 self.descent_px
685 }
686
687 #[must_use]
689 pub const fn line_height_px(&self) -> f32 {
690 self.line_height_px
691 }
692
693 #[must_use]
696 pub const fn ink_extent_px(&self) -> Option<(f32, f32)> {
697 match (self.ink_left_px, self.ink_right_px) {
698 (Some(l), Some(r)) => Some((l, r)),
699 _ => None,
700 }
701 }
702
703 #[must_use]
705 pub const fn paragraph_level(&self) -> u8 {
706 self.paragraph_level
707 }
708
709 #[must_use]
711 pub const fn metrics(&self) -> DeviceMetrics {
712 DeviceMetrics {
713 ascent: self.ascent_px,
714 descent: self.descent_px,
715 line_gap: self.line_height_px - self.ascent_px - self.descent_px,
716 line_height: self.line_height_px,
717 }
718 }
719
720 #[must_use]
726 pub fn by_cluster(&self) -> Vec<(u32, Vec<&GlyphPlacement>)> {
727 let mut clusters: Vec<(u32, Vec<&GlyphPlacement>)> = Vec::new();
728 for p in &self.placements {
729 match clusters.last_mut() {
730 Some((c, list)) if *c == p.cluster => list.push(p),
731 _ => clusters.push((p.cluster, vec![p])),
732 }
733 }
734 clusters.sort_by_key(|(cluster, _)| *cluster);
735 clusters
736 }
737}
738
739pub fn set_explicit_levels(levels: &mut [u8], explicit: &[u8]) {
760 for (slot, &v) in levels.iter_mut().zip(explicit.iter()) {
761 *slot = if v > 8 { 8 } else { v };
762 }
763}
764
765#[allow(clippy::result_large_err)]
787pub fn measure_glyph(font: &Font, glyph: GlyphId, size_px: f32) -> Result<f32, ShapeError> {
788 if !size_px.is_finite() || size_px <= 0.0 {
789 return Err(ShapeError::InvalidScale { scale: size_px });
790 }
791 let g = font.glyph(glyph).ok_or(ShapeError::UnknownGlyph {
792 glyph: glyph.to_u32(),
793 glyph_count: font.glyph_count(),
794 })?;
795 let scale = size_px / f32::from(font.units_per_em().max(1));
796 Ok(f32::from(g.advance_width()) * scale)
797}
798
799#[allow(clippy::result_large_err)]
831pub fn measure_run(font: &Font, text: &str, size_px: f32) -> Result<f32, ShapeError> {
832 if !size_px.is_finite() || size_px <= 0.0 {
833 return Err(ShapeError::InvalidScale { scale: size_px });
834 }
835 let scale = size_px / f32::from(font.units_per_em().max(1));
836 let mut pen = 0.0f32;
837 let mut prev: Option<GlyphId> = None;
838 for ch in text.chars() {
839 let glyph = glyph_for_char(font, ch);
840 pen += f32::from(advance_of(font, glyph)) * scale;
841 if let Some(p) = prev {
842 pen += f32::from(font.kern(p, glyph)) * scale;
843 }
844 prev = Some(glyph);
845 }
846 Ok(pen)
847}
848
849#[allow(clippy::result_large_err)]
884pub fn shape_line(font: &Font, text: &str, size_px: f32) -> Result<ShapedLine, ShapeError> {
885 shape_line_with(font, text, size_px, LayoutDirection::LeftToRight)
886}
887
888#[allow(clippy::result_large_err)]
916pub fn shape_line_with(
917 font: &Font,
918 text: &str,
919 size_px: f32,
920 direction: LayoutDirection,
921) -> Result<ShapedLine, ShapeError> {
922 if !size_px.is_finite() || size_px <= 0.0 {
923 return Err(ShapeError::InvalidScale { scale: size_px });
924 }
925 let metrics = crate::glyph::scaled_metrics(font, size_px)?;
926 let scale = size_px / f32::from(font.units_per_em().max(1));
927 let chars: Vec<char> = text.chars().collect();
928
929 let mut bidi = resolve_bidi_chars(&chars);
930 if direction == LayoutDirection::RightToLeft {
931 bidi.paragraph_level = 1;
932 for level in bidi.levels.iter_mut() {
933 *level = (*level & 0xFE) | 1;
934 }
935 }
936 let mut logical: Vec<GlyphPlacement> = Vec::with_capacity(chars.len());
939 let mut pen = 0.0f32;
940 let mut prev: Option<GlyphId> = None;
941 for (i, &ch) in chars.iter().enumerate() {
942 let glyph = glyph_for_char(font, ch);
943 let advance = f32::from(advance_of(font, glyph)) * scale;
944 let kern = match prev {
945 Some(p) => f32::from(font.kern(p, glyph)) * scale,
946 None => 0.0,
947 };
948 logical.push(GlyphPlacement {
949 glyph,
950 cluster: i as u32,
951 level: bidi.level(i),
952 x: pen + kern,
953 y: 0.0,
954 x_offset: 0.0,
955 advance_px: advance,
956 });
957 pen += advance + kern;
958 prev = Some(glyph);
959 }
960
961 let order = bidi.visual_order();
964 let placements: Vec<GlyphPlacement> = order
965 .iter()
966 .filter_map(|i| logical.get(*i).cloned())
967 .collect();
968
969 Ok(ShapedLine {
970 placements,
971 advance_px: pen,
972 ascent_px: metrics.ascent,
973 descent_px: metrics.descent,
974 line_height_px: metrics.line_height,
975 ink_left_px: None,
976 ink_right_px: None,
977 paragraph_level: bidi.paragraph_level,
978 })
979}
980
981pub fn ascii_cmap() -> font_model::Cmap {
984 let mut cmap = font_model::Cmap::format4();
985 for (cp, gid) in [
986 (b'A' as u32, GlyphId::new(1)),
987 (b'B' as u32, GlyphId::new(2)),
988 ] {
989 let updated = cmap
993 .subtables()
994 .first()
995 .map_or_else(font_model::CmapSubtable::empty_format4, |sub| {
996 font_model::insert_entry(sub, cp, gid)
997 });
998 if let Some(slot) = cmap.subtables_mut().first_mut() {
999 *slot = updated;
1000 }
1001 }
1002 cmap
1003}
1004
1005fn glyph_for_char(font: &Font, ch: char) -> GlyphId {
1007 font.glyph_for(ch as u32)
1008 .or_else(|| font.notdef().map(|g| g.id()))
1009 .unwrap_or(GlyphId::NOTDEF)
1010}
1011
1012fn advance_of(font: &Font, glyph: GlyphId) -> u16 {
1014 font.glyph(glyph)
1015 .map_or(0, font_model::Glyph::advance_width)
1016}
1017
1018#[must_use]
1020pub fn describe_run(font: &Font, text: &str, size_px: f32) -> String {
1021 let mut s = String::new();
1022 for ch in text.chars() {
1023 s.push(ch);
1024 }
1025 let advance = measure_run(font, text, size_px).unwrap_or(0.0);
1026 alloc::format!("{s:?} at {size_px}px = {advance:.2}px")
1027}
1028
1029#[cfg(test)]
1030mod tests {
1031 #![allow(
1032 clippy::unwrap_used,
1033 clippy::expect_used,
1034 clippy::panic,
1035 clippy::indexing_slicing,
1036 clippy::float_cmp
1037 )]
1038 use super::{
1039 bidi_class, measure_glyph, measure_run, reorder_indices, resolve_bidi, resolve_bidi_chars,
1040 set_explicit_levels, shape_line, shape_line_with, BidiClass, LayoutDirection, ShapedLine,
1041 };
1042 use crate::error::ShapeError;
1043 use alloc::string::String;
1044 use alloc::vec;
1045 use alloc::vec::Vec;
1046 use font_model::{Font, Glyph, GlyphId};
1047
1048 fn close(a: f32, b: f32) -> bool {
1052 (a - b).abs() < 1e-3
1053 }
1054
1055 fn blank_font(widths: &[(u32, u16)]) -> Font {
1058 let mut font = Font::builder().units_per_em(1000);
1059 font = font.glyph(Glyph::empty(GlyphId::NOTDEF, 500));
1060 let mut cmap = font_model::Cmap::format4();
1061 for (cp, w) in widths {
1062 let index = widths.iter().position(|(c, _)| c == cp).unwrap_or(0);
1063 let gid = GlyphId::new(index as u16 + 1);
1064 let g = Glyph::empty(gid, *w);
1065 font = font.glyph(g);
1066 cmap.subtables_mut()[0] = font_model::insert_entry(&cmap.subtables()[0], *cp, gid);
1067 }
1068 font.cmap(cmap).build().expect("font")
1069 }
1070
1071 #[test]
1072 fn bidi_class_covers_the_script_families() {
1073 assert_eq!(bidi_class('a'), BidiClass::L);
1074 assert_eq!(bidi_class('Z'), BidiClass::L);
1075 assert_eq!(bidi_class('\u{4E00}'), BidiClass::L, "CJK is L");
1076 assert_eq!(bidi_class('\u{05D0}'), BidiClass::R, "Hebrew");
1077 assert_eq!(bidi_class('\u{0627}'), BidiClass::Al, "Arabic");
1078 assert_eq!(bidi_class('\u{0660}'), BidiClass::An, "Arabic-Indic digit");
1079 assert_eq!(
1080 bidi_class('\u{06F0}'),
1081 BidiClass::An,
1082 "extended Arabic digit"
1083 );
1084 assert_eq!(bidi_class('7'), BidiClass::En);
1085 assert_eq!(bidi_class('\u{FF10}'), BidiClass::En, "fullwidth digit");
1086 assert_eq!(bidi_class('\u{0301}'), BidiClass::Nsm);
1087 assert_eq!(bidi_class(' '), BidiClass::Other);
1088 assert_eq!(
1089 bidi_class('.'),
1090 BidiClass::Other,
1091 "ASCII period is a neutral"
1092 );
1093 assert_eq!(bidi_class('-'), BidiClass::Other, "and so is a hyphen");
1094 assert_eq!(bidi_class('\u{20AC}'), BidiClass::Et, "euro sign");
1095 assert!(BidiClass::L.is_strong() && BidiClass::R.is_strong());
1097 assert!(BidiClass::Al.is_strong());
1098 assert!(!BidiClass::En.is_strong() && !BidiClass::Nsm.is_strong());
1099 assert!(!BidiClass::L.is_rtl() && BidiClass::R.is_rtl() && BidiClass::Al.is_rtl());
1100 assert!(!BidiClass::En.is_rtl());
1101 }
1102
1103 #[test]
1104 fn rtl_level_test() {
1105 assert!(super::is_rtl_level(1));
1106 assert!(!super::is_rtl_level(0));
1107 assert!(super::is_rtl_level(3) && !super::is_rtl_level(2));
1108 }
1109
1110 #[test]
1111 fn pure_ltr_resolves_to_level_zero() {
1112 let b = resolve_bidi("hello world");
1113 assert_eq!(b.paragraph_level, 0);
1114 assert!(b.levels.iter().all(|&l| l == 0), "{b:?}");
1115 assert_eq!(b.visual_order(), (0..11).collect::<Vec<_>>());
1116 assert_eq!(b.level(0), 0);
1117 assert_eq!(b.level(999), 0);
1119 }
1120
1121 #[test]
1122 fn leading_rtl_sets_the_paragraph_to_rtl() {
1123 let b = resolve_bidi("\u{05D0}\u{05D1}abc");
1124 assert_eq!(b.paragraph_level, 1);
1125 assert_eq!(b.levels, vec![1, 1, 2, 2, 2], "{b:?}");
1126 assert_eq!(b.visual_order(), vec![2, 3, 4, 1, 0]);
1129 let visual: String = b
1131 .visual_order()
1132 .into_iter()
1133 .filter_map(|i| "\u{05D0}\u{05D1}abc".chars().nth(i))
1134 .collect();
1135 assert_eq!(visual, "abc\u{05D1}\u{05D0}");
1136 }
1137
1138 #[test]
1139 fn embedded_rtl_in_ltr_reverses_only_its_run() {
1140 let b = resolve_bidi("a\u{05D0}\u{05D1}b");
1141 assert_eq!(b.paragraph_level, 0);
1142 assert_eq!(b.levels, vec![0, 1, 1, 0], "{b:?}");
1143 assert_eq!(b.visual_order(), vec![0, 2, 1, 3]);
1146 let visual: String = b
1147 .visual_order()
1148 .into_iter()
1149 .filter_map(|i| "a\u{05D0}\u{05D1}b".chars().nth(i))
1150 .collect();
1151 assert_eq!(visual, "a\u{05D1}\u{05D0}b");
1152 }
1153
1154 #[test]
1155 fn numbers_inside_rtl_take_an_even_level() {
1156 let b = resolve_bidi("\u{05D0}5\u{05D1}");
1157 assert_eq!(b.levels, vec![1, 2, 1], "{b:?}");
1158 assert_eq!(b.visual_order(), vec![2, 1, 0]);
1161 let visual: String = b
1162 .visual_order()
1163 .into_iter()
1164 .filter_map(|i| "\u{05D0}5\u{05D1}".chars().nth(i))
1165 .collect();
1166 assert_eq!(visual, "\u{05D1}5\u{05D0}");
1167 }
1168
1169 #[test]
1170 fn numbers_inside_ltr_stay_ltr() {
1171 let b = resolve_bidi("a5b");
1172 assert_eq!(b.levels, vec![0, 0, 0], "{b:?}");
1173 assert_eq!(b.visual_order(), vec![0, 1, 2]);
1174 }
1175
1176 #[test]
1177 fn a_neutral_between_mixed_strong_runs_resolves_to_the_base() {
1178 let b = resolve_bidi("a \u{05D0}");
1181 assert_eq!(b.paragraph_level, 0);
1182 assert_eq!(b.levels, vec![0, 0, 1], "{b:?}");
1183 }
1184
1185 #[test]
1186 fn a_neutral_between_two_ltr_stays_ltr() {
1187 let b = resolve_bidi("a b");
1188 assert_eq!(b.levels, vec![0, 0, 0], "{b:?}");
1189 }
1190
1191 #[test]
1192 fn combining_marks_take_their_neighbour_direction() {
1193 let b = resolve_bidi("\u{05D0}\u{05B0}");
1195 assert_eq!(b.levels, vec![1, 1], "mark after Hebrew is RTL: {b:?}");
1196 let b = resolve_bidi("a\u{0301}");
1197 assert_eq!(b.levels, vec![0, 0], "mark after Latin is LTR: {b:?}");
1198 }
1199
1200 #[test]
1201 fn reorder_indices_is_the_identity_for_uniform_levels() {
1202 assert_eq!(reorder_indices(&[]), Vec::<usize>::new());
1203 assert_eq!(reorder_indices(&[0]), vec![0]);
1204 assert_eq!(reorder_indices(&[0, 0, 0, 0]), vec![0, 1, 2, 3]);
1205 assert_eq!(reorder_indices(&[1, 1, 1, 1]), vec![3, 2, 1, 0]);
1206 assert_eq!(reorder_indices(&[2, 2, 2]), vec![0, 1, 2]);
1207 }
1208
1209 #[test]
1210 fn reorder_handles_nested_levels() {
1211 assert_eq!(reorder_indices(&[0, 1, 2, 2, 1]), vec![0, 4, 2, 3, 1]);
1215 assert_eq!(reorder_indices(&[0, 1, 1, 0]), vec![0, 2, 1, 3]);
1217 }
1218
1219 #[test]
1220 fn set_explicit_levels_clamps_and_applies() {
1221 let mut b = resolve_bidi("AB");
1222 set_explicit_levels(&mut b.levels, &[1, 1]);
1223 assert_eq!(b.levels, vec![1, 1]);
1224 assert_eq!(b.visual_order(), vec![1, 0]);
1225 set_explicit_levels(&mut b.levels, &[99, 4]);
1226 assert_eq!(b.levels, vec![8, 4]);
1227 set_explicit_levels(&mut b.levels, &[0]);
1229 assert_eq!(b.levels, vec![0, 4]);
1230 }
1231
1232 #[test]
1233 fn measure_glyph_scales_the_advance() {
1234 let font = blank_font(&[(b'A' as u32, 600)]);
1235 assert!(close(
1236 measure_glyph(&font, GlyphId::new(1), 50.0).expect("ok"),
1237 30.0
1238 ));
1239 assert!(close(
1240 measure_glyph(&font, GlyphId::new(1), 10.0).expect("ok"),
1241 6.0
1242 ));
1243 assert!(matches!(
1245 measure_glyph(&font, GlyphId::new(1), 0.0),
1246 Err(ShapeError::InvalidScale { .. })
1247 ));
1248 match measure_glyph(&font, GlyphId::new(9), 12.0).unwrap_err() {
1249 ShapeError::UnknownGlyph { glyph, glyph_count } => {
1250 assert_eq!(glyph, 9);
1251 assert_eq!(glyph_count, 2);
1252 }
1253 other => panic!("expected UnknownGlyph, got {other:?}"),
1254 }
1255 }
1256
1257 #[test]
1258 fn numbers_keep_their_order_inside_an_rtl_paragraph() {
1259 let b = resolve_bidi("\u{05D0}1.5\u{05D1}");
1262 assert_eq!(b.levels, vec![1, 2, 2, 2, 1], "{b:?}");
1263 let visual: String = b
1264 .visual_order()
1265 .into_iter()
1266 .filter_map(|i| "\u{05D0}1.5\u{05D1}".chars().nth(i))
1267 .collect();
1268 assert_eq!(visual, "\u{05D1}1.5\u{05D0}");
1269 }
1270
1271 #[test]
1272 fn arabic_digits_inside_arabic_text_stay_in_place() {
1273 let text = "\u{0627}\u{0661}\u{0628}\u{0662}\u{0627}";
1276 let b = resolve_bidi(text);
1277 assert_eq!(b.levels, vec![1, 2, 1, 2, 1], "{b:?}");
1278 let visual: String = b
1279 .visual_order()
1280 .into_iter()
1281 .filter_map(|i| text.chars().nth(i))
1282 .collect();
1283 assert_eq!(visual, "\u{0627}\u{0662}\u{0628}\u{0661}\u{0627}");
1284 }
1285
1286 #[test]
1287 fn measure_run_sums_advances_and_kerning() {
1288 let mut font = blank_font(&[(b'A' as u32, 500), (b'B' as u32, 700)]);
1289 font.kerning_mut()
1290 .insert(GlyphId::new(1), GlyphId::new(2), -100);
1291 assert!(close(measure_run(&font, "AB", 100.0).expect("ok"), 110.0));
1293 assert!(close(measure_run(&font, "BA", 100.0).expect("ok"), 120.0));
1296 assert!(close(
1298 measure_run(&font, "AAB", 100.0).expect("ok"),
1299 50.0 + 50.0 + 70.0 - 10.0
1300 ));
1301 assert!(close(
1303 measure_run(&font, "AAAB", 100.0).expect("ok"),
1304 50.0 * 3.0 + 70.0 - 10.0
1305 ));
1306 assert!(close(
1308 measure_run(&font, "AAAA", 200.0).expect("ok"),
1309 4.0 * 500.0 * 0.2
1310 ));
1311 }
1312
1313 #[test]
1314 fn measure_run_edge_cases() {
1315 let font = blank_font(&[(b'A' as u32, 500)]);
1316 assert_eq!(measure_run(&font, "", 12.0).expect("ok"), 0.0);
1317 assert!(close(measure_run(&font, "z", 100.0).expect("ok"), 50.0));
1319 for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] {
1321 assert!(
1322 matches!(
1323 measure_run(&font, "A", bad),
1324 Err(ShapeError::InvalidScale { .. })
1325 ),
1326 "{bad}"
1327 );
1328 }
1329 }
1330
1331 #[test]
1332 fn shape_line_places_glyphs_left_to_right() {
1333 let font = blank_font(&[(b'A' as u32, 500), (b'B' as u32, 500)]);
1334 let line = shape_line(&font, "AB", 100.0).expect("ok");
1335 assert_eq!(line.len(), 2);
1336 assert!(!line.is_empty());
1337 assert!(close(line.advance_px(), 100.0));
1338 assert!(close(line.get(0).unwrap().x, 0.0));
1339 assert!(close(line.get(1).unwrap().x, 50.0));
1340 assert!(close(line.get(1).unwrap().advance_px, 50.0));
1341 assert!(close(line.get(1).unwrap().origin_px().0, 50.0));
1343 assert_eq!(line.get(1).unwrap().origin_px().1, 0.0);
1344 assert_eq!(line.get(0).unwrap().cluster, 0);
1346 assert_eq!(line.get(1).unwrap().cluster, 1);
1347 assert!(!line.get(0).unwrap().is_rtl());
1348 }
1349
1350 #[test]
1351 fn shape_line_carries_the_font_metrics() {
1352 let mut font = blank_font(&[(b'A' as u32, 500)]);
1353 *font.metrics_mut() = font_model::FontMetrics {
1354 ascender: 800,
1355 descender: -200,
1356 ..font_model::FontMetrics::default()
1357 };
1358 let line = shape_line(&font, "A", 100.0).expect("ok");
1359 assert!(close(line.ascent_px(), 80.0), "{}", line.ascent_px());
1360 assert!(close(line.descent_px(), 20.0));
1361 assert!(close(line.line_height_px(), 100.0));
1362 let m = line.metrics();
1363 assert!(close(m.ascent, 80.0) && close(m.line_height, 100.0));
1364 let empty = shape_line(&font, "", 100.0).expect("ok");
1366 assert!(empty.is_empty());
1367 assert_eq!(empty.advance_px(), 0.0);
1368 assert_eq!(empty.ink_extent_px(), None);
1369 }
1370
1371 #[test]
1372 fn shape_line_right_to_left_reverses_visual_order() {
1373 let font = blank_font(&[(b'A' as u32, 500), (b'B' as u32, 500)]);
1374 let line = shape_line_with(&font, "AB", 100.0, LayoutDirection::RightToLeft).expect("ok");
1375 assert_eq!(line.paragraph_level(), 1);
1376 assert_eq!(line.get(0).unwrap().cluster, 1, "B first");
1378 assert_eq!(line.get(1).unwrap().cluster, 0, "then A");
1379 let a = line
1381 .placements()
1382 .iter()
1383 .find(|p| p.cluster == 0)
1384 .expect("A");
1385 assert!(close(a.x, 0.0));
1386 assert!(a.is_rtl());
1387 }
1388
1389 #[test]
1390 fn shape_line_auto_takes_direction_from_the_text() {
1391 let font = blank_font(&[(b'A' as u32, 500)]);
1392 let auto = shape_line_with(&font, "A", 100.0, LayoutDirection::Auto).expect("ok");
1393 assert_eq!(auto.paragraph_level(), 0);
1395 assert_eq!(LayoutDirection::default(), LayoutDirection::LeftToRight);
1396 }
1397
1398 #[test]
1399 fn shape_line_honours_the_bidi_resolution() {
1400 let mut font = Font::builder()
1403 .units_per_em(1000)
1404 .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
1405 .glyph(Glyph::empty(GlyphId::new(1), 500))
1406 .glyph(Glyph::empty(GlyphId::new(2), 500))
1407 .build()
1408 .expect("font");
1409 let mut cmap = font_model::Cmap::format4();
1410 cmap.subtables_mut()[0] =
1411 font_model::insert_entry(&cmap.subtables()[0], b'A' as u32, GlyphId::new(1));
1412 cmap.subtables_mut()[0] =
1413 font_model::insert_entry(&cmap.subtables()[0], '\u{05D0}' as u32, GlyphId::new(2));
1414 *font.cmap_mut() = cmap;
1415
1416 let line = shape_line(&font, "A\u{05D0}", 100.0).expect("ok");
1417 assert_eq!(line.paragraph_level(), 0);
1418 let hebrew = line
1420 .placements()
1421 .iter()
1422 .find(|p| p.glyph == GlyphId::new(2))
1423 .expect("he");
1424 assert_eq!(hebrew.level, 1);
1425 assert!(hebrew.is_rtl());
1426 }
1427
1428 #[test]
1429 fn shape_line_kerns_in_logical_order() {
1430 let mut font = blank_font(&[(b'A' as u32, 500), (b'B' as u32, 500)]);
1431 font.kerning_mut()
1432 .insert(GlyphId::new(1), GlyphId::new(2), -50);
1433 let ltr = shape_line(&font, "AB", 100.0).expect("ok");
1434 assert!(
1436 close(ltr.get(1).unwrap().x, 45.0),
1437 "{}",
1438 ltr.get(1).unwrap().x
1439 );
1440 let rtl = shape_line_with(&font, "AB", 100.0, LayoutDirection::RightToLeft).expect("ok");
1442 let a = rtl.placements().iter().find(|p| p.cluster == 0).expect("A");
1443 assert!(close(a.x, 0.0), "A keeps its logical position");
1444 }
1445
1446 #[test]
1447 fn by_cluster_regroups_visual_placements() {
1448 let font = blank_font(&[(b'A' as u32, 500), (b'B' as u32, 500)]);
1449 let line = shape_line_with(&font, "AB", 100.0, LayoutDirection::RightToLeft).expect("ok");
1450 assert_eq!(line.get(0).unwrap().cluster, 1);
1452 assert_eq!(line.get(1).unwrap().cluster, 0);
1453 let clusters = line.by_cluster();
1455 assert_eq!(clusters.len(), 2);
1456 assert_eq!(clusters[0].0, 0);
1457 assert_eq!(clusters[1].0, 1);
1458 assert_eq!(clusters[0].1[0].glyph, GlyphId::new(1));
1459 }
1460
1461 #[test]
1462 fn get_out_of_range_is_none() {
1463 let font = blank_font(&[(b'A' as u32, 500)]);
1464 let line = shape_line(&font, "A", 100.0).expect("ok");
1465 assert!(line.get(0).is_some());
1466 assert!(line.get(1).is_none());
1467 assert!(line.get(9999).is_none());
1468 assert_eq!(line.ink_extent_px(), None);
1469 }
1470
1471 #[test]
1472 fn empty_line_and_empty_text() {
1473 let line = ShapedLine::empty();
1474 assert!(line.is_empty());
1475 assert_eq!(line.len(), 0);
1476 assert_eq!(line.advance_px(), 0.0);
1477 assert!(line.by_cluster().is_empty());
1478 assert!(line.into_placements().is_empty());
1480 }
1481
1482 #[test]
1483 fn shape_line_with_bad_size_is_a_typed_error() {
1484 let font = blank_font(&[(b'A' as u32, 500)]);
1485 for bad in [0.0, -1.0, f32::NAN] {
1486 assert!(
1487 matches!(
1488 shape_line_with(&font, "A", bad, LayoutDirection::Auto),
1489 Err(ShapeError::InvalidScale { .. })
1490 ),
1491 "{bad}"
1492 );
1493 }
1494 }
1495
1496 #[test]
1497 fn resolve_over_char_slice_matches_resolve_bidi() {
1498 let text = "a\u{05D0}b5";
1499 let chars: Vec<char> = text.chars().collect();
1500 assert_eq!(
1501 resolve_bidi(text),
1502 resolve_bidi_chars(&chars),
1503 "the slice form must agree with the string form"
1504 );
1505 let empty = resolve_bidi_chars(&[]);
1507 assert!(empty.levels.is_empty());
1508 assert_eq!(empty.paragraph_level, 0);
1509 assert!(empty.visual_order().is_empty());
1510 }
1511
1512 #[test]
1513 fn describe_run_is_a_readable_summary() {
1514 let font = blank_font(&[(b'A' as u32, 500)]);
1515 let s = super::describe_run(&font, "AA", 100.0);
1516 assert!(s.contains("100"), "{s}");
1517 assert!(s.contains("AA"), "{s}");
1518 let s = super::describe_run(&font, "A", 0.0);
1520 assert!(!s.is_empty());
1521 let _: String = s;
1522 }
1523
1524 #[test]
1525 fn placement_origin_and_is_rtl() {
1526 let p = super::GlyphPlacement {
1527 glyph: GlyphId::new(1),
1528 cluster: 0,
1529 level: 1,
1530 x: 10.0,
1531 y: 0.0,
1532 x_offset: -2.0,
1533 advance_px: 5.0,
1534 };
1535 assert!(close(p.origin_px().0, 8.0));
1536 assert!(p.is_rtl());
1537 }
1538}