1use std::collections::{HashMap, HashSet};
5use std::num::NonZeroU16;
6use std::sync::Arc;
7
8use fontdb::ID;
9use harfrust::ShapeOptions;
10use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
11use strict_num::NonZeroPositiveF32;
12use tiny_skia_path::{NonZeroRect, Transform};
13use unicode_script::UnicodeScript;
14
15use super::cache::{FontCache, FontInstance, with_optical_sizing};
16use crate::tree::{BBox, IsValidLength};
17use crate::{
18 AlignmentBaseline, ApproxZeroUlps, BaselineShift, DominantBaseline, Fill, FillRule, Font,
19 FontResolver, GlyphId, LengthAdjust, PaintOrder, Path, ShapeRendering, Stroke, Text,
20 TextAnchor, TextChunk, TextDecorationStyle, TextFlow, TextPath, TextSpan, WritingMode,
21};
22
23#[derive(Clone, Debug)]
28pub struct PositionedGlyph {
29 glyph_ts: Transform,
33 cluster_ts: Transform,
35 span_ts: Transform,
37 units_per_em: u16,
39 font_size: f32,
41 pub id: GlyphId,
43 pub text: String,
45 pub font: ID,
48}
49
50impl PositionedGlyph {
51 pub fn font_size(&self) -> f32 {
53 self.font_size
54 }
55
56 pub fn transform(&self) -> Transform {
58 let sx = self.font_size / self.units_per_em as f32;
59
60 self.span_ts
61 .pre_concat(self.cluster_ts)
62 .pre_concat(Transform::from_scale(sx, sx))
63 .pre_concat(self.glyph_ts)
64 }
65
66 pub fn outline_transform(&self) -> Transform {
69 self.transform()
71 .pre_concat(Transform::from_scale(1.0, -1.0))
72 }
73
74 pub fn cbdt_transform(&self, x: f32, y: f32, pixels_per_em: f32) -> Transform {
77 self.transform()
78 .pre_concat(Transform::from_scale(
79 self.units_per_em as f32 / pixels_per_em,
80 self.units_per_em as f32 / pixels_per_em,
81 ))
82 .pre_translate(x, -y)
86 }
87
88 pub fn sbix_transform(
91 &self,
92 x: f32,
93 y: f32,
94 bearing_x: f32,
95 bearing_y: f32,
96 pixels_per_em: f32,
97 height: f32,
98 ) -> Transform {
99 self.transform()
100 .pre_translate(bearing_x, -bearing_y)
101 .pre_concat(Transform::from_scale(
102 self.units_per_em as f32 / pixels_per_em,
103 self.units_per_em as f32 / pixels_per_em,
104 ))
105 .pre_translate(x, -height - y)
109 }
110
111 pub fn svg_transform(&self) -> Transform {
114 self.transform()
115 }
116
117 pub fn colr_transform(&self) -> Transform {
120 self.outline_transform()
121 }
122}
123
124#[derive(Clone, Debug)]
127pub struct Span {
128 pub fill: Option<Fill>,
130 pub stroke: Option<Stroke>,
132 pub paint_order: PaintOrder,
134 pub font_size: NonZeroPositiveF32,
136 pub variations: Vec<crate::FontVariation>,
138 pub font_optical_sizing: crate::FontOpticalSizing,
140 pub visible: bool,
142 pub positioned_glyphs: Vec<PositionedGlyph>,
144 pub underline: Option<Box<Path>>,
147 pub overline: Option<Box<Path>>,
150 pub line_through: Option<Box<Path>>,
153}
154
155#[derive(Clone, Debug)]
156struct GlyphCluster {
157 byte_idx: ByteIndex,
158 codepoint: char,
159 width: f32,
160 advance: f32,
161 text_length_spacing: f32,
162 ascent: f32,
163 descent: f32,
164 has_relative_shift: bool,
165 glyphs: Vec<PositionedGlyph>,
166 transform: Transform,
167 path_transform: Transform,
168 visible: bool,
169}
170
171impl GlyphCluster {
172 pub(crate) fn height(&self) -> f32 {
173 self.ascent - self.descent
174 }
175
176 pub(crate) fn transform(&self) -> Transform {
177 self.path_transform.post_concat(self.transform)
178 }
179}
180
181pub(crate) fn layout_text(
182 text_node: &Text,
183 resolver: &FontResolver,
184 fonts: &mut FontCache,
185) -> Option<(Vec<Span>, NonZeroRect)> {
186 for chunk in &text_node.chunks {
187 for span in &chunk.spans {
188 if !fonts.resolved.contains_key(&span.font) {
189 if let Some(font) = (resolver.select_font)(&span.font, &mut fonts.fontdb)
190 .and_then(|id| resolve_font(id, &span.font.variations, fonts))
191 {
192 fonts.resolved.insert(span.font.clone(), Arc::new(font));
193 }
194 }
195 }
196 }
197
198 let mut spans = Vec::with_capacity(text_node.chunks.iter().map(|c| c.spans.len()).sum());
199 let mut char_offset = 0;
200 let mut last_x = 0.0;
201 let mut last_y = 0.0;
202 let mut bbox = BBox::default();
203 for chunk in &text_node.chunks {
204 let (x, y) = match chunk.text_flow {
205 TextFlow::Linear => (chunk.x.unwrap_or(last_x), chunk.y.unwrap_or(last_y)),
206 TextFlow::Path(_) => (0.0, 0.0),
207 };
208
209 let mut clusters = process_chunk(chunk, resolver, fonts);
210 if clusters.is_empty() {
211 char_offset += chunk.text.chars().count();
212 continue;
213 }
214
215 apply_writing_mode(text_node.writing_mode, &mut clusters);
216 apply_letter_spacing(chunk, &mut clusters);
217 apply_word_spacing(chunk, &mut clusters);
218
219 apply_length_adjust(chunk, &mut clusters);
220 let mut curr_pos = resolve_clusters_positions(
221 text_node,
222 chunk,
223 char_offset,
224 text_node.writing_mode,
225 &fonts.resolved,
226 &mut clusters,
227 );
228
229 let mut text_ts = Transform::default();
230 if text_node.writing_mode == WritingMode::TopToBottom {
231 if let TextFlow::Linear = chunk.text_flow {
232 text_ts = text_ts.pre_rotate_at(90.0, x, y);
233 }
234 }
235
236 for span in &chunk.spans {
237 let font = match fonts.resolved.get(&span.font) {
238 Some(v) => v,
239 None => continue,
240 };
241
242 let decoration_spans = collect_decoration_spans(span, &clusters);
243
244 let mut span_ts = text_ts;
245 span_ts = span_ts.pre_translate(x, y);
246 if let TextFlow::Linear = chunk.text_flow {
247 let shift = resolve_baseline(span, font, text_node.writing_mode);
248
249 span_ts = span_ts.pre_translate(0.0, shift);
253 }
254
255 let mut underline = None;
256 let mut overline = None;
257 let mut line_through = None;
258
259 if let Some(decoration) = span.decoration.underline.clone() {
260 let offset = match text_node.writing_mode {
265 WritingMode::LeftToRight => -font.underline_position(span.font_size.get()),
266 WritingMode::TopToBottom => font.height(span.font_size.get()) / 2.0,
267 };
268
269 if let Some(path) =
270 convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)
271 {
272 bbox = bbox.expand(path.data.bounds());
273 underline = Some(Box::new(path));
274 }
275 }
276
277 if let Some(decoration) = span.decoration.overline.clone() {
278 let offset = match text_node.writing_mode {
279 WritingMode::LeftToRight => -font.ascent(span.font_size.get()),
280 WritingMode::TopToBottom => -font.height(span.font_size.get()) / 2.0,
281 };
282
283 if let Some(path) =
284 convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)
285 {
286 bbox = bbox.expand(path.data.bounds());
287 overline = Some(Box::new(path));
288 }
289 }
290
291 if let Some(decoration) = span.decoration.line_through.clone() {
292 let offset = match text_node.writing_mode {
293 WritingMode::LeftToRight => -font.line_through_position(span.font_size.get()),
294 WritingMode::TopToBottom => 0.0,
295 };
296
297 if let Some(path) =
298 convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)
299 {
300 bbox = bbox.expand(path.data.bounds());
301 line_through = Some(Box::new(path));
302 }
303 }
304
305 let mut fill = span.fill.clone();
306 if let Some(ref mut fill) = fill {
307 fill.rule = FillRule::NonZero;
313 }
314
315 if let Some((span_fragments, span_bbox)) = convert_span(span, &clusters, span_ts) {
316 bbox = bbox.expand(span_bbox);
317
318 let positioned_glyphs = span_fragments
319 .into_iter()
320 .flat_map(|mut gc| {
321 let cluster_ts = gc.transform();
322 gc.glyphs.iter_mut().for_each(|pg| {
323 pg.cluster_ts = cluster_ts;
324 pg.span_ts = span_ts;
325 });
326 gc.glyphs
327 })
328 .collect();
329
330 spans.push(Span {
331 fill,
332 stroke: span.stroke.clone(),
333 paint_order: span.paint_order,
334 font_size: span.font_size,
335 variations: span.font.variations.clone(),
336 font_optical_sizing: span.font_optical_sizing,
337 visible: span.visible,
338 positioned_glyphs,
339 underline,
340 overline,
341 line_through,
342 });
343 }
344 }
345
346 char_offset += chunk.text.chars().count();
347
348 if text_node.writing_mode == WritingMode::TopToBottom {
349 if let TextFlow::Linear = chunk.text_flow {
350 std::mem::swap(&mut curr_pos.0, &mut curr_pos.1);
351 }
352 }
353
354 last_x = x + curr_pos.0;
355 last_y = y + curr_pos.1;
356 }
357
358 let bbox = bbox.to_non_zero_rect()?;
359
360 Some((spans, bbox))
361}
362
363fn convert_span(
364 span: &TextSpan,
365 clusters: &[GlyphCluster],
366 text_ts: Transform,
367) -> Option<(Vec<GlyphCluster>, NonZeroRect)> {
368 let mut span_clusters = vec![];
369 let mut bboxes_builder = tiny_skia_path::PathBuilder::new();
370
371 for cluster in clusters {
372 if !cluster.visible {
373 continue;
374 }
375
376 if span_contains(span, cluster.byte_idx) {
377 span_clusters.push(cluster.clone());
378 }
379
380 let mut advance = cluster.advance;
381 if advance <= 0.0 {
382 advance = 1.0;
383 }
384
385 if let Some(r) = NonZeroRect::from_xywh(0.0, -cluster.ascent, advance, cluster.height()) {
387 if let Some(r) = r.transform(cluster.transform()) {
388 bboxes_builder.push_rect(r.to_rect());
389 }
390 }
391 }
392
393 let mut bboxes = bboxes_builder.finish()?;
394 bboxes = bboxes.transform(text_ts)?;
395 let bbox = bboxes.compute_tight_bounds()?.to_non_zero_rect()?;
396
397 Some((span_clusters, bbox))
398}
399
400fn collect_decoration_spans(span: &TextSpan, clusters: &[GlyphCluster]) -> Vec<DecorationSpan> {
401 let mut spans = Vec::new();
402
403 let mut started = false;
404 let mut width = 0.0;
405 let mut transform = Transform::default();
406
407 for cluster in clusters {
408 if span_contains(span, cluster.byte_idx) {
409 if started && cluster.has_relative_shift {
410 started = false;
411 spans.push(DecorationSpan { width, transform });
412 }
413
414 if !started {
415 width = cluster.advance;
416 started = true;
417 transform = cluster.transform;
418 } else {
419 width += cluster.advance;
420 }
421 } else if started {
422 spans.push(DecorationSpan { width, transform });
423 started = false;
424 }
425 }
426
427 if started {
428 spans.push(DecorationSpan { width, transform });
429 }
430
431 spans
432}
433
434pub(crate) fn convert_decoration(
435 dy: f32,
436 span: &TextSpan,
437 font: &ResolvedFont,
438 mut decoration: TextDecorationStyle,
439 decoration_spans: &[DecorationSpan],
440 transform: Transform,
441) -> Option<Path> {
442 debug_assert!(!decoration_spans.is_empty());
443
444 let thickness = font.underline_thickness(span.font_size.get());
445
446 let mut builder = tiny_skia_path::PathBuilder::new();
447 for dec_span in decoration_spans {
448 let rect = match NonZeroRect::from_xywh(0.0, -thickness / 2.0, dec_span.width, thickness) {
449 Some(v) => v,
450 None => {
451 log::warn!("a decoration span has a malformed bbox");
452 continue;
453 }
454 };
455
456 let ts = dec_span.transform.pre_translate(0.0, dy);
457
458 let mut path = tiny_skia_path::PathBuilder::from_rect(rect.to_rect());
459 path = match path.transform(ts) {
460 Some(v) => v,
461 None => continue,
462 };
463
464 builder.push_path(&path);
465 }
466
467 let mut path_data = builder.finish()?;
468 path_data = path_data.transform(transform)?;
469
470 Some(Path::new(
471 Box::default(),
472 span.visible,
473 decoration.fill.take(),
474 decoration.stroke.take(),
475 PaintOrder::default(),
476 ShapeRendering::default(),
477 Arc::new(path_data),
478 Transform::default(),
479 ))
480}
481
482#[derive(Clone, Copy)]
487pub(crate) struct DecorationSpan {
488 pub(crate) width: f32,
489 pub(crate) transform: Transform,
490}
491
492fn resolve_clusters_positions(
498 text: &Text,
499 chunk: &TextChunk,
500 char_offset: usize,
501 writing_mode: WritingMode,
502 fonts_cache: &FontsCache,
503 clusters: &mut [GlyphCluster],
504) -> (f32, f32) {
505 match chunk.text_flow {
506 TextFlow::Linear => {
507 resolve_clusters_positions_horizontal(text, chunk, char_offset, writing_mode, clusters)
508 }
509 TextFlow::Path(ref path) => resolve_clusters_positions_path(
510 text,
511 chunk,
512 char_offset,
513 path,
514 writing_mode,
515 fonts_cache,
516 clusters,
517 ),
518 }
519}
520
521fn clusters_length(clusters: &[GlyphCluster]) -> f32 {
522 clusters.iter().fold(0.0, |w, cluster| w + cluster.advance)
523}
524
525fn resolve_relative_shifts(
526 text: &Text,
527 chunk: &TextChunk,
528 offset: usize,
529 clusters: &[GlyphCluster],
530) -> (Vec<(f32, f32)>, Vec<usize>) {
531 let mut logical_order: Vec<usize> = (0..clusters.len()).collect();
534 logical_order.sort_by_key(|&i| clusters[i].byte_idx.value());
535
536 let mut shifts = vec![(0.0, 0.0); clusters.len()];
537 let (mut shift_x, mut shift_y) = (0.0, 0.0);
538 for &i in &logical_order {
539 let cp = offset + clusters[i].byte_idx.code_point_at(&chunk.text);
540 shift_x += text.dx.get(cp).cloned().unwrap_or(0.0);
541 shift_y += text.dy.get(cp).cloned().unwrap_or(0.0);
542 shifts[i] = (shift_x, shift_y);
543 }
544
545 (shifts, logical_order)
546}
547
548fn resolve_clusters_positions_horizontal(
549 text: &Text,
550 chunk: &TextChunk,
551 offset: usize,
552 writing_mode: WritingMode,
553 clusters: &mut [GlyphCluster],
554) -> (f32, f32) {
555 let (mut shifts, logical_order) = resolve_relative_shifts(text, chunk, offset, clusters);
556 let first = logical_order[0];
557 let last = logical_order[logical_order.len() - 1];
558
559 if writing_mode == WritingMode::TopToBottom {
561 for shift in &mut shifts {
562 *shift = (shift.1, -shift.0);
563 }
564 }
565
566 for i in 1..clusters.len() {
567 if shifts[i] != shifts[i - 1] {
568 clusters[i].has_relative_shift = true;
569 }
570 }
571
572 let mut left = f32::INFINITY;
573 let mut right = f32::NEG_INFINITY;
574 let mut advance = 0.0;
575 for (cluster, (shift_x, _)) in clusters.iter().zip(&shifts) {
576 let start = advance + shift_x;
577 let end = start + cluster.advance - cluster.text_length_spacing;
578 left = left.min(start).min(end);
579 right = right.max(start).max(end);
580 advance += cluster.advance;
581 }
582
583 let mut x = shifts[first].0 - left + process_anchor(chunk.anchor, right - left);
584
585 for (cluster, (shift_x, shift_y)) in clusters.iter_mut().zip(&shifts) {
586 let cp = offset + cluster.byte_idx.code_point_at(&chunk.text);
587
588 cluster.transform = cluster.transform.pre_translate(x + shift_x, *shift_y);
589
590 if let Some(angle) = text.rotate.get(cp).cloned() {
591 if !angle.approx_zero_ulps(4) {
592 cluster.transform = cluster.transform.pre_rotate(angle);
593 cluster.has_relative_shift = true;
594 }
595 }
596
597 x += cluster.advance;
598 }
599
600 (x + shifts[last].0, shifts[last].1)
601}
602
603pub(crate) fn resolve_baseline(
612 span: &TextSpan,
613 font: &ResolvedFont,
614 writing_mode: WritingMode,
615) -> f32 {
616 let mut shift = -resolve_baseline_shift(&span.baseline_shift, font, span.font_size.get());
617
618 if writing_mode == WritingMode::LeftToRight {
620 if span.alignment_baseline == AlignmentBaseline::Auto
621 || span.alignment_baseline == AlignmentBaseline::Baseline
622 {
623 shift += font.dominant_baseline_shift(span.dominant_baseline, span.font_size.get());
624 } else {
625 shift += font.alignment_baseline_shift(span.alignment_baseline, span.font_size.get());
626 }
627 }
628
629 shift
630}
631
632fn resolve_baseline_shift(baselines: &[BaselineShift], font: &ResolvedFont, font_size: f32) -> f32 {
633 let mut shift = 0.0;
634 for baseline in baselines.iter().rev() {
635 match baseline {
636 BaselineShift::Baseline => {}
637 BaselineShift::Subscript => shift -= font.subscript_offset(font_size),
638 BaselineShift::Superscript => shift += font.superscript_offset(font_size),
639 BaselineShift::Number(n) => shift += n,
640 }
641 }
642
643 shift
644}
645
646fn resolve_clusters_positions_path(
647 text: &Text,
648 chunk: &TextChunk,
649 char_offset: usize,
650 path: &TextPath,
651 writing_mode: WritingMode,
652 fonts_cache: &FontsCache,
653 clusters: &mut [GlyphCluster],
654) -> (f32, f32) {
655 let mut last_x = 0.0;
656 let mut last_y = 0.0;
657
658 let (shifts, _) = resolve_relative_shifts(text, chunk, char_offset, clusters);
659
660 let chunk_offset = match writing_mode {
663 WritingMode::LeftToRight => chunk.x.unwrap_or(0.0),
664 WritingMode::TopToBottom => chunk.y.unwrap_or(0.0),
665 };
666
667 let start_offset =
668 chunk_offset + path.start_offset + process_anchor(chunk.anchor, clusters_length(clusters));
669
670 let normals = collect_normals(text, clusters, &shifts, &path.path, start_offset);
671 for ((cluster, normal), (_, dy)) in clusters.iter_mut().zip(normals).zip(shifts) {
672 let (x, y, angle) = match normal {
673 Some(normal) => (normal.x, normal.y, normal.angle),
674 None => {
675 cluster.visible = false;
677 continue;
678 }
679 };
680
681 cluster.has_relative_shift = true;
683
684 let orig_ts = cluster.transform;
685
686 let half_width = cluster.width / 2.0;
688 cluster.transform = Transform::default();
689 cluster.transform = cluster.transform.pre_translate(x - half_width, y);
690 cluster.transform = cluster.transform.pre_rotate_at(angle, half_width, 0.0);
691
692 let cp = char_offset + cluster.byte_idx.code_point_at(&chunk.text);
693
694 let baseline_shift = chunk_span_at(chunk, cluster.byte_idx)
695 .map(|span| {
696 let font = match fonts_cache.get(&span.font) {
697 Some(v) => v,
698 None => return 0.0,
699 };
700 -resolve_baseline(span, font, writing_mode)
701 })
702 .unwrap_or(0.0);
703
704 if !dy.approx_zero_ulps(4) || !baseline_shift.approx_zero_ulps(4) {
707 let shift = kurbo::Vec2::new(0.0, (dy - baseline_shift) as f64);
708 cluster.transform = cluster
709 .transform
710 .pre_translate(shift.x as f32, shift.y as f32);
711 }
712
713 if let Some(angle) = text.rotate.get(cp).cloned() {
714 if !angle.approx_zero_ulps(4) {
715 cluster.transform = cluster.transform.pre_rotate(angle);
716 }
717 }
718
719 cluster.transform = cluster.transform.pre_concat(orig_ts);
721
722 last_x = x + cluster.advance;
723 last_y = y;
724 }
725
726 (last_x, last_y)
727}
728
729pub(crate) fn process_anchor(a: TextAnchor, text_width: f32) -> f32 {
730 match a {
731 TextAnchor::Start => 0.0, TextAnchor::Middle => -text_width / 2.0,
733 TextAnchor::End => -text_width,
734 }
735}
736
737pub(crate) struct PathNormal {
738 pub(crate) x: f32,
739 pub(crate) y: f32,
740 pub(crate) angle: f32,
741}
742
743fn collect_normals(
744 text: &Text,
745 clusters: &[GlyphCluster],
746 shifts: &[(f32, f32)],
747 path: &tiny_skia_path::Path,
748 offset: f32,
749) -> Vec<Option<PathNormal>> {
750 let mut offsets = Vec::with_capacity(clusters.len());
751 let mut normals = Vec::with_capacity(clusters.len());
752 {
753 let mut advance = offset;
754 for (cluster, (shift_x, _)) in clusters.iter().zip(shifts) {
755 let half_width = cluster.width / 2.0;
757
758 let offset = advance + shift_x + half_width;
759
760 if offset < 0.0 {
762 normals.push(None);
763 }
764
765 offsets.push(offset as f64);
766 advance += cluster.advance;
767 }
768 }
769
770 let mut prev_mx = path.points()[0].x;
771 let mut prev_my = path.points()[0].y;
772 let mut prev_x = prev_mx;
773 let mut prev_y = prev_my;
774
775 fn create_curve_from_line(px: f32, py: f32, x: f32, y: f32) -> kurbo::CubicBez {
776 let line = kurbo::Line::new(
777 kurbo::Point::new(px as f64, py as f64),
778 kurbo::Point::new(x as f64, y as f64),
779 );
780 let p1 = line.eval(0.33);
781 let p2 = line.eval(0.66);
782 kurbo::CubicBez {
783 p0: line.p0,
784 p1,
785 p2,
786 p3: line.p1,
787 }
788 }
789
790 let mut length: f64 = 0.0;
791 for seg in path.segments() {
792 let curve = match seg {
793 tiny_skia_path::PathSegment::MoveTo(p) => {
794 prev_mx = p.x;
795 prev_my = p.y;
796 prev_x = p.x;
797 prev_y = p.y;
798 continue;
799 }
800 tiny_skia_path::PathSegment::LineTo(p) => {
801 create_curve_from_line(prev_x, prev_y, p.x, p.y)
802 }
803 tiny_skia_path::PathSegment::QuadTo(p1, p) => kurbo::QuadBez {
804 p0: kurbo::Point::new(prev_x as f64, prev_y as f64),
805 p1: kurbo::Point::new(p1.x as f64, p1.y as f64),
806 p2: kurbo::Point::new(p.x as f64, p.y as f64),
807 }
808 .raise(),
809 tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => kurbo::CubicBez {
810 p0: kurbo::Point::new(prev_x as f64, prev_y as f64),
811 p1: kurbo::Point::new(p1.x as f64, p1.y as f64),
812 p2: kurbo::Point::new(p2.x as f64, p2.y as f64),
813 p3: kurbo::Point::new(p.x as f64, p.y as f64),
814 },
815 tiny_skia_path::PathSegment::Close => {
816 create_curve_from_line(prev_x, prev_y, prev_mx, prev_my)
817 }
818 };
819
820 let arclen_accuracy = {
821 let base_arclen_accuracy = 0.5;
822 let (sx, sy) = text.abs_transform.get_scale();
826 base_arclen_accuracy / (sx * sy).sqrt().max(1.0)
828 };
829
830 let curve_len = curve.arclen(arclen_accuracy as f64);
831
832 for offset in &offsets[normals.len()..] {
833 if *offset >= length && *offset <= length + curve_len {
834 let mut offset = curve.inv_arclen(offset - length, arclen_accuracy as f64);
835 debug_assert!((-1.0e-3..=1.0 + 1.0e-3).contains(&offset));
837 offset = offset.clamp(0.0, 1.0);
838
839 let pos = curve.eval(offset);
840 let d = curve.deriv().eval(offset);
841 let d = kurbo::Vec2::new(-d.y, d.x); let angle = d.atan2().to_degrees() - 90.0;
843
844 normals.push(Some(PathNormal {
845 x: pos.x as f32,
846 y: pos.y as f32,
847 angle: angle as f32,
848 }));
849
850 if normals.len() == offsets.len() {
851 break;
852 }
853 }
854 }
855
856 length += curve_len;
857 prev_x = curve.p3.x as f32;
858 prev_y = curve.p3.y as f32;
859 }
860
861 for _ in 0..(offsets.len() - normals.len()) {
863 normals.push(None);
864 }
865
866 normals
867}
868
869fn process_chunk(
874 chunk: &TextChunk,
875 resolver: &FontResolver,
876 fonts: &mut FontCache,
877) -> Vec<GlyphCluster> {
878 let mut positions = HashSet::new();
913
914 let mut glyphs = Vec::new();
915 for span in &chunk.spans {
916 let font = match fonts.resolved.get(&span.font) {
917 Some(v) => v.clone(),
918 None => continue,
919 };
920
921 let tmp_glyphs = shape_text(
922 &chunk.text,
923 font,
924 span.small_caps,
925 span.apply_kerning,
926 &span.font.variations,
927 span.font_size.get(),
928 span.font_optical_sizing,
929 resolver,
930 fonts,
931 );
932
933 if glyphs.is_empty() {
935 glyphs = tmp_glyphs;
936 continue;
937 }
938
939 positions.clear();
940
941 let mut iter = tmp_glyphs.into_iter();
943 while let Some(new_glyph) = iter.next() {
944 if !span_contains(span, new_glyph.byte_idx) {
945 continue;
946 }
947
948 let Some(idx) = glyphs
949 .iter()
950 .position(|g| g.byte_idx == new_glyph.byte_idx)
951 .filter(|pos| !positions.contains(pos))
952 else {
953 continue;
954 };
955
956 positions.insert(idx);
957
958 let prev_cluster_len = glyphs[idx].cluster_len;
959 if prev_cluster_len < new_glyph.cluster_len {
960 for _ in 1..new_glyph.cluster_len {
963 glyphs.remove(idx + 1);
964 }
965 } else if prev_cluster_len > new_glyph.cluster_len {
966 for j in 1..prev_cluster_len {
969 if let Some(g) = iter.next() {
970 glyphs.insert(idx + j, g);
971 }
972 }
973 }
974
975 glyphs[idx] = new_glyph;
976 }
977 }
978
979 let mut clusters = Vec::new();
981 for (range, byte_idx) in GlyphClusters::new(&glyphs) {
982 if let Some(span) = chunk_span_at(chunk, byte_idx) {
983 clusters.push(form_glyph_clusters(
984 &glyphs[range],
985 &chunk.text,
986 span.font_size.get(),
987 ));
988 }
989 }
990
991 clusters
992}
993
994fn apply_length_adjust(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {
995 let is_horizontal = matches!(chunk.text_flow, TextFlow::Linear);
996
997 for span in &chunk.spans {
998 let target_width = match span.text_length {
999 Some(v) => v,
1000 None => continue,
1001 };
1002
1003 let mut width = 0.0;
1004 let mut cluster_indexes = Vec::new();
1005 for i in span.start..span.end {
1006 if let Some(index) = clusters.iter().position(|c| c.byte_idx.value() == i) {
1007 cluster_indexes.push(index);
1008 }
1009 }
1010 cluster_indexes.sort();
1012 cluster_indexes.dedup();
1013
1014 for i in &cluster_indexes {
1015 width += clusters[*i].width;
1018 }
1019
1020 if cluster_indexes.is_empty() {
1021 continue;
1022 }
1023
1024 if span.length_adjust == LengthAdjust::Spacing {
1025 let factor = if cluster_indexes.len() > 1 {
1026 (target_width - width) / (cluster_indexes.len() - 1) as f32
1027 } else {
1028 0.0
1029 };
1030
1031 for i in cluster_indexes {
1032 clusters[i].advance = clusters[i].width + factor;
1033 clusters[i].text_length_spacing = factor;
1034 }
1035 } else {
1036 let factor = target_width / width;
1037 if factor < 0.001 {
1039 continue;
1040 }
1041
1042 for i in cluster_indexes {
1043 clusters[i].transform = clusters[i].transform.pre_scale(factor, 1.0);
1044
1045 if !is_horizontal {
1047 clusters[i].advance *= factor;
1048 clusters[i].width *= factor;
1049 }
1050 }
1051 }
1052 }
1053}
1054
1055fn apply_writing_mode(writing_mode: WritingMode, clusters: &mut [GlyphCluster]) {
1058 if writing_mode != WritingMode::TopToBottom {
1059 return;
1060 }
1061
1062 for cluster in clusters {
1063 let orientation = unicode_vo::char_orientation(cluster.codepoint);
1064 if orientation == unicode_vo::Orientation::Upright {
1065 let mut ts = Transform::default();
1066 ts = ts.pre_translate(0.0, (cluster.ascent + cluster.descent) / 2.0);
1068 ts = ts.pre_rotate_at(
1070 -90.0,
1071 cluster.width / 2.0,
1072 -(cluster.ascent + cluster.descent) / 2.0,
1073 );
1074
1075 cluster.path_transform = ts;
1076
1077 cluster.ascent = cluster.width / 2.0;
1079 cluster.descent = -cluster.width / 2.0;
1080 } else {
1081 cluster.transform = cluster
1085 .transform
1086 .pre_translate(0.0, (cluster.ascent + cluster.descent) / 2.0);
1087 }
1088 }
1089}
1090
1091fn apply_letter_spacing(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {
1095 if !chunk
1097 .spans
1098 .iter()
1099 .any(|span| !span.letter_spacing.approx_zero_ulps(4))
1100 {
1101 return;
1102 }
1103
1104 let num_clusters = clusters.len();
1105 for (i, cluster) in clusters.iter_mut().enumerate() {
1106 let script = cluster.codepoint.script();
1111 if script_supports_letter_spacing(script) {
1112 if let Some(span) = chunk_span_at(chunk, cluster.byte_idx) {
1113 if i != num_clusters - 1 {
1116 cluster.advance += span.letter_spacing;
1117 }
1118
1119 if !cluster.advance.is_valid_length() {
1122 cluster.width = 0.0;
1123 cluster.advance = 0.0;
1124 cluster.glyphs = vec![];
1125 }
1126 }
1127 }
1128 }
1129}
1130
1131fn apply_word_spacing(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {
1135 if !chunk
1137 .spans
1138 .iter()
1139 .any(|span| !span.word_spacing.approx_zero_ulps(4))
1140 {
1141 return;
1142 }
1143
1144 for cluster in clusters {
1145 if is_word_separator_characters(cluster.codepoint) {
1146 if let Some(span) = chunk_span_at(chunk, cluster.byte_idx) {
1147 cluster.advance += span.word_spacing;
1151
1152 }
1154 }
1155 }
1156}
1157
1158fn form_glyph_clusters(glyphs: &[Glyph], text: &str, font_size: f32) -> GlyphCluster {
1159 debug_assert!(!glyphs.is_empty());
1160
1161 let mut x = 0.0;
1162 let mut width = 0.0;
1163 let mut advance = 0.0;
1164
1165 let mut positioned_glyphs = vec![];
1166
1167 for glyph in glyphs {
1168 let sx = glyph.font.scale(font_size);
1169
1170 let ts = Transform::from_translate(x + glyph.dx as f32, -glyph.dy as f32);
1177
1178 positioned_glyphs.push(PositionedGlyph {
1179 glyph_ts: ts,
1180 cluster_ts: Transform::default(),
1182 span_ts: Transform::default(),
1184 units_per_em: glyph.font.units_per_em.get(),
1185 font_size,
1186 font: glyph.font.id,
1187 text: glyph.text.clone(),
1188 id: glyph.id,
1189 });
1190
1191 x += glyph.width as f32;
1192
1193 let glyph_width = glyph.width as f32 * sx;
1194 advance += glyph_width;
1195 if glyph_width > width {
1196 width = glyph_width;
1197 }
1198 }
1199
1200 let byte_idx = glyphs[0].byte_idx;
1201 let font = glyphs[0].font.clone();
1202 GlyphCluster {
1203 byte_idx,
1204 codepoint: byte_idx.char_from(text),
1205 width,
1206 advance,
1207 text_length_spacing: 0.0,
1208 ascent: font.ascent(font_size),
1209 descent: font.descent(font_size),
1210 has_relative_shift: false,
1211 transform: Transform::default(),
1212 path_transform: Transform::default(),
1213 glyphs: positioned_glyphs,
1214 visible: true,
1215 }
1216}
1217
1218#[inline(never)]
1219fn resolve_font(
1220 id: ID,
1221 variations: &[crate::FontVariation],
1222 fonts: &mut FontCache,
1223) -> Option<ResolvedFont> {
1224 let font = &fonts.load(id)?.instance(variations.iter().copied()).font;
1225 let metrics = font.metrics();
1226
1227 if !(16..=16384).contains(&metrics.raw_units_per_em) {
1229 return None;
1230 }
1231 let units_per_em = NonZeroU16::new(metrics.raw_units_per_em)?;
1232
1233 let line = metrics.h_line().unwrap_or_default();
1234 let ascent = line.ascender.to_f32();
1235 let descent = line.descender.to_f32();
1236
1237 let x_height = metrics
1238 .x_height
1239 .map(|x| x.to_f32())
1240 .filter(|x| *x > 0.0)
1241 .and_then(|x| u16::try_from(x.round() as i32).ok())
1242 .and_then(NonZeroU16::new);
1243 let x_height = match x_height {
1244 Some(height) => height,
1245 None => {
1246 u16::try_from(((ascent - descent) * 0.45).round() as i32)
1249 .ok()
1250 .and_then(NonZeroU16::new)?
1251 }
1252 };
1253
1254 let style_metrics = font.style_metrics();
1255
1256 let line_through_position = match style_metrics.strike_through {
1257 Some(metrics) => metrics.position.to_f32().round() as i16,
1258 None => x_height.get() as i16 / 2,
1259 };
1260
1261 let (underline_position, underline_thickness) = match style_metrics.underline {
1262 Some(metrics) => {
1263 let thickness = u16::try_from(metrics.thickness.to_f32().round() as i32)
1264 .ok()
1265 .and_then(NonZeroU16::new)
1266 .unwrap_or_else(|| NonZeroU16::new(units_per_em.get() / 12).unwrap());
1267
1268 (metrics.position.to_f32().round() as i16, thickness)
1269 }
1270 None => (
1271 -(units_per_em.get() as i16) / 9,
1272 NonZeroU16::new(units_per_em.get() / 12).unwrap(),
1273 ),
1274 };
1275
1276 let subscript_offset = match style_metrics.subscript {
1278 Some(metrics) => metrics.y_offset.to_f32().round() as i16,
1279 None => (units_per_em.get() as f32 / 0.2).round() as i16,
1280 };
1281 let superscript_offset = match style_metrics.superscript {
1282 Some(metrics) => metrics.y_offset.to_f32().round() as i16,
1283 None => (units_per_em.get() as f32 / 0.4).round() as i16,
1284 };
1285
1286 Some(ResolvedFont {
1287 id,
1288 units_per_em,
1289 ascent: ascent.round() as i16,
1290 descent: descent.round() as i16,
1291 x_height,
1292 underline_position,
1293 underline_thickness,
1294 line_through_position,
1295 subscript_offset,
1296 superscript_offset,
1297 })
1298}
1299
1300pub(crate) fn shape_text(
1302 text: &str,
1303 font: Arc<ResolvedFont>,
1304 small_caps: bool,
1305 apply_kerning: bool,
1306 variations: &[crate::FontVariation],
1307 font_size: f32,
1308 font_optical_sizing: crate::FontOpticalSizing,
1309 resolver: &FontResolver,
1310 fonts: &mut FontCache,
1311) -> Vec<Glyph> {
1312 let shaping_variations = with_optical_sizing(variations, font_optical_sizing, font_size);
1313
1314 let mut glyphs = shape_text_with_font(
1315 text,
1316 font.clone(),
1317 small_caps,
1318 apply_kerning,
1319 shaping_variations.clone(),
1320 fonts,
1321 )
1322 .unwrap_or_default();
1323
1324 let mut used_fonts = vec![font.id];
1326
1327 'outer: loop {
1329 let mut missing = None;
1330 for glyph in &glyphs {
1331 if glyph.is_missing() {
1332 missing = Some(glyph.byte_idx.char_from(text));
1333 break;
1334 }
1335 }
1336
1337 if let Some(c) = missing {
1338 let fallback_font = match (resolver.select_fallback)(c, &used_fonts, &mut fonts.fontdb)
1339 .and_then(|id| resolve_font(id, variations, fonts))
1340 {
1341 Some(v) => Arc::new(v),
1342 None => break 'outer,
1343 };
1344
1345 let fallback_glyphs = shape_text_with_font(
1347 text,
1348 fallback_font.clone(),
1349 small_caps,
1350 apply_kerning,
1351 shaping_variations.clone(),
1352 fonts,
1353 )
1354 .unwrap_or_default();
1355
1356 let all_matched = fallback_glyphs.iter().all(|g| !g.is_missing());
1357 if all_matched {
1358 glyphs = fallback_glyphs;
1360 break 'outer;
1361 }
1362
1363 if glyphs.len() != fallback_glyphs.len() {
1366 break 'outer;
1367 }
1368
1369 for i in 0..glyphs.len() {
1373 if glyphs[i].is_missing() && !fallback_glyphs[i].is_missing() {
1374 glyphs[i] = fallback_glyphs[i].clone();
1375 }
1376 }
1377
1378 used_fonts.push(fallback_font.id);
1380 } else {
1381 break 'outer;
1382 }
1383 }
1384
1385 for glyph in &glyphs {
1387 if glyph.is_missing() {
1388 let c = glyph.byte_idx.char_from(text);
1389 log::warn!(
1391 "No fonts with a {}/U+{:X} character were found.",
1392 c,
1393 c as u32
1394 );
1395 }
1396 }
1397
1398 glyphs
1399}
1400
1401fn shape_text_with_font(
1405 text: &str,
1406 font: Arc<ResolvedFont>,
1407 small_caps: bool,
1408 apply_kerning: bool,
1409 variations: impl IntoIterator<Item = crate::FontVariation>,
1410 fonts: &mut FontCache,
1411) -> Option<Vec<Glyph>> {
1412 use harfrust::{Buffer, Feature, ShapePlan, ShapePlanKey, ShaperFont, Tag};
1413
1414 let FontInstance {
1415 font: hr_font,
1416 plans,
1417 ..
1418 } = fonts.load(font.id)?.instance(variations);
1419
1420 let bidi_info = unicode_bidi::BidiInfo::new(text, Some(unicode_bidi::Level::ltr()));
1421 let paragraph = &bidi_info.paragraphs[0];
1422 let line = paragraph.range.clone();
1423
1424 let mut glyphs = Vec::new();
1425
1426 let shaper = ShaperFont::new(hr_font);
1427
1428 let mut features = Vec::new();
1429 if small_caps {
1430 features.push(Feature::new(Tag::new(b"smcp"), 1, ..));
1431 }
1432 if !apply_kerning {
1433 features.push(Feature::new(Tag::new(b"kern"), 0, ..));
1434 }
1435
1436 let (levels, runs) = bidi_info.visual_runs(paragraph, line);
1437 for run in runs.iter() {
1438 let sub_text = &text[run.clone()];
1439 if sub_text.is_empty() {
1440 continue;
1441 }
1442
1443 let ltr = levels[run.start].is_ltr();
1444 let direction = if ltr {
1445 harfrust::Direction::LeftToRight
1446 } else {
1447 harfrust::Direction::RightToLeft
1448 };
1449
1450 let mut buffer = Buffer::new();
1451 buffer.push_str(sub_text);
1452 buffer.set_direction(direction);
1453
1454 buffer.guess_segment_properties();
1456
1457 let key = ShapePlanKey::new(hr_font, buffer.script(), direction)
1458 .language(buffer.language())
1459 .features(&features);
1460 let plan = match plans.iter().position(|plan| key.matches(plan)) {
1461 Some(index) => &plans[index],
1462 None => {
1463 plans.push(ShapePlan::new(
1464 hr_font,
1465 direction,
1466 buffer.script(),
1467 buffer.language(),
1468 &features,
1469 ));
1470 plans.last()?
1471 }
1472 };
1473
1474 harfrust::shape(
1475 &shaper,
1476 &mut buffer,
1477 ShapeOptions::new().features(&features).plan(Some(plan)),
1478 )
1479 .ok()?;
1480
1481 let positions = buffer.glyph_positions();
1482 let infos = buffer.glyph_infos();
1483
1484 for i in 0..buffer.len() {
1485 let pos = positions[i];
1486 let info = infos[i];
1487 let idx = run.start + info.cluster as usize;
1488
1489 let start = info.cluster as usize;
1490
1491 let end = if ltr {
1492 i.checked_add(1)
1493 } else {
1494 i.checked_sub(1)
1495 }
1496 .and_then(|last| infos.get(last))
1497 .map_or(sub_text.len(), |info| info.cluster as usize);
1498
1499 glyphs.push(Glyph {
1500 byte_idx: ByteIndex::new(idx),
1501 cluster_len: end.checked_sub(start).unwrap_or(0), text: sub_text[start..end].to_string(),
1503 id: GlyphId(info.glyph_id),
1504 dx: pos.x_offset,
1505 dy: pos.y_offset,
1506 width: pos.x_advance,
1507 font: font.clone(),
1508 });
1509 }
1510 }
1511
1512 Some(glyphs)
1513}
1514
1515pub(crate) struct GlyphClusters<'a> {
1520 data: &'a [Glyph],
1521 idx: usize,
1522}
1523
1524impl<'a> GlyphClusters<'a> {
1525 pub(crate) fn new(data: &'a [Glyph]) -> Self {
1526 GlyphClusters { data, idx: 0 }
1527 }
1528}
1529
1530impl Iterator for GlyphClusters<'_> {
1531 type Item = (std::ops::Range<usize>, ByteIndex);
1532
1533 fn next(&mut self) -> Option<Self::Item> {
1534 if self.idx == self.data.len() {
1535 return None;
1536 }
1537
1538 let start = self.idx;
1539 let cluster = self.data[self.idx].byte_idx;
1540 for g in &self.data[self.idx..] {
1541 if g.byte_idx != cluster {
1542 break;
1543 }
1544
1545 self.idx += 1;
1546 }
1547
1548 Some((start..self.idx, cluster))
1549 }
1550}
1551
1552pub(crate) fn script_supports_letter_spacing(script: unicode_script::Script) -> bool {
1558 use unicode_script::Script;
1559
1560 !matches!(
1561 script,
1562 Script::Arabic
1563 | Script::Syriac
1564 | Script::Nko
1565 | Script::Manichaean
1566 | Script::Psalter_Pahlavi
1567 | Script::Mandaic
1568 | Script::Mongolian
1569 | Script::Phags_Pa
1570 | Script::Devanagari
1571 | Script::Bengali
1572 | Script::Gurmukhi
1573 | Script::Modi
1574 | Script::Sharada
1575 | Script::Syloti_Nagri
1576 | Script::Tirhuta
1577 | Script::Ogham
1578 )
1579}
1580
1581#[derive(Clone)]
1585pub(crate) struct Glyph {
1586 pub(crate) id: GlyphId,
1588
1589 pub(crate) byte_idx: ByteIndex,
1593
1594 pub(crate) cluster_len: usize,
1596
1597 pub(crate) text: String,
1599
1600 pub(crate) dx: i32,
1602
1603 pub(crate) dy: i32,
1605
1606 pub(crate) width: i32,
1608
1609 pub(crate) font: Arc<ResolvedFont>,
1613}
1614
1615impl Glyph {
1616 fn is_missing(&self) -> bool {
1617 self.id.0 == 0
1618 }
1619}
1620
1621#[derive(Clone, Copy, Debug)]
1622pub(crate) struct ResolvedFont {
1623 pub(crate) id: ID,
1624
1625 units_per_em: NonZeroU16,
1626
1627 ascent: i16,
1629 descent: i16,
1630 x_height: NonZeroU16,
1631
1632 underline_position: i16,
1633 underline_thickness: NonZeroU16,
1634
1635 line_through_position: i16,
1639
1640 subscript_offset: i16,
1641 superscript_offset: i16,
1642}
1643
1644pub(crate) fn chunk_span_at(chunk: &TextChunk, byte_offset: ByteIndex) -> Option<&TextSpan> {
1645 chunk
1646 .spans
1647 .iter()
1648 .find(|&span| span_contains(span, byte_offset))
1649}
1650
1651pub(crate) fn span_contains(span: &TextSpan, byte_offset: ByteIndex) -> bool {
1652 byte_offset.value() >= span.start && byte_offset.value() < span.end
1653}
1654
1655pub(crate) fn is_word_separator_characters(c: char) -> bool {
1659 matches!(
1660 c as u32,
1661 0x0020 | 0x00A0 | 0x1361 | 0x010100 | 0x010101 | 0x01039F | 0x01091F
1662 )
1663}
1664
1665impl ResolvedFont {
1666 #[inline]
1667 pub(crate) fn scale(&self, font_size: f32) -> f32 {
1668 font_size / self.units_per_em.get() as f32
1669 }
1670
1671 #[inline]
1672 pub(crate) fn ascent(&self, font_size: f32) -> f32 {
1673 self.ascent as f32 * self.scale(font_size)
1674 }
1675
1676 #[inline]
1677 pub(crate) fn descent(&self, font_size: f32) -> f32 {
1678 self.descent as f32 * self.scale(font_size)
1679 }
1680
1681 #[inline]
1682 pub(crate) fn height(&self, font_size: f32) -> f32 {
1683 self.ascent(font_size) - self.descent(font_size)
1684 }
1685
1686 #[inline]
1687 pub(crate) fn x_height(&self, font_size: f32) -> f32 {
1688 self.x_height.get() as f32 * self.scale(font_size)
1689 }
1690
1691 #[inline]
1692 pub(crate) fn underline_position(&self, font_size: f32) -> f32 {
1693 self.underline_position as f32 * self.scale(font_size)
1694 }
1695
1696 #[inline]
1697 fn underline_thickness(&self, font_size: f32) -> f32 {
1698 self.underline_thickness.get() as f32 * self.scale(font_size)
1699 }
1700
1701 #[inline]
1702 pub(crate) fn line_through_position(&self, font_size: f32) -> f32 {
1703 self.line_through_position as f32 * self.scale(font_size)
1704 }
1705
1706 #[inline]
1707 fn subscript_offset(&self, font_size: f32) -> f32 {
1708 self.subscript_offset as f32 * self.scale(font_size)
1709 }
1710
1711 #[inline]
1712 fn superscript_offset(&self, font_size: f32) -> f32 {
1713 self.superscript_offset as f32 * self.scale(font_size)
1714 }
1715
1716 fn dominant_baseline_shift(&self, baseline: DominantBaseline, font_size: f32) -> f32 {
1717 let alignment = match baseline {
1718 DominantBaseline::Auto => AlignmentBaseline::Auto,
1719 DominantBaseline::UseScript => AlignmentBaseline::Auto, DominantBaseline::NoChange => AlignmentBaseline::Auto, DominantBaseline::ResetSize => AlignmentBaseline::Auto, DominantBaseline::Ideographic => AlignmentBaseline::Ideographic,
1723 DominantBaseline::Alphabetic => AlignmentBaseline::Alphabetic,
1724 DominantBaseline::Hanging => AlignmentBaseline::Hanging,
1725 DominantBaseline::Mathematical => AlignmentBaseline::Mathematical,
1726 DominantBaseline::Central => AlignmentBaseline::Central,
1727 DominantBaseline::Middle => AlignmentBaseline::Middle,
1728 DominantBaseline::TextAfterEdge => AlignmentBaseline::TextAfterEdge,
1729 DominantBaseline::TextBeforeEdge => AlignmentBaseline::TextBeforeEdge,
1730 };
1731
1732 self.alignment_baseline_shift(alignment, font_size)
1733 }
1734
1735 fn alignment_baseline_shift(&self, alignment: AlignmentBaseline, font_size: f32) -> f32 {
1765 match alignment {
1766 AlignmentBaseline::Auto => 0.0,
1767 AlignmentBaseline::Baseline => 0.0,
1768 AlignmentBaseline::BeforeEdge | AlignmentBaseline::TextBeforeEdge => {
1769 self.ascent(font_size)
1770 }
1771 AlignmentBaseline::Middle => self.x_height(font_size) * 0.5,
1772 AlignmentBaseline::Central => self.ascent(font_size) - self.height(font_size) * 0.5,
1773 AlignmentBaseline::AfterEdge | AlignmentBaseline::TextAfterEdge => {
1774 self.descent(font_size)
1775 }
1776 AlignmentBaseline::Ideographic => self.descent(font_size),
1777 AlignmentBaseline::Alphabetic => 0.0,
1778 AlignmentBaseline::Hanging => self.ascent(font_size) * 0.8,
1779 AlignmentBaseline::Mathematical => self.ascent(font_size) * 0.5,
1780 }
1781 }
1782}
1783
1784pub(crate) type FontsCache = HashMap<Font, Arc<ResolvedFont>>;
1785
1786#[derive(Clone, Copy, PartialEq, Debug)]
1790pub(crate) struct ByteIndex(usize);
1791
1792impl ByteIndex {
1793 fn new(i: usize) -> Self {
1794 ByteIndex(i)
1795 }
1796
1797 pub(crate) fn value(&self) -> usize {
1798 self.0
1799 }
1800
1801 pub(crate) fn code_point_at(&self, text: &str) -> usize {
1803 text.char_indices()
1804 .take_while(|(i, _)| *i != self.0)
1805 .count()
1806 }
1807
1808 pub(crate) fn char_from(&self, text: &str) -> char {
1810 text[self.0..].chars().next().unwrap()
1811 }
1812}