1use std::ops::Range;
4
5use crate::fonts::{Features, ShapedGlyph};
6
7use super::flatten::{FlatParagraph, StyleSpan};
8use super::line::{ShapedRun, cut_runs};
9use super::paragraph::ParagraphStyle;
10use super::{LineLayout, Uncovered};
11
12impl LineLayout<'_> {
13 pub fn shape(&self, text: &str, style: &ParagraphStyle) -> Option<Vec<ShapedRun>> {
17 let upem = self.registry.metrics(style.font_id)?.units_per_em as f32;
18 let mut flat = FlatParagraph::new();
19 flat.push_styled(text, style, self.small_caps(style));
20 let shaped = self.shape_spans(&flat, style, upem);
21 Some(cut_runs(&flat, &shaped, 0, flat.text.len()))
22 }
23
24 pub(super) fn shape_spans(
32 &self,
33 flat: &FlatParagraph,
34 style: &ParagraphStyle,
35 upem: f32,
36 ) -> Vec<ShapedSpan> {
37 flat.spans
38 .iter()
39 .map(|span| {
40 let mut glyphs = self
41 .registry
42 .shape_with(span.font_id, &flat.text[span.range.clone()], &span.features)
43 .unwrap_or_default();
44 self.find_uncovered(flat, span, &glyphs);
45 let track = self.tracking_units(span);
46 if track != 0 {
47 for at in 0..glyphs.len() {
48 let last = glyphs
49 .get(at + 1)
50 .is_none_or(|next| next.cluster != glyphs[at].cluster);
51 if last {
52 glyphs[at].x_advance =
53 (glyphs[at].x_advance as i64 + track).max(0) as u32;
54 }
55 }
56 }
57 let scale = self.scale(span.font_id, span.size, style, upem);
58 ShapedSpan {
59 range: span.range.clone(),
60 scale,
61 track,
62 tracking: track as f32 * scale,
63 glyphs,
64 }
65 })
66 .collect()
67 }
68
69 fn find_uncovered(&self, flat: &FlatParagraph, span: &StyleSpan, glyphs: &[ShapedGlyph]) {
75 for glyph in glyphs.iter().filter(|glyph| glyph.id == 0) {
76 let at = span.range.start + glyph.cluster as usize;
77 let Some(character) = flat.text.get(at..).and_then(|rest| rest.chars().next()) else {
78 continue;
79 };
80 if character.is_control() {
81 continue;
82 }
83 let mut found = self.uncovered.borrow_mut();
84 if found.seen.insert(character) {
85 found.list.push(Uncovered {
86 character,
87 font_id: span.font_id,
88 position: flat.written_at(at),
89 });
90 }
91 }
92 }
93
94 fn tracking_units(&self, span: &StyleSpan) -> i64 {
96 if span.tracking == 0.0 || span.size <= 0.0 {
97 return 0;
98 }
99 let upem = self
100 .registry
101 .metrics(span.font_id)
102 .map(|m| m.units_per_em as f32)
103 .unwrap_or(1000.0);
104 (span.tracking / span.size * upem).round() as i64
105 }
106
107 fn scale(&self, font_id: u16, size: f32, style: &ParagraphStyle, upem: f32) -> f32 {
111 let span_upem = self
112 .registry
113 .metrics(font_id)
114 .map(|m| m.units_per_em as f32)
115 .unwrap_or(upem);
116 if span_upem <= 0.0 || style.size <= 0.0 {
117 return 1.0;
118 }
119 size / span_upem * upem / style.size
120 }
121
122 pub(super) fn hyphenate(&self, runs: &mut Vec<ShapedRun>, style: &ParagraphStyle) {
129 let Some(id) = self.registry.char_glyph(style.font_id, '-') else {
130 return;
131 };
132 let advance = self
133 .registry
134 .advance_width(style.font_id, id)
135 .unwrap_or_default() as u32;
136 let ending = runs
137 .last()
138 .map(|run| run.text_start + run.text.len() as u32)
139 .unwrap_or_default();
140 let color = runs.last().map_or(style.color, |run| run.color);
144 let decoration = runs.last().map_or(style.decoration, |run| run.decoration);
147 let blend = runs.last().map_or(style.blend, |run| run.blend);
148 let inline = runs.last().and_then(|run| run.inline);
151 match runs.last_mut() {
152 Some(run) if run.font_id == style.font_id && run.size == style.size => {
153 run.text.push('-');
154 if let Some(end) = run.source_map.last().copied() {
158 run.source_map.push(end);
159 }
160 run.glyphs.push(ShapedGlyph {
161 id,
162 x_advance: advance,
163 cluster: ending,
164 });
165 run.advance += advance;
166 }
167 _ => runs.push(ShapedRun {
171 font_id: style.font_id,
172 size: style.size,
173 text: "-".to_string(),
174 source: String::new(),
175 source_map: Vec::new(),
176 text_start: ending,
177 origin: None,
178 pseudo_element: None,
179 inline,
180 lead: 0.0,
181 trail: 0.0,
182 features: Features::NONE,
183 color,
184 decoration,
185 blend,
186 glyphs: vec![ShapedGlyph {
187 id,
188 x_advance: advance,
189 cluster: ending,
190 }],
191 advance,
192 }),
193 }
194 }
195
196 pub(super) fn hyphen_advance(&self, style: &ParagraphStyle) -> u32 {
197 self.registry
198 .char_glyph(style.font_id, '-')
199 .and_then(|g| self.registry.advance_width(style.font_id, g))
200 .unwrap_or(0) as u32
201 }
202}
203
204pub(super) struct ShapedSpan {
207 pub(super) range: Range<usize>,
209 pub(super) scale: f32,
212 pub(super) track: i64,
215 pub(super) tracking: f32,
217 pub(super) glyphs: Vec<ShapedGlyph>,
218}
219
220impl ShapedSpan {
221 pub(super) fn glyphs_in(&self, start: usize, end: usize) -> Vec<ShapedGlyph> {
224 self.glyphs
225 .iter()
226 .filter(|g| {
227 let cluster = self.range.start + g.cluster as usize;
228 cluster >= start && cluster < end
229 })
230 .map(|g| ShapedGlyph {
231 cluster: g.cluster + self.range.start as u32,
232 ..*g
233 })
234 .collect()
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use crate::content::{Attributes, Inline, NodeId, SourcePos};
241 use crate::lines::Uncovered;
242 use crate::lines::flatten::SMALL_CAPS_RATIO;
243 use crate::lines::testing::{
244 body, hyphenated, layout_body_opts, layout_style, line_text, registry, units_per_em,
245 };
246 use crate::lines::{LineBreakOptions, LineLayout, Measure, Opening, ParagraphStyle};
247 use crate::style::{FontVariantCaps, TextTransform};
248
249 #[test]
252 fn a_hyphenated_line_paints_the_hyphen_it_paid_for() {
253 let text = "extraordinarily";
254 let lines = layout_body_opts(text, 53.0, hyphenated());
255 let first = &lines[0];
256 assert_eq!(line_text(first), "extraordi-");
257
258 let run = first.runs.last().expect("the line has no runs");
259 assert_eq!(
260 run.glyphs.len(),
261 run.text.chars().count(),
262 "the hyphen is in the text and not in the glyphs",
263 );
264 let ranges = run.glyph_ranges();
265 let last = ranges.last().expect("the run has no glyphs");
266 assert_eq!(
267 &run.text[last.start as usize..last.end as usize],
268 "-",
269 "the last glyph does not stand for the hyphen",
270 );
271
272 let hyphen = run.glyphs.last().expect("the run has no glyphs").x_advance;
275 assert!(hyphen > 0, "the hyphen has no advance");
276 assert_eq!(
277 first.width,
278 first.runs.iter().map(|r| r.advance).sum::<u32>(),
279 "the line's width and its runs disagree",
280 );
281
282 let last_line = lines.last().expect("no lines");
283 assert!(
284 !line_text(last_line).ends_with('-'),
285 "the last line was hyphenated: {:?}",
286 line_text(last_line),
287 );
288 }
289
290 #[test]
294 fn an_uncovered_character_is_found_once_where_it_was_written() {
295 let layout = LineLayout::new(registry());
296 let inlines = vec![Inline::Text {
297 id: NodeId::UNASSIGNED,
298 value: "stra\u{df}e \u{2605} and \u{2605}".into(),
299 attributes: Attributes::default(),
300 position: Some(SourcePos { line: 4, column: 3 }),
301 span: None,
302 }];
303 let mut style = body();
304 style.transform = TextTransform::Uppercase;
305 layout.layout(&inlines, &style, 400.0, Default::default());
306
307 let found = layout.take_uncovered();
308 assert_eq!(
309 found,
310 [Uncovered {
311 character: '\u{2605}',
312 font_id: style.font_id,
313 position: Some(SourcePos {
316 line: 4,
317 column: 11
318 }),
319 }]
320 );
321 assert_eq!(layout.take_uncovered(), []);
322 }
323
324 #[test]
329 fn emphasis_shapes_on_its_own_face() {
330 let mut book = crate::content::Book {
331 metadata: Default::default(),
332 sections: vec![crate::content::Section {
333 attributes: Default::default(),
334 blocks: vec![crate::content::Block::Paragraph {
335 id: NodeId::UNASSIGNED,
336 inlines: vec![
337 Inline::Text {
338 id: NodeId::UNASSIGNED,
339 value: "He said ".into(),
340 attributes: Attributes::default(),
341 position: None,
342 span: None,
343 },
344 Inline::Emphasis {
345 id: NodeId::UNASSIGNED,
346 children: vec![
347 Inline::Text {
348 id: NodeId::UNASSIGNED,
349 value: "never ".into(),
350 attributes: Attributes::default(),
351 position: None,
352 span: None,
353 },
354 Inline::Strong {
355 id: NodeId::UNASSIGNED,
356 children: vec![Inline::Text {
357 id: NodeId::UNASSIGNED,
358 value: "again".into(),
359 attributes: Attributes::default(),
360 position: None,
361 span: None,
362 }],
363 attributes: Attributes::default(),
364 position: None,
365 span: None,
366 },
367 ],
368 attributes: Attributes::default(),
369 position: None,
370 span: None,
371 },
372 Inline::Text {
373 id: NodeId::UNASSIGNED,
374 value: " to her.".into(),
375 attributes: Attributes::default(),
376 position: None,
377 span: None,
378 },
379 ],
380 attributes: Attributes::default(),
381 position: None,
382 span: None,
383 }],
384 ..Default::default()
385 }],
386 };
387 book.assign_node_ids();
388 let styles = crate::style::defaults(&book, registry());
389 let crate::content::Block::Paragraph { id, inlines, .. } = &book.sections[0].blocks[0]
390 else {
391 unreachable!()
392 };
393 let lines = LineLayout::new(registry()).layout_styled(
394 inlines,
395 &styles.paragraph(*id),
396 &styles,
397 &Measure::uniform(400.0),
398 Default::default(),
399 Opening::default(),
400 );
401 assert_eq!(lines.len(), 1);
402 let runs: Vec<(u16, &str)> = lines[0]
403 .runs
404 .iter()
405 .map(|run| (run.font_id, run.text.as_str()))
406 .collect();
407 let face = |italic, weight| {
408 registry()
409 .select(
410 "eb garamond",
411 crate::fonts::FaceAttributes { italic, weight },
412 )
413 .unwrap()
414 .id
415 };
416 assert_eq!(
417 runs,
418 vec![
419 (face(false, 400), "He said "),
420 (face(true, 400), "never "),
421 (face(true, 700), "again"),
422 (face(false, 400), " to her."),
423 ],
424 );
425 }
426
427 #[test]
432 fn letter_spacing_opens_the_gaps_between_glyphs() {
433 let plain = layout_style("HANDGLOVES", 400.0, &body());
434 let tracking = 0.08 * body().size;
435 let tracked = layout_style(
436 "HANDGLOVES",
437 400.0,
438 &ParagraphStyle {
439 letter_spacing: tracking,
440 ..body()
441 },
442 );
443 let glyphs = plain[0].runs[0].glyphs.len();
444 assert_eq!(glyphs, 10, "the title shaped to one glyph a letter");
445 let units = tracking / body().size * units_per_em() as f32;
446 assert_eq!(
447 tracked[0].width - plain[0].width,
448 (units * (glyphs - 1) as f32).round() as u32,
449 "tracking did not open exactly the gaps between the glyphs",
450 );
451 for (loose, tight) in tracked[0].runs[0]
452 .glyphs
453 .iter()
454 .zip(&plain[0].runs[0].glyphs)
455 .take(glyphs - 1)
456 {
457 assert_eq!(
458 loose.x_advance - tight.x_advance,
459 units.round() as u32,
460 "a glyph has no tracking of its own",
461 );
462 }
463 }
464
465 #[test]
472 fn small_caps_take_the_feature_or_a_synthesis() {
473 let style = ParagraphStyle {
474 caps: FontVariantCaps::SmallCaps,
475 ..body()
476 };
477 let plain = layout_style("hello", 400.0, &body());
478 let feature = layout_style("hello", 400.0, &style);
479 assert_eq!(feature[0].runs.len(), 1, "the feature split the run");
480 assert_eq!(feature[0].runs[0].size, body().size);
481 assert_ne!(
482 feature[0].runs[0]
483 .glyphs
484 .iter()
485 .map(|g| g.id)
486 .collect::<Vec<_>>(),
487 plain[0].runs[0]
488 .glyphs
489 .iter()
490 .map(|g| g.id)
491 .collect::<Vec<_>>(),
492 "the face's small capitals drew the lowercase glyphs",
493 );
494
495 let bare = crate::fonts::registry_without_substitutions();
496 assert!(!bare.has_small_caps(0), "the face still substitutes");
497 let inlines = vec![Inline::Text {
498 id: NodeId::UNASSIGNED,
499 value: "hi Ho".to_string(),
500 attributes: Attributes::default(),
501 position: None,
502 span: None,
503 }];
504 let synthesized =
505 LineLayout::new(&bare).layout(&inlines, &style, 400.0, LineBreakOptions::default());
506 let runs: Vec<(f32, &str, &str)> = synthesized[0]
507 .runs
508 .iter()
509 .map(|run| (run.size, run.text.as_str(), run.source.as_str()))
510 .collect();
511 assert_eq!(
512 runs,
513 vec![
514 (body().size * SMALL_CAPS_RATIO, "HI", "hi"),
515 (body().size, " H", ""),
516 (body().size * SMALL_CAPS_RATIO, "O", "o"),
517 ],
518 "the synthesis did not raise what was lowercase, leave the rest, \
519 and keep what the author wrote",
520 );
521 }
522}