fleuron/lines/paragraph.rs
1//! What a paragraph is set in: the style over its runs, the style
2//! over the line it opens on, and what it hangs into the margin.
3
4use crate::content::{Inline, Metadata, NodeId};
5use crate::fonts::{FaceAttributes, FeatureSetting, FontRegistry};
6use crate::style::{BlendMode, Color, Edges, FontVariantCaps, TextDecoration, TextTransform};
7use serde::Serialize;
8
9/// Everything one paragraph's layout depends on, and the colour its
10/// runs are painted in. The style tree compiles down to this.
11#[derive(Debug, Clone)]
12pub struct ParagraphStyle {
13 /// Face id from the font registry.
14 pub font_id: u16,
15 /// Font size in points.
16 pub size: f32,
17 /// Line height as a unitless multiple of `size`, as in CSS
18 /// `line-height: <number>`.
19 pub line_height: f32,
20 /// Extra advance between glyphs, in points, from
21 /// `letter-spacing`. A line ends at its last glyph's own edge, so
22 /// nothing is added after it.
23 pub letter_spacing: f32,
24 /// Which capitals the text is drawn with.
25 pub caps: FontVariantCaps,
26 /// The features the text is shaped with, beyond the ones the
27 /// shaper turns on for every run.
28 pub features: Vec<FeatureSetting>,
29 /// What the text is transformed to before it is shaped.
30 pub transform: TextTransform,
31 /// What the run is painted in. Nothing measures it: a run
32 /// carries it from here to the display structure.
33 pub color: Color,
34 /// What is drawn across the run. Nothing measures it either: the
35 /// rules are painted over the advance the glyphs already took.
36 pub decoration: TextDecoration,
37 /// How the run and its rules are mixed with what is under them.
38 /// Nothing measures it.
39 pub blend: BlendMode,
40}
41
42/// What `::first-line` changes about the paragraph it opens.
43///
44/// A field is set where the pseudo-element's style differs from the
45/// element's own, so what it changes reaches an emphasis or a link on
46/// the opening line without replacing the rest of their style.
47#[derive(Debug, Clone, Copy, Default, PartialEq)]
48pub struct FirstLine {
49 /// The cut the opening line is set in, where the rule asked for
50 /// another one.
51 pub face: Option<Face>,
52 /// `font-size`, in points.
53 pub size: Option<f32>,
54 /// `line-height`, as a multiple of the opening line's own size.
55 /// It sets the height of the line and leaves its runs alone.
56 pub line_height: Option<f32>,
57 /// `letter-spacing`, in points.
58 pub letter_spacing: Option<f32>,
59 /// `font-variant-caps`.
60 pub caps: Option<FontVariantCaps>,
61 /// `text-transform`.
62 pub transform: Option<TextTransform>,
63 /// `color`.
64 pub color: Option<Color>,
65 /// What `text-decoration` draws across the line.
66 pub decoration: Option<TextDecoration>,
67}
68
69/// The face `::first-line` asks its runs for: a family, a slope and
70/// a weight, each one set only where the rule set it.
71///
72/// A run of the opening line keeps what the rule left alone, so
73/// `font-style: italic` over a bold emphasis picks the bold italic
74/// rather than the regular one. The family is a face of the family
75/// asked for, because a family is named once in the style tree and
76/// carried here by one of its cuts.
77#[derive(Debug, Clone, Copy, Default, PartialEq)]
78pub struct Face {
79 /// A face of the family the line is set in.
80 pub family: Option<u16>,
81 /// Whether the line is italic.
82 pub italic: Option<bool>,
83 /// Weight on the CSS 1 to 1000 scale.
84 pub weight: Option<u16>,
85}
86
87impl FirstLine {
88 /// The style one run of the opening line is set in, with `face`
89 /// matched against `registry`.
90 pub fn over(&self, style: &ParagraphStyle, registry: &FontRegistry) -> ParagraphStyle {
91 ParagraphStyle {
92 font_id: self.font_id(style, registry),
93 size: self.size.unwrap_or(style.size),
94 line_height: self.line_height.unwrap_or(style.line_height),
95 letter_spacing: self.letter_spacing.unwrap_or(style.letter_spacing),
96 caps: self.caps.unwrap_or(style.caps),
97 transform: self.transform.unwrap_or(style.transform),
98 color: self.color.unwrap_or(style.color),
99 decoration: self.decoration.unwrap_or(style.decoration),
100 ..style.clone()
101 }
102 }
103
104 /// The face one run of the opening line is shaped with: the run's
105 /// own, where the rule asked for no other cut, and otherwise the
106 /// closest cut of the family asked for.
107 ///
108 /// A family with nothing at the slope or weight asked for answers
109 /// with what it has, which is CSS font matching. The run keeps
110 /// its own face where the family answers with nothing at all.
111 fn font_id(&self, style: &ParagraphStyle, registry: &FontRegistry) -> u16 {
112 let Some(face) = self.face else {
113 return style.font_id;
114 };
115 let Some(own) = registry.font_ref(style.font_id) else {
116 return style.font_id;
117 };
118 let want = FaceAttributes {
119 italic: face.italic.unwrap_or(own.attributes.italic),
120 weight: face.weight.unwrap_or(own.attributes.weight),
121 };
122 let family = face
123 .family
124 .and_then(|id| registry.font_ref(id))
125 .unwrap_or(own);
126 registry
127 .select(&family.family, want)
128 .map_or(style.font_id, |found| found.id)
129 }
130}
131
132/// What sets a paragraph's opening apart from the rest of it.
133#[derive(Debug, Clone, Copy, Default, PartialEq)]
134pub struct Opening {
135 /// What `::first-line` changes about the line the paragraph
136 /// opens on.
137 pub first_line: Option<FirstLine>,
138 /// Bytes of the paragraph's text a drop cap already set. They
139 /// are neither shaped nor broken here; the cap carries the range
140 /// they cover.
141 pub taken: usize,
142 /// The paragraph. The runs its `::first-line` style reaches carry
143 /// the id of that pseudo-element.
144 pub node: NodeId,
145}
146
147/// What one pass of the breaker is told about the paragraph's
148/// opening: the style it is set in, how far that reaches, and what a
149/// drop cap already took off the front of it.
150#[derive(Debug, Clone, Copy, Default)]
151pub(super) struct Lead {
152 pub(super) style: Option<FirstLine>,
153 /// Bytes of the shaped text the style covers. `None` on the pass
154 /// that has no break to read it off yet, where it covers the
155 /// paragraph.
156 pub(super) extent: Option<usize>,
157 /// Bytes of the source the paragraph starts past.
158 pub(super) taken: usize,
159 /// The id of the `::first-line` the style comes from.
160 pub(super) pseudo_element: Option<NodeId>,
161}
162
163impl Lead {
164 /// How far into the shaped text the opening style reaches.
165 pub(super) fn reach(self) -> usize {
166 self.extent.unwrap_or(usize::MAX)
167 }
168}
169
170/// What one inline element paints around its runs, and what that
171/// takes on each edge.
172///
173/// The edges are points. The leading and trailing ones are width
174/// like any other, so the breaker is told about them; the ones above
175/// and below leave the line the height it was.
176#[derive(Debug, Clone, Copy, PartialEq)]
177pub struct InlineBox {
178 /// Padding, in points.
179 pub padding: Edges,
180 /// Border widths, in points, zero on an edge that is not drawn.
181 pub border: Edges,
182 /// Whether `box-decoration-break: clone` closes the edges a line
183 /// break cuts.
184 pub cloned: bool,
185}
186
187impl InlineBox {
188 /// What the box takes before the first of its runs.
189 pub fn leading(&self) -> f32 {
190 self.padding.left + self.border.left
191 }
192
193 /// What it takes after the last of them.
194 pub fn trailing(&self) -> f32 {
195 self.padding.right + self.border.right
196 }
197
198 /// How far it reaches over the runs it covers.
199 pub fn above(&self) -> f32 {
200 self.padding.top + self.border.top
201 }
202
203 /// How far it reaches under them.
204 pub fn below(&self) -> f32 {
205 self.padding.bottom + self.border.bottom
206 }
207}
208
209/// Where line layout gets the style of one inline node.
210///
211/// The style tree answers by node id. `Inherited` answers with the
212/// block's own style, which is what a run of uniform text needs and
213/// what a caller with no tree in hand can supply.
214pub trait InlineStyles {
215 /// The style of `id`, given the style of the block it sits in.
216 fn style(&self, id: NodeId, block: &ParagraphStyle) -> ParagraphStyle;
217
218 /// The box the inline element `id` paints around its runs, where
219 /// it paints one. Nothing, for a caller with no tree to ask.
220 fn inline_box(&self, _id: NodeId) -> Option<InlineBox> {
221 None
222 }
223
224 /// The text the sheet generates around one inline element.
225 /// Nothing, for a caller with no sheet to ask.
226 fn generated(&self, _inline: &Inline) -> Generated {
227 Generated::default()
228 }
229
230 /// The reference of one note, in the style it is set in: the
231 /// note's number as the cascade spells it. Nothing, for a caller
232 /// with no book to number the notes of.
233 fn call(&self, _note: &Inline) -> Option<(String, ParagraphStyle)> {
234 None
235 }
236}
237
238/// Text the sheet generates around one inline element: what
239/// `::before` and `::after` hold, each with the style it is set in.
240#[derive(Debug, Clone, Default)]
241pub struct Generated {
242 /// Set before the element's own text.
243 pub before: Option<(String, ParagraphStyle)>,
244 /// Set after it.
245 pub after: Option<(String, ParagraphStyle)>,
246}
247
248/// Every inline takes the style of the block around it.
249pub struct Inherited;
250
251impl InlineStyles for Inherited {
252 fn style(&self, _id: NodeId, block: &ParagraphStyle) -> ParagraphStyle {
253 block.clone()
254 }
255}
256
257/// How a paragraph is broken and filled. The defaults are ragged
258/// right, no hyphenation, and no mark hanging past the measure.
259#[derive(Debug, Clone, Copy, Default, PartialEq)]
260pub struct LineBreakOptions {
261 /// Whether `hyphens: auto` is in force.
262 pub hyphenate: bool,
263 /// Which language's syllables `hyphenate` breaks at.
264 pub patterns: Patterns,
265 /// Whether the lines fill the measure, from
266 /// `text-align: justify`. Left, right and centred text all break
267 /// the same way; where the line then sits is the caller's.
268 pub justify: bool,
269 /// Whether justification also opens the space between letters,
270 /// from `text-justify: inter-character`.
271 pub inter_character: bool,
272 /// Which marks hang past the measure.
273 pub hanging: HangingPunctuation,
274 /// Whether the text is preformatted: it breaks at its own
275 /// newlines and nowhere else, and its spaces stand where they
276 /// were written. A code block is set this way.
277 pub preformatted: bool,
278}
279
280/// Which marks may hang past the measure, from
281/// `hanging-punctuation`.
282#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize)]
283pub struct HangingPunctuation {
284 /// `first`: opening punctuation hangs into the margin the line
285 /// starts at.
286 pub first: bool,
287 /// `allow-end` or `force-end`.
288 pub end: HangEnd,
289 /// `last`: the mark a paragraph ends on hangs past the measure.
290 pub last: bool,
291}
292
293impl HangingPunctuation {
294 /// Nothing hangs.
295 pub const NONE: HangingPunctuation = HangingPunctuation {
296 first: false,
297 end: HangEnd::None,
298 last: false,
299 };
300}
301
302/// How far `hanging-punctuation` goes at the end of a line.
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize)]
304#[serde(rename_all = "snake_case")]
305pub enum HangEnd {
306 /// Nothing hangs at a line end.
307 #[default]
308 None,
309 /// `allow-end`: a mark hangs only where hanging is what makes the
310 /// line fit.
311 Allow,
312 /// `force-end`: a mark at a line end always hangs.
313 Force,
314}
315
316/// How much of a mark hangs past the measure it ends a line at, as a
317/// fraction of its advance. The lighter the mark, the further it
318/// goes: a full stop leaves a hole in the margin that the eye reads
319/// as a ragged edge, a colon does not.
320pub(super) fn hang_end(mark: char) -> f32 {
321 match mark {
322 '.' | ',' => 0.7,
323 '-' | '\u{2010}' | '\u{2013}' => 0.5,
324 '"' | '\'' | '\u{201d}' | '\u{2019}' | '\u{00bb}' => 0.4,
325 '\u{2014}' => 0.25,
326 ';' | ':' | '!' | '?' => 0.2,
327 _ => 0.0,
328 }
329}
330
331/// The same for the mark a line opens with, hanging back into the
332/// margin the line starts at.
333pub(super) fn hang_start(mark: char) -> f32 {
334 match mark {
335 '"' | '\'' | '\u{201c}' | '\u{2018}' | '\u{00ab}' => 0.4,
336 '(' | '[' | '\u{2013}' | '\u{2014}' => 0.25,
337 _ => 0.0,
338 }
339}
340
341/// The syllable patterns `hyphens: auto` breaks words by.
342///
343/// The book's declared language chooses them; a book that declares
344/// none breaks by English.
345#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
346pub struct Patterns(pub(super) Option<hypher::Lang>);
347
348impl Default for Patterns {
349 fn default() -> Patterns {
350 Patterns::ENGLISH
351 }
352}
353
354impl Patterns {
355 /// No patterns at all: every word stays whole.
356 pub const NONE: Patterns = Patterns(None);
357
358 /// The English patterns, which a book that declares no language
359 /// breaks by.
360 pub const ENGLISH: Patterns = Patterns(Some(hypher::Lang::English));
361
362 /// The patterns a book breaks by: the ones its declared
363 /// language names, English where it declares none, and `NONE`
364 /// where there are no patterns for the language it declares.
365 pub fn of(metadata: &Metadata) -> Patterns {
366 match metadata.language() {
367 Some(tag) => Patterns::of_tag(tag).unwrap_or(Patterns::NONE),
368 None => Patterns::default(),
369 }
370 }
371
372 /// The patterns a BCP 47 tag names, read from its primary
373 /// subtag, so `fr-CA` is French. `None` where there are no
374 /// patterns for that language.
375 pub fn of_tag(tag: &str) -> Option<Patterns> {
376 let primary = tag.split(['-', '_']).next().unwrap_or_default();
377 let code: [u8; 2] = primary.as_bytes().try_into().ok()?;
378 hypher::Lang::from_iso(code.map(|byte| byte.to_ascii_lowercase()))
379 .map(|lang| Patterns(Some(lang)))
380 }
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386 use crate::lines::testing::{
387 body, hyphenated, layout_body, layout_body_opts, line_text, registry, units_per_em,
388 };
389 use crate::lines::{LineBreakOptions, Patterns};
390
391 /// A BCP 47 tag is read by its primary subtag, whatever the
392 /// case and whatever follows it. A tag with no patterns behind it
393 /// resolves to nothing rather than to English.
394 #[test]
395 fn patterns_come_from_the_primary_subtag() {
396 let french = Patterns::of_tag("fr");
397 assert!(french.is_some());
398 assert_eq!(Patterns::of_tag("fr-CA"), french);
399 assert_eq!(Patterns::of_tag("FR_ca"), french);
400 assert_ne!(Patterns::of_tag("de"), french);
401
402 assert_eq!(Patterns::of_tag("xx"), None);
403 assert_eq!(Patterns::of_tag("haw"), None);
404 assert_eq!(Patterns::of_tag(""), None);
405 }
406
407 /// A book that declares nothing breaks by English, and one that
408 /// declares a language with no patterns breaks nowhere.
409 #[test]
410 fn a_book_without_a_language_breaks_by_english() {
411 let declared = |tag: &str| {
412 Patterns::of(&Metadata {
413 extra: [("language".to_string(), tag.to_string())]
414 .into_iter()
415 .collect(),
416 ..Default::default()
417 })
418 };
419 assert_eq!(Patterns::of(&Metadata::default()), Patterns::default());
420 assert_eq!(declared("en"), Patterns::default());
421 assert_eq!(declared(" "), Patterns::default());
422 assert_eq!(declared("xx"), Patterns::NONE);
423 }
424
425 /// Without patterns nothing breaks inside a word: the same lines
426 /// hyphenation off gives.
427 #[test]
428 fn no_patterns_leaves_every_word_whole() {
429 let text = "extraordinarily inconsiderate";
430 let whole = LineBreakOptions {
431 patterns: Patterns::NONE,
432 ..hyphenated()
433 };
434 assert_eq!(
435 layout_body_opts(text, 44.0, whole)
436 .iter()
437 .map(line_text)
438 .collect::<Vec<_>>(),
439 layout_body(text, 44.0)
440 .iter()
441 .map(line_text)
442 .collect::<Vec<_>>(),
443 );
444 }
445
446 /// Hanging punctuation: a mark at a line end is not charged to
447 /// the measure, so a word that would not otherwise fit does.
448 #[test]
449 fn a_mark_at_a_line_end_hangs_past_the_measure() {
450 // `My father had a small estate,` is 117.74pt: over a 116pt
451 // measure by less than the comma hangs.
452 let text = "My father had a small estate, and I was the third of five sons.";
453 let hanging = LineBreakOptions {
454 hanging: HangingPunctuation {
455 end: HangEnd::Force,
456 ..Default::default()
457 },
458 ..Default::default()
459 };
460 let flush = layout_body(text, 116.0);
461 let hung = layout_body_opts(text, 116.0, hanging);
462 assert_eq!(line_text(&flush[0]), "My father had a small");
463 assert_eq!(line_text(&hung[0]), "My father had a small estate,");
464 assert!(hung[0].overhang > 0.0, "the comma was still charged");
465 }
466
467 /// Margin kerning: a line opening on a quotation mark starts
468 /// before the measure does, by part of the mark's own width.
469 #[test]
470 fn an_opening_mark_hangs_into_the_margin() {
471 let text = "\"He said it would be so,\" and it was.";
472 let kerned = LineBreakOptions {
473 hanging: HangingPunctuation {
474 first: true,
475 ..Default::default()
476 },
477 ..Default::default()
478 };
479 let lines = layout_body_opts(text, 200.0, kerned);
480 assert_eq!(lines.len(), 1);
481 assert!(
482 lines[0].protrusion > 0.0,
483 "the quotation mark was not pulled out",
484 );
485 let quote = registry()
486 .advance_width(0, registry().char_glyph(0, '"').unwrap())
487 .unwrap() as f32
488 / units_per_em() as f32
489 * body().size;
490 assert!(
491 lines[0].protrusion < quote,
492 "the whole mark left the measure",
493 );
494 }
495}