oxedyne/fe2o3/fe2o3_austenite/src/flow/math.rs
14.0 KiB, 8 runs
created by r1870400018:63528, 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.rs`, version 0.15.1). |
| 3 | // Modified for Austenite: ported to Hematite's types, IR and error handling. |
| 4 | // U7 owns this file: an equation's realised maths into IR, a port of Typst 0.15's |
| 5 | // `typst-layout/src/math/mod.rs`. An inline equation becomes horizontal boxes a paragraph sets, split |
| 6 | // after relations and binary operators so a line may break there; a block equation becomes its box, with |
| 7 | // its number placed beside it when `numbering` is set. |
| 8 | // |
| 9 | // The styles arrive with the equation's built-in show-set styles (display size, the maths font at weight |
| 10 | // 450, centring; `lib::math::show_set`) beneath the document's own show-set rules, as realisation applies |
| 11 | // them, so `show math.equation: set text(font: ..)` selects the maths font. |
| 12 | |
| 13 | use crate::diag::DiagnosticKind; |
| 14 | use crate::eval::content::{ |
| 15 | Content, |
| 16 | ElemKind, |
| 17 | }; |
| 18 | use crate::eval::lib::model::lookup; |
| 19 | use crate::eval::lib::numbering; |
| 20 | use crate::eval::content::display; |
| 21 | use crate::eval::styles::{ |
| 22 | StyleChain, |
| 23 | }; |
| 24 | use crate::eval::value::{ |
| 25 | HAlign, |
| 26 | VAlign, |
| 27 | Value, |
| 28 | }; |
| 29 | use crate::eval::Engine; |
| 30 | use crate::flow::visual::P2; |
| 31 | use crate::flow::Region; |
| 32 | use crate::ir::{ |
| 33 | BoxNode, |
| 34 | Dims, |
| 35 | Glue, |
| 36 | Node, |
| 37 | Sp, |
| 38 | }; |
| 39 | use crate::math::font::{ |
| 40 | resolve as resolve_font, |
| 41 | MathFont, |
| 42 | }; |
| 43 | use crate::math::fragment::Frag; |
| 44 | use crate::math::frame::{ |
| 45 | to_node, |
| 46 | FItem, |
| 47 | MFrame, |
| 48 | }; |
| 49 | use crate::math::item::{ |
| 50 | Item, |
| 51 | Kind, |
| 52 | }; |
| 53 | use crate::math::layout::{ |
| 54 | into_frame, |
| 55 | Builder, |
| 56 | Ctx, |
| 57 | }; |
| 58 | use crate::math::props; |
| 59 | use crate::math::resolve::Resolver; |
| 60 | use crate::math::class::MathClass; |
| 61 | |
| 62 | use oxedyne_fe2o3_core::prelude::*; |
| 63 | |
| 64 | use std::sync::Arc; |
| 65 | |
| 66 | const NUMBER_GUTTER: f64 = 0.5; // ems between an equation and its number |
| 67 | |
| 68 | /// An equation as one node: a block equation's box (numbered when it is), or an inline equation's |
| 69 | /// pieces in one horizontal box. |
| 70 | pub fn layout_equation( |
| 71 | engine: &mut Engine, |
| 72 | elem: &Content, |
| 73 | styles: &StyleChain, |
| 74 | region: Region, |
| 75 | ) |
| 76 | -> Outcome<Node> |
| 77 | { |
| 78 | if res!(is_block(elem, styles)) { |
| 79 | let mut nodes = res!(layout_equation_block(engine, elem, styles, region)); |
| 80 | if nodes.len() == 1 { |
| 81 | if let Some(n) = nodes.pop() { |
| 82 | return Ok(n); |
| 83 | } |
| 84 | } |
| 85 | let dims = crate::flow::visual::vlist_dims(&nodes); |
| 86 | return Ok(Node::VBox(BoxNode::new(nodes, dims))); |
| 87 | } |
| 88 | let pieces = res!(layout_equation_inline(engine, elem, styles, region)); |
| 89 | let mut w = Sp::ZERO; |
| 90 | let mut h = Sp::ZERO; |
| 91 | let mut d = Sp::ZERO; |
| 92 | for p in &pieces { |
| 93 | match p { |
| 94 | Node::HBox(b) => { |
| 95 | w += b.dims.width; |
| 96 | h = h.max(b.dims.height); |
| 97 | d = d.max(b.dims.depth); |
| 98 | } |
| 99 | Node::Glue(g) => w += g.natural, |
| 100 | _ => (), |
| 101 | } |
| 102 | } |
| 103 | Ok(Node::HBox(BoxNode::new(pieces, Dims::new(w, h, d)))) |
| 104 | } |
| 105 | |
| 106 | /// Is the equation set as a block? |
| 107 | pub fn is_block(elem: &Content, styles: &StyleChain) -> Outcome<bool> { |
| 108 | Ok(matches!(res!(efield(elem, styles, "block")), Some(Value::Bool(true)))) |
| 109 | } |
| 110 | |
| 111 | // An equation field, its own value else the chain's. |
| 112 | fn efield(elem: &Content, styles: &StyleChain, name: &str) -> Outcome<Option<Value>> { |
| 113 | match ElemKind::Equation.field_id(name) { |
| 114 | Some(id) => styles.resolve(elem, id), |
| 115 | None => Ok(None), |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // The maths font the styles select, a warning when it carries no MATH table, and the chain with its |
| 120 | // script percentages. |
| 121 | fn prepare(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<(StyleChain, Arc<MathFont>)> { |
| 122 | let st = styles.clone(); |
| 123 | let book = res!(engine.fonts.book()); |
| 124 | let families = res!(props::families(&st)); |
| 125 | crate::flow::text::ask_for_face(engine, &book, families.iter().map(|f| f.as_str())); |
| 126 | let found = resolve_font(&book, &families, res!(props::fallback(&st)), res!(props::face_variant(&st))); |
| 127 | // No family of the list in the book, and no fallback to turn to, fails the equation. |
| 128 | let font = match found { |
| 129 | Ok(f) => f, |
| 130 | Err(_) => return Err(engine.error(DiagnosticKind::MissingFont, elem.span(), "no font could be found")), |
| 131 | }; |
| 132 | if !font.has_math { |
| 133 | let d = crate::diag::Diagnostic::warning(DiagnosticKind::Lint, elem.span(), "current font is not designed for math") |
| 134 | .with_hint("rendering may be poor"); |
| 135 | engine.diags.push(d); |
| 136 | } |
| 137 | let st = props::chain_with(&st, vec![props::set_script_scale( |
| 138 | font.consts.script_percent_scale_down, font.consts.script_script_percent_scale_down)]); |
| 139 | Ok((st, font)) |
| 140 | } |
| 141 | |
| 142 | fn body(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Content> { |
| 143 | match res!(efield(elem, styles, "body")) { |
| 144 | Some(v) => display(engine, v, elem.span()), |
| 145 | None => Ok(Content::empty()), |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | fn region_size(region: Region) -> (f64, f64) { |
| 150 | let f = |s: Sp| if s.0 >= (1 << 30) { f64::INFINITY } else { s.to_pt() }; |
| 151 | (f(region.base.0), f(region.base.1)) |
| 152 | } |
| 153 | |
| 154 | /// An inline equation as the pieces a paragraph sets: horizontal boxes, split after a relation or binary |
| 155 | /// operator, with fixed glue between them where Typst puts a space (a break opportunity). |
| 156 | pub fn layout_equation_inline( |
| 157 | engine: &mut Engine, |
| 158 | elem: &Content, |
| 159 | styles: &StyleChain, |
| 160 | region: Region, |
| 161 | ) |
| 162 | -> Outcome<Vec<Node>> |
| 163 | { |
| 164 | let (st, font) = res!(prepare(engine, elem, styles)); |
| 165 | let b = res!(body(engine, elem, &st)); |
| 166 | let item = { |
| 167 | let mut r = Resolver::new(engine); |
| 168 | res!(r.resolve_into_item(&b, &st)) |
| 169 | }; |
| 170 | let mut ctx = Ctx::new(engine, region_size(region), font.clone()); |
| 171 | let mut pieces: Vec<Piece> = if !item.is_multiline() { |
| 172 | par_items(res!(ctx.layout_into_fragments(&item, &st))) |
| 173 | } else { |
| 174 | vec![Piece::Frame(res!(ctx.layout_into_fragment(&item, &st)).into_frame())] |
| 175 | }; |
| 176 | if pieces.is_empty() { |
| 177 | pieces.push(Piece::Frame(MFrame::new(0.0, 0.0))); |
| 178 | } |
| 179 | let size = props::font_size(&st); |
| 180 | let slack = res!(props::leading(&st)) * 0.7; |
| 181 | let mut out = Vec::with_capacity(pieces.len()); |
| 182 | for p in pieces { |
| 183 | match p { |
| 184 | Piece::Space(w) => out.push(Node::Glue(Glue::fixed(Sp::from_pt(w)))), |
| 185 | Piece::Frame(mut frame) => { |
| 186 | let top = edge(res!(props::top_edge(&st)), &font, size, frame.ascent(), true); |
| 187 | let bottom = edge(res!(props::bottom_edge(&st)), &font, size, frame.descent(), false); |
| 188 | let ascent = top.max(frame.ascent() - slack); |
| 189 | let descent = bottom.max(frame.descent() - slack); |
| 190 | let b = frame.baseline(); |
| 191 | frame.translate(0.0, ascent - b); |
| 192 | frame.h = ascent + descent; |
| 193 | out.push(res!(to_node(engine, &frame, elem.span()))); |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | Ok(out) |
| 198 | } |
| 199 | |
| 200 | // A text edge in points: a font metric, a length, or the frame's own bounds. A bottom edge is a depth. |
| 201 | fn edge(e: props::Edge, font: &MathFont, size: f64, bounds: f64, top: bool) -> f64 { |
| 202 | let sign = if top { 1.0 } else { -1.0 }; |
| 203 | match e { |
| 204 | props::Edge::Ascender => sign * font.ascender() * size, |
| 205 | props::Edge::CapHeight => sign * font.cap_height() * size, |
| 206 | props::Edge::XHeight => sign * font.x_height() * size, |
| 207 | props::Edge::Baseline => 0.0, |
| 208 | props::Edge::Descender => sign * font.descender() * size, |
| 209 | props::Edge::Bounds => bounds, |
| 210 | props::Edge::Length(l) => sign * l, |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | enum Piece { |
| 215 | Frame(MFrame), |
| 216 | Space(f64), |
| 217 | } |
| 218 | |
| 219 | // Typst's `into_par_items`: a new piece after each relation or binary operator not followed by a |
| 220 | // closing delimiter (or a second relation), spaces after such a break kept visible. |
| 221 | fn par_items(frags: Vec<Frag>) -> Vec<Piece> { |
| 222 | let mut items = Vec::new(); |
| 223 | let mut x = 0.0f64; |
| 224 | let mut ascent = 0.0f64; |
| 225 | let mut descent = 0.0f64; |
| 226 | let mut frame = MFrame::new(0.0, 0.0); |
| 227 | let mut empty = true; |
| 228 | let mut space_visible = false; |
| 229 | let finish = |frame: &mut MFrame, x: f64, a: f64, d: f64| { |
| 230 | frame.w = x; |
| 231 | frame.h = a + d; |
| 232 | frame.set_baseline(0.0); |
| 233 | frame.translate(0.0, a); |
| 234 | }; |
| 235 | let mut iter = frags.into_iter().peekable(); |
| 236 | while let Some(f) = iter.next() { |
| 237 | if space_visible { |
| 238 | if let Frag::Space(w) = f { |
| 239 | items.push(Piece::Space(w)); |
| 240 | continue; |
| 241 | } |
| 242 | } |
| 243 | let class = f.class(); |
| 244 | let y = f.ascent(); |
| 245 | ascent = ascent.max(y); |
| 246 | descent = descent.max(f.descent()); |
| 247 | let w = f.width(); |
| 248 | frame.push_frame(P2::new(x, -y), f.into_frame()); |
| 249 | x += w; |
| 250 | empty = false; |
| 251 | let next = iter.peek().map(|n| n.class()); |
| 252 | let brk = match class { |
| 253 | MathClass::Binary => next != Some(MathClass::Closing), |
| 254 | MathClass::Relation => !matches!(next, Some(MathClass::Relation | MathClass::Closing)), |
| 255 | _ => false, |
| 256 | }; |
| 257 | if brk { |
| 258 | let mut prev = std::mem::take(&mut frame); |
| 259 | finish(&mut prev, x, ascent, descent); |
| 260 | items.push(Piece::Frame(prev)); |
| 261 | empty = true; |
| 262 | x = 0.0; |
| 263 | ascent = 0.0; |
| 264 | descent = 0.0; |
| 265 | space_visible = true; |
| 266 | if let Some(n) = iter.peek() { |
| 267 | if !matches!(n, Frag::Space(_)) { |
| 268 | items.push(Piece::Space(0.0)); |
| 269 | } |
| 270 | } |
| 271 | } else { |
| 272 | space_visible = false; |
| 273 | } |
| 274 | } |
| 275 | if !empty { |
| 276 | finish(&mut frame, x, ascent, descent); |
| 277 | items.push(Piece::Frame(frame)); |
| 278 | } |
| 279 | items |
| 280 | } |
| 281 | |
| 282 | /// A block equation as nodes: one box, or with `block.breakable` on and several rows, one box per row |
| 283 | /// with the leading between them as glue so the page may break there. |
| 284 | pub fn layout_equation_block( |
| 285 | engine: &mut Engine, |
| 286 | elem: &Content, |
| 287 | styles: &StyleChain, |
| 288 | region: Region, |
| 289 | ) |
| 290 | -> Outcome<Vec<Node>> |
| 291 | { |
| 292 | let (st, font) = res!(prepare(engine, elem, styles)); |
| 293 | let b = res!(body(engine, elem, &st)); |
| 294 | let item = { |
| 295 | let mut r = Resolver::new(engine); |
| 296 | res!(r.resolve_into_item(&b, &st)) |
| 297 | }; |
| 298 | let (rw, _) = region_size(region); |
| 299 | let mut ctx = Ctx::new(engine, region_size(region), font.clone()); |
| 300 | let builder = match &item { |
| 301 | Item::Comp(c) => match &c.kind { |
| 302 | Kind::Multiline { rows, .. } => res!(ctx.multiline(rows, &c.styles)), |
| 303 | _ => from_frame(into_frame(res!(ctx.layout_into_fragments(&item, &st)))), |
| 304 | }, |
| 305 | _ => from_frame(into_frame(res!(ctx.layout_into_fragments(&item, &st)))), |
| 306 | }; |
| 307 | let numbering = match res!(efield(elem, &st, "numbering")) { |
| 308 | None | Some(Value::None) => None, |
| 309 | Some(n) => Some(n), |
| 310 | }; |
| 311 | let span = elem.span(); |
| 312 | match numbering { |
| 313 | None if res!(props::breakable(&st)) && builder.frames.len() > 1 => { |
| 314 | // One box per row, the gaps between rows as glue the page may break at. |
| 315 | let mut out = Vec::new(); |
| 316 | let mut bottom = 0.0f64; |
| 317 | for (i, (row, pos)) in builder.frames.into_iter().enumerate() { |
| 318 | if i > 0 { |
| 319 | out.push(Node::Glue(Glue::fixed(Sp::from_pt(pos.y - bottom)))); |
| 320 | } |
| 321 | bottom = pos.y + row.h; |
| 322 | let mut f = MFrame::new(builder.w, row.h); |
| 323 | f.set_baseline(row.baseline()); |
| 324 | f.push_frame(P2::new(pos.x, 0.0), row); |
| 325 | out.push(res!(to_node(engine, &f, span))); |
| 326 | } |
| 327 | Ok(out) |
| 328 | } |
| 329 | None => { |
| 330 | let frame = builder.build(true); |
| 331 | Ok(vec![res!(to_node(engine, &frame, span))]) |
| 332 | } |
| 333 | Some(n) => { |
| 334 | let number = res!(number_frame(engine, elem, &st, &n, region)); |
| 335 | let size = props::font_size(&st); |
| 336 | let full = number.w + NUMBER_GUTTER * size; |
| 337 | let (nh, nv) = res!(number_align(elem, &st)); |
| 338 | let eq_align = match res!(props::align_x(&st)) { |
| 339 | Some(HAlign::Center) => 0.5, |
| 340 | Some(HAlign::Right) | Some(HAlign::End) => 1.0, |
| 341 | _ => 0.0, |
| 342 | }; |
| 343 | let frame = add_number(builder, number, (nh, nv), eq_align, rw, full); |
| 344 | Ok(vec![res!(to_node(engine, &frame, span))]) |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | fn from_frame(frame: MFrame) -> Builder { |
| 350 | Builder { w: frame.w, h: frame.h, frames: vec![(frame, P2::new(0.0, 0.0))] } |
| 351 | } |
| 352 | |
| 353 | // The number's horizontal side (0 start, 1 end) and vertical placement (0 top, 0.5 horizon, 1 bottom). |
| 354 | fn number_align(elem: &Content, styles: &StyleChain) -> Outcome<(f64, f64)> { |
| 355 | let (x, y) = match res!(efield(elem, styles, "number-align")) { |
| 356 | Some(Value::Alignment(a)) => (a.x, a.y), |
| 357 | _ => (None, None), |
| 358 | }; |
| 359 | let h = match x { |
| 360 | Some(HAlign::Start) | Some(HAlign::Left) => 0.0, |
| 361 | _ => 1.0, |
| 362 | }; |
| 363 | let v = match y { |
| 364 | Some(VAlign::Top) => 0.0, |
| 365 | Some(VAlign::Bottom) => 1.0, |
| 366 | _ => 0.5, |
| 367 | }; |
| 368 | Ok((h, v)) |
| 369 | } |
| 370 | |
| 371 | fn number_frame(engine: &mut Engine, elem: &Content, styles: &StyleChain, numbering_v: &Value, region: Region) -> Outcome<MFrame> { |
| 372 | // The number is the equation counter at the equation's own location, read through the model's lookup |
| 373 | // seam so a counter update and the previous pass's layout facts reach it. An equation with no |
| 374 | // location reads the counter's initial state, as the first pass does. |
| 375 | let content = match elem.location() { |
| 376 | Some(loc) => res!(lookup::display_counter( |
| 377 | engine, &lookup::elem_counter(ElemKind::Equation), loc, numbering_v, elem.span())), |
| 378 | None => { |
| 379 | let shown = res!(numbering::apply(engine, numbering_v, &[0])); |
| 380 | res!(display(engine, shown, elem.span())) |
| 381 | } |
| 382 | }; |
| 383 | let nodes = res!(crate::flow::layout_block(engine, &content, styles, Region { |
| 384 | expand_x: false, |
| 385 | expand_y: false, |
| 386 | ..region |
| 387 | })); |
| 388 | let dims = crate::flow::visual::vlist_dims(&nodes); |
| 389 | let (w, h) = (dims.width.to_pt(), dims.vextent().to_pt()); |
| 390 | let mut f = MFrame::new(w, h); |
| 391 | if let Some(b) = crate::flow::visual::first_baseline(&nodes) { |
| 392 | f.set_baseline(b.to_pt()); |
| 393 | } |
| 394 | f.push(P2::new(0.0, 0.0), FItem::Node { nodes, w, h }); |
| 395 | Ok(f) |
| 396 | } |
| 397 | |
| 398 | // Typst's `add_equation_number` and `resize_equation`. |
| 399 | fn add_number(builder: Builder, number: MFrame, align: (f64, f64), eq_align: f64, region_w: f64, full: f64) -> MFrame { |
| 400 | let first = builder.frames.first().map(|(f, p)| (f.h, *p, f.baseline())).unwrap_or((builder.h, P2::default(), 0.0)); |
| 401 | let last = builder.frames.last().map(|(f, p)| (f.h, *p, f.baseline())).unwrap_or((builder.h, P2::default(), 0.0)); |
| 402 | let lines = builder.frames.len(); |
| 403 | let mut eq = builder.build(true); |
| 404 | let width = if region_w.is_finite() { region_w } else { eq.w + 2.0 * full }; |
| 405 | let multiline = lines >= 2; |
| 406 | let offset = if align.1 == 0.5 && multiline { |
| 407 | let h = eq.h.max(number.h); |
| 408 | eq.resize(width, h, eq_align, 0.5) |
| 409 | } else { |
| 410 | let above = if !multiline || align.1 == 0.0 { (number.baseline() - first.2).max(0.0) } else { 0.0 }; |
| 411 | let below = if !multiline || align.1 == 1.0 { ((number.h - number.baseline()) - (last.0 - last.2)).max(0.0) } else { 0.0 }; |
| 412 | let h = eq.h + above + below; |
| 413 | let o = eq.resize(width, h, eq_align, 0.0); |
| 414 | eq.translate(0.0, above); |
| 415 | (o.0, o.1 + above) |
| 416 | }; |
| 417 | let shift = if eq_align == 0.0 && align.0 == 0.0 { |
| 418 | full |
| 419 | } else if eq_align == 1.0 && align.0 == 1.0 { |
| 420 | -full |
| 421 | } else { |
| 422 | 0.0 |
| 423 | }; |
| 424 | eq.translate(shift, 0.0); |
| 425 | let x = if align.0 == 0.0 { 0.0 } else { eq.w - number.w }; |
| 426 | let baselines = |(_, pos, base): (f64, P2, f64)| offset.1 + pos.y + base - number.baseline(); |
| 427 | let y = if align.1 == 0.0 { |
| 428 | baselines(first) |
| 429 | } else if align.1 == 0.5 && !multiline { |
| 430 | baselines(first) |
| 431 | } else if align.1 == 0.5 { |
| 432 | (eq.h - number.h) / 2.0 |
| 433 | } else { |
| 434 | baselines(last) |
| 435 | }; |
| 436 | eq.push_frame(P2::new(x, y), number); |
| 437 | eq |
| 438 | } |