Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/math/fragment.rs

17.4 KiB, 1 run

created by r1870400018:63544, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// SPDX-License-Identifier: Apache-2.0
2// Original work copyright (c) the Typst project authors (typst-layout `math/fragment`, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4//! Laid-out maths pieces: glyphs (with their stretching to a size through variants and assemblies),
5//! frames, spaces and tags. A port of Typst 0.15's `typst-layout/src/math/fragment`.
6
7use crate::diag::DiagnosticKind;
8use crate::eval::realise::Tag;
9use crate::eval::styles::StyleChain;
10use crate::eval::value::Paint;
11use crate::eval::Engine;
12use crate::flow::visual::P2;
13use crate::math::class::{
14 default_math_class,
15 MathClass,
16};
17use crate::math::font::{
18 chain,
19 Corner,
20 MathFont,
21 ShapedGlyph,
22};
23use crate::math::frame::{
24 FItem,
25 GlyphRun,
26 MFrame,
27};
28use crate::math::item::{
29 Props,
30 Stretch,
31};
32use crate::math::props;
33use crate::math::style::MathSize;
34use crate::syntax::Span;
35
36use oxedyne_fe2o3_core::prelude::*;
37use oxedyne_fe2o3_font::shape::Feature;
38
39use std::sync::Arc;
40
41const MAX_REPEATS: usize = 1024; // most repetitions of an assembly's extenders
42
43#[derive(Clone)]
44pub struct GlyphFrag {
45 pub font: Arc<MathFont>,
46 pub size: f64, // font size, points
47 pub fill: Paint,
48 pub text: String,
49 pub glyphs: Vec<ShapedGlyph>,
50 pub w: f64,
51 pub h: f64,
52 baseline: Option<f64>,
53 pub italics: f64,
54 pub accent_attach: (f64, f64),
55 pub math_size: MathSize,
56 pub class: MathClass,
57 pub extended: bool,
58 shift: f64,
59 align: f64,
60 pub span: Span,
61}
62
63impl GlyphFrag {
64 /// A glyph for one character in the maths font chain the styles name.
65 pub fn synthetic(engine: &mut Engine, styles: &StyleChain, c: char, span: Span) -> Outcome<Option<Self>> {
66 let class = default_math_class(c).unwrap_or(MathClass::Normal);
67 let mut s = String::new();
68 s.push(c);
69 let g = res!(Self::base(engine, styles, &res!(props::features(styles)), &s, class, props::size(styles)));
70 Ok(g.map(|mut g| { g.span = span; g }))
71 }
72
73 /// A glyph for `text` (one grapheme), stretched as `stretch` asks.
74 pub fn new(
75 engine: &mut Engine,
76 text: &str,
77 stretch: &Stretch,
78 styles: &StyleChain,
79 features: Vec<Feature>,
80 props: &Props,
81 class: MathClass,
82 )
83 -> Outcome<Option<Self>>
84 {
85 let mut glyph = match res!(Self::base(engine, styles, &features, text, class, props.size)) {
86 Some(g) => g,
87 None => return Ok(None),
88 };
89 glyph.span = props.span;
90 let mut action = res!(decide(&glyph, stretch));
91 if matches!(action, Action::Fallback) {
92 // Retry without the flattened-accent and script-style forms until one can stretch or fits.
93 let had_flac = features.iter().rev().find(|f| &f.tag == b"flac").map(|f| f.value != 0).unwrap_or(false);
94 let prev_ssty = features.iter().rev().find(|f| &f.tag == b"ssty").map(|f| f.value).unwrap_or(0);
95 let base: Vec<Feature> = features.iter().copied().filter(|f| &f.tag != b"flac" && &f.tag != b"ssty").collect();
96 const OPTIONS: [(bool, u32); 6] = [(true, 2), (true, 1), (true, 0), (false, 2), (false, 1), (false, 0)];
97 for (flac, ssty) in OPTIONS {
98 if (flac && !had_flac) || ssty > prev_ssty || (flac, ssty) == (had_flac, prev_ssty) {
99 continue;
100 }
101 let mut f = base.clone();
102 if flac {
103 f.push(Feature { tag: *b"flac", value: 1 });
104 }
105 if ssty > 0 {
106 f.push(Feature { tag: *b"ssty", value: ssty });
107 }
108 if let Some(mut g) = res!(Self::base(engine, styles, &f, text, class, props.size)) {
109 g.span = props.span;
110 let a = res!(decide(&g, stretch));
111 if !matches!(a, Action::Fallback) {
112 glyph = g;
113 action = a;
114 break;
115 }
116 }
117 }
118 }
119 match action {
120 Action::Stretch { vertical, target, short_fall } => {
121 res!(glyph.stretch(engine, target, short_fall, vertical));
122 if vertical {
123 glyph.center_on_axis();
124 }
125 }
126 Action::WarnBothAxes => {
127 let d = crate::diag::Diagnostic::warning(DiagnosticKind::Lint, props.span, "glyph has both vertical and horizontal constructions")
128 .with_hint("this is probably a font bug");
129 engine.diags.push(d);
130 }
131 Action::Keep | Action::Fallback => (),
132 }
133 Ok(Some(glyph))
134 }
135
136 fn base(engine: &mut Engine, styles: &StyleChain, features: &[Feature], text: &str, class: MathClass, math_size: MathSize) -> Outcome<Option<Self>> {
137 let book = res!(engine.fonts.book());
138 let fonts = res!(chain(&book, &res!(props::families(styles)), res!(props::fallback(styles)), res!(props::face_variant(styles))));
139 let mut chosen: Option<(Arc<MathFont>, Vec<ShapedGlyph>)> = None;
140 for f in &fonts {
141 let glyphs = res!(f.shape(text, features));
142 let complete = !glyphs.is_empty() && glyphs.iter().all(|g| g.id != 0) && f.covers(text);
143 if complete {
144 chosen = Some((f.clone(), glyphs));
145 break;
146 }
147 if chosen.is_none() && !glyphs.is_empty() {
148 chosen = Some((f.clone(), glyphs));
149 }
150 }
151 let (font, glyphs) = match chosen {
152 Some(c) => c,
153 None => return Ok(None),
154 };
155 let mut g = Self {
156 font,
157 size: props::font_size(styles),
158 fill: res!(props::fill(styles)),
159 text: text.to_string(),
160 glyphs,
161 w: 0.0,
162 h: 0.0,
163 baseline: None,
164 italics: 0.0,
165 accent_attach: (0.0, 0.0),
166 math_size,
167 class,
168 extended: false,
169 shift: res!(props::baseline(styles)),
170 align: 0.0,
171 span: Span::detached(),
172 };
173 res!(g.update_glyph());
174 Ok(Some(g))
175 }
176
177 fn run_width(&self) -> f64 { self.glyphs.iter().map(|g| g.x_advance).sum::<f64>() * self.size }
178
179 fn first(&self) -> u16 { self.glyphs.first().map(|g| g.id).unwrap_or(0) }
180
181 // Typst's `update_glyph`: metrics from the first glyph, its italics correction added to its advance
182 // unless it is an extended shape.
183 fn update_glyph(&mut self) -> Outcome<()> {
184 let id = self.first();
185 let extended = self.font.is_extended_shape(id);
186 let italics_em = self.font.italics_correction(id).unwrap_or(0.0);
187 let width = self.run_width();
188 if !extended {
189 if let Some(g) = self.glyphs.first_mut() {
190 g.x_advance += italics_em;
191 }
192 }
193 let italics = italics_em * self.size;
194 let (asc, desc) = res!(self.font.ascent_descent(id)).unwrap_or((0.0, 0.0));
195 let top = self.font.top_accent_attachment(id).map(|a| a * self.size).unwrap_or((width + italics) / 2.0);
196 let bottom = (width - italics) / 2.0;
197 self.baseline = Some(asc * self.size);
198 self.w = self.run_width();
199 self.h = (asc + desc) * self.size;
200 self.italics = italics;
201 self.accent_attach = (top, bottom);
202 self.extended = extended;
203 Ok(())
204 }
205
206 pub fn ascent(&self) -> f64 { self.baseline.unwrap_or(self.h) }
207 pub fn descent(&self) -> f64 { self.h - self.ascent() }
208
209 pub fn into_frame(self) -> MFrame {
210 let mut f = MFrame::new(self.w, self.h);
211 let asc = self.ascent();
212 f.set_baseline(asc);
213 let y = asc + self.shift + self.align;
214 f.push(P2::new(0.0, y), FItem::Glyphs(GlyphRun {
215 font: self.font,
216 size: self.size,
217 fill: self.fill,
218 text: self.text,
219 glyphs: self.glyphs,
220 }));
221 f
222 }
223
224 fn stretch_advance(&self, vertical: bool) -> f64 {
225 if vertical {
226 self.h
227 } else if !self.extended {
228 self.w - self.italics
229 } else {
230 self.w
231 }
232 }
233
234 /// Grows the glyph toward `target` along an axis: the smallest pre-drawn variant that reaches it,
235 /// else an assembly from parts.
236 fn stretch(&mut self, engine: &mut Engine, target: f64, short_fall: f64, vertical: bool) -> Outcome<()> {
237 let advance = self.stretch_advance(vertical);
238 let short_target = target - short_fall;
239 if short_target <= advance {
240 return Ok(());
241 }
242 let id = self.first();
243 let font = self.font.clone();
244 let construction = match font.construction(id, vertical) {
245 Some(c) => c.clone(),
246 None => return Ok(()),
247 };
248 let mut best_id = id;
249 let mut best_adv = advance;
250 for &(gid, adv) in &construction.variants {
251 best_id = gid;
252 best_adv = font.em(adv as f64) * self.size;
253 if short_target <= best_adv {
254 break;
255 }
256 }
257 if short_target <= best_adv || construction.assembly.is_none() {
258 self.glyphs = vec![ShapedGlyph {
259 id: best_id,
260 x_advance: font.advance(best_id),
261 x_offset: 0.0,
262 y_advance: 0.0,
263 y_offset: 0.0,
264 }];
265 return self.update_glyph();
266 }
267 let assembly = match construction.assembly {
268 Some(a) => a,
269 None => return Ok(()),
270 };
271 let min_overlap = font.min_connector_overlap().unwrap_or(0.0) * self.size;
272 self.assemble(engine, &assembly, min_overlap, target, vertical)
273 }
274
275 fn assemble(
276 &mut self,
277 engine: &mut Engine,
278 assembly: &crate::mathtable::Assembly,
279 min_overlap: f64,
280 target: f64,
281 vertical: bool,
282 )
283 -> Outcome<()>
284 {
285 let font = self.font.clone();
286 let size = self.size;
287 let parts = |repeat: usize| -> Vec<crate::mathtable::Part> {
288 let mut v = Vec::new();
289 for p in &assembly.parts {
290 let n = if p.extender { repeat } else { 1 };
291 for _ in 0..n {
292 v.push(*p);
293 }
294 }
295 v
296 };
297 let mut full;
298 let mut ratio;
299 let mut repeat = 0;
300 let mut warned = false;
301 loop {
302 full = 0.0;
303 ratio = 0.0;
304 let ps = parts(repeat);
305 let mut growable = 0.0;
306 for (i, part) in ps.iter().enumerate() {
307 let mut advance = font.em(part.full_advance as f64) * size;
308 if let Some(next) = ps.get(i + 1) {
309 let max_overlap = font.em(part.end_connector.min(next.start_connector) as f64) * size;
310 if max_overlap < min_overlap && !warned {
311 warned = true;
312 let d = crate::diag::Diagnostic::warning(DiagnosticKind::Lint, self.span,
313 "glyph has assembly parts with overlap less than minConnectorOverlap")
314 .with_hint("its rendering may appear broken - this is probably a font bug");
315 engine.diags.push(d);
316 }
317 advance -= max_overlap;
318 growable += (max_overlap - min_overlap).max(0.0);
319 }
320 full += advance;
321 }
322 if full < target {
323 let delta = target - full;
324 ratio = if growable > 0.0 { (delta / growable).min(1.0) } else { 0.0 };
325 full += ratio * growable;
326 }
327 if target <= full || repeat >= MAX_REPEATS {
328 break;
329 }
330 repeat += 1;
331 }
332 let ps = parts(repeat);
333 let mut glyphs = Vec::with_capacity(ps.len());
334 for (i, part) in ps.iter().enumerate() {
335 let mut advance = font.em(part.full_advance as f64) * size;
336 if let Some(next) = ps.get(i + 1) {
337 let max_overlap = font.em(part.end_connector.min(next.start_connector) as f64) * size;
338 advance -= max_overlap;
339 advance += ratio * (max_overlap - min_overlap);
340 }
341 let g = if vertical {
342 let desc = res!(font.ascent_descent(part.glyph)).map(|x| x.1).unwrap_or(0.0);
343 ShapedGlyph { id: part.glyph, x_advance: 0.0, x_offset: 0.0, y_advance: advance / size, y_offset: desc }
344 } else {
345 ShapedGlyph { id: part.glyph, x_advance: advance / size, x_offset: 0.0, y_advance: 0.0, y_offset: 0.0 }
346 };
347 glyphs.push(g);
348 }
349 if vertical {
350 self.baseline = None;
351 self.h = full;
352 let mut w = 0.0f64;
353 for g in &glyphs {
354 w = w.max(font.advance(g.id));
355 }
356 self.w = w * size;
357 } else {
358 self.w = full;
359 // The parts' extremes, not clamped to the baseline: a rule above it has a negative depth.
360 let mut ext: Option<(f64, f64)> = None;
361 for g in &glyphs {
362 if let Some((a, d)) = res!(font.ascent_descent(g.id)) {
363 ext = Some(match ext {
364 None => (a, d),
365 Some((ma, md)) => (ma.max(a), md.max(d)),
366 });
367 }
368 }
369 let (asc, desc) = ext.unwrap_or((0.0, 0.0));
370 self.baseline = Some(asc * size);
371 self.h = (asc + desc) * size;
372 }
373 self.glyphs = glyphs;
374 self.italics = font.em(assembly.italics_correction as f64) * size;
375 if !vertical {
376 self.accent_attach = (full / 2.0, full / 2.0);
377 }
378 self.extended = true;
379 Ok(())
380 }
381
382 /// Centres the glyph vertically on the maths axis.
383 pub fn center_on_axis(&mut self) {
384 let axis = self.font.consts.axis_height * self.size;
385 self.align += self.ascent();
386 self.baseline = Some((self.h + 2.0 * axis) / 2.0);
387 self.align -= self.ascent();
388 }
389
390 pub fn kern_at_height(&self, corner: Corner, height: f64) -> f64 {
391 let vertical = self.glyphs.iter().all(|g| g.y_advance != 0.0);
392 let last = self.glyphs.len().saturating_sub(1);
393 let i = match (vertical, corner) {
394 (true, Corner::TopLeft | Corner::TopRight) => last,
395 (false, Corner::TopRight | Corner::BottomRight) => last,
396 _ => 0,
397 };
398 let id = self.glyphs.get(i).map(|g| g.id).unwrap_or(0);
399 self.font.kern_at_height(id, corner, height / self.size).unwrap_or(0.0) * self.size
400 }
401}
402
403#[derive(Clone, Copy)]
404enum Action {
405 Keep,
406 Stretch { vertical: bool, target: f64, short_fall: f64 },
407 WarnBothAxes,
408 Fallback,
409}
410
411enum AxisStatus {
412 Sufficient,
413 Stretchable(f64, f64),
414 Fallback,
415}
416
417fn decide(glyph: &GlyphFrag, stretch: &Stretch) -> Outcome<Action> {
418 let id = glyph.first();
419 let font = &glyph.font;
420 let assess = |vertical: bool| -> Outcome<AxisStatus> {
421 let (target, short_fall) = match resolve_stretch(glyph, stretch, vertical) {
422 Some(t) => t,
423 None => return Ok(AxisStatus::Sufficient),
424 };
425 if font.construction(id, vertical).is_some() {
426 return Ok(AxisStatus::Stretchable(target, short_fall));
427 }
428 let mut advance = glyph.stretch_advance(vertical);
429 // A combining mark has no advance; its ink box says how wide it is.
430 if let Some(b) = res!(font.bbox(id)) {
431 let ext = if vertical { b.y1 - b.y0 } else { b.x1 - b.x0 };
432 advance = advance.max(ext * glyph.size);
433 }
434 Ok(if target - short_fall <= advance { AxisStatus::Sufficient } else { AxisStatus::Fallback })
435 };
436 Ok(match (res!(assess(false)), res!(assess(true))) {
437 (AxisStatus::Stretchable(..), AxisStatus::Stretchable(..)) => Action::WarnBothAxes,
438 (AxisStatus::Stretchable(t, s), _) => Action::Stretch { vertical: false, target: t, short_fall: s },
439 (_, AxisStatus::Stretchable(t, s)) => Action::Stretch { vertical: true, target: t, short_fall: s },
440 (AxisStatus::Sufficient, AxisStatus::Sufficient) => Action::Keep,
441 _ => Action::Fallback,
442 })
443}
444
445fn resolve_stretch(glyph: &GlyphFrag, stretch: &Stretch, vertical: bool) -> Option<(f64, f64)> {
446 let info = stretch.resolve(vertical)?;
447 let rel = info.relative_to.unwrap_or_else(|| {
448 if vertical && glyph.class == MathClass::Large && glyph.math_size == MathSize::Display {
449 glyph.font.consts.display_operator_min_height * glyph.size
450 } else if vertical {
451 glyph.h
452 } else {
453 glyph.w
454 }
455 });
456 let target = info.target.relative_to(rel);
457 let short_fall = info.short_fall * info.font_size.unwrap_or(glyph.size);
458 Some((target, short_fall))
459}
460
461/// A laid-out part with the metadata maths placement reads.
462#[derive(Clone)]
463pub struct FrameFrag {
464 pub frame: MFrame,
465 pub font_size: f64,
466 pub class: MathClass,
467 pub math_size: MathSize,
468 pub base_ascent: f64,
469 pub base_descent: f64,
470 pub italics: f64,
471 pub accent_attach: (f64, f64),
472 pub text_like: bool,
473}
474
475impl FrameFrag {
476 pub fn new(props: &Props, styles: &StyleChain, frame: MFrame) -> Self {
477 let half = frame.w / 2.0;
478 Self {
479 font_size: props::font_size(styles),
480 class: props.class(),
481 math_size: props.size,
482 base_ascent: frame.ascent(),
483 base_descent: frame.descent(),
484 italics: 0.0,
485 accent_attach: (half, half),
486 text_like: false,
487 frame,
488 }
489 }
490}
491
492#[derive(Clone)]
493pub enum Frag {
494 Glyph(GlyphFrag),
495 Frame(FrameFrag),
496 Space(f64),
497 Tag(Tag),
498}
499
500impl Frag {
501 pub fn width(&self) -> f64 {
502 match self {
503 Frag::Glyph(g) => g.w,
504 Frag::Frame(f) => f.frame.w,
505 Frag::Space(w) => *w,
506 Frag::Tag(_) => 0.0,
507 }
508 }
509
510 pub fn height(&self) -> f64 {
511 match self {
512 Frag::Glyph(g) => g.h,
513 Frag::Frame(f) => f.frame.h,
514 _ => 0.0,
515 }
516 }
517
518 pub fn ascent(&self) -> f64 {
519 match self {
520 Frag::Glyph(g) => g.ascent(),
521 Frag::Frame(f) => f.frame.ascent(),
522 _ => 0.0,
523 }
524 }
525
526 pub fn descent(&self) -> f64 {
527 match self {
528 Frag::Glyph(g) => g.descent(),
529 Frag::Frame(f) => f.frame.descent(),
530 _ => 0.0,
531 }
532 }
533
534 pub fn base_ascent(&self) -> f64 {
535 match self {
536 Frag::Frame(f) => f.base_ascent,
537 _ => self.ascent(),
538 }
539 }
540
541 pub fn base_descent(&self) -> f64 {
542 match self {
543 Frag::Frame(f) => f.base_descent,
544 _ => self.descent(),
545 }
546 }
547
548 pub fn class(&self) -> MathClass {
549 match self {
550 Frag::Glyph(g) => g.class,
551 Frag::Frame(f) => f.class,
552 Frag::Space(_) => MathClass::Space,
553 Frag::Tag(_) => MathClass::Special,
554 }
555 }
556
557 pub fn math_size(&self) -> Option<MathSize> {
558 match self {
559 Frag::Glyph(g) => Some(g.math_size),
560 Frag::Frame(f) => Some(f.math_size),
561 _ => None,
562 }
563 }
564
565 /// The font a fragment was set in and its size: a glyph's own, else the context's.
566 pub fn font(&self, current: &Arc<MathFont>, styles: &StyleChain) -> (Arc<MathFont>, f64) {
567 match self {
568 Frag::Glyph(g) => (g.font.clone(), g.size),
569 Frag::Frame(f) => (current.clone(), f.font_size),
570 _ => (current.clone(), props::font_size(styles)),
571 }
572 }
573
574 pub fn is_text_like(&self) -> bool {
575 match self {
576 Frag::Glyph(g) => !g.extended,
577 Frag::Frame(f) => f.text_like,
578 _ => false,
579 }
580 }
581
582 pub fn italics_correction(&self) -> f64 {
583 match self {
584 Frag::Glyph(g) => g.italics,
585 Frag::Frame(f) => f.italics,
586 _ => 0.0,
587 }
588 }
589
590 pub fn accent_attach(&self) -> (f64, f64) {
591 match self {
592 Frag::Glyph(g) => g.accent_attach,
593 Frag::Frame(f) => f.accent_attach,
594 _ => (self.width() / 2.0, self.width() / 2.0),
595 }
596 }
597
598 pub fn fill(&self) -> Option<Paint> {
599 match self {
600 Frag::Glyph(g) => Some(g.fill.clone()),
601 _ => None,
602 }
603 }
604
605 pub fn kern_at_height(&self, corner: Corner, height: f64) -> f64 {
606 match self {
607 Frag::Glyph(g) => g.kern_at_height(corner, height),
608 _ => 0.0,
609 }
610 }
611
612 pub fn into_frame(self) -> MFrame {
613 match self {
614 Frag::Glyph(g) => g.into_frame(),
615 Frag::Frame(f) => f.frame,
616 Frag::Tag(t) => {
617 let mut f = MFrame::new(0.0, 0.0);
618 f.push(P2::new(0.0, 0.0), FItem::Tag(t));
619 f
620 }
621 Frag::Space(w) => MFrame::new(w, 0.0),
622 }
623 }
624}