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 {
514 fn id(&self) -> FontId;
515 fn metrics(&self) -> Result<FontMetrics, FontAccessError>;
516 fn covers(&self, grapheme: &str) -> Result<bool, FontAccessError>;
517 fn supports_complex_shaping(&self) -> bool {
518 true
519 }
520 fn shape_into(
521 &self,
522 request: &ShapeRequest<'_>,
523 output: &mut [ShapedGlyph],
524 ) -> Result<usize, ShapeError>;
525}
526
527pub trait GlyphSource {
528 fn id(&self) -> FontId;
529 fn metrics(&self) -> Result<FontMetrics, FontAccessError>;
530 fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError>;
531 fn glyph_advance(&self, glyph: GlyphId) -> Result<FlowPoint, FontAccessError>;
532
533 fn notdef_glyph(&self) -> Result<Option<GlyphId>, FontAccessError> {
534 Ok(Some(GlyphId::new(0)))
535 }
536
537 fn kerning(&self, _left: GlyphId, _right: GlyphId) -> Result<i32, FontAccessError> {
538 Ok(0)
539 }
540}
541
542pub struct SimpleTypeface<'a, T: ?Sized> {
543 source: &'a T,
544}
545
546impl<'a, T: ?Sized> SimpleTypeface<'a, T> {
547 pub const fn new(source: &'a T) -> Self {
548 Self { source }
549 }
550}
551
552impl<T: ?Sized> Typeface for SimpleTypeface<'_, T>
553where
554 T: GlyphSource,
555{
556 fn id(&self) -> FontId {
557 self.source.id()
558 }
559
560 fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
561 self.source.metrics()
562 }
563
564 fn covers(&self, grapheme: &str) -> Result<bool, FontAccessError> {
565 let mut characters = grapheme.chars();
566 let Some(character) = characters.next() else {
567 return Ok(false);
568 };
569 if characters.next().is_some() {
570 return Ok(false);
571 }
572 Ok(self.source.glyph_for(character)?.is_some())
573 }
574
575 fn supports_complex_shaping(&self) -> bool {
576 false
577 }
578
579 fn shape_into(
580 &self,
581 request: &ShapeRequest<'_>,
582 output: &mut [ShapedGlyph],
583 ) -> Result<usize, ShapeError> {
584 validate_request(request)?;
585 if matches!(request.script, Script::Arabic | Script::Devanagari) {
586 return Err(ShapeError::UnsupportedScript {
587 script: request.script,
588 });
589 }
590 let kern = kerning_enabled(request.features)?;
591 let text = &request.text[request.range.clone()];
592 let required = graphemes(text).count();
593 if output.len() < required {
594 return Err(ShapeError::InsufficientCapacity { required });
595 }
596
597 let mut previous: Option<(usize, GlyphId)> = None;
598 for (logical_index, cluster) in graphemes(text).enumerate() {
599 let mut characters = cluster.text.chars();
600 let character = characters.next().unwrap();
601 if characters.next().is_some() {
602 return Err(ShapeError::UnsupportedCluster {
603 offset: request.range.start + cluster.range.start,
604 });
605 }
606 let glyph_id = match self.source.glyph_for(character)? {
607 Some(glyph) => glyph,
608 None => self
609 .source
610 .notdef_glyph()?
611 .ok_or(ShapeError::MissingGlyph {
612 offset: request.range.start + cluster.range.start,
613 })?,
614 };
615 let output_index = match request.direction {
616 Direction::LeftToRight => logical_index,
617 Direction::RightToLeft => required - logical_index - 1,
618 };
619 let start = request.range.start + cluster.range.start;
620 let end = request.range.start + cluster.range.end;
621 output[output_index] = ShapedGlyph {
622 glyph_id,
623 flags: 0,
624 cluster: TextRange::new(start as u32, end as u32),
625 advance: self.source.glyph_advance(glyph_id)?,
626 offset: FlowPoint::default(),
627 };
628 if kern {
629 if let Some((previous_index, previous_glyph)) = previous {
630 output[previous_index].advance.x +=
631 self.source.kerning(previous_glyph, glyph_id)?;
632 }
633 previous = Some((output_index, glyph_id));
634 }
635 }
636 Ok(required)
637 }
638}
639
640fn validate_request(request: &ShapeRequest<'_>) -> Result<(), ShapeError> {
641 if request.range.start > request.range.end
642 || request.range.end > request.text.len()
643 || !request.text.is_char_boundary(request.range.start)
644 || !request.text.is_char_boundary(request.range.end)
645 {
646 return Err(ShapeError::InvalidTextRange);
647 }
648 if request.text.len() > u32::MAX as usize {
649 return Err(ShapeError::TextTooLong);
650 }
651 Ok(())
652}
653
654fn kerning_enabled(features: &[FontFeature]) -> Result<bool, ShapeError> {
655 let mut enabled = true;
656 for feature in features {
657 if feature.tag == *b"kern" {
658 enabled = feature.value != 0;
659 } else {
660 return Err(ShapeError::UnsupportedFeature { tag: feature.tag });
661 }
662 }
663 Ok(enabled)
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669 use std::prelude::v1::*;
670
671 #[test]
672 fn positioned_glyph_builder_preserves_static_placement() {
673 let glyph = PositionedGlyph::new(GlyphId::new(7), FlowPoint { x: 10, y: 20 })
674 .with_cluster(TextRange::new(2, 4))
675 .with_advance(FlowPoint { x: 8, y: 0 })
676 .with_offset(FlowPoint { x: 1, y: -2 })
677 .with_bidi_level(1);
678
679 assert_eq!(glyph.glyph_id(), GlyphId::new(7));
680 assert_eq!(glyph.cluster, TextRange::new(2, 4));
681 assert_eq!(glyph.origin, FlowPoint { x: 10, y: 20 });
682 assert_eq!(glyph.advance, FlowPoint { x: 8, y: 0 });
683 assert_eq!(glyph.offset, FlowPoint { x: 1, y: -2 });
684 assert_eq!(glyph.bidi_level, 1);
685 }
686
687 struct MockFont;
688
689 impl GlyphSource for MockFont {
690 fn id(&self) -> FontId {
691 FontId::new(4)
692 }
693
694 fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
695 Ok(FontMetrics {
696 units_per_em: 1000,
697 ascender: 800,
698 descender: -200,
699 line_gap: 0,
700 })
701 }
702
703 fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
704 Ok(character
705 .is_ascii()
706 .then_some(GlyphId::new(character as u16)))
707 }
708
709 fn glyph_advance(&self, _glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
710 Ok(FlowPoint { x: 600, y: 0 })
711 }
712
713 fn kerning(&self, left: GlyphId, right: GlyphId) -> Result<i32, FontAccessError> {
714 Ok(
715 if left.value() == b'A' as u16 && right.value() == b'V' as u16 {
716 -80
717 } else {
718 0
719 },
720 )
721 }
722 }
723
724 #[test]
725 fn shapes_into_caller_storage_with_kerning() {
726 let face = SimpleTypeface::new(&MockFont);
727 assert!(!face.supports_complex_shaping());
728 let text = "AV";
729 let mut output = [ShapedGlyph::default(); 2];
730 let count = face
731 .shape_into(
732 &ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Latin),
733 &mut output,
734 )
735 .unwrap();
736
737 assert_eq!(count, 2);
738 assert_eq!(output[0].advance.x, 520);
739 assert_eq!(output[1].advance.x, 600);
740 }
741
742 #[test]
743 fn reverses_rtl_output_without_heap_storage() {
744 let face = SimpleTypeface::new(&MockFont);
745 let text = "abc";
746 let mut output = [ShapedGlyph::default(); 3];
747 face.shape_into(
748 &ShapeRequest::new(text, 0..text.len(), Direction::RightToLeft, Script::Hebrew),
749 &mut output,
750 )
751 .unwrap();
752
753 assert_eq!(output[0].glyph_id(), GlyphId::new(b'c' as u16));
754 assert_eq!(output[2].glyph_id(), GlyphId::new(b'a' as u16));
755 }
756
757 #[test]
758 fn reports_capacity_and_unsupported_clusters() {
759 let face = SimpleTypeface::new(&MockFont);
760 let mut output = [ShapedGlyph::default(); 1];
761 let text = "ab";
762 assert_eq!(
763 face.shape_into(
764 &ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Latin,),
765 &mut output,
766 ),
767 Err(ShapeError::InsufficientCapacity { required: 2 })
768 );
769 let combined = "a\u{301}";
770 assert_eq!(
771 face.shape_into(
772 &ShapeRequest::new(
773 combined,
774 0..combined.len(),
775 Direction::LeftToRight,
776 Script::Latin,
777 ),
778 &mut output,
779 ),
780 Err(ShapeError::UnsupportedCluster { offset: 0 })
781 );
782 }
783
784 #[test]
785 fn run_rejects_breaks_inside_or_before_unsafe_clusters() {
786 let mut glyphs = [
787 ShapedGlyph::new(GlyphId::new(1), TextRange::new(0, 3)),
788 ShapedGlyph::new(GlyphId::new(2), TextRange::new(3, 4)),
789 ];
790 glyphs[1].set_unsafe_to_break(true);
791 let run = ShapedRun::new(FontId::new(4), TextRange::new(0, 4), 0, &glyphs);
792
793 assert!(run.is_safe_break(0));
794 assert!(!run.is_safe_break(1));
795 assert!(!run.is_safe_break(3));
796 assert!(run.is_safe_break(4));
797 assert!(!run.is_safe_break(5));
798 }
799
800 #[test]
801 fn run_filters_unsafe_unicode_breaks() {
802 let text = "hello world";
803 let mut glyphs = [ShapedGlyph::default(); 11];
804 for (index, glyph) in glyphs.iter_mut().enumerate() {
805 *glyph = ShapedGlyph::new(
806 GlyphId::new(index as u16),
807 TextRange::new(index as u32, index as u32 + 1),
808 );
809 }
810 glyphs[6].set_unsafe_to_break(true);
811 let run = ShapedRun::new(
812 FontId::new(4),
813 TextRange::new(0, text.len() as u32),
814 0,
815 &glyphs,
816 );
817 let breaks = run.line_breaks(text).unwrap().collect::<Vec<_>>();
818
819 assert_eq!(breaks.len(), 1);
820 assert_eq!(breaks[0].offset, text.len());
821 }
822
823 #[test]
824 fn positions_glyphs_and_emits_visual_carets() {
825 let mut glyphs = [
826 ShapedGlyph::new(GlyphId::new(1), TextRange::new(0, 1)),
827 ShapedGlyph::new(GlyphId::new(2), TextRange::new(1, 2)),
828 ];
829 glyphs[0].advance.x = 3;
830 glyphs[1].advance.x = 4;
831 let run = ShapedRun::new(FontId::new(4), TextRange::new(0, 2), 0, &glyphs);
832 let mut positioned = [PositionedGlyph::default(); 2];
833 let positioned = run
834 .position_into(FlowPoint { x: 10, y: 20 }, &mut positioned)
835 .unwrap();
836
837 assert_eq!(positioned.glyphs()[0].origin, FlowPoint { x: 10, y: 20 });
838 assert_eq!(positioned.glyphs()[1].origin, FlowPoint { x: 13, y: 20 });
839 assert_eq!(positioned.end(), FlowPoint { x: 17, y: 20 });
840
841 let mut carets = [CaretStop::default(); 3];
842 let carets = positioned.carets_into(&mut carets).unwrap();
843 assert_eq!(carets[0].text_offset, 0);
844 assert_eq!(carets[1].text_offset, 1);
845 assert_eq!(carets[2].text_offset, 2);
846 assert_eq!(carets[2].position.x, 17);
847 }
848
849 #[test]
850 fn request_carries_explicit_line_edges() {
851 let request = ShapeRequest::new("a", 0..1, Direction::LeftToRight, Script::Latin)
852 .with_line_edges(LineEdges::BOTH);
853
854 assert!(request.line_edges.has_start());
855 assert!(request.line_edges.has_end());
856 }
857
858 #[test]
859 fn uses_notdef_for_an_uncovered_scalar() {
860 let face = SimpleTypeface::new(&MockFont);
861 let text = "δΈ–";
862 let mut output = [ShapedGlyph::default(); 1];
863 let count = face
864 .shape_into(
865 &ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Han),
866 &mut output,
867 )
868 .unwrap();
869
870 assert_eq!(count, 1);
871 assert_eq!(output[0].glyph_id(), GlyphId::new(0));
872 }
873}