1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! The text decision module: the target's decisions about the widths and advances of glyphs
//! and about the faces that a run's text takes, made on the settings that a shaper applies to
//! every run ([`ShaperSettings`]).
use f_office_fonts::{FamilyName, KerningSource};
use f_office_units::Length;
use super::face::{DrawnGlow, DrawnReflection, DrawnShadow, TextRelief};
use super::script::{InvisibleKind, invisible_kind, mirror};
use super::{
AUTOMATIC_HYPHEN, Edges, HintLanguage, HintedLatin, HintedSet, LINE_END_HYPHEN,
MISSING_COMPLEX, MISSING_WITH_THEME, MISSING_WITHOUT_THEME, MathRoom, NON_BREAKING_HYPHEN,
OPERATOR_BREAK_SPACE, RunLines, SOFT_HYPHEN, ScriptMove, ScriptScale, ShadowRoom, SymbolFont,
ThemeScript,
};
use crate::FaceMetrics;
use crate::font_choice::HELVETICA;
use crate::params::{ADVANCE_PARTS_PER_POINT, SYMBOL_AREA, SYMBOL_BULLET};
use crate::props::{
EastAsianScript, RunProps, Strike, TextGlow, TextReflection, TextShadow, Underline,
};
use crate::quirks::{
ComplexItalicFace, DeviceAdvance, DisplayFractionRoom, FixedSpaceWidths, GlyphEdgeCheck,
GridAdvances, HelveticaLine, HintedFontSide, HintedSlot, InvisibleCharacters,
KernedDeviceWidths, LigatureSteps, LineHeight, MirroredBracketText, MissingComplexFont,
MissingFontFallback, NonBreakingHyphen, ScriptPlacement, ScriptRoom, ScriptSize,
ShapedGlyphText, SubstituteFaces, SuffixedFontNames, SymbolText, SyntheticBoldWidth,
TextShadows, ThemeEastAsian, UnderlineForms, WrittenWidths,
};
use crate::styles::{
FontClass, FontEntry, FullWidthSpacing, PunctuationKerning, Settings, SpaceBalance,
SuffixCharset,
};
/// What the shaper does with a character of a text, from the target's
/// `InvisibleCharacters`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Invisible {
/// The character takes its font's glyph, as any other character does.
Drawn,
/// The character takes no room, draws nothing and does not size its line.
Left,
/// A variation selector that joins the character before it in its paragraph: none inside
/// its run, and one that opens its run is drawn as its font's missing glyph, which the
/// layout makes a mark without width that sizes the line when a character comes before
/// it in the paragraph.
Joined,
}
/// The drawn text effects of a run resolved for the current target.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct DrawnEffects {
/// Drawn shadow (`w14:shadow`, or else legacy `w:shadow`).
pub(super) shadow: Option<DrawnShadow>,
/// Drawn glow (`w14:glow`).
pub(super) glow: Option<DrawnGlow>,
/// Drawn reflection (`w14:reflection`).
pub(super) reflection: Option<DrawnReflection>,
/// Drawn legacy relief (`w:emboss` or `w:imprint`).
pub(super) relief: Option<TextRelief>,
/// Whether legacy `w:outline` is active (without `w14:textOutline` or legacy relief).
pub(super) legacy_outline: bool,
/// Whether `w14:shadow` is drawn.
pub(super) w14_shadow: bool,
/// Whether legacy WordprocessingML effects (`w:shadow`, `w:outline`, `w:emboss`, `w:imprint`)
/// are drawn on this target.
pub(super) legacy: bool,
}
/// What a shaper and its forks apply to every run: the document's settings and the target's
/// quirks that shaping asks, made once for a layout ([`Self::of`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShaperSettings {
/// Whether runs may turn on standard ligatures: not in a compatibility mode before 14.
pub ligatures: bool,
/// Whether kerned runs close up pairs of East Asian punctuation marks, the document's
/// setting.
pub punctuation_kerning: PunctuationKerning,
/// How much of its run's character spacing a full-width character takes, the document's
/// setting.
pub full_width_spacing: FullWidthSpacing,
/// How wide a space next to East Asian text is, the document's setting.
pub space_balance: SpaceBalance,
/// The script of the document's East Asian language (`w:themeFontLang w:eastAsia`).
pub east_asian_script: Option<EastAsianScript>,
/// The rules of the document's compatibility mode where they reach the shaper: the steps
/// of a kerned run (`KernedDeviceWidths::in_run`).
pub mode_rules: crate::mode::ModeRules,
/// The variant of every quirk that the target's profile names, with which the methods of
/// this module decide.
pub quirks: crate::quirks::Quirks,
/// One dot of the target's layout device, to which the edges of a superscript or
/// subscript round and at whose pixels per em the shaper reads a font's pixel heights.
pub dot: crate::grid::Dot,
}
impl ShaperSettings {
/// The settings of a shaper for a document with the settings `settings`, on a target with
/// the quirks `quirks` whose device has the dot `dot`: the one place where the shaper
/// takes the document's settings and the target's quirks.
#[must_use]
pub fn of(settings: &Settings, quirks: &crate::quirks::Quirks, dot: crate::grid::Dot) -> Self {
Self {
ligatures: settings.mode_rules.joins_ligatures(),
punctuation_kerning: settings.punctuation_kerning,
full_width_spacing: settings.full_width_spacing,
space_balance: settings.space_balance,
east_asian_script: settings.east_asian_script,
mode_rules: settings.mode_rules,
quirks: *quirks,
dot,
}
}
/// The settings of a shaper for a document with the default settings on the base target,
/// for tests.
#[cfg(test)]
#[must_use]
pub fn base() -> Self {
Self::of(
&Settings::default(),
&crate::grid::base_quirks(),
crate::grid::base_device().dot_size(),
)
}
/// The settings of [`Self::base`] on the base target's configuration with some quirks of
/// another variant (`change`), for a test that names the variant that it means.
#[cfg(test)]
#[must_use]
pub fn base_with(
change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
) -> Self {
let profile = change(&crate::profile::Profile::base());
Self::of(
&Settings::default(),
&profile.quirks(),
profile.device().dot_size(),
)
}
}
impl ShaperSettings {
/// The room in its line of the shadow, glow, and reflection of a run's text with line
/// `(ascent, descent, size)` (the full size of a superscript or a subscript): on a target
/// whose shadows of text take a share of their lengths by the size (`TextShadows::Scaled`),
/// the maximum of their rooms above and below, and none elsewhere.
pub(super) fn shadow_room(
self,
(shadow, glow, reflection): (Option<TextShadow>, Option<TextGlow>, Option<TextReflection>),
(ascent, descent, size): (Length, Length, Length),
) -> ShadowRoom {
match self.quirks.text_shadows {
TextShadows::Unknown => ShadowRoom::default(),
// quirk: TextShadows::Scaled (src/quirks.rs)
TextShadows::Scaled => {
let s = shadow.map_or_else(ShadowRoom::default, |s| super::shadow::room(s, size));
let g =
glow.map_or_else(ShadowRoom::default, |g| super::shadow::glow_room(g, size));
let r = reflection.map_or_else(ShadowRoom::default, |r| {
super::shadow::reflection_room(r, (ascent, descent, size))
});
ShadowRoom {
above: s.above.max(g.above).max(r.above),
below: s.below.max(g.below).max(r.below),
}
}
}
}
/// The drawn text effects of a run with `props` at drawn size `size` and line metrics
/// `(ascent, descent, line_size)`, with `outline` along its glyphs, if any: on a target whose
/// text shadows scale with size (`TextShadows::Scaled`), resolves `w14:shadow`, `w14:glow`,
/// `w14:reflection`, and legacy WordprocessingML text effects (`w:shadow`, `w:outline`,
/// `w:emboss`, `w:imprint`), and none elsewhere.
pub(super) fn drawn_text_effects(
self,
props: &RunProps,
outline: Option<f_office_paint::Outline>,
size: Length,
metrics: (Length, Length, Length),
) -> DrawnEffects {
match self.quirks.text_shadows {
TextShadows::Unknown => DrawnEffects::default(),
// quirk: TextShadows::Scaled (src/quirks.rs)
TextShadows::Scaled => {
let line_size = metrics.2;
let scaled = super::shadow::scaled_run(props);
let w14_shadow = props
.shadow
.and_then(|s| super::shadow::drawn(s, outline, scaled, line_size));
let glow = props
.glow
.and_then(|g| super::shadow::drawn_glow(g, scaled, line_size));
let reflection = props
.reflection
.as_deref()
.copied()
.and_then(|r| super::shadow::drawn_reflection(r, outline, scaled, metrics));
let relief = if props.emboss.unwrap_or(false) {
Some(TextRelief::Emboss)
} else if props.imprint.unwrap_or(false) {
Some(TextRelief::Imprint)
} else {
None
};
let legacy_shadow = w14_shadow.is_none()
&& relief.is_none()
&& props.legacy_shadow.unwrap_or(false);
let legacy_outline =
outline.is_none() && relief.is_none() && props.legacy_outline.unwrap_or(false);
let shadow = w14_shadow
.or_else(|| legacy_shadow.then(|| super::shadow::legacy_shadow(size)));
DrawnEffects {
shadow,
glow,
reflection,
relief,
legacy_outline,
w14_shadow: w14_shadow.is_some(),
legacy: true,
}
}
}
}
/// The target face of a font, which `face` gives, when the target's device steps glyphs by
/// whole dots, so that the glyphs of its own faces take the device widths that the face's
/// instructions give (`GridAdvances::RightEdgeSteps`). `None` on a device that does not.
pub(crate) fn device_width_face<T>(self, face: impl FnOnce() -> Option<T>) -> Option<T> {
// quirk: GridAdvances::RightEdgeSteps (src/quirks.rs)
match self.quirks.grid_advances {
GridAdvances::RightEdgeSteps => face(),
GridAdvances::RoundToPdfSteps => None,
}
}
/// Whether a run steps as a kerned run, and then whether as a face that stands in for the
/// run's font: a run that kerns (`kerned`) with its face's standing (`stands_in`), and
/// under `LigatureSteps::AsKernedRun` a run whose standard ligatures are on (`ligatures`),
/// as a face under its own name. Nothing for a run that steps as one without kerning.
pub(crate) fn kerned_steps_of(
self,
kerned: bool,
ligatures: bool,
stands_in: bool,
) -> Option<bool> {
// quirk: LigatureSteps (src/quirks.rs), whose variant the target carries.
match self.quirks.ligature_steps {
LigatureSteps::AsKernedRun if ligatures => Some(false),
LigatureSteps::AsKernedRun | LigatureSteps::AsTheirRun => kerned.then_some(stands_in),
}
}
/// How the glyphs of a kerned run step, for a face whose kerning comes from `source` and
/// that stands in for the run's font (`stands_in`) or not: the target's variant in the
/// document's mode and the face's kerning source, which a stand-in face can change.
fn kerned_steps(self, (source, stands_in): (KerningSource, bool)) -> KernedDeviceWidths {
let steps = self
.quirks
.kerned_device_widths
.in_run(self.mode_rules, source);
// quirk: DeviceAdvance::ExtrasOnTheirOwn (src/quirks.rs)
self.quirks.device_advance.stand_in_steps(steps, stands_in)
}
/// The device width `width` of a glyph of a run that is kerned (`kerned`, with its face's
/// kerning source and whether the face stands in) or not: kept unless the kerned run steps
/// without device widths (`KernedDeviceWidths` other than `Own` and
/// `OwnWithKerningOnItsOwn`, after `KernedDeviceWidths::in_run`).
pub(crate) fn kerned_device_width<T>(
self,
kerned: Option<(KerningSource, bool)>,
width: Option<T>,
) -> Option<T> {
// quirk: KernedDeviceWidths (src/quirks.rs), whose variant the run takes.
let dropped = kerned.is_some_and(|run| {
!matches!(
self.kerned_steps(run),
KernedDeviceWidths::Own | KernedDeviceWidths::OwnWithKerningOnItsOwn
)
});
width.filter(|_| !dropped)
}
/// The part of a glyph's pair kerning `kerning` that the device steps in whole dots on its
/// own, as character spacing, in a kerned run (`kerned`) that steps so
/// (`KernedDeviceWidths::OwnWithKerningOnItsOwn` after `KernedDeviceWidths::in_run`): all of
/// it there, and zero elsewhere.
pub(crate) fn kerning_on_its_own(
self,
kerned: Option<(KerningSource, bool)>,
kerning: Length,
) -> Length {
// quirk: KernedDeviceWidths::OwnWithKerningOnItsOwn (src/quirks.rs)
match kerned.map(|run| self.kerned_steps(run)) {
Some(KernedDeviceWidths::OwnWithKerningOnItsOwn) => kerning,
_ => Length::ZERO,
}
}
/// Whether the device steps the glyphs of a kerned run (`kerned`) by their exact distances
/// rounded without the bias (`KernedDeviceWidths::Nearest` after
/// `KernedDeviceWidths::in_run`).
pub(crate) fn steps_without_bias(self, kerned: Option<(KerningSource, bool)>) -> bool {
// quirk: KernedDeviceWidths::Nearest (src/quirks.rs)
kerned.map(|run| self.kerned_steps(run)) == Some(KernedDeviceWidths::Nearest)
}
/// The table that the pairs of a kerned run read, by the target's variant in the
/// document's mode (`KerningTableRead::in_mode`).
pub(crate) fn kerning_table(self) -> crate::KerningTable {
// quirk: KerningTableRead (src/quirks.rs), whose variant the document's mode takes.
self.quirks.kerning_table_read.in_mode(self.mode_rules)
}
/// The character that a glyph for the character `ch` shows: the hyphen-minus for a soft or
/// automatic hyphen and for the hyphen at a line's end, the no-break space for an operator
/// break space, and for a non-breaking hyphen
/// U+2011 under `NonBreakingHyphen::OwnGlyph` and the hyphen-minus under `AsHyphenMinus`;
/// every other character itself.
pub(crate) fn shown_char(self, ch: char) -> char {
match ch {
SOFT_HYPHEN | AUTOMATIC_HYPHEN | LINE_END_HYPHEN => '-',
OPERATOR_BREAK_SPACE => '\u{00A0}',
// quirk: NonBreakingHyphen (src/quirks.rs), whose variant the target carries.
NON_BREAKING_HYPHEN => match self.quirks.non_breaking_hyphen {
NonBreakingHyphen::OwnGlyph => '\u{2011}',
NonBreakingHyphen::AsHyphenMinus => '-',
},
_ => ch,
}
}
/// What the shaper does with `ch`, one of the characters that F-Office takes as invisible
/// or any other, in text of an equation when `math` holds: `Invisible::Drawn` for a
/// character that it draws as any other. Text of an equation leaves every invisible
/// character out.
pub(crate) const fn invisible(self, ch: char, math: bool) -> Invisible {
let Some(kind) = invisible_kind(ch) else {
return Invisible::Drawn;
};
if math {
return Invisible::Left;
}
match (self.quirks.invisible_characters, kind) {
// quirk: InvisibleCharacters::TakeNoRoom (src/quirks.rs)
(InvisibleCharacters::TakeNoRoom, _)
// quirk: InvisibleCharacters::OperatorsDrawnSelectorsJoined (src/quirks.rs)
| (InvisibleCharacters::OperatorsDrawnSelectorsJoined, InvisibleKind::Format) => {
Invisible::Left
}
(InvisibleCharacters::OperatorsDrawnSelectorsJoined, InvisibleKind::Operator) => {
Invisible::Drawn
}
(InvisibleCharacters::OperatorsDrawnSelectorsJoined, InvisibleKind::Selector) => {
Invisible::Joined
}
}
}
/// Whether the shaper leaves `ch` out of a text whose glyphs come from the font's layout
/// tables, in text of an equation when `math` holds: every character that it does not
/// draw as any other.
pub(crate) const fn leaves_out(self, ch: char, math: bool) -> bool {
!matches!(self.invisible(ch, math), Invisible::Drawn)
}
/// The characters, in order, whose glyph gives the kerning pairs of a glyph for `ch` that
/// is drawn as another glyph: a non-breaking hyphen drawn as a hyphen-minus under
/// `NonBreakingHyphen::AsHyphenMinus` keeps the pairs of U+2011, or else of the
/// hyphen-minus. `None` for a glyph that keeps its own pairs.
pub(crate) fn kerning_chars(self, ch: char) -> Option<[char; 2]> {
// quirk: NonBreakingHyphen::AsHyphenMinus (src/quirks.rs)
(ch == NON_BREAKING_HYPHEN
&& self.quirks.non_breaking_hyphen == NonBreakingHyphen::AsHyphenMinus)
.then_some(['\u{2011}', '-'])
}
/// What a synthetic bold adds to the advance of each of its glyphs of a face of the size
/// `size`, but spaces and the later parts of a ligature: a fiftieth of the size under
/// `SyntheticBoldWidth::WidensByFiftieth`. `None` under the other variants.
pub(crate) fn bold_widening(self, size: Length) -> Option<Length> {
// quirk: SyntheticBoldWidth::WidensByFiftieth (src/quirks.rs)
(self.quirks.synthetic_bold_width == SyntheticBoldWidth::WidensByFiftieth)
.then(|| Length::from_units(size.units() / crate::params::SYNTHETIC_BOLD_PARTS))
}
/// What the edge check and the segment rule count beside the advance of a glyph of a
/// synthetic bold face of the size `size` in half-EMUs and `units_per_em` font units per em,
/// a numerator over a denominator: one font unit of the face under
/// `SyntheticBoldWidth::CountsAFontUnit`. `None` under the other variants.
pub(crate) fn bold_counted_unit(self, size: i64, units_per_em: i64) -> Option<(i64, i64)> {
// quirk: SyntheticBoldWidth::CountsAFontUnit (src/quirks.rs)
(self.quirks.synthetic_bold_width == SyntheticBoldWidth::CountsAFontUnit)
.then_some((size, units_per_em))
}
/// The exact advance that the edge check of right-edge steps counts for a glyph whose
/// advance at the size is `advance`, a numerator over a positive denominator in half-EMUs
/// (the font's advance times the size, over the font's units per em), as a numerator over a
/// positive denominator in half-EMUs: that advance cut down to whole parts of
/// `params::ADVANCE_PARTS_PER_POINT` under `GlyphEdgeCheck::Exact`, and the advance itself
/// under `RoundedWithTie`, which counts the advances as the glyphs keep them.
pub(crate) fn counted_advance(self, advance: (i64, i64)) -> (i64, i64) {
let (scaled, per) = advance;
match self.quirks.glyph_edge_check {
// quirk: GlyphEdgeCheck::RoundedWithTie (src/quirks.rs)
GlyphEdgeCheck::RoundedWithTie => advance,
// quirk: GlyphEdgeCheck::Exact (src/quirks.rs)
GlyphEdgeCheck::Exact => {
let point = Length::UNITS_PER_POINT;
let parts = (scaled * ADVANCE_PARTS_PER_POINT).div_euclid(per.max(1) * point);
(parts * point, ADVANCE_PARTS_PER_POINT)
}
}
}
/// The width in whole thousandths of an em that the target's PDF writer writes for a glyph,
/// where it differs from the text object's rounding of the glyph's own advance: under
/// `WrittenWidths::HintedAdvanceAt1000`, from `widths`, which gives the glyph's advance at
/// 1000 per em rounded from its font units (`linear`), its bi-level advance at 1000 pixels
/// per em where the face can be hinted (`width`, else `linear`), and its advance kept at the
/// size in thousandths (`kept`, none at a size of zero): `width` where it differs from
/// `linear` or from `kept`. `None` under `RoundsAdvance`, where the writer's width is that
/// rounding, and where `widths` gives none.
pub(crate) fn written_width(
self,
widths: impl FnOnce() -> Option<(i64, i64, Option<i64>)>,
) -> Option<u16> {
match self.quirks.written_widths {
// quirk: WrittenWidths::RoundsAdvance (src/quirks.rs)
WrittenWidths::RoundsAdvance => None,
// quirk: WrittenWidths::HintedAdvanceAt1000 (src/quirks.rs)
WrittenWidths::HintedAdvanceAt1000 => {
let (linear, width, kept) = widths()?;
(width != linear || kept.is_some_and(|kept| kept != width))
.then(|| u16::try_from(width).ok())
.flatten()
}
}
}
/// The character spacing `spacing` of a glyph that the device steps on its own, beside the
/// glyph's own width (`DeviceAdvance::ExtrasOnTheirOwn`): all of it there. `None` where the
/// spacing steps as a part of the advance.
pub(crate) fn spacing_on_its_own<T>(self, spacing: T) -> Option<T> {
// quirk: DeviceAdvance::ExtrasOnTheirOwn (src/quirks.rs)
(self.quirks.device_advance == DeviceAdvance::ExtrasOnTheirOwn).then_some(spacing)
}
}
impl ShaperSettings {
/// The upright face that an italic complex script run takes instead of its italic face,
/// which `upright` gives, under `ComplexItalicFace::UprightForLanguage`. `None` where the
/// run keeps its italic face.
pub(crate) fn complex_upright<T>(self, upright: impl FnOnce() -> Option<T>) -> Option<T> {
match self.quirks.complex_italic_face {
ComplexItalicFace::Italic => None,
// quirk: ComplexItalicFace::UprightForLanguage (src/quirks.rs)
ComplexItalicFace::UprightForLanguage => upright(),
}
}
/// The family before the suffix of a suffixed font name `written`, such as Times New Roman
/// CYR, with the suffix's character set, on a target that draws such a name with that
/// family (`SuffixedFontNames::DrawBase`). `None` for another name, and on a target where
/// the name is missing.
pub(crate) fn suffixed_base(self, written: &str) -> Option<(&str, SuffixCharset)> {
match self.quirks.suffixed_font_names {
// quirk: SuffixedFontNames::DrawBase (src/quirks.rs)
SuffixedFontNames::DrawBase => SuffixCharset::split(written),
SuffixedFontNames::Missing => None,
}
}
/// The face from the table of substitute faces, which `substitute` gives, for a character
/// that its face lacks or that the target draws with a substitute by its block
/// (`SubstituteFaces::ByBlock`). `None` where the target substitutes by its list of East
/// Asian fonts only.
pub(crate) fn block_substitute<T>(self, substitute: impl FnOnce() -> Option<T>) -> Option<T> {
match self.quirks.substitute_faces {
SubstituteFaces::EastAsianList => None,
// quirk: SubstituteFaces::ByBlock (src/quirks.rs)
SubstituteFaces::ByBlock => substitute(),
}
}
/// The characters that a run's East Asian hint moves into the East Asian slot: the shared
/// punctuation, or under `HintedSlot::Symbols` also the symbols, Greek and Cyrillic, and
/// none when `times` says that the run's East Asian face is Times New Roman.
pub(super) fn hinted_set(self, times: impl FnOnce() -> bool) -> Option<HintedSet> {
match self.quirks.hinted_slot {
HintedSlot::Punctuation => Some(HintedSet::Punctuation),
// quirk: HintedSlot::Symbols (src/quirks.rs)
HintedSlot::Symbols => (!times()).then_some(HintedSet::Symbols),
}
}
/// The script whose theme font an East Asian theme font with an empty typeface stands for,
/// in a run whose East Asian language has the script `run`: that script, or under
/// `ThemeEastAsian::SettingsLanguage` the settings' script, and the unnamed face when the
/// settings name none.
pub(super) fn theme_script(self, run: Option<EastAsianScript>) -> ThemeScript {
match self.quirks.theme_east_asian {
ThemeEastAsian::RunLanguage => ThemeScript::Of(run),
// quirk: ThemeEastAsian::SettingsLanguage (src/quirks.rs)
ThemeEastAsian::SettingsLanguage => self
.east_asian_script
.map_or(ThemeScript::Unnamed, |script| ThemeScript::Of(Some(script))),
}
}
/// The side that a run's East Asian hint gives the characters of Latin-1, the Latin
/// letters outside it and Greek Extended: open, or under `HintedFontSide::ByLanguage` the
/// side of the run's East Asian language and font, which `language` reads.
pub(super) fn hinted_latin(self, language: impl FnOnce() -> HintLanguage) -> HintedLatin {
match self.quirks.hinted_font_side {
HintedFontSide::Open => HintedLatin::Open,
// quirk: HintedFontSide::ByLanguage (src/quirks.rs)
HintedFontSide::ByLanguage => HintedLatin::ByLanguage(language()),
}
}
/// The family that a named font that is missing gives way to: in a document with a theme
/// (`themed`) Calibri and without one Cambria; or under `MissingFontFallback::ByFontTable`
/// Cambria when the font table, which `entry` reads, has no entry for the font or its
/// entry's font class is roman, and Calibri otherwise.
pub(crate) fn missing_font_fallback(
self,
themed: bool,
entry: impl FnOnce() -> FontEntry,
) -> FamilyName {
match self.quirks.missing_font_fallback {
MissingFontFallback::ByTheme if themed => MISSING_WITH_THEME,
MissingFontFallback::ByTheme => MISSING_WITHOUT_THEME,
// quirk: MissingFontFallback::ByFontTable (src/quirks.rs)
MissingFontFallback::ByFontTable => match entry() {
FontEntry::Absent | FontEntry::Class(FontClass::Roman) => MISSING_WITHOUT_THEME,
FontEntry::NoClass | FontEntry::Class(_) => MISSING_WITH_THEME,
},
}
}
/// The family that a named complex script font that is missing gives way to for complex
/// script text: Arial, or under `MissingComplexFont::ByFontTable` the family that its font
/// table entry gives, which `by_table` reads.
pub(crate) fn missing_complex_font(self, by_table: impl FnOnce() -> FamilyName) -> FamilyName {
match self.quirks.missing_complex_font {
MissingComplexFont::Arial => MISSING_COMPLEX,
// quirk: MissingComplexFont::ByFontTable (src/quirks.rs)
MissingComplexFont::ByFontTable => by_table(),
}
}
}
impl ShaperSettings {
/// How a superscript or subscript of a face moves: by the size that it loses, no higher
/// than the cap that `cap` gives, or under `ScriptPlacement::AlignsLineEdges` to the edges
/// of its line, which `edges` gives.
pub(super) fn script_move<'e>(
self,
cap: impl FnOnce() -> Option<Length>,
edges: impl FnOnce() -> Edges<'e>,
) -> ScriptMove<'e> {
match self.quirks.script_placement {
ScriptPlacement::LostSize => ScriptMove::LostSize(cap()),
// quirk: ScriptPlacement::AlignsLineEdges (src/quirks.rs)
ScriptPlacement::AlignsLineEdges => ScriptMove::LineEdges(edges()),
}
}
/// How large a superscript or subscript is: two thirds of its run's size, or under
/// `ScriptSize::FaceValues` the share of its font, which `of_face` gives.
pub(super) fn script_scale(self, of_face: impl FnOnce() -> ScriptScale) -> ScriptScale {
match self.quirks.script_size {
ScriptSize::TwoThirds => ScriptScale::TwoThirds,
// quirk: ScriptSize::FaceValues (src/quirks.rs)
ScriptSize::FaceValues => of_face(),
}
}
/// How the line gives a run of an equation its room, from where the run lies: a display's
/// n-ary operator drawn with the larger variant of its glyph or a run in a limit over or
/// under it (`operator`), a part of a fraction that takes the room of its ink below the
/// line (`part`), a part of any fraction (`in_fraction`) and a superscript or a subscript
/// (`script`); and from the `MathLeading` of its math font,
/// which `leading` gives where the font has a `MATH` table. The room of the ink with the
/// leading above it for an operator, a part and, under `DisplayFractionRoom::Ink`, a part
/// of a display's fraction; under `ScriptRoom::Ink` the room of the font's lines and of
/// the ink for a script outside a fraction; without a `MATH` table the room of the
/// ink below the line for a part; and otherwise the room of the font's lines.
pub(super) fn math_room(
self,
(operator, part, in_fraction, script): (bool, bool, bool, bool),
leading: impl FnOnce() -> Option<Length>,
) -> MathRoom {
// quirk: DisplayFractionRoom::Ink (src/quirks.rs)
let display_part =
in_fraction && self.quirks.display_fraction_room == DisplayFractionRoom::Ink;
// quirk: ScriptRoom::Ink (src/quirks.rs)
let script = !in_fraction && self.quirks.script_room == ScriptRoom::Ink && script;
let leading = (operator || part || display_part || script)
.then(leading)
.flatten();
match leading {
Some(leading) if script => MathRoom::LinesAndInk { leading },
Some(leading) => MathRoom::Ink { leading },
None if part => MathRoom::InkBelow,
None => MathRoom::Lines,
}
}
/// The character that the target writes for a symbol `ch` of a symbol font `font`, drawn
/// with the glyph `id`: for a code of the symbol area, or a character of one byte of such
/// a font, which takes the area's code of its byte. Under `SymbolText::TableOrSymbol`, a
/// symbol is the character that the table of symbol text gives for the font and the code,
/// and otherwise a character of the area keeps itself. Otherwise, and for a character of
/// one byte that the table lacks, it is the bullet U+2022 for the Symbol bullet, the
/// replacement character U+FFFD when the font draws the character with its missing glyph
/// (`id` 0), and otherwise the character of the low byte.
pub(super) fn symbol_text(self, ch: char, font: Option<SymbolFont>, id: u32) -> char {
let (start, end) = SYMBOL_AREA.map(u32::from).into();
let one_byte = font.is_some() && (' '..='\u{FF}').contains(&ch);
let code = if one_byte {
start + u32::from(ch)
} else {
u32::from(ch)
};
if !(start..=end).contains(&code) {
return ch;
}
if self.quirks.symbol_text == SymbolText::TableOrSymbol {
// quirk: SymbolText::TableOrSymbol (src/quirks.rs)
let table = font.zip(char::from_u32(code));
if let Some(text) =
table.and_then(|(font, symbol)| super::symbol_table::text(font, symbol))
{
return text;
}
if !one_byte {
return ch;
}
}
// quirk: SymbolText::LowByte (src/quirks.rs)
match code {
_ if id == 0 => char::REPLACEMENT_CHARACTER,
_ if font == Some(SymbolFont::Symbol) && code == u32::from(SYMBOL_BULLET) => '\u{2022}',
_ => char::from_u32(code - start).unwrap_or(ch),
}
}
/// The character that the target writes for the character `drawn` of a run that reads from
/// right to left, whose brackets are mirrored already: the mirrored bracket itself, or
/// under `MirroredBracketText::AsInFile` the bracket of the file, which is its mirror image.
pub(super) fn bracket_text(self, drawn: char) -> char {
// quirk: MirroredBracketText (src/quirks.rs)
match self.quirks.mirrored_bracket_text {
MirroredBracketText::Mirrored => drawn,
MirroredBracketText::AsInFile => mirror(drawn),
}
}
/// Whether the target writes, for a glyph of shaped Arabic text, the lowest character that
/// the font maps to the glyph (`ShapedGlyphText::LowestMappedCharacter`), or else the
/// letters of the document that the glyph stands for.
pub(super) fn writes_lowest_mapped_character(self) -> bool {
// quirk: ShapedGlyphText (src/quirks.rs)
matches!(
self.quirks.shaped_glyph_text,
ShapedGlyphText::LowestMappedCharacter
)
}
/// The character whose glyph's advance the space `ch` takes in place of its own: the en
/// dash for an en space and the em dash for an em space, where the target lays them out so
/// (`FixedSpaceWidths::DashWidths`); `None` for any other character or target.
pub(super) const fn width_of(self, ch: char) -> Option<char> {
// quirk: FixedSpaceWidths (src/quirks.rs)
match (self.quirks.fixed_space_widths, ch) {
(FixedSpaceWidths::DashWidths, '\u{2002}') => Some('\u{2013}'),
(FixedSpaceWidths::DashWidths, '\u{2003}') => Some('\u{2014}'),
_ => None,
}
}
/// The target's rule for the single line of each face.
pub(super) fn single_line(self) -> SingleLine {
SingleLine(self.quirks.line_height)
}
/// The lines of a run whose properties give the underline `under` and the line through
/// `through`, as the target draws them: every line that is on as a single one, or under
/// `UnderlineForms::ByKind` each kind as itself but the waves, which stay single.
pub(crate) fn run_lines(
self,
(under, through): (Option<Underline>, Option<Strike>),
change_bar: bool,
) -> RunLines {
let forms = self.quirks.underline_forms;
let under = match under {
None | Some(Underline::None) => Underline::None,
Some(Underline::Wave | Underline::WavyHeavy | Underline::WavyDouble) => {
Underline::Single
}
Some(kind) => match forms {
UnderlineForms::AllSingle => Underline::Single,
// quirk: UnderlineForms::ByKind (src/quirks.rs)
UnderlineForms::ByKind => kind,
},
};
let through = match through {
None | Some(Strike::None) => Strike::None,
Some(kind) => match forms {
UnderlineForms::AllSingle => Strike::Single,
UnderlineForms::ByKind => kind,
},
};
RunLines {
under,
through,
change_bar,
}
}
}
/// The target's rule for a face's single line ([`ShaperSettings::single_line`]), which a face
/// keeps to give its line height from its metrics.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SingleLine(LineHeight);
impl SingleLine {
/// The rule of a variant of the quirk, for tests.
#[cfg(test)]
pub(crate) const fn of(line_height: LineHeight) -> Self {
Self(line_height)
}
/// The single line in font units of a face of the metrics `m`: the `hhea` ascender minus
/// descender plus line gap, or the top of the font's line above the baseline plus its
/// descent, which is the taller of the `hhea` line and the win line, or the typographic
/// line when the font sets `USE_TYPO_METRICS`. A font made for East Asian text leaves its
/// `hhea` line gap out of its `hhea` line, on every target.
pub(crate) fn of_metrics(self, m: &FaceMetrics) -> i64 {
let hhea = i64::from(m.hhea_ascender) - i64::from(m.hhea_descender);
let gap = i64::from(m.hhea_line_gap);
match self.0 {
LineHeight::TakesHheaLine if m.east_asian => hhea,
LineHeight::TakesHheaLine => hhea + gap,
// quirk: LineHeight::TakesTallerLine (src/quirks.rs)
// quirk: LineHeight::TakesTallerLineEastAsianWin (src/quirks.rs)
LineHeight::TakesTallerLine | LineHeight::TakesTallerLineEastAsianWin => {
let taller = i64::from(m.line_top) + i64::from(m.descent);
// When the hhea line with its gap is the taller line, the font made for East
// Asian text takes the taller of the hhea line without it and the win line, or
// the win line where the target takes it.
if m.east_asian && taller == hhea + gap {
let win = i64::from(m.script_top) + i64::from(m.descent);
if self.0 == LineHeight::TakesTallerLineEastAsianWin {
win
} else {
hhea.max(win)
}
} else {
taller
}
}
}
}
/// The room that the line of a font of the metrics `m` gets above and below its text, in
/// font units: [`crate::params::EAST_ASIAN_LINE_EXTRA`] of its single line each for a font
/// made for East Asian text, to the nearest unit, and 0 for another font.
pub(crate) fn east_asian_room(self, m: &FaceMetrics) -> i64 {
if m.east_asian {
f_office_units::div_round(
self.of_metrics(m) * crate::params::EAST_ASIAN_LINE_EXTRA,
f_office_units::scale::PERCENT,
)
} else {
0
}
}
}
/// The target's rule for the families that a stand-in lays out with its own line metrics,
/// which are those of the base target, in place of the line of the face that draws them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct StandInLines(HelveticaLine);
impl StandInLines {
/// The rule of the target with `quirks`.
pub(crate) const fn of(quirks: &crate::quirks::Quirks) -> Self {
Self(quirks.helvetica_line)
}
/// Whether the stand-in of `family` gives the family its own line metrics. A target that
/// draws Helvetica with another font takes the line of the face that draws it.
pub(crate) fn of_family(self, family: &str) -> bool {
// quirk: HelveticaLine
family != HELVETICA || self.0 == HelveticaLine::TwelveTenthsEm
}
}