Skip to main content

textflow/
shaping.rs

1use crate::bidi::Direction;
2use crate::unicode::{graphemes, line_breaks, LineBreak, LineBreaks, Script};
3use core::ops::Range;
4
5#[cfg(feature = "complex-shaping")]
6mod complex;
7#[cfg(feature = "complex-shaping")]
8pub use complex::{
9    GlyphBuffer, GlyphMask, LookupRequest, LookupStatus, ScriptProvider, ScriptTypeface,
10    ShapingData,
11};
12
13#[cfg(any(
14    feature = "script-arabic",
15    feature = "script-thai",
16    feature = "script-devanagari"
17))]
18pub mod scripts;
19
20#[repr(transparent)]
21#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
22pub struct FontId(u64);
23
24impl FontId {
25    pub const fn new(value: u64) -> Self {
26        Self(value)
27    }
28
29    pub const fn value(self) -> u64 {
30        self.0
31    }
32}
33
34#[repr(transparent)]
35#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
36pub struct GlyphId(u16);
37
38impl GlyphId {
39    pub const fn new(value: u16) -> Self {
40        Self(value)
41    }
42
43    pub const fn value(self) -> u16 {
44        self.0
45    }
46}
47
48#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
49pub struct FlowPoint {
50    pub x: i32,
51    pub y: i32,
52}
53
54#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
55pub struct FontMetrics {
56    pub units_per_em: u16,
57    pub ascender: i32,
58    pub descender: i32,
59    pub line_gap: i32,
60}
61
62#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
63pub struct TextRange {
64    pub start: u32,
65    pub end: u32,
66}
67
68impl TextRange {
69    pub const fn new(start: u32, end: u32) -> Self {
70        Self { start, end }
71    }
72
73    pub const fn len(self) -> u32 {
74        self.end.saturating_sub(self.start)
75    }
76
77    pub const fn is_empty(self) -> bool {
78        self.start >= self.end
79    }
80}
81
82#[derive(Clone, Copy, Debug, Eq, PartialEq)]
83pub struct FontFeature {
84    pub tag: [u8; 4],
85    pub value: u32,
86    pub range: TextRange,
87}
88
89#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
90pub struct LineEdges(u8);
91
92impl LineEdges {
93    pub const NONE: Self = Self(0);
94    pub const START: Self = Self(1);
95    pub const END: Self = Self(2);
96    pub const BOTH: Self = Self(3);
97
98    pub const fn has_start(self) -> bool {
99        self.0 & Self::START.0 != 0
100    }
101
102    pub const fn has_end(self) -> bool {
103        self.0 & Self::END.0 != 0
104    }
105}
106
107impl FontFeature {
108    pub const fn new(tag: [u8; 4], value: u32) -> Self {
109        Self {
110            tag,
111            value,
112            range: TextRange::new(0, u32::MAX),
113        }
114    }
115
116    pub const fn with_range(mut self, range: TextRange) -> Self {
117        self.range = range;
118        self
119    }
120}
121
122pub struct ShapeRequest<'a> {
123    pub text: &'a str,
124    pub range: Range<usize>,
125    pub direction: Direction,
126    pub script: Script,
127    pub language: Option<&'a str>,
128    pub features: &'a [FontFeature],
129    pub line_edges: LineEdges,
130}
131
132impl<'a> ShapeRequest<'a> {
133    pub fn new(text: &'a str, range: Range<usize>, direction: Direction, script: Script) -> Self {
134        Self {
135            text,
136            range,
137            direction,
138            script,
139            language: None,
140            features: &[],
141            line_edges: LineEdges::NONE,
142        }
143    }
144
145    pub fn with_language(mut self, language: &'a str) -> Self {
146        self.language = Some(language);
147        self
148    }
149
150    pub fn with_features(mut self, features: &'a [FontFeature]) -> Self {
151        self.features = features;
152        self
153    }
154
155    pub fn with_line_edges(mut self, edges: LineEdges) -> Self {
156        self.line_edges = edges;
157        self
158    }
159}
160
161#[derive(Clone, Copy, Debug, Eq, PartialEq)]
162pub enum ShapeError {
163    InvalidTextRange,
164    InvalidGlyphRange,
165    TextTooLong,
166    InsufficientCapacity { required: usize },
167    UnsupportedScript { script: Script },
168    UnsupportedFeature { tag: [u8; 4] },
169    UnsupportedCluster { offset: usize },
170    MissingGlyph { offset: usize },
171    ShapingUnavailable,
172    Source(FontAccessError),
173}
174
175#[derive(Clone, Copy, Debug, Eq, PartialEq)]
176pub enum FontAccessError {
177    Unavailable,
178    Malformed,
179    Unsupported,
180}
181
182impl From<FontAccessError> for ShapeError {
183    fn from(error: FontAccessError) -> Self {
184        Self::Source(error)
185    }
186}
187
188#[repr(C)]
189#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
190pub struct ShapedGlyph {
191    glyph_id: GlyphId,
192    flags: u16,
193    pub cluster: TextRange,
194    pub advance: FlowPoint,
195    pub offset: FlowPoint,
196}
197
198impl ShapedGlyph {
199    const UNSAFE_TO_BREAK: u16 = 1;
200
201    pub const fn new(glyph_id: GlyphId, cluster: TextRange) -> Self {
202        Self {
203            glyph_id,
204            flags: 0,
205            cluster,
206            advance: FlowPoint { x: 0, y: 0 },
207            offset: FlowPoint { x: 0, y: 0 },
208        }
209    }
210
211    pub const fn glyph_id(self) -> GlyphId {
212        self.glyph_id
213    }
214
215    pub const fn unsafe_to_break(self) -> bool {
216        self.flags & Self::UNSAFE_TO_BREAK != 0
217    }
218
219    pub fn set_unsafe_to_break(&mut self, unsafe_to_break: bool) {
220        if unsafe_to_break {
221            self.flags |= Self::UNSAFE_TO_BREAK;
222        } else {
223            self.flags &= !Self::UNSAFE_TO_BREAK;
224        }
225    }
226}
227
228pub struct ShapedRun<'a> {
229    font_id: FontId,
230    text: TextRange,
231    bidi_level: u8,
232    glyphs: &'a [ShapedGlyph],
233}
234
235impl<'a> ShapedRun<'a> {
236    pub const fn new(
237        font_id: FontId,
238        text: TextRange,
239        bidi_level: u8,
240        glyphs: &'a [ShapedGlyph],
241    ) -> Self {
242        Self {
243            font_id,
244            text,
245            bidi_level,
246            glyphs,
247        }
248    }
249
250    pub const fn font_id(&self) -> FontId {
251        self.font_id
252    }
253
254    pub const fn text(&self) -> TextRange {
255        self.text
256    }
257
258    pub const fn direction(&self) -> Direction {
259        Direction::from_level(self.bidi_level)
260    }
261
262    pub const fn bidi_level(&self) -> u8 {
263        self.bidi_level
264    }
265
266    pub const fn glyphs(&self) -> &[ShapedGlyph] {
267        self.glyphs
268    }
269
270    pub fn is_safe_break(&self, offset: u32) -> bool {
271        if offset == self.text.start || offset == self.text.end {
272            return true;
273        }
274        if offset < self.text.start || offset > self.text.end {
275            return false;
276        }
277        !self.glyphs.iter().any(|glyph| {
278            glyph.cluster.start < offset && offset < glyph.cluster.end
279                || glyph.cluster.start == offset && glyph.unsafe_to_break()
280        })
281    }
282
283    pub fn line_breaks<'text, 'run>(
284        &'run self,
285        text: &'text str,
286    ) -> Result<SafeLineBreaks<'text, 'run, 'a>, ShapeError> {
287        let start = self.text.start as usize;
288        let end = self.text.end as usize;
289        if start > end
290            || end > text.len()
291            || !text.is_char_boundary(start)
292            || !text.is_char_boundary(end)
293        {
294            return Err(ShapeError::InvalidTextRange);
295        }
296        Ok(SafeLineBreaks {
297            inner: line_breaks(&text[start..end]),
298            run: self,
299            base: self.text.start,
300        })
301    }
302
303    pub fn position_into<'output>(
304        &self,
305        origin: FlowPoint,
306        output: &'output mut [PositionedGlyph],
307    ) -> Result<PositionedRun<'output>, PositionError> {
308        if output.len() < self.glyphs.len() {
309            return Err(PositionError::InsufficientCapacity {
310                required: self.glyphs.len(),
311            });
312        }
313        let mut pen = origin;
314        for (slot, glyph) in output.iter_mut().zip(self.glyphs) {
315            *slot = PositionedGlyph {
316                glyph_id: glyph.glyph_id(),
317                cluster: glyph.cluster,
318                origin: pen,
319                advance: glyph.advance,
320                offset: glyph.offset,
321                bidi_level: self.bidi_level,
322            };
323            pen.x = pen
324                .x
325                .checked_add(glyph.advance.x)
326                .ok_or(PositionError::CoordinateOverflow)?;
327            pen.y = pen
328                .y
329                .checked_add(glyph.advance.y)
330                .ok_or(PositionError::CoordinateOverflow)?;
331        }
332        Ok(PositionedRun {
333            font_id: self.font_id,
334            text: self.text,
335            direction: self.direction(),
336            bidi_level: self.bidi_level,
337            end: pen,
338            glyphs: &output[..self.glyphs.len()],
339        })
340    }
341}
342
343pub struct SafeLineBreaks<'text, 'run, 'glyph> {
344    inner: LineBreaks<'text>,
345    run: &'run ShapedRun<'glyph>,
346    base: u32,
347}
348
349impl Iterator for SafeLineBreaks<'_, '_, '_> {
350    type Item = LineBreak;
351
352    fn next(&mut self) -> Option<Self::Item> {
353        loop {
354            let mut next = self.inner.next()?;
355            next.offset += self.base as usize;
356            if self.run.is_safe_break(next.offset as u32) {
357                return Some(next);
358            }
359        }
360    }
361}
362
363#[derive(Clone, Copy, Debug, Eq, PartialEq)]
364pub enum PositionError {
365    InsufficientCapacity { required: usize },
366    CoordinateOverflow,
367}
368
369#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
370pub struct PositionedGlyph {
371    glyph_id: GlyphId,
372    pub cluster: TextRange,
373    pub origin: FlowPoint,
374    pub advance: FlowPoint,
375    pub offset: FlowPoint,
376    pub bidi_level: u8,
377}
378
379impl PositionedGlyph {
380    pub const fn new(glyph_id: GlyphId, origin: FlowPoint) -> Self {
381        Self {
382            glyph_id,
383            cluster: TextRange::new(0, 0),
384            origin,
385            advance: FlowPoint { x: 0, y: 0 },
386            offset: FlowPoint { x: 0, y: 0 },
387            bidi_level: 0,
388        }
389    }
390
391    pub const fn glyph_id(self) -> GlyphId {
392        self.glyph_id
393    }
394
395    pub const fn with_cluster(mut self, cluster: TextRange) -> Self {
396        self.cluster = cluster;
397        self
398    }
399
400    pub const fn with_advance(mut self, advance: FlowPoint) -> Self {
401        self.advance = advance;
402        self
403    }
404
405    pub const fn with_offset(mut self, offset: FlowPoint) -> Self {
406        self.offset = offset;
407        self
408    }
409
410    pub const fn with_bidi_level(mut self, bidi_level: u8) -> Self {
411        self.bidi_level = bidi_level;
412        self
413    }
414}
415
416pub struct PositionedRun<'a> {
417    font_id: FontId,
418    text: TextRange,
419    direction: Direction,
420    bidi_level: u8,
421    end: FlowPoint,
422    glyphs: &'a [PositionedGlyph],
423}
424
425impl PositionedRun<'_> {
426    pub const fn font_id(&self) -> FontId {
427        self.font_id
428    }
429
430    pub const fn text(&self) -> TextRange {
431        self.text
432    }
433
434    pub const fn direction(&self) -> Direction {
435        self.direction
436    }
437
438    pub const fn end(&self) -> FlowPoint {
439        self.end
440    }
441
442    pub const fn glyphs(&self) -> &[PositionedGlyph] {
443        self.glyphs
444    }
445
446    pub fn carets_into<'output>(
447        &self,
448        output: &'output mut [CaretStop],
449    ) -> Result<&'output [CaretStop], PositionError> {
450        let mut required = 0;
451        let mut previous = None;
452        for glyph in self.glyphs {
453            let text_offset = match self.direction {
454                Direction::LeftToRight => glyph.cluster.start,
455                Direction::RightToLeft => glyph.cluster.end,
456            };
457            if previous != Some(text_offset) {
458                required += 1;
459                previous = Some(text_offset);
460            }
461        }
462        let final_offset = match self.direction {
463            Direction::LeftToRight => self.text.end,
464            Direction::RightToLeft => self.text.start,
465        };
466        if previous != Some(final_offset) {
467            required += 1;
468        }
469        if output.len() < required {
470            return Err(PositionError::InsufficientCapacity { required });
471        }
472        let mut count = 0;
473        for glyph in self.glyphs {
474            let text_offset = match self.direction {
475                Direction::LeftToRight => glyph.cluster.start,
476                Direction::RightToLeft => glyph.cluster.end,
477            };
478            if count == 0 || output[count - 1].text_offset != text_offset {
479                output[count] = CaretStop {
480                    text_offset,
481                    position: glyph.origin,
482                    bidi_level: self.bidi_level,
483                };
484                count += 1;
485            }
486        }
487        let text_offset = match self.direction {
488            Direction::LeftToRight => self.text.end,
489            Direction::RightToLeft => self.text.start,
490        };
491        if count == 0 || output[count - 1].text_offset != text_offset {
492            output[count] = CaretStop {
493                text_offset,
494                position: self.end,
495                bidi_level: self.bidi_level,
496            };
497            count += 1;
498        }
499        Ok(&output[..count])
500    }
501}
502
503#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
504pub struct CaretStop {
505    pub text_offset: u32,
506    pub position: FlowPoint,
507    pub bidi_level: u8,
508}
509
510pub trait Typeface {
511    fn id(&self) -> FontId;
512    fn metrics(&self) -> Result<FontMetrics, FontAccessError>;
513    fn covers(&self, grapheme: &str) -> Result<bool, FontAccessError>;
514    fn supports_complex_shaping(&self) -> bool {
515        true
516    }
517    fn shape_into(
518        &self,
519        request: &ShapeRequest<'_>,
520        output: &mut [ShapedGlyph],
521    ) -> Result<usize, ShapeError>;
522}
523
524pub trait GlyphSource {
525    fn id(&self) -> FontId;
526    fn metrics(&self) -> Result<FontMetrics, FontAccessError>;
527    fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError>;
528    fn glyph_advance(&self, glyph: GlyphId) -> Result<FlowPoint, FontAccessError>;
529
530    fn notdef_glyph(&self) -> Result<Option<GlyphId>, FontAccessError> {
531        Ok(Some(GlyphId::new(0)))
532    }
533
534    fn kerning(&self, _left: GlyphId, _right: GlyphId) -> Result<i32, FontAccessError> {
535        Ok(0)
536    }
537}
538
539pub struct SimpleTypeface<'a, T: ?Sized> {
540    source: &'a T,
541}
542
543impl<'a, T: ?Sized> SimpleTypeface<'a, T> {
544    pub const fn new(source: &'a T) -> Self {
545        Self { source }
546    }
547}
548
549impl<T: ?Sized> Typeface for SimpleTypeface<'_, T>
550where
551    T: GlyphSource,
552{
553    fn id(&self) -> FontId {
554        self.source.id()
555    }
556
557    fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
558        self.source.metrics()
559    }
560
561    fn covers(&self, grapheme: &str) -> Result<bool, FontAccessError> {
562        let mut characters = grapheme.chars();
563        let Some(character) = characters.next() else {
564            return Ok(false);
565        };
566        if characters.next().is_some() {
567            return Ok(false);
568        }
569        Ok(self.source.glyph_for(character)?.is_some())
570    }
571
572    fn supports_complex_shaping(&self) -> bool {
573        false
574    }
575
576    fn shape_into(
577        &self,
578        request: &ShapeRequest<'_>,
579        output: &mut [ShapedGlyph],
580    ) -> Result<usize, ShapeError> {
581        validate_request(request)?;
582        if matches!(request.script, Script::Arabic | Script::Devanagari) {
583            return Err(ShapeError::UnsupportedScript {
584                script: request.script,
585            });
586        }
587        let kern = kerning_enabled(request.features)?;
588        let text = &request.text[request.range.clone()];
589        let required = graphemes(text).count();
590        if output.len() < required {
591            return Err(ShapeError::InsufficientCapacity { required });
592        }
593
594        let mut previous: Option<(usize, GlyphId)> = None;
595        for (logical_index, cluster) in graphemes(text).enumerate() {
596            let mut characters = cluster.text.chars();
597            let character = characters.next().unwrap();
598            if characters.next().is_some() {
599                return Err(ShapeError::UnsupportedCluster {
600                    offset: request.range.start + cluster.range.start,
601                });
602            }
603            let glyph_id = match self.source.glyph_for(character)? {
604                Some(glyph) => glyph,
605                None => self
606                    .source
607                    .notdef_glyph()?
608                    .ok_or(ShapeError::MissingGlyph {
609                        offset: request.range.start + cluster.range.start,
610                    })?,
611            };
612            let output_index = match request.direction {
613                Direction::LeftToRight => logical_index,
614                Direction::RightToLeft => required - logical_index - 1,
615            };
616            let start = request.range.start + cluster.range.start;
617            let end = request.range.start + cluster.range.end;
618            output[output_index] = ShapedGlyph {
619                glyph_id,
620                flags: 0,
621                cluster: TextRange::new(start as u32, end as u32),
622                advance: self.source.glyph_advance(glyph_id)?,
623                offset: FlowPoint::default(),
624            };
625            if kern {
626                if let Some((previous_index, previous_glyph)) = previous {
627                    output[previous_index].advance.x +=
628                        self.source.kerning(previous_glyph, glyph_id)?;
629                }
630                previous = Some((output_index, glyph_id));
631            }
632        }
633        Ok(required)
634    }
635}
636
637fn validate_request(request: &ShapeRequest<'_>) -> Result<(), ShapeError> {
638    if request.range.start > request.range.end
639        || request.range.end > request.text.len()
640        || !request.text.is_char_boundary(request.range.start)
641        || !request.text.is_char_boundary(request.range.end)
642    {
643        return Err(ShapeError::InvalidTextRange);
644    }
645    if request.text.len() > u32::MAX as usize {
646        return Err(ShapeError::TextTooLong);
647    }
648    Ok(())
649}
650
651fn kerning_enabled(features: &[FontFeature]) -> Result<bool, ShapeError> {
652    let mut enabled = true;
653    for feature in features {
654        if feature.tag == *b"kern" {
655            enabled = feature.value != 0;
656        } else {
657            return Err(ShapeError::UnsupportedFeature { tag: feature.tag });
658        }
659    }
660    Ok(enabled)
661}
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666    use std::prelude::v1::*;
667
668    #[test]
669    fn positioned_glyph_builder_preserves_static_placement() {
670        let glyph = PositionedGlyph::new(GlyphId::new(7), FlowPoint { x: 10, y: 20 })
671            .with_cluster(TextRange::new(2, 4))
672            .with_advance(FlowPoint { x: 8, y: 0 })
673            .with_offset(FlowPoint { x: 1, y: -2 })
674            .with_bidi_level(1);
675
676        assert_eq!(glyph.glyph_id(), GlyphId::new(7));
677        assert_eq!(glyph.cluster, TextRange::new(2, 4));
678        assert_eq!(glyph.origin, FlowPoint { x: 10, y: 20 });
679        assert_eq!(glyph.advance, FlowPoint { x: 8, y: 0 });
680        assert_eq!(glyph.offset, FlowPoint { x: 1, y: -2 });
681        assert_eq!(glyph.bidi_level, 1);
682    }
683
684    struct MockFont;
685
686    impl GlyphSource for MockFont {
687        fn id(&self) -> FontId {
688            FontId::new(4)
689        }
690
691        fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
692            Ok(FontMetrics {
693                units_per_em: 1000,
694                ascender: 800,
695                descender: -200,
696                line_gap: 0,
697            })
698        }
699
700        fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
701            Ok(character
702                .is_ascii()
703                .then_some(GlyphId::new(character as u16)))
704        }
705
706        fn glyph_advance(&self, _glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
707            Ok(FlowPoint { x: 600, y: 0 })
708        }
709
710        fn kerning(&self, left: GlyphId, right: GlyphId) -> Result<i32, FontAccessError> {
711            Ok(
712                if left.value() == b'A' as u16 && right.value() == b'V' as u16 {
713                    -80
714                } else {
715                    0
716                },
717            )
718        }
719    }
720
721    #[test]
722    fn shapes_into_caller_storage_with_kerning() {
723        let face = SimpleTypeface::new(&MockFont);
724        assert!(!face.supports_complex_shaping());
725        let text = "AV";
726        let mut output = [ShapedGlyph::default(); 2];
727        let count = face
728            .shape_into(
729                &ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Latin),
730                &mut output,
731            )
732            .unwrap();
733
734        assert_eq!(count, 2);
735        assert_eq!(output[0].advance.x, 520);
736        assert_eq!(output[1].advance.x, 600);
737    }
738
739    #[test]
740    fn reverses_rtl_output_without_heap_storage() {
741        let face = SimpleTypeface::new(&MockFont);
742        let text = "abc";
743        let mut output = [ShapedGlyph::default(); 3];
744        face.shape_into(
745            &ShapeRequest::new(text, 0..text.len(), Direction::RightToLeft, Script::Hebrew),
746            &mut output,
747        )
748        .unwrap();
749
750        assert_eq!(output[0].glyph_id(), GlyphId::new(b'c' as u16));
751        assert_eq!(output[2].glyph_id(), GlyphId::new(b'a' as u16));
752    }
753
754    #[test]
755    fn reports_capacity_and_unsupported_clusters() {
756        let face = SimpleTypeface::new(&MockFont);
757        let mut output = [ShapedGlyph::default(); 1];
758        let text = "ab";
759        assert_eq!(
760            face.shape_into(
761                &ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Latin,),
762                &mut output,
763            ),
764            Err(ShapeError::InsufficientCapacity { required: 2 })
765        );
766        let combined = "a\u{301}";
767        assert_eq!(
768            face.shape_into(
769                &ShapeRequest::new(
770                    combined,
771                    0..combined.len(),
772                    Direction::LeftToRight,
773                    Script::Latin,
774                ),
775                &mut output,
776            ),
777            Err(ShapeError::UnsupportedCluster { offset: 0 })
778        );
779    }
780
781    #[test]
782    fn run_rejects_breaks_inside_or_before_unsafe_clusters() {
783        let mut glyphs = [
784            ShapedGlyph::new(GlyphId::new(1), TextRange::new(0, 3)),
785            ShapedGlyph::new(GlyphId::new(2), TextRange::new(3, 4)),
786        ];
787        glyphs[1].set_unsafe_to_break(true);
788        let run = ShapedRun::new(FontId::new(4), TextRange::new(0, 4), 0, &glyphs);
789
790        assert!(run.is_safe_break(0));
791        assert!(!run.is_safe_break(1));
792        assert!(!run.is_safe_break(3));
793        assert!(run.is_safe_break(4));
794        assert!(!run.is_safe_break(5));
795    }
796
797    #[test]
798    fn run_filters_unsafe_unicode_breaks() {
799        let text = "hello world";
800        let mut glyphs = [ShapedGlyph::default(); 11];
801        for (index, glyph) in glyphs.iter_mut().enumerate() {
802            *glyph = ShapedGlyph::new(
803                GlyphId::new(index as u16),
804                TextRange::new(index as u32, index as u32 + 1),
805            );
806        }
807        glyphs[6].set_unsafe_to_break(true);
808        let run = ShapedRun::new(
809            FontId::new(4),
810            TextRange::new(0, text.len() as u32),
811            0,
812            &glyphs,
813        );
814        let breaks = run.line_breaks(text).unwrap().collect::<Vec<_>>();
815
816        assert_eq!(breaks.len(), 1);
817        assert_eq!(breaks[0].offset, text.len());
818    }
819
820    #[test]
821    fn positions_glyphs_and_emits_visual_carets() {
822        let mut glyphs = [
823            ShapedGlyph::new(GlyphId::new(1), TextRange::new(0, 1)),
824            ShapedGlyph::new(GlyphId::new(2), TextRange::new(1, 2)),
825        ];
826        glyphs[0].advance.x = 3;
827        glyphs[1].advance.x = 4;
828        let run = ShapedRun::new(FontId::new(4), TextRange::new(0, 2), 0, &glyphs);
829        let mut positioned = [PositionedGlyph::default(); 2];
830        let positioned = run
831            .position_into(FlowPoint { x: 10, y: 20 }, &mut positioned)
832            .unwrap();
833
834        assert_eq!(positioned.glyphs()[0].origin, FlowPoint { x: 10, y: 20 });
835        assert_eq!(positioned.glyphs()[1].origin, FlowPoint { x: 13, y: 20 });
836        assert_eq!(positioned.end(), FlowPoint { x: 17, y: 20 });
837
838        let mut carets = [CaretStop::default(); 3];
839        let carets = positioned.carets_into(&mut carets).unwrap();
840        assert_eq!(carets[0].text_offset, 0);
841        assert_eq!(carets[1].text_offset, 1);
842        assert_eq!(carets[2].text_offset, 2);
843        assert_eq!(carets[2].position.x, 17);
844    }
845
846    #[test]
847    fn request_carries_explicit_line_edges() {
848        let request = ShapeRequest::new("a", 0..1, Direction::LeftToRight, Script::Latin)
849            .with_line_edges(LineEdges::BOTH);
850
851        assert!(request.line_edges.has_start());
852        assert!(request.line_edges.has_end());
853    }
854
855    #[test]
856    fn uses_notdef_for_an_uncovered_scalar() {
857        let face = SimpleTypeface::new(&MockFont);
858        let text = "δΈ–";
859        let mut output = [ShapedGlyph::default(); 1];
860        let count = face
861            .shape_into(
862                &ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Han),
863                &mut output,
864            )
865            .unwrap();
866
867        assert_eq!(count, 1);
868        assert_eq!(output[0].glyph_id(), GlyphId::new(0));
869    }
870}