Oregami
Repositories/oxedyne/fe2o3

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

41.7 KiB, 1 run

created by r1870400018:63550, 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/` (mod, run, text, scripts, fraction, radical, fenced, accent, line, cancel, table), version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4//! Maths IR into fragments and frames: a port of Typst 0.15's `typst-layout/src/math` (mod, run, text,
5//! scripts, fraction, radical, fenced, accent, line, cancel, table). Lengths are points, y down.
6
7use crate::diag::DiagnosticKind;
8use crate::eval::content::Content;
9use crate::eval::func::Func;
10use crate::eval::styles::StyleChain;
11use crate::eval::value::{
12 Angle,
13 HAlign,
14 LineCap,
15 Value,
16};
17use crate::eval::Engine;
18use crate::flow::visual::P2;
19use crate::flow::Region;
20use crate::math::class::MathClass;
21use crate::math::font::{
22 resolve as resolve_font,
23 Corner,
24 MathFont,
25};
26use crate::math::fragment::{
27 Frag,
28 FrameFrag,
29 GlyphFrag,
30};
31use crate::math::frame::{
32 line_pen,
33 pen,
34 FItem,
35 GlyphRun,
36 MFrame,
37 Pen,
38};
39use crate::math::item::{
40 Alternator,
41 Cancel,
42 FencedBody,
43 Fixed,
44 Item,
45 Kind,
46 Position,
47 Props,
48 Row,
49 Scripts,
50 Table,
51};
52use crate::math::props;
53use crate::math::style::MathSize;
54use crate::syntax::Span;
55
56use oxedyne_fe2o3_core::prelude::*;
57use oxedyne_fe2o3_font::shape::Feature;
58
59use std::sync::Arc;
60
61const TIGHT_LEADING: f64 = 0.25; // ems, between rows in script sizes
62const DEFAULT_STROKE_THICKNESS: f64 = 0.05; // ems, matrix augmentation lines
63
64pub type Run = Vec<Frag>;
65
66/// The state of one equation's layout.
67pub struct Ctx<'e> {
68 pub engine: &'e mut Engine,
69 pub region: (f64, f64),
70 fonts: Vec<Arc<MathFont>>,
71 frags: Vec<Frag>,
72}
73
74impl<'e> Ctx<'e> {
75 pub fn new(engine: &'e mut Engine, region: (f64, f64), font: Arc<MathFont>) -> Self {
76 Self { engine, region, fonts: vec![font], frags: Vec::new() }
77 }
78
79 pub fn font(&self) -> Arc<MathFont> {
80 match self.fonts.last() {
81 Some(f) => f.clone(),
82 None => Arc::clone(&self.fonts[0]),
83 }
84 }
85
86 fn push(&mut self, f: Frag) { self.frags.push(f); }
87
88 pub fn layout_into_fragments(&mut self, item: &Item, styles: &StyleChain) -> Outcome<Run> {
89 let start = self.frags.len();
90 res!(self.layout_into_self(item, styles));
91 Ok(self.frags.drain(start..).collect())
92 }
93
94 pub fn layout_into_fragment(&mut self, item: &Item, styles: &StyleChain) -> Outcome<Frag> {
95 let mut frags = res!(self.layout_into_fragments(item, styles));
96 if frags.len() == 1 {
97 if let Some(f) = frags.pop() {
98 return Ok(f);
99 }
100 }
101 let text_like = frags.iter().filter(|f| f.math_size().is_some()).all(|f| f.is_text_like());
102 let st = item.styles().cloned().unwrap_or_else(|| styles.clone());
103 let props = Props::new(&st, None, Span::detached());
104 let frame = into_frame(frags);
105 let mut ff = FrameFrag::new(&props, &st, frame);
106 ff.text_like = text_like;
107 Ok(Frag::Frame(ff))
108 }
109
110 fn layout_into_self(&mut self, item: &Item, styles: &StyleChain) -> Outcome<()> {
111 let outer = item.styles().cloned().unwrap_or_else(|| styles.clone());
112 let outer_families = res!(props::families(&outer));
113 for it in item.as_slice() {
114 let st = it.styles().cloned().unwrap_or_else(|| outer.clone());
115 if !st.ptr_eq(&outer) && res!(props::families(&st)) != outer_families {
116 let book = res!(self.engine.fonts.book());
117 let f = res!(resolve_font(&book, &res!(props::families(&st)), res!(props::fallback(&st)), res!(props::face_variant(&st))));
118 let scaled = props::chain_with(&st, vec![props::set_script_scale(
119 f.consts.script_percent_scale_down, f.consts.script_script_percent_scale_down)]);
120 self.fonts.push(f);
121 let r = self.layout_realised(it, &scaled);
122 self.fonts.pop();
123 res!(r);
124 } else {
125 res!(self.layout_realised(it, &st));
126 }
127 }
128 Ok(())
129 }
130
131 fn layout_realised(&mut self, item: &Item, styles: &StyleChain) -> Outcome<()> {
132 let comp = match item {
133 Item::Comp(c) => c,
134 Item::Spacing(w, _) => { self.push(Frag::Space(*w)); return Ok(()); }
135 Item::Space => {
136 let w = self.font().consts.space_width * props::font_size(styles);
137 self.push(Frag::Space(w));
138 return Ok(());
139 }
140 Item::Tag(t) => { self.push(Frag::Tag(t.clone())); return Ok(()); }
141 };
142 let p = &comp.props;
143 if let Some(l) = p.lspace {
144 if !p.align_form_infix && l != 0.0 {
145 self.push(Frag::Space(l * props::font_size(styles)));
146 }
147 }
148 match &comp.kind {
149 Kind::External(c) => res!(self.external(c, styles, p)),
150 Kind::Glyph(g) => res!(self.glyph(g, styles, p)),
151 Kind::Cancel(c) => res!(self.cancel(c, styles, p)),
152 Kind::Radical { radicand, index, sqrt } => res!(self.radical(radicand, index.as_ref(), sqrt, styles, p)),
153 Kind::Line { base, position } => res!(self.line(base, *position, styles, p)),
154 Kind::Accent { base, accent, position, exact, .. } => res!(self.accent(base, accent, *position, *exact, styles, p)),
155 Kind::Scripts(s) => res!(self.scripts(s, styles, p)),
156 Kind::Primes(n) => res!(self.primes(*n, styles, p)),
157 Kind::Table(t) => res!(self.table(t, styles, p)),
158 Kind::Fraction { num, denom, line, padding } => res!(self.fraction(num, denom, *line, *padding, styles, p)),
159 Kind::Skewed { num, denom, slash } => res!(self.skewed(num, denom, slash, styles, p)),
160 Kind::Text(t) => res!(self.text(t, styles, p)),
161 Kind::Number(t) => res!(self.number(t, styles, p)),
162 Kind::Fenced { open, close, body, balanced } => res!(self.fenced(open.as_ref(), close.as_ref(), body, *balanced, styles)),
163 Kind::Multiline { rows, centered } => {
164 let mut frame = res!(self.multiline(rows, styles)).build(false);
165 if *centered {
166 let axis = self.font().consts.axis_height * props::font_size(styles);
167 frame.set_baseline(frame.h / 2.0 + axis);
168 }
169 self.push(Frag::Frame(FrameFrag::new(p, styles, frame)));
170 }
171 Kind::Group(_) => {
172 let f = res!(self.layout_into_fragment(item, styles));
173 let italics = f.italics_correction();
174 let attach = f.accent_attach();
175 let mut ff = FrameFrag::new(p, styles, f.into_frame());
176 ff.italics = italics;
177 ff.accent_attach = attach;
178 self.push(Frag::Frame(ff));
179 }
180 }
181 if let Some(r) = p.rspace {
182 if r != 0.0 {
183 self.push(Frag::Space(r * props::font_size(styles)));
184 }
185 }
186 Ok(())
187 }
188
189 // Leaves
190
191 fn external(&mut self, content: &Content, styles: &StyleChain, p: &Props) -> Outcome<()> {
192 let w = self.region.0;
193 let h = self.region.1;
194 let region = Region {
195 width: sp(w),
196 height: sp(h),
197 base: (sp(w), sp(h)),
198 expand_x: false,
199 expand_y: false,
200 };
201 let nodes = res!(crate::flow::layout_block(self.engine, content, styles, region));
202 let dims = crate::flow::visual::vlist_dims(&nodes);
203 let fw = dims.width.to_pt();
204 let fh = dims.vextent().to_pt();
205 let mut frame = MFrame::new(fw, fh);
206 match crate::flow::visual::first_baseline(&nodes) {
207 Some(b) => frame.set_baseline(b.to_pt()),
208 None => {
209 let axis = self.font().consts.axis_height * props::font_size(styles);
210 frame.set_baseline(fh / 2.0 + axis);
211 }
212 }
213 frame.push(P2::new(0.0, 0.0), FItem::Node { nodes, w: fw, h: fh });
214 self.push(Frag::Frame(FrameFrag::new(p, styles, frame)));
215 Ok(())
216 }
217
218 fn glyph(&mut self, g: &crate::math::item::Glyph, styles: &StyleChain, p: &Props) -> Outcome<()> {
219 let mut features = res!(props::features(styles));
220 if props::dtls(styles) {
221 features.push(Feature { tag: *b"dtls", value: 1 });
222 }
223 if g.flac.get() {
224 features.push(Feature { tag: *b"flac", value: 1 });
225 }
226 // A dotless letter is shaped from its dotted form with the `dtls` feature where the font has it.
227 let font = self.font();
228 let mut text = g.text.clone();
229 if text.chars().any(|c| dotted(c).is_some()) && font.has_feature(b"dtls") {
230 features.push(Feature { tag: *b"dtls", value: 1 });
231 let (v, b, i) = (props::variant(styles), props::bold(styles), props::italic(styles));
232 let mut s = String::new();
233 for c in text.chars() {
234 let c = dotted(c).unwrap_or(c);
235 crate::math::style::push_styled(&mut s, c, crate::math::style::MathStyle::select(c, v, b, i));
236 }
237 text = s;
238 }
239 let glyph = res!(GlyphFrag::new(self.engine, &text, &g.stretch.get(), styles, features, p, g.class));
240 if let Some(mut glyph) = glyph {
241 if glyph.class == MathClass::Large {
242 glyph.center_on_axis();
243 }
244 glyph.class = p.class();
245 self.push(Frag::Glyph(glyph));
246 }
247 Ok(())
248 }
249
250 fn text(&mut self, text: &str, styles: &StyleChain, p: &Props) -> Outcome<()> {
251 // A run of text in maths sets as a line of its own, its box the ink's bounds.
252 let book = res!(self.engine.fonts.book());
253 let fonts = res!(crate::math::font::chain(&book, &res!(props::families(styles)), res!(props::fallback(styles)), res!(props::face_variant(styles))));
254 let mut feats: Vec<Feature> = res!(props::features(styles)).into_iter().filter(|f| &f.tag != b"ssty").collect();
255 if props::dtls(styles) {
256 feats.push(Feature { tag: *b"dtls", value: 1 });
257 }
258 let font = match fonts.iter().find(|f| f.covers(text)).or_else(|| fonts.first()) {
259 Some(f) => f.clone(),
260 None => return Ok(()),
261 };
262 let glyphs = res!(font.shape_text(text, &feats));
263 let size = props::font_size(styles);
264 let mut asc = 0.0f64;
265 let mut desc = 0.0f64;
266 let mut pen = 0.0f64;
267 let mut any = false;
268 for g in &glyphs {
269 if let Some(b) = res!(font.bbox(g.id)) {
270 let dy = g.y_offset;
271 asc = if any { asc.max(b.y1 + dy) } else { b.y1 + dy };
272 desc = if any { desc.max(-(b.y0 + dy)) } else { -(b.y0 + dy) };
273 any = true;
274 }
275 pen += g.x_advance;
276 }
277 let (asc, desc) = (asc * size, desc * size);
278 let mut frame = MFrame::new(pen * size, asc + desc);
279 frame.set_baseline(asc);
280 frame.push(P2::new(0.0, asc + res!(props::baseline(styles))), FItem::Glyphs(GlyphRun {
281 font,
282 size,
283 fill: res!(props::fill(styles)),
284 text: text.to_string(),
285 glyphs,
286 }));
287 let mut ff = FrameFrag::new(p, styles, frame);
288 ff.text_like = true;
289 self.push(Frag::Frame(ff));
290 Ok(())
291 }
292
293 fn number(&mut self, text: &str, styles: &StyleChain, p: &Props) -> Outcome<()> {
294 let mut frags = Vec::new();
295 for c in text.chars() {
296 if let Some(g) = res!(GlyphFrag::synthetic(self.engine, styles, c, p.span)) {
297 frags.push(Frag::Glyph(g));
298 }
299 }
300 let mut ff = FrameFrag::new(p, styles, into_frame(frags));
301 ff.text_like = true;
302 self.push(Frag::Frame(ff));
303 Ok(())
304 }
305
306 fn primes(&mut self, count: usize, styles: &StyleChain, p: &Props) -> Outcome<()> {
307 let prime = match res!(GlyphFrag::synthetic(self.engine, styles, '\u{2032}', p.span)) {
308 Some(g) => Frag::Glyph(g).into_frame(),
309 None => return Ok(()),
310 };
311 let w = prime.w * (count + 1) as f64 / 2.0;
312 let mut frame = MFrame::new(w, prime.h);
313 frame.set_baseline(prime.ascent());
314 for i in 0..count {
315 frame.push_frame(P2::new(prime.w * (i as f64 / 2.0), 0.0), prime.clone());
316 }
317 let mut ff = FrameFrag::new(p, styles, frame);
318 ff.text_like = true;
319 self.push(Frag::Frame(ff));
320 Ok(())
321 }
322
323 // Scripts
324
325 fn scripts(&mut self, s: &Scripts, styles: &StyleChain, p: &Props) -> Outcome<()> {
326 let t = match &s.t { Some(i) => Some(res!(self.layout_into_fragment(i, styles))), None => None };
327 let b = match &s.b { Some(i) => Some(res!(self.layout_into_fragment(i, styles))), None => None };
328 let rel = t.as_ref().map(|f| f.width()).unwrap_or(0.0).max(b.as_ref().map(|f| f.width()).unwrap_or(0.0));
329 s.base.set_stretch_relative_to(rel, false);
330 let base = res!(self.layout_into_fragment(&s.base, styles));
331 let tl = match &s.tl { Some(i) => Some(res!(self.layout_into_fragment(i, styles))), None => None };
332 let tr = match &s.tr { Some(i) => Some(res!(self.layout_into_fragment(i, styles))), None => None };
333 let bl = match &s.bl { Some(i) => Some(res!(self.layout_into_fragment(i, styles))), None => None };
334 let br = match &s.br { Some(i) => Some(res!(self.layout_into_fragment(i, styles))), None => None };
335 let bstyles = s.base.styles().cloned().unwrap_or_else(|| styles.clone());
336 self.attachments(p, &bstyles, base, [tl, t, tr, bl, b, br])
337 }
338
339 fn attachments(&mut self, p: &Props, styles: &StyleChain, base: Frag, parts: [Option<Frag>; 6]) -> Outcome<()> {
340 let [tl, t, tr, bl, b, br] = parts;
341 let (font, size) = base.font(&self.font(), styles);
342 let c = font.consts;
343 let cramped = props::cramped(styles);
344 let asc = |f: &Option<Frag>| f.as_ref().map(|f| f.ascent()).unwrap_or(0.0);
345 let desc = |f: &Option<Frag>| f.as_ref().map(|f| f.descent()).unwrap_or(0.0);
346 let wid = |f: &Option<Frag>| f.as_ref().map(|f| f.width()).unwrap_or(0.0);
347
348 // Shifts of the side scripts' baselines from the base's.
349 let (tx_shift, bx_shift) = if tl.is_none() && tr.is_none() && bl.is_none() && br.is_none() {
350 (0.0, 0.0)
351 } else {
352 let sup_shift_up = (if cramped { c.superscript_shift_up_cramped } else { c.superscript_shift_up }) * size;
353 let sup_bottom_min = c.superscript_bottom_min * size;
354 let sup_bottom_max_with_sub = c.superscript_bottom_max_with_subscript * size;
355 let sup_drop_max = c.superscript_baseline_drop_max * size;
356 let gap_min = c.sub_superscript_gap_min * size;
357 let sub_shift_down = c.subscript_shift_down * size;
358 let sub_top_max = c.subscript_top_max * size;
359 let sub_drop_min = c.subscript_baseline_drop_min * size;
360 let text_like = base.is_text_like();
361 let mut up = 0.0f64;
362 let mut down = 0.0f64;
363 if tl.is_some() || tr.is_some() {
364 let a = base.base_ascent();
365 up = up.max(sup_shift_up)
366 .max(if text_like { 0.0 } else { a - sup_drop_max })
367 .max(sup_bottom_min + desc(&tl))
368 .max(sup_bottom_min + desc(&tr));
369 }
370 if bl.is_some() || br.is_some() {
371 let d = base.base_descent();
372 down = down.max(sub_shift_down)
373 .max(if text_like { 0.0 } else { d + sub_drop_min })
374 .max(asc(&bl) - sub_top_max)
375 .max(asc(&br) - sub_top_max);
376 }
377 for (sup, sub) in [(&tl, &bl), (&tr, &br)] {
378 if let (Some(sup), Some(sub)) = (sup, sub) {
379 let sup_bottom = up - sup.descent();
380 let sub_top = sub.ascent() - down;
381 let gap = sup_bottom - sub_top;
382 if gap >= gap_min {
383 continue;
384 }
385 let increase = gap_min - gap;
386 let sup_only = (sup_bottom_max_with_sub - sup_bottom).clamp(0.0, increase);
387 let rest = (increase - sup_only) / 2.0;
388 up += sup_only + rest;
389 down += rest;
390 }
391 }
392 (up, down)
393 };
394 // Limits' baselines.
395 let t_shift = match &t {
396 Some(t) => base.ascent() + (c.upper_limit_baseline_rise_min * size).max(c.upper_limit_gap_min * size + t.descent()),
397 None => 0.0,
398 };
399 let b_shift = match &b {
400 Some(b) => base.descent() + (c.lower_limit_baseline_drop_min * size).max(c.lower_limit_gap_min * size + b.ascent()),
401 None => 0.0,
402 };
403 let ascent = base.ascent().max(tx_shift + asc(&tr)).max(tx_shift + asc(&tl)).max(t_shift + asc(&t));
404 let descent = base.descent().max(bx_shift + desc(&br)).max(bx_shift + desc(&bl)).max(b_shift + desc(&b));
405 let height = ascent + descent;
406 let delta = base.italics_correction() / 2.0;
407 let (t_pre, t_post) = match &t {
408 Some(t) => { let h = (t.width() - base.width()) / 2.0; (h - delta, h + delta) }
409 None => (0.0, 0.0),
410 };
411 let (b_pre, b_post) = match &b {
412 Some(b) => { let h = (b.width() - base.width()) / 2.0; (h + delta, h - delta) }
413 None => (0.0, 0.0),
414 };
415 let space_after = c.space_after_script * size;
416 let tl_pre = match &tl {
417 Some(f) => space_after + f.width() + math_kern(&base, f, tx_shift, Corner::TopLeft),
418 None => 0.0,
419 };
420 let bl_pre = match &bl {
421 Some(f) => space_after + f.width() + math_kern(&base, f, bx_shift, Corner::BottomLeft),
422 None => 0.0,
423 };
424 let (tr_post, tr_kern) = match &tr {
425 Some(f) => { let k = math_kern(&base, f, tx_shift, Corner::TopRight); (space_after + f.width() + k, k) }
426 None => (0.0, 0.0),
427 };
428 let (br_post, br_kern) = match &br {
429 Some(f) => {
430 let k = math_kern(&base, f, bx_shift, Corner::BottomRight) - base.italics_correction();
431 (space_after + f.width() + k, k)
432 }
433 None => (0.0, 0.0),
434 };
435 let pre = t_pre.max(b_pre).max(tl_pre).max(bl_pre);
436 let base_w = base.width();
437 let post = t_post.max(b_post).max(tr_post).max(br_post);
438 let width = pre + base_w + post;
439 let base_y = ascent - base.ascent();
440 let mut frame = MFrame::new(width, height);
441 frame.set_baseline(ascent);
442 frame.push_frame(P2::new(pre, base_y), base.into_frame());
443 let place = |f: Option<Frag>, x: f64, y_of: &dyn Fn(&Frag) -> f64, frame: &mut MFrame| {
444 if let Some(f) = f {
445 let y = y_of(&f);
446 frame.push_frame(P2::new(x, y), f.into_frame());
447 }
448 };
449 let tx_y = |f: &Frag| ascent - tx_shift - f.ascent();
450 let bx_y = |f: &Frag| ascent + bx_shift - f.ascent();
451 let t_y = |f: &Frag| ascent - t_shift - f.ascent();
452 let b_y = |f: &Frag| ascent + b_shift - f.ascent();
453 let _ = wid;
454 place(tl, pre - tl_pre + space_after, &tx_y, &mut frame);
455 place(bl, pre - bl_pre + space_after, &bx_y, &mut frame);
456 place(tr, pre + base_w + tr_kern, &tx_y, &mut frame);
457 place(br, pre + base_w + br_kern, &bx_y, &mut frame);
458 place(t, pre - t_pre, &t_y, &mut frame);
459 place(b, pre - b_pre, &b_y, &mut frame);
460 self.push(Frag::Frame(FrameFrag::new(p, styles, frame)));
461 Ok(())
462 }
463
464 // Fractions
465
466 fn fraction(&mut self, num: &Item, denom: &Item, line: bool, padding: f64, styles: &StyleChain, p: &Props) -> Outcome<()> {
467 let num = res!(self.layout_into_fragment(num, styles)).into_frame();
468 let denom = res!(self.layout_into_fragment(denom, styles)).into_frame();
469 let c = self.font().consts;
470 let size = props::font_size(styles);
471 let display = p.size == MathSize::Display;
472 let pad = padding * size;
473 let frame = if line {
474 let axis = c.axis_height * size;
475 let thickness = c.fraction_rule_thickness * size;
476 let shift_up = (if display { c.fraction_numerator_display_style_shift_up } else { c.fraction_numerator_shift_up }) * size;
477 let shift_down = (if display { c.fraction_denominator_display_style_shift_down } else { c.fraction_denominator_shift_down }) * size;
478 let num_min = (if display { c.fraction_num_display_style_gap_min } else { c.fraction_numerator_gap_min }) * size;
479 let denom_min = (if display { c.fraction_denom_display_style_gap_min } else { c.fraction_denominator_gap_min }) * size;
480 let num_gap = (shift_up - (axis + thickness / 2.0) - num.descent()).max(num_min);
481 let denom_gap = (shift_down + (axis - thickness / 2.0) - denom.ascent()).max(denom_min);
482 let line_w = num.w.max(denom.w);
483 let width = line_w + 2.0 * pad;
484 let height = num.h + num_gap + thickness + denom_gap + denom.h;
485 let line_pos = P2::new((width - line_w) / 2.0, num.h + num_gap + thickness / 2.0);
486 let mut frame = MFrame::new(width, height);
487 frame.set_baseline(line_pos.y + axis);
488 let (nw, dw, dh) = (num.w, denom.w, denom.h);
489 frame.push_frame(P2::new((width - nw) / 2.0, 0.0), num);
490 frame.push_frame(P2::new((width - dw) / 2.0, height - dh), denom);
491 let fill = res!(props::fill(styles));
492 match res!(props::stroke(styles)) {
493 Some(s) => frame.push(P2::new(line_pos.x, line_pos.y - thickness / 2.0),
494 FItem::Rect { w: line_w, h: thickness, fill, pen: Some(pen(&s, size, res!(props::fill(styles)))) }),
495 None => frame.push(line_pos, FItem::Line { to: P2::new(line_w, 0.0), pen: line_pen(fill, thickness) }),
496 }
497 frame
498 } else {
499 let shift_up = (if display { c.stack_top_display_style_shift_up } else { c.stack_top_shift_up }) * size;
500 let shift_down = (if display { c.stack_bottom_display_style_shift_down } else { c.stack_bottom_shift_down }) * size;
501 let gap_min = (if display { c.stack_display_style_gap_min } else { c.stack_gap_min }) * size;
502 let gap = (shift_up - num.descent()) + (shift_down - denom.ascent());
503 let width = num.w.max(denom.w) + 2.0 * pad;
504 let height = num.h + gap.max(gap_min) + denom.h;
505 let baseline = num.ascent() + shift_up + (gap_min - gap).max(0.0) / 2.0;
506 let mut frame = MFrame::new(width, height);
507 frame.set_baseline(baseline);
508 let (nw, dw, dh) = (num.w, denom.w, denom.h);
509 frame.push_frame(P2::new((width - nw) / 2.0, 0.0), num);
510 frame.push_frame(P2::new((width - dw) / 2.0, height - dh), denom);
511 frame
512 };
513 self.push(Frag::Frame(FrameFrag::new(p, styles, frame)));
514 Ok(())
515 }
516
517 fn skewed(&mut self, num: &Item, denom: &Item, slash: &Item, styles: &StyleChain, p: &Props) -> Outcome<()> {
518 let c = self.font().consts;
519 let size = props::font_size(styles);
520 let vgap = c.skewed_fraction_vertical_gap * size;
521 let hgap = c.skewed_fraction_horizontal_gap * size;
522 let axis = c.axis_height * size;
523 let num = res!(self.layout_into_fragment(num, styles)).into_frame();
524 let denom = res!(self.layout_into_fragment(denom, styles)).into_frame();
525 let mut height = num.h + denom.h + vgap;
526 slash.set_stretch_relative_to(height, true);
527 let slash = res!(self.layout_into_fragment(slash, styles)).into_frame();
528 let voff = (slash.h - height).max(0.0) / 2.0;
529 height = height.max(slash.h);
530 let mut slash_pos = P2::new(num.w + hgap / 2.0 - slash.w / 2.0, height / 2.0 - slash.h / 2.0);
531 let mut num_pos = P2::new(0.0, voff);
532 let mut denom_pos = P2::new(num_pos.x + num.w + hgap, num_pos.y + num.h + vgap);
533 let width = (denom_pos.x + denom.w).max(slash_pos.x + slash.w) + (-slash_pos.x).max(0.0);
534 let hoff = (-slash_pos.x).max(0.0);
535 slash_pos.x += hoff;
536 num_pos.x += hoff;
537 denom_pos.x += hoff;
538 let mut frame = MFrame::new(width, height);
539 frame.set_baseline(height / 2.0 + axis);
540 frame.push_frame(num_pos, num);
541 frame.push_frame(denom_pos, denom);
542 frame.push_frame(slash_pos, slash);
543 self.push(Frag::Frame(FrameFrag::new(p, styles, frame)));
544 Ok(())
545 }
546
547 // Radicals
548
549 fn radical(&mut self, radicand: &Item, index: Option<&Item>, sqrt: &Item, styles: &StyleChain, p: &Props) -> Outcome<()> {
550 let radicand = res!(self.layout_into_fragment(radicand, styles)).into_frame();
551 let sq_styles = sqrt.styles().cloned().unwrap_or_else(|| styles.clone());
552 let target = {
553 let s = res!(self.layout_into_fragment(sqrt, styles));
554 let (font, size) = s.font(&self.font(), &sq_styles);
555 let thickness = font.consts.radical_rule_thickness * size;
556 let gap = (if props::size(&sq_styles) == MathSize::Display {
557 font.consts.radical_display_style_vertical_gap
558 } else {
559 font.consts.radical_vertical_gap
560 }) * size;
561 radicand.h + thickness + gap
562 };
563 sqrt.set_stretch_relative_to(target, true);
564 let s = res!(self.layout_into_fragment(sqrt, styles));
565 let (font, size) = s.font(&self.font(), &sq_styles);
566 let c = font.consts;
567 let thickness = c.radical_rule_thickness * size;
568 let extra = c.radical_extra_ascender * size;
569 let kern_before = c.radical_kern_before_degree * size;
570 let kern_after = c.radical_kern_after_degree * size;
571 let raise = c.radical_degree_bottom_raise_percent;
572 let gap0 = (if props::size(&sq_styles) == MathSize::Display { c.radical_display_style_vertical_gap } else { c.radical_vertical_gap }) * size;
573 let fill = match s.fill() {
574 Some(f) => f,
575 None => res!(props::fill(&sq_styles)),
576 };
577 let line_w = radicand.w;
578 let sqrt_f = s.into_frame();
579 let index = match index {
580 Some(i) => Some(res!(self.layout_into_fragment(i, styles)).into_frame()),
581 None => None,
582 };
583 let gap = gap0.max((sqrt_f.h - thickness - radicand.h + gap0) / 2.0);
584 let sqrt_ascent = radicand.ascent() + gap + thickness;
585 let descent = sqrt_f.h - sqrt_ascent;
586 let inner_ascent = sqrt_ascent + extra;
587 let mut offset = 0.0;
588 let mut shift_up = 0.0;
589 let mut ascent = inner_ascent;
590 if let Some(i) = &index {
591 offset = kern_before + i.w + kern_after;
592 shift_up = raise * (inner_ascent - descent) + i.descent();
593 ascent = ascent.max(shift_up + i.ascent());
594 }
595 let sqrt_x = offset.max(0.0);
596 let radicand_x = sqrt_x + sqrt_f.w;
597 let radicand_y = ascent - radicand.ascent();
598 let mut frame = MFrame::new(radicand_x + line_w, ascent + descent);
599 frame.set_baseline(ascent);
600 if let Some(i) = index {
601 let ix = -offset.min(0.0) + kern_before;
602 let iy = ascent - i.ascent() - shift_up;
603 frame.push_frame(P2::new(ix, iy), i);
604 }
605 frame.push_frame(P2::new(sqrt_x, radicand_y - gap - thickness), sqrt_f);
606 let line_pos = P2::new(radicand_x, radicand_y - gap - thickness / 2.0);
607 frame.push(line_pos, FItem::Line { to: P2::new(line_w, 0.0), pen: line_pen(fill, thickness) });
608 frame.push_frame(P2::new(radicand_x, radicand_y), radicand);
609 self.push(Frag::Frame(FrameFrag::new(p, styles, frame)));
610 Ok(())
611 }
612
613 // Accents and lines
614
615 fn accent(&mut self, base: &Item, accent: &Item, position: Position, exact: bool, styles: &StyleChain, p: &Props) -> Outcome<()> {
616 let top = position == Position::Above;
617 let bstyles = base.styles().cloned().unwrap_or_else(|| styles.clone());
618 let base = res!(self.layout_into_fragment(base, styles));
619 let (font, size) = base.font(&self.font(), &bstyles);
620 let base_attach = base.accent_attach();
621 if top && base.ascent() > font.consts.flattened_accent_base_height * size {
622 accent.set_flac();
623 }
624 accent.set_stretch_relative_to(base.width(), false);
625 accent.set_stretch_font_size(size, false);
626 let acc = res!(self.layout_into_fragment(accent, styles));
627 let acc_attach = acc.accent_attach().0;
628 let acc = acc.into_frame();
629 let battach = if top { base_attach.0 } else { base_attach.1 };
630 let (width, base_x, acc_x) = if !exact {
631 (base.width(), 0.0, battach - acc_attach)
632 } else {
633 let pre = acc_attach - battach;
634 let post = (acc.w - acc_attach) - (base.width() - battach);
635 let width = pre.max(0.0) + base.width() + post.max(0.0);
636 if pre < 0.0 { (width, 0.0, -pre) } else { (width, pre, 0.0) }
637 };
638 let (gap, acc_pos, base_pos) = if top {
639 let abh = font.consts.accent_base_height * size;
640 let gap = -acc.descent() - base.ascent().min(abh);
641 (gap, P2::new(acc_x, 0.0), P2::new(base_x, acc.h + gap))
642 } else {
643 let gap = -acc.ascent();
644 (gap, P2::new(acc_x, base.height() + gap), P2::new(base_x, 0.0))
645 };
646 let height = acc.h + gap + base.height();
647 let baseline = base_pos.y + base.ascent();
648 let text_like = !exact && base.is_text_like();
649 let italics = base.italics_correction();
650 let (ba, bd) = (base.base_ascent(), base.base_descent());
651 let mut frame = MFrame::new(width, height);
652 frame.set_baseline(baseline);
653 frame.push_frame(base_pos, base.into_frame());
654 frame.push_frame(acc_pos, acc);
655 let mut ff = FrameFrag::new(p, styles, frame);
656 ff.base_ascent = ba;
657 ff.base_descent = bd;
658 ff.italics = italics;
659 ff.text_like = text_like;
660 ff.accent_attach = base_attach;
661 self.push(Frag::Frame(ff));
662 Ok(())
663 }
664
665 fn line(&mut self, base: &Item, position: Position, styles: &StyleChain, p: &Props) -> Outcome<()> {
666 let bstyles = base.styles().cloned().unwrap_or_else(|| styles.clone());
667 let content = res!(self.layout_into_fragment(base, styles));
668 let (font, size) = content.font(&self.font(), &bstyles);
669 let c = font.consts;
670 let (extra, line_y, content_y, baseline, thickness, adjust) = match position {
671 Position::Below => {
672 let sep = c.underbar_extra_descender * size;
673 let t = c.underbar_rule_thickness * size;
674 let gap = c.underbar_vertical_gap * size;
675 (sep + t + gap, content.height() + gap + t / 2.0, 0.0, content.ascent(), t, -content.italics_correction())
676 }
677 Position::Above => {
678 let sep = c.overbar_extra_ascender * size;
679 let t = c.overbar_rule_thickness * size;
680 let gap = c.overbar_vertical_gap * size;
681 let extra = sep + t + gap;
682 (extra, sep + t / 2.0, extra, content.ascent() + extra, t, 0.0)
683 }
684 };
685 let width = content.width();
686 let height = content.height() + extra;
687 let line_w = width + adjust;
688 let text_like = content.is_text_like();
689 let italics = content.italics_correction();
690 let mut frame = MFrame::new(width, height);
691 frame.set_baseline(baseline);
692 frame.push_frame(P2::new(0.0, content_y), content.into_frame());
693 let fill = res!(props::fill(styles));
694 match res!(props::stroke(styles)) {
695 Some(s) => frame.push(P2::new(0.0, line_y - thickness / 2.0),
696 FItem::Rect { w: line_w, h: thickness, fill, pen: Some(pen(&s, size, res!(props::fill(styles)))) }),
697 None => frame.push(P2::new(0.0, line_y), FItem::Line { to: P2::new(line_w, 0.0), pen: line_pen(fill, thickness) }),
698 }
699 let mut ff = FrameFrag::new(p, styles, frame);
700 ff.italics = italics;
701 ff.text_like = text_like;
702 self.push(Frag::Frame(ff));
703 Ok(())
704 }
705
706 fn cancel(&mut self, c: &Cancel, styles: &StyleChain, p: &Props) -> Outcome<()> {
707 let body = res!(self.layout_into_fragment(&c.base, styles));
708 let text_like = body.is_text_like();
709 let italics = body.italics_correction();
710 let attach = body.accent_attach();
711 let mut frame = body.into_frame();
712 let (w, h) = (frame.w, frame.h);
713 let center = P2::new(w / 2.0, h / 2.0);
714 res!(self.cancel_line(&mut frame, c, c.invert_first_line, center, styles, p.span));
715 if c.cross {
716 res!(self.cancel_line(&mut frame, c, true, center, styles, p.span));
717 }
718 let mut ff = FrameFrag::new(p, styles, frame);
719 ff.italics = italics;
720 ff.text_like = text_like;
721 ff.accent_attach = attach;
722 self.push(Frag::Frame(ff));
723 Ok(())
724 }
725
726 fn cancel_line(&mut self, frame: &mut MFrame, c: &Cancel, invert: bool, center: P2, styles: &StyleChain, span: Span) -> Outcome<()> {
727 let (w, h) = (frame.w, frame.h);
728 let default = (w / h).atan();
729 let mut angle = match &c.angle {
730 Value::Angle(a) => a.0,
731 Value::Func(f) => {
732 let f: Func = f.clone();
733 let mut args = crate::eval::args::Args::new(span);
734 args.push(span, Value::Angle(Angle(default)));
735 let saved = std::mem::replace(&mut self.engine.context.styles, Some(styles.clone()));
736 let out = self.engine.call_func(&f, args);
737 self.engine.context.styles = saved;
738 match res!(out) {
739 Value::Angle(a) => a.0,
740 other => return Err(self.engine.error(DiagnosticKind::Type, span, fmt!(
741 "expected angle, found {}", other.ty().long_name()))),
742 }
743 }
744 _ => default,
745 };
746 if invert {
747 angle = -angle;
748 }
749 let length = c.length.relative_to(w.hypot(h));
750 // A vertical segment of `length` centred on the origin, rotated clockwise from the y axis.
751 let (s, co) = angle.sin_cos();
752 let rot = |x: f64, y: f64| P2::new(x * co - y * s, x * s + y * co);
753 let a = rot(0.0, length / 2.0);
754 let b = rot(0.0, -length / 2.0);
755 frame.push(P2::new(center.x + a.x, center.y + a.y), FItem::Line { to: P2::new(b.x - a.x, b.y - a.y), pen: c.stroke.clone() });
756 Ok(())
757 }
758
759 // Fences
760
761 fn fenced(&mut self, open: Option<&Item>, close: Option<&Item>, body: &FencedBody, balanced: bool, styles: &StyleChain) -> Outcome<()> {
762 let (relative_to, initial) = match body {
763 FencedBody::Shared { sizing, .. } => {
764 let r = match sizing.relative_to.get() {
765 Some(r) => r,
766 None => {
767 let mut m = 0.0f64;
768 for it in &sizing.items {
769 let frags = res!(self.layout_into_fragments(it, &sizing.styles));
770 let st = it.styles().cloned().unwrap_or_else(|| sizing.styles.clone());
771 m = m.max(self.relative_to(&frags, &st, balanced));
772 }
773 sizing.relative_to.set(Some(m));
774 m
775 }
776 };
777 (r, None)
778 }
779 FencedBody::Owned(item) => {
780 let frags = res!(self.layout_into_fragments(item, styles));
781 let st = item.styles().cloned().unwrap_or_else(|| styles.clone());
782 let r = self.relative_to(&frags, &st, balanced);
783 (r, Some(frags))
784 }
785 };
786 let mut mid = false;
787 for it in body.item().as_slice() {
788 if it.mid_stretched() == Some(true) {
789 mid = true;
790 it.set_stretch_relative_to(relative_to, true);
791 }
792 }
793 if let Some(o) = open {
794 o.set_stretch_relative_to(relative_to, true);
795 let f = res!(self.layout_into_fragment(o, styles));
796 self.push(f);
797 }
798 let frags = match initial {
799 Some(f) if !mid => f,
800 _ => res!(self.layout_into_fragments(body.item(), styles)),
801 };
802 self.frags.extend(frags);
803 if let Some(c) = close {
804 c.set_stretch_relative_to(relative_to, true);
805 let f = res!(self.layout_into_fragment(c, styles));
806 self.push(f);
807 }
808 Ok(())
809 }
810
811 fn relative_to(&self, frags: &[Frag], styles: &StyleChain, balanced: bool) -> f64 {
812 let cur = self.font();
813 let mut m = 0.0f64;
814 for f in frags {
815 let v = if balanced {
816 let (font, size) = f.font(&cur, styles);
817 let axis = font.consts.axis_height * size;
818 2.0 * (f.ascent() - axis).max(f.descent() + axis)
819 } else {
820 f.height()
821 };
822 m = m.max(v);
823 }
824 m
825 }
826
827 // Rows and tables
828
829 pub fn aligned_row(&mut self, row: &Row, styles: &StyleChain) -> Outcome<Vec<Run>> {
830 let mut cells = Vec::with_capacity(row.len());
831 for (c, item) in row.0.iter().enumerate() {
832 let mut frags = res!(self.layout_into_fragments(item, styles));
833 if c % 2 == 0 {
834 if let Some(next) = row.0.get(c + 1) {
835 if let Some(sp) = alignment_lspace(next) {
836 frags.push(Frag::Space(sp));
837 }
838 }
839 }
840 cells.push(frags);
841 }
842 Ok(cells)
843 }
844
845 pub fn multiline(&mut self, rows: &[Row], styles: &StyleChain) -> Outcome<Builder> {
846 let nrows = rows.len();
847 let ncols = rows.first().map(|r| r.len()).unwrap_or(0);
848 if nrows == 0 || ncols == 0 {
849 return Ok(Builder::default());
850 }
851 let mut widths = vec![0.0f64; ncols];
852 let mut laid = Vec::with_capacity(nrows);
853 for row in rows {
854 let cells = res!(self.aligned_row(row, styles));
855 for (c, cell) in cells.iter().enumerate() {
856 if let Some(w) = widths.get_mut(c) {
857 *w = w.max(cell.iter().map(|f| f.width()).sum());
858 }
859 }
860 laid.push(cells);
861 }
862 let leading = if props::size(styles) >= MathSize::Text {
863 res!(props::leading(styles))
864 } else {
865 TIGHT_LEADING * props::font_size(styles)
866 };
867 let align = match res!(props::align_x(styles)) {
868 Some(HAlign::Center) => Fixed::Center,
869 Some(HAlign::Right) | Some(HAlign::End) => Fixed::End,
870 _ => Fixed::Start,
871 };
872 let layouts = laid.into_iter().map(|cells| {
873 let h = measure_row(&cells);
874 RowLayout { cells, frame_height: h, row_height: None }
875 }).collect();
876 Ok(stack_rows(layouts, &widths, Alternator::Right, align, leading, 0.0))
877 }
878
879 fn table(&mut self, t: &Table, styles: &StyleChain, p: &Props) -> Outcome<()> {
880 let nrows = t.cells.len();
881 let ncols = t.cells.first().map(|r| r.len()).unwrap_or(0);
882 if nrows == 0 || ncols == 0 {
883 self.push(Frag::Frame(FrameFrag::new(p, styles, MFrame::new(0.0, 0.0))));
884 return Ok(());
885 }
886 let gap_x = t.gap.0.relative_to(self.region.0);
887 let gap_y = t.gap.1.relative_to(self.region.1);
888 let size = props::font_size(styles);
889 let fill = res!(props::fill(styles));
890 let mut default_pen = line_pen(fill.clone(), DEFAULT_STROKE_THICKNESS * size);
891 default_pen.cap = LineCap::Square;
892 let (mut hline, mut vline, stroke) = match &t.augment {
893 Some(a) => {
894 let s = match &a.stroke {
895 Some(s) => {
896 let mut base = crate::eval::value::Stroke::default();
897 base.thickness = Some(crate::eval::value::Length::pt(DEFAULT_STROKE_THICKNESS * size));
898 base.cap = Some(LineCap::Square);
899 let merged = crate::eval::value::Stroke {
900 paint: s.paint.clone().or(base.paint),
901 thickness: s.thickness.or(base.thickness),
902 cap: s.cap.or(base.cap),
903 join: s.join.or(base.join),
904 dash: s.dash.clone().or(base.dash),
905 miter_limit: s.miter_limit.or(base.miter_limit),
906 };
907 pen(&merged, size, fill.clone())
908 }
909 None => default_pen.clone(),
910 };
911 (a.hline.clone(), a.vline.clone(), s)
912 }
913 None => (Vec::new(), Vec::new(), default_pen.clone()),
914 };
915 let den = props::chain_with(styles, props::for_denominator(styles));
916 let (pa, pd) = match res!(GlyphFrag::synthetic(self.engine, &den, '(', Span::detached())) {
917 Some(g) => (g.ascent(), g.descent()),
918 None => (0.0, 0.0),
919 };
920 let mut cols: Vec<Vec<(Vec<Run>, (f64, f64))>> = (0..ncols).map(|_| Vec::with_capacity(nrows)).collect();
921 let mut heights = vec![(0.0f64, 0.0f64); nrows];
922 for (r, row) in t.cells.iter().enumerate() {
923 for (c, cell) in row.iter().enumerate() {
924 let subs = res!(self.aligned_row(cell, styles));
925 let h = measure_row(&subs);
926 heights[r].0 = heights[r].0.max(h.0.max(pa));
927 heights[r].1 = heights[r].1.max(h.1.max(pd));
928 if let Some(col) = cols.get_mut(c) {
929 col.push((subs, h));
930 }
931 }
932 }
933 for l in hline.iter_mut() {
934 if *l < 0 {
935 *l += nrows as i64;
936 }
937 }
938 for l in vline.iter_mut() {
939 if *l < 0 {
940 *l += ncols as i64;
941 }
942 }
943 let mut total_h: f64 = heights.iter().map(|(a, b)| a + b).sum::<f64>() + gap_y * (nrows as f64 - 1.0);
944 if hline.contains(&0) {
945 total_h += gap_y;
946 }
947 if hline.contains(&(nrows as i64)) {
948 total_h += gap_y;
949 }
950 let mut frame = MFrame::new(0.0, total_h);
951 let mut x = 0.0;
952 let vert = |len: f64, pen: &Pen| FItem::Line { to: P2::new(0.0, len), pen: pen.clone() };
953 if vline.contains(&0) {
954 frame.push(P2::new(x + gap_x / 2.0, 0.0), vert(total_h, &stroke));
955 x += gap_x;
956 }
957 for (index, col) in cols.into_iter().enumerate() {
958 let widths = sub_column_widths(&col);
959 let layouts = col.into_iter().enumerate().map(|(r, (subs, h))| RowLayout {
960 cells: subs,
961 frame_height: h,
962 row_height: Some(heights[r]),
963 }).collect();
964 let start = if hline.contains(&0) { gap_y } else { 0.0 };
965 let b = stack_rows(layouts, &widths, t.alternator, t.align, gap_y, start);
966 for (cell, mut pos) in b.frames {
967 pos.x += x;
968 frame.push_frame(pos, cell);
969 }
970 x += b.w;
971 if vline.contains(&(index as i64 + 1)) {
972 frame.push(P2::new(x + gap_x / 2.0, 0.0), vert(total_h, &stroke));
973 }
974 x += gap_x;
975 }
976 let total_w = if !vline.contains(&(ncols as i64)) { x - gap_x } else { x };
977 for l in hline {
978 let off = if l == 0 {
979 gap_y
980 } else {
981 heights[0..(l as usize).min(nrows)].iter().map(|(a, b)| a + b).sum::<f64>() + gap_y * (l as f64 - 1.0) + gap_y / 2.0
982 };
983 frame.push(P2::new(0.0, off), FItem::Line { to: P2::new(total_w, 0.0), pen: stroke.clone() });
984 }
985 frame.w = total_w;
986 let axis = self.font().consts.axis_height * size;
987 let h = frame.h;
988 frame.set_baseline(h / 2.0 + axis);
989 self.push(Frag::Frame(FrameFrag::new(p, styles, frame)));
990 Ok(())
991 }
992}
993
994fn sp(pt: f64) -> crate::ir::Sp {
995 if !pt.is_finite() || pt >= (1u64 << 30) as f64 / 65536.0 { crate::ir::Sp(i32::MAX) } else { crate::ir::Sp::from_pt(pt) }
996}
997
998// Cut-in kerning of a script against its base (OpenType MATH, MathKernInfo), the larger of the two
999// correction heights' sums.
1000fn math_kern(base: &Frag, script: &Frag, shift: f64, corner: Corner) -> f64 {
1001 let (top, bot) = match corner {
1002 Corner::TopLeft | Corner::TopRight => (base.ascent() - shift, shift - script.descent()),
1003 Corner::BottomLeft | Corner::BottomRight => (script.ascent() - shift, shift - base.descent()),
1004 };
1005 let sum = |h: f64| base.kern_at_height(corner, h) + script.kern_at_height(corner.inv(), h);
1006 sum(top).max(sum(bot))
1007}
1008
1009fn alignment_lspace(cell: &Item) -> Option<f64> {
1010 cell.as_slice().iter().find(|i| !matches!(i, Item::Tag(_))).and_then(|i| match i {
1011 Item::Comp(c) if c.props.align_form_infix => c.props.lspace.map(|l| l * props::font_size(&c.styles)),
1012 _ => None,
1013 })
1014}
1015
1016fn sub_column_widths(col: &[(Vec<Run>, (f64, f64))]) -> Vec<f64> {
1017 let n = col.iter().map(|(s, _)| s.len()).max().unwrap_or(1);
1018 let mut w = vec![0.0f64; n];
1019 for (subs, _) in col {
1020 for (i, s) in subs.iter().enumerate() {
1021 if let Some(x) = w.get_mut(i) {
1022 *x = x.max(s.iter().map(|f| f.width()).sum());
1023 }
1024 }
1025 }
1026 w
1027}
1028
1029/// A row to stack: its cells and the ascent and descent its frame and its slot take.
1030pub struct RowLayout {
1031 pub cells: Vec<Run>,
1032 pub frame_height: (f64, f64),
1033 pub row_height: Option<(f64, f64)>,
1034}
1035
1036/// Rows stacked into one frame's worth of positioned line frames.
1037#[derive(Default)]
1038pub struct Builder {
1039 pub w: f64,
1040 pub h: f64,
1041 pub frames: Vec<(MFrame, P2)>,
1042}
1043
1044impl Builder {
1045 /// The frame, its baseline the first row's when `aligned`.
1046 pub fn build(self, aligned: bool) -> MFrame {
1047 let mut f = MFrame::new(self.w, self.h);
1048 let mut set = aligned;
1049 for (sub, pos) in self.frames {
1050 if set && sub.has_baseline() {
1051 f.set_baseline(sub.baseline());
1052 }
1053 f.push_frame(pos, sub);
1054 set = false;
1055 }
1056 f
1057 }
1058}
1059
1060pub fn measure_row(cells: &[Run]) -> (f64, f64) {
1061 let mut out: Option<(f64, f64)> = None;
1062 for f in cells.iter().flat_map(|c| c.iter()) {
1063 if matches!(f, Frag::Tag(_)) {
1064 continue;
1065 }
1066 let (a, d) = (f.ascent(), f.descent());
1067 out = Some(match out {
1068 None => (a, d),
1069 Some((ma, md)) => (ma.max(a), md.max(d)),
1070 });
1071 }
1072 out.unwrap_or((0.0, 0.0))
1073}
1074
1075pub fn stack_rows(rows: Vec<RowLayout>, widths: &[f64], alternator: Alternator, align: Fixed, leading: f64, start_y: f64) -> Builder {
1076 let (points, total) = cumulative(widths);
1077 let has_alignment = !points.is_empty();
1078 let mut frames = Vec::new();
1079 let mut w = 0.0f64;
1080 let mut h = start_y;
1081 for (i, row) in rows.into_iter().enumerate() {
1082 let rh = row.row_height.unwrap_or(row.frame_height);
1083 let sub = line_frame(row.cells, &points, alternator, Some(row.frame_height));
1084 if i > 0 {
1085 h += leading;
1086 }
1087 let mut pos = P2::new(0.0, h + rh.0 - sub.ascent());
1088 if !has_alignment {
1089 pos.x = align.position(total - sub.w);
1090 }
1091 w = w.max(sub.w);
1092 h += rh.0 + rh.1;
1093 frames.push((sub, pos));
1094 }
1095 Builder { w, h, frames }
1096}
1097
1098fn cumulative(widths: &[f64]) -> (Vec<f64>, f64) {
1099 if widths.len() <= 1 {
1100 return (Vec::new(), widths.first().copied().unwrap_or(0.0));
1101 }
1102 let mut points = Vec::with_capacity(widths.len());
1103 let mut acc = 0.0;
1104 for w in widths {
1105 acc += w;
1106 points.push(acc);
1107 }
1108 (points, acc)
1109}
1110
1111/// Cells placed at alignment points on one baseline.
1112pub fn line_frame(cells: Vec<Run>, points: &[f64], mut alternator: Alternator, height: Option<(f64, f64)>) -> MFrame {
1113 let (ascent, descent) = height.unwrap_or_else(|| measure_row(&cells));
1114 let mut frame = MFrame::new(0.0, ascent + descent);
1115 frame.set_baseline(ascent);
1116 let mut prev = 0.0;
1117 let mut pts = points.iter().copied();
1118 let mut x_end = 0.0;
1119 for cell in cells {
1120 let width: f64 = cell.iter().map(|f| f.width()).sum();
1121 let cell_x = match pts.next() {
1122 Some(pt) => {
1123 let x = match alternator.next() {
1124 Alternator::Right => pt - width,
1125 _ => prev,
1126 };
1127 prev = pt;
1128 x
1129 }
1130 None => prev,
1131 };
1132 let mut x = cell_x;
1133 for f in cell {
1134 let y = ascent - f.ascent();
1135 let w = f.width();
1136 frame.push_frame(P2::new(x, y), f.into_frame());
1137 x += w;
1138 }
1139 x_end = x;
1140 }
1141 frame.w = x_end;
1142 frame
1143}
1144
1145/// A run of fragments as one line frame.
1146pub fn into_frame(run: Run) -> MFrame {
1147 line_frame(vec![run], &[], Alternator::Right, None)
1148}
1149
1150// The dotted letter behind a dotless one, shaped with `dtls` where the font offers it.
1151fn dotted(c: char) -> Option<char> {
1152 match c {
1153 '\u{131}' | '\u{1d6a4}' => Some('i'),
1154 '\u{237}' | '\u{1d6a5}' => Some('j'),
1155 _ => None,
1156 }
1157}