Skip to main content

font_shape/
measure.rs

1//! Text measurement: advances, kerning, and bidirectional reordering.
2//!
3//! This module answers three questions a renderer asks before it draws a
4//! line:
5//!
6//! 1. **How wide is it?** [`measure_run`] sums advances and kerning pairs and
7//!    reports the ink bounds alongside the advance, because the two differ and
8//!    a caller needs both.
9//! 2. **Where does each glyph go?** [`shape_line`] turns a string into
10//!    [`GlyphPlacement`]s — glyph id, pen position, and the cluster index that
11//!    ties the placement back to the character that produced it.
12//! 3. **In what order should they be drawn?** [`Direction`] reorders a run
13//!    for right-to-left scripts, using the same Unicode Bidirectional
14//!    Algorithm rules a text engine uses, in the form that matters here:
15//!    resolve per-character embedding levels, then reorder runs of the line.
16//!
17//! # Kerning
18//!
19//! [`Font::kern`](font_model::Font::kern) is consulted for every adjacent pair,
20//! in **logical** order — before any reordering — because a kern pair is
21//! defined by reading order, not by the order glyphs happen to be painted.
22//!
23//! # Bidirectional reordering
24//!
25//! [`shape_line`] implements the *resolution* half of UAX #9: paragraph level
26//! from the first strong character, then rules P, X (no explicit levels here),
27//! W, N, I, and L. Explicit embedding controls are honoured via
28//! [`set_explicit_levels`], which is how a caller injects a direction for text
29//! whose context this function cannot see.
30//!
31//! ```
32//! use font_model::{Font, Glyph, GlyphId};
33//! use font_shape::{ascii_cmap, shape_line, shape_line_with, LayoutDirection};
34//!
35//! // A two-glyph font: 'A' is 500 units wide, 'B' is 600, kerned -30.
36//! let font = Font::builder()
37//!     .units_per_em(1000)
38//!     .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
39//!     .glyph(Glyph::empty(GlyphId::new(1), 500))
40//!     .glyph(Glyph::empty(GlyphId::new(2), 600))
41//!     .kern(GlyphId::new(1), GlyphId::new(2), -30)
42//!     .cmap(ascii_cmap())
43//!     .build()
44//!     .unwrap();
45//!
46//! let line = shape_line(&font, "AB", 100.0).unwrap();
47//! assert_eq!(line.len(), 2);
48//! // 500 + 600 - 30 = 1070 font units = 107 px at 100 px/em.
49//! assert!((line.advance_px() - 107.0).abs() < 1e-3, "{}", line.advance_px());
50//! // The kern pulls B 3 px closer than the unkerned 50 px advance would.
51//! assert!((line.get(1).unwrap().x - 47.0).abs() < 1e-3, "{}", line.get(1).unwrap().x);
52//!
53//! // Right-to-left draws the same glyphs in the opposite order, at the same
54//! // total width.
55//! let rtl = shape_line_with(&font, "AB", 100.0, LayoutDirection::RightToLeft).unwrap();
56//! assert_eq!(rtl.get(0).unwrap().cluster, 1, "B is drawn first");
57//! assert!((rtl.advance_px() - 107.0).abs() < 1e-3);
58//! ```
59
60use 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/// Which way a run reads.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71pub enum LayoutDirection {
72    /// Left to right. The default.
73    #[default]
74    LeftToRight,
75    /// Right to left: the line's glyphs are reversed after kerning.
76    RightToLeft,
77    /// Take the direction from the first strong character in the text, as
78    /// UAX #9's P2/P3 rules do. Neutral or empty text is left to right.
79    Auto,
80}
81
82/// The Unicode bidirectional categories this module distinguishes.
83///
84/// The full list is 30-odd classes; the ones that change a *reordering* are
85/// the strong ones (`L`, `R`, `AL`), the numbers (`EN`, `AN`), and the
86/// neutrals that inherit from their neighbours. The rest collapse into
87/// [`BidiClass::Other`], which resolves exactly like a neutral.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum BidiClass {
90    /// Left-to-right.
91    L,
92    /// Right-to-left.
93    R,
94    /// Arabic letter.
95    Al,
96    /// European number.
97    En,
98    /// Arabic number.
99    An,
100    /// A combining mark.
101    Nsm,
102    /// European terminator: a currency symbol, a percent sign, a degree sign.
103    /// It takes the direction of an adjacent number, and is neutral otherwise.
104    Et,
105    /// Anything else: whitespace, punctuation, symbols, format characters.
106    Other,
107}
108
109impl BidiClass {
110    /// True for the classes that establish a direction of their own.
111    #[must_use]
112    pub const fn is_strong(self) -> bool {
113        matches!(self, BidiClass::L | BidiClass::R | BidiClass::Al)
114    }
115
116    /// The direction a strong class implies, as an embedding level parity.
117    #[must_use]
118    pub const fn is_rtl(self) -> bool {
119        matches!(self, BidiClass::R | BidiClass::Al)
120    }
121}
122
123/// The bidirectional class of a character.
124///
125/// ```
126/// use font_shape::{bidi_class, BidiClass};
127///
128/// assert_eq!(bidi_class('A'), BidiClass::L);
129/// assert_eq!(bidi_class('5'), BidiClass::En);
130/// assert_eq!(bidi_class('\u{05D0}'), BidiClass::R);        // Hebrew alef
131/// assert_eq!(bidi_class('\u{0627}'), BidiClass::Al);       // Arabic alef
132/// assert_eq!(bidi_class('\u{0301}'), BidiClass::Nsm);      // combining acute
133/// assert_eq!(bidi_class(' '), BidiClass::Other);
134/// ```
135#[must_use]
136pub fn bidi_class(ch: char) -> BidiClass {
137    let c = ch as u32;
138    match c {
139        // Latin, Greek, Cyrillic, CJK, and the rest of the left-to-right
140        // scripts. Rather than enumerate 150 blocks, the rule is: a character
141        // is `L` unless it falls in an explicitly RTL or numeric range below.
142        //
143        // Combining marks first: they sit *inside* the RTL ranges below,
144        // and a mark is a mark wherever it lives.
145        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, // Hebrew
153        0x0600..=0x07BF => {
154            // Arabic, Syriac, Thaana, N'Ko. The Arabic-Indic and extended
155            // Arabic-Indic digits are `AN`; the rest are letters.
156            match c {
157                0x0660..=0x0669 | 0x06F0..=0x06F9 | 0x066B | 0x066C | 0x06DD => BidiClass::An,
158                _ => BidiClass::Al,
159            }
160        }
161        0xFB1D..=0xFB4F => BidiClass::R, // Hebrew presentation forms
162        0xFB50..=0xFDFF => BidiClass::Al, // Arabic presentation forms A
163        0xFE70..=0xFEFF => BidiClass::Al, // Arabic presentation forms B
164        0x200B..=0x200D => BidiClass::Other, // zero-width joiners
165        0x2010..=0x2027 => BidiClass::Other, // dashes, quotes, brackets
166        0x2000..=0x200A | 0x2028 | 0x2029 | 0x205F | 0x3000 => BidiClass::Other,
167        0x30FB => BidiClass::Other,       // katakana middle dot
168        0x20A0..=0x20CF => BidiClass::Et, // currency symbols
169        0x00A2..=0x00A5 | 0x00B0 | 0x00B1 => BidiClass::Et, // currency, degree
170        0x0030..=0x0039 => BidiClass::En,
171        0x00B2 | 0x00B3 | 0x00B9 => BidiClass::En, // superscript digits
172        0x2070 | 0x2074..=0x2079 => BidiClass::En,
173        0xFF10..=0xFF19 => BidiClass::En, // fullwidth digits
174        // ASCII's non-alphanumeric characters are all neutrals: space,
175        // control, punctuation, and symbols. Getting these right is what makes
176        // a period in "1.5" stay inside its number and a period in "a.b" stay
177        // a neutral that can resolve either way.
178        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, // punctuation and symbols
184        0x2100..=0x214F => BidiClass::Other, // letterlike symbols
185        0x2190..=0x2BFF => BidiClass::Other, // arrows, math, shapes
186        0xFB00..=0xFB17 => BidiClass::Other, // hebrew ligatures and punctuation
187        _ => BidiClass::L,
188    }
189}
190
191/// The embedding level of one character in a resolved line: even is LTR, odd
192/// is RTL.
193#[must_use]
194pub const fn is_rtl_level(level: u8) -> bool {
195    level % 2 == 1
196}
197
198/// Resolved per-character embedding levels for a line of text.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct BidiLevels {
201    /// One level per `char` in the text, in logical order.
202    pub levels: Vec<u8>,
203    /// The paragraph embedding level: `0` for LTR, `1` for RTL.
204    pub paragraph_level: u8,
205}
206
207impl BidiLevels {
208    /// The level at a logical character index.
209    #[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    /// The visual order: logical indices sorted for display.
218    ///
219    /// This is UAX #9 rule L2 — reverse contiguous runs of characters at or
220    /// above the lowest *odd* level, from the highest level down. For an
221    /// all-LTR line it is simply `0..n`.
222    #[must_use]
223    pub fn visual_order(&self) -> Vec<usize> {
224        reorder_indices(&self.levels)
225    }
226}
227
228/// Reorder logical indices for display under rule L2.
229///
230/// ```
231/// use font_shape::reorder_indices;
232///
233/// // All LTR: identity.
234/// assert_eq!(reorder_indices(&[0, 0, 0]), vec![0, 1, 2]);
235/// // All RTL: reversed.
236/// assert_eq!(reorder_indices(&[1, 1, 1]), vec![2, 1, 0]);
237/// // Two Latin then two Hebrew: only the Hebrew pair reverses.
238/// assert_eq!(reorder_indices(&[0, 0, 1, 1]), vec![0, 1, 3, 2]);
239/// ```
240#[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    // The lowest odd level present, or nothing to do.
248    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    // Rule L2 proper: from the highest level present down to the lowest odd
258    // one, reverse every maximal run of characters at that level or above.
259    // The comparison has to go through the *current* order, because a run that
260    // a higher pass has already reversed now holds different characters.
261    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/// Resolve embedding levels for `text` under UAX #9 rules P2/P3, W, N, and I.
293///
294/// The rules implemented, in order:
295///
296/// | Rule | Effect |
297/// |---|---|
298/// | P2/P3 | paragraph level from the first strong character |
299/// | W1 | a mark takes the class of the character before it |
300/// | W2 | `EN` after `AL` becomes `AN` |
301/// | W3 | `AL` becomes `R` |
302/// | W4 | a `CS` between two numbers of the same kind becomes that kind |
303/// | W5 | a run of `ET` adjacent to `EN` becomes `EN` |
304/// | W6 | remaining `ET`/`ES`/`CS` become `Other` |
305/// | W7 | `EN` after `L` becomes `L` |
306/// | N1/N2 | a neutral takes its neighbours' direction, else the paragraph's |
307/// | I1/I2 | implicit levels: one above the base for a direction change |
308///
309/// ```
310/// use font_shape::resolve_bidi;
311///
312/// // Pure Latin: all level 0.
313/// let b = resolve_bidi("abc");
314/// assert_eq!(b.paragraph_level, 0);
315/// assert_eq!(b.levels, vec![0, 0, 0]);
316///
317/// // Latin first, so the paragraph is LTR and the Hebrew is an RTL island.
318/// let b = resolve_bidi("abc\u{05D0}\u{05D1}");
319/// assert_eq!(b.paragraph_level, 0, "Latin came first");
320/// assert_eq!(b.levels, vec![0, 0, 0, 1, 1], "{b:?}");
321/// assert_eq!(b.visual_order(), vec![0, 1, 2, 4, 3]);
322///
323/// // Hebrew first: the paragraph is RTL, and the trailing Latin rises one
324/// // level to 2 — not two — so it keeps its own left-to-right order.
325/// let b = resolve_bidi("\u{05D0}\u{05D1}abc");
326/// assert_eq!(b.paragraph_level, 1);
327/// assert_eq!(b.levels, vec![1, 1, 2, 2, 2], "{b:?}");
328///
329/// // A number inside Hebrew is level 2 as well: one above the RTL run around
330/// // it, so the digits still read left to right.
331/// let b = resolve_bidi("\u{05D0}5\u{05D1}");
332/// assert_eq!(b.levels, vec![1, 2, 1], "EN inside RTL is level 2");
333/// assert_eq!(b.visual_order(), vec![2, 1, 0]);
334/// ```
335#[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/// [`resolve_bidi`] over an explicit character slice, so a caller that already
342/// split the text does not pay for a second pass.
343#[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    // Rules N1 and N2: a neutral takes its neighbours' direction when they
350    // agree, and the paragraph's when they do not. Resolving neutrals first
351    // means every remaining character has a definite strong direction, which
352    // is what rules I1 and I2 need.
353    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    // Rules I1 and I2: the implicit embedding level.
375    let mut levels: Vec<u8> = resolved
376        .iter()
377        .map(|&cls| implicit_level(cls, base_rtl, paragraph_level))
378        .collect();
379    // Rule L1: segment separators and trailing whitespace reset to the
380    // paragraph level, so a trailing space does not sit on the wrong side of
381    // the line's origin.
382    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
395/// True for the characters UAX #9 treats as segment or paragraph separators.
396fn is_separator(ch: char) -> bool {
397    matches!(ch, '\u{2029}' | '\u{2028}' | '\r' | '\n')
398}
399
400/// UAX #9 rules P2 and P3: the paragraph level is set by the first strong
401/// character, defaulting to left to right.
402fn 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
413/// UAX #9 rules W1 through W7.
414fn apply_w_rules(chars: &[char], classes: &mut [BidiClass]) {
415    // W1: a mark takes the class of the previous character.
416    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    // W2: European numbers after Arabic letters become Arabic numbers.
424    // Scan for the last strong character as we go.
425    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    // W3: Arabic letters become plain R.
435    for cls in classes.iter_mut() {
436        if *cls == BidiClass::Al {
437            *cls = BidiClass::R;
438        }
439    }
440    // W4: a common separator between two numbers of the same kind takes that
441    // kind. This is what keeps "1,234" one number rather than three runs.
442    // It fires only for CS, so the *character* decides: a space or a comma
443    // inside a number is punctuation that leaves its class alone.
444    let snapshot: Vec<BidiClass> = classes.to_vec();
445    let is_number = |c: BidiClass| matches!(c, BidiClass::En | BidiClass::An);
446    // A separator at index `i` needs both neighbours, so walk the middle
447    // positions from 1 to `len - 2`.
448    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    // W5: a run of ETs adjacent to an EN becomes EN.
462    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    // W6: remaining separators and terminators become neutral.
485    for cls in classes.iter_mut() {
486        if *cls == BidiClass::Et {
487            *cls = BidiClass::Other;
488        }
489    }
490    // W7: a European number after a strong L becomes L.
491    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
502/// True for the characters UAX #9 gives the class `CS` (common separator):
503/// the ones rule W4 uses to glue a number group into one run.
504fn 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
519/// The strong direction a neutral resolves to, per rules N1 and N2.
520///
521/// A neutral takes its neighbours' direction when they agree, and the
522/// paragraph's when they do not. Numbers are *not* neutral — they keep their
523/// own class, and a number acts as the strong type on its side when it is a
524/// neutral's neighbour (rule N1: "European and Arabic numbers act as if they
525/// were R in an RTL paragraph").
526fn 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
548/// The implicit embedding level for a character, per rules I1 and I2.
549///
550/// - At an **even** base: `L` stays put, `R` rises one level, and a number
551///   rises two — so a digit run inside a right-to-left island reads
552///   left-to-right within it, which is what makes "abc 123" come back
553///   `abc 123` and not `abc 321`.
554/// - At an **odd** base: `R` stays put, and `L` or a number rises one.
555fn 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/// One glyph's place in a shaped line.
573#[derive(Debug, Clone, PartialEq)]
574pub struct GlyphPlacement {
575    /// The glyph to draw.
576    pub glyph: GlyphId,
577    /// The logical index of the character that produced it. Cluster indices
578    /// are what let a caller map a drawn glyph back to text for selection and
579    /// accessibility; with a ligature or a combining sequence, several
580    /// characters share one placement and report the same cluster.
581    pub cluster: u32,
582    /// The embedding level this placement resolved to.
583    pub level: u8,
584    /// The horizontal pen position in pixels, before `x_offset`.
585    pub x: f32,
586    /// The vertical position in pixels, always `0.0` for a horizontal run.
587    pub y: f32,
588    /// The additional offset in pixels — a right-to-left glyph's negative
589    /// bearing, or a mark's adjustment.
590    pub x_offset: f32,
591    /// How far the pen advances after this glyph, in pixels, kerning included.
592    pub advance_px: f32,
593}
594
595impl GlyphPlacement {
596    /// The device position of the glyph's origin: pen plus offset.
597    #[must_use]
598    pub fn origin_px(&self) -> (f32, f32) {
599        (self.x + self.x_offset, self.y)
600    }
601
602    /// True when this placement reads right to left.
603    #[must_use]
604    pub const fn is_rtl(&self) -> bool {
605        is_rtl_level(self.level)
606    }
607}
608
609/// A shaped line of text: glyphs, their pen positions, and the run's metrics.
610#[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    /// An empty line.
624    #[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    /// The placements, in *visual* order for a bidi line and logical order
639    /// otherwise.
640    #[must_use]
641    pub fn placements(&self) -> &[GlyphPlacement] {
642        &self.placements
643    }
644
645    /// The placements, owned.
646    #[must_use]
647    pub fn into_placements(self) -> Vec<GlyphPlacement> {
648        self.placements
649    }
650
651    /// Number of glyphs.
652    #[must_use]
653    pub fn len(&self) -> usize {
654        self.placements.len()
655    }
656
657    /// True when the line has no glyphs.
658    #[must_use]
659    pub fn is_empty(&self) -> bool {
660        self.placements.is_empty()
661    }
662
663    /// A placement by visual index.
664    #[must_use]
665    pub fn get(&self, index: usize) -> Option<&GlyphPlacement> {
666        self.placements.get(index)
667    }
668
669    /// The total advance width in pixels, kerning included.
670    #[must_use]
671    pub const fn advance_px(&self) -> f32 {
672        self.advance_px
673    }
674
675    /// Pixels above the baseline.
676    #[must_use]
677    pub const fn ascent_px(&self) -> f32 {
678        self.ascent_px
679    }
680
681    /// Pixels below the baseline, as a positive number.
682    #[must_use]
683    pub const fn descent_px(&self) -> f32 {
684        self.descent_px
685    }
686
687    /// The font's recommended distance between baselines, in pixels.
688    #[must_use]
689    pub const fn line_height_px(&self) -> f32 {
690        self.line_height_px
691    }
692
693    /// The horizontal ink extent, `left..right` in pixels from the origin, or
694    /// `None` when the line has no ink.
695    #[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    /// The paragraph embedding level.
704    #[must_use]
705    pub const fn paragraph_level(&self) -> u8 {
706        self.paragraph_level
707    }
708
709    /// The line's font metrics.
710    #[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    /// The placements grouped by cluster, in **logical** order.
721    ///
722    /// This is the inverse of [`placements`](Self::placements): for a line
723    /// whose glyphs were reversed for display, the clusters come back in
724    /// reading order, which is what a text-extraction or selection path wants.
725    #[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
739/// Set explicit embedding levels on a resolved set.
740///
741/// The caller owns explicit-direction input — a paragraph tagged RTL by the
742/// application, an override in an editor — and this is how it arrives. Levels
743/// are per logical character and must be in `0..=8`; anything past 8 is
744/// clamped, which keeps the reorderer's loops finite.
745///
746/// ```
747/// use font_shape::{resolve_bidi, set_explicit_levels};
748///
749/// // A Hebrew word in an LTR paragraph: the caller forces level 1 on it.
750/// let mut b = resolve_bidi("A\u{05D0}");
751/// set_explicit_levels(&mut b.levels, &[0, 1]);
752/// assert_eq!(b.levels, vec![0, 1]);
753/// assert_eq!(b.visual_order(), vec![0, 1]);
754///
755/// // Out-of-range levels clamp rather than panic.
756/// set_explicit_levels(&mut b.levels, &[200, 200]);
757/// assert_eq!(b.levels, vec![8, 8]);
758/// ```
759pub 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/// The advance width of a single glyph in pixels, no kerning.
766///
767/// # Errors
768/// [`ShapeError::InvalidScale`] for a non-positive or non-finite size, and
769/// [`ShapeError::UnknownGlyph`] when the font has no such glyph.
770///
771/// ```
772/// use font_model::{Font, Glyph, GlyphId};
773/// use font_shape::measure_glyph;
774///
775/// let font = Font::builder()
776///     .units_per_em(1000)
777///     .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
778///     .glyph(Glyph::empty(GlyphId::new(1), 600))
779///     .build()
780///     .unwrap();
781/// assert!((measure_glyph(&font, GlyphId::new(1), 50.0).unwrap() - 30.0).abs() < 1e-4);
782///
783/// // A glyph past the store is a typed error.
784/// assert!(measure_glyph(&font, GlyphId::new(9), 50.0).is_err());
785/// ```
786#[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/// The advance width of a run of characters in pixels, kerning included.
800///
801/// Kerning is applied to every adjacent pair in logical order. Characters
802/// with no glyph in the font contribute the `.notdef` advance rather than
803/// being dropped, so a run's measured width matches what would be drawn.
804///
805/// # Errors
806/// [`ShapeError::InvalidScale`] for a non-positive or non-finite size.
807///
808/// ```
809/// use font_model::{Font, Glyph, GlyphId};
810/// use font_shape::{ascii_cmap, measure_run};
811///
812/// let font = Font::builder()
813///     .units_per_em(1000)
814///     .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
815///     .glyph(Glyph::empty(GlyphId::new(1), 500))
816///     .glyph(Glyph::empty(GlyphId::new(2), 700))
817///     .kern(GlyphId::new(1), GlyphId::new(2), -100)
818///     .cmap(ascii_cmap())
819///     .build()
820///     .unwrap();
821/// // "AB" = 500 + 700 - 100 = 1100 units = 110 px at 100 px/em.
822/// assert!((measure_run(&font, "AB", 100.0).unwrap() - 110.0).abs() < 1e-3);
823///
824/// // An empty run is zero wide.
825/// assert_eq!(measure_run(&font, "", 100.0).unwrap(), 0.0);
826///
827/// // Bad size is a typed error.
828/// assert!(measure_run(&font, "A", 0.0).is_err());
829/// ```
830#[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/// Lay out a line of text: glyphs, pen positions, kerning, and bidi order.
850///
851/// A character with no glyph in the font falls back to `.notdef` if the font
852/// has one, so the run measures and draws at the width a renderer would
853/// actually produce.
854///
855/// # Errors
856/// [`ShapeError::InvalidScale`] for a non-positive or non-finite size.
857///
858/// ```
859/// use font_model::{Font, Glyph, GlyphId};
860/// use font_shape::{ascii_cmap, shape_line, shape_line_with, LayoutDirection};
861///
862/// let font = Font::builder()
863///     .units_per_em(1000)
864///     .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
865///     .glyph(Glyph::empty(GlyphId::new(1), 500))
866///     .glyph(Glyph::empty(GlyphId::new(2), 500))
867///     .cmap(ascii_cmap())
868///     .build()
869///     .unwrap();
870///
871/// let line = shape_line(&font, "AAA", 100.0).unwrap();
872/// assert_eq!(line.len(), 3);
873/// assert!((line.advance_px() - 150.0).abs() < 1e-3);
874/// // Each glyph starts where the previous advance ended.
875/// assert!((line.get(1).unwrap().x - 50.0).abs() < 1e-3);
876/// // The cluster index ties a placement back to its character.
877/// assert_eq!(line.get(2).unwrap().cluster, 2);
878///
879/// // Right-to-left reverses the visual order of the glyphs.
880/// let rtl = shape_line_with(&font, "AAA", 100.0, LayoutDirection::RightToLeft).unwrap();
881/// assert_eq!(rtl.get(0).unwrap().cluster, 2, "visually the last glyph is first");
882/// ```
883#[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/// [`shape_line`] with an explicit direction.
889///
890/// ```
891/// use font_shape::{shape_line_with, LayoutDirection};
892/// # use font_model::{Font, Glyph, GlyphId};
893/// # let font = Font::builder().units_per_em(1000)
894/// #     .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
895/// #     .glyph(Glyph::empty(GlyphId::new(1), 500))
896/// #     .glyph(Glyph::empty(GlyphId::new(2), 500))
897/// #     .build().unwrap();
898/// # let font = {
899/// #     let mut f = font;
900/// #     let mut cmap = font_model::Cmap::format4();
901/// #     for (cp, gid) in [(b'A' as u32, GlyphId::new(1)), (b'B' as u32, GlyphId::new(2))] {
902/// #         cmap.subtables_mut()[0] = font_model::insert_entry(&cmap.subtables()[0], cp, gid);
903/// #     }
904/// #     *f.cmap_mut() = cmap;
905/// #     f
906/// # };
907/// let ltr = shape_line_with(&font, "AB", 100.0, LayoutDirection::LeftToRight).unwrap();
908/// let rtl = shape_line_with(&font, "AB", 100.0, LayoutDirection::RightToLeft).unwrap();
909/// assert_eq!(ltr.paragraph_level(), 0);
910/// assert_eq!(rtl.paragraph_level(), 1);
911/// // The advance is the same either way; only the drawing order differs.
912/// assert!((ltr.advance_px() - rtl.advance_px()).abs() < 1e-4);
913/// assert_eq!(rtl.get(0).unwrap().cluster, 1);
914/// ```
915#[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    // Pass one: logical order, kerning applied. This is where advances are
937    // decided; a kern pair is defined by reading order, not paint order.
938    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    // Pass two: visual order by rule L2. Pen positions stay attached to their
962    // glyphs, so a renderer draws each at its own x regardless of order.
963    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
981/// A cmap mapping `A` and `B` to glyphs 1 and 2. Exists for the doctests,
982/// which each need a font that actually resolves the characters they measure.
983pub 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        // `format4()` always produces exactly one subtable, so this cannot
990        // miss; `first_mut` keeps the deny-level indexing lint satisfied
991        // without an unwrap.
992        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
1005/// The glyph a character maps to, falling back to `.notdef`.
1006fn 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
1012/// The advance of a glyph, or zero when the font has no such glyph.
1013fn advance_of(font: &Font, glyph: GlyphId) -> u16 {
1014    font.glyph(glyph)
1015        .map_or(0, font_model::Glyph::advance_width)
1016}
1017
1018/// A short description of a run, for diagnostics.
1019#[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    // Test harness: assertions legitimately panic; the lib target stays
1049    // lint-clean.
1050
1051    fn close(a: f32, b: f32) -> bool {
1052        (a - b).abs() < 1e-3
1053    }
1054
1055    /// A font whose glyphs are all blank, with a cmap for the ASCII letters
1056    /// mapped one-to-one.
1057    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        // Predicates.
1096        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        // Out-of-range index reads the paragraph level.
1118        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        // The Latin run is level 2 — one *above* the paragraph, not two — so
1127        // it keeps its own left-to-right order inside a right-to-left line.
1128        assert_eq!(b.visual_order(), vec![2, 3, 4, 1, 0]);
1129        // Which renders as the Latin unchanged, then the Hebrew reversed.
1130        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        // The trailing `b` keeps its place at the right of the RTL island's
1144        // slot; only the two Hebrew characters swap.
1145        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        // The digit is on level 2, so rule L2 reverses the level-1 run around
1159        // it without disturbing the digit's own order.
1160        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        // A space between L and R has no agreed direction, so it takes the
1179        // paragraph's.
1180        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        // A mark after a Hebrew letter is RTL (W1), after a Latin letter LTR.
1194        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        // Level 2 inside level 1 inside level 0. Rule L2 works from the
1212        // highest level down: first the level-2 run reverses, then every
1213        // level-1 character reverses as one span.
1214        assert_eq!(reorder_indices(&[0, 1, 2, 2, 1]), vec![0, 4, 2, 3, 1]);
1215        // Two separate level-1 islands each reverse on their own.
1216        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        // A shorter explicit list leaves the rest alone.
1228        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        // Errors.
1244        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        // "1.5" in a right-to-left paragraph: the digits are level 2, so the
1260        // decimal point stays between them. Reversing them would render "5.1".
1261        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        // Arabic-Indic digits are `AN`, so they act as right-to-left and stay
1274        // put: the word reverses, the digits do not.
1275        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        // "AB" = 500 + 700 - 100 = 1100 units = 110 px at 100 px/em.
1292        assert!(close(measure_run(&font, "AB", 100.0).expect("ok"), 110.0));
1293        // Kerning is symmetric per pair but only applies left-to-right in the
1294        // run: "BA" has no pair in that order.
1295        assert!(close(measure_run(&font, "BA", 100.0).expect("ok"), 120.0));
1296        // "AAB" kerns the A-B pair once: 50 + 50 + 70 - 10 px at 100 px/em.
1297        assert!(close(
1298            measure_run(&font, "AAB", 100.0).expect("ok"),
1299            50.0 + 50.0 + 70.0 - 10.0
1300        ));
1301        // "AAAB" kerns once too: there is only one A-B adjacency.
1302        assert!(close(
1303            measure_run(&font, "AAAB", 100.0).expect("ok"),
1304            50.0 * 3.0 + 70.0 - 10.0
1305        ));
1306        // Repeat scales linearly.
1307        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        // An unmapped character falls back to notdef's advance (500).
1318        assert!(close(measure_run(&font, "z", 100.0).expect("ok"), 50.0));
1319        // Bad sizes are typed errors.
1320        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        // Origin is pen + offset.
1342        assert!(close(line.get(1).unwrap().origin_px().0, 50.0));
1343        assert_eq!(line.get(1).unwrap().origin_px().1, 0.0);
1344        // Clusters tie placements to characters.
1345        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        // Empty line: no glyphs, zero advance.
1365        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        // Visually the last character is drawn first, at the origin.
1377        assert_eq!(line.get(0).unwrap().cluster, 1, "B first");
1378        assert_eq!(line.get(1).unwrap().cluster, 0, "then A");
1379        // But the pen positions are still logical: A is at x=0, B at x=50.
1380        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        // Latin, so LTR.
1394        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        // A run that is Latin with a Hebrew letter in it: the letter's
1401        // placement is level 1 and the base stays LTR.
1402        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        // The Hebrew glyph carries the RTL level.
1419        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        // B starts 50 units earlier than the unkerned 500.
1435        assert!(
1436            close(ltr.get(1).unwrap().x, 45.0),
1437            "{}",
1438            ltr.get(1).unwrap().x
1439        );
1440        // Reversed display, same logical kern applied: A still kerns to B.
1441        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        // Display order really is reversed...
1451        assert_eq!(line.get(0).unwrap().cluster, 1);
1452        assert_eq!(line.get(1).unwrap().cluster, 0);
1453        // ...but the cluster view is in reading order.
1454        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        // consume
1479        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        // Empty slice.
1506        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        // Even a bad size gives a string rather than panicking.
1519        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}