oxedyne/fe2o3/fe2o3_austenite/src/math/frame.rs
9.2 KiB, 16 runs
created by r1870400018:63546, 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-library `layout/frame.rs`, cut down to what maths places, version 0.15.1). |
| 3 | // Modified for Austenite: ported to Hematite's types, IR and error handling. |
| 4 | //! A maths frame -- Typst's `Frame` cut down to what maths layout places: glyph runs, stroked lines, |
| 5 | //! nested frames, laid-out external content and location tags, at points from the frame's top-left, y |
| 6 | //! down -- and its lowering to one IR horizontal box. |
| 7 | //! |
| 8 | //! The box sets everything on its baseline: glyph runs become text leaves, whatever their glyphs, raised |
| 9 | //! or lowered by their shift, the ink a rule needs becomes one graphic leaf, and external content keeps |
| 10 | //! its own nodes. Leaves are zero-width and seated by fixed glue, so overlapping parts (a script |
| 11 | //! over a base, a rule over a radicand) need no nested boxes. |
| 12 | |
| 13 | use crate::eval::realise::Tag; |
| 14 | use crate::eval::value::{ |
| 15 | LineCap, |
| 16 | Paint, |
| 17 | Stroke, |
| 18 | }; |
| 19 | use crate::eval::Engine; |
| 20 | use crate::flow::visual::{ |
| 21 | fix_stroke, |
| 22 | paint_ink, |
| 23 | pen_of, |
| 24 | Curve, |
| 25 | FixedStroke, |
| 26 | P2, |
| 27 | }; |
| 28 | use crate::font::ShapedText; |
| 29 | use crate::ir::{ |
| 30 | BoxNode, |
| 31 | Dims, |
| 32 | DrawOp, |
| 33 | Glue, |
| 34 | Graphic, |
| 35 | Leaf, |
| 36 | Node, |
| 37 | Sp, |
| 38 | }; |
| 39 | use crate::math::font::{ |
| 40 | MathFont, |
| 41 | ShapedGlyph, |
| 42 | }; |
| 43 | use crate::syntax::Span; |
| 44 | |
| 45 | use oxedyne_fe2o3_core::prelude::*; |
| 46 | use oxedyne_fe2o3_font::shape::Glyph; |
| 47 | use oxedyne_fe2o3_graphics::colour::Ink; |
| 48 | |
| 49 | use std::sync::Arc; |
| 50 | |
| 51 | /// A stroke with every part decided, lengths in points. |
| 52 | pub type Pen = FixedStroke; |
| 53 | |
| 54 | /// A stroke's unset parts from Typst's defaults, its paint from the text fill. |
| 55 | pub fn pen(stroke: &Stroke, font_size: f64, fill: Paint) -> Pen { |
| 56 | let mut p = fix_stroke(stroke, font_size); |
| 57 | if stroke.paint.is_none() { |
| 58 | p.paint = fill; |
| 59 | } |
| 60 | p |
| 61 | } |
| 62 | |
| 63 | /// A plain line pen: `paint` at `thickness`, butt caps. |
| 64 | pub fn line_pen(paint: Paint, thickness: f64) -> Pen { |
| 65 | let mut p = fix_stroke(&Stroke::default(), 11.0); |
| 66 | p.paint = paint; |
| 67 | p.thickness = thickness; |
| 68 | p.cap = LineCap::Butt; |
| 69 | p |
| 70 | } |
| 71 | |
| 72 | /// A run of glyphs from one font at one size, positioned from its baseline origin. |
| 73 | #[derive(Clone)] |
| 74 | pub struct GlyphRun { |
| 75 | pub font: Arc<MathFont>, |
| 76 | pub size: f64, |
| 77 | pub fill: Paint, |
| 78 | pub text: String, |
| 79 | pub glyphs: Vec<ShapedGlyph>, |
| 80 | } |
| 81 | |
| 82 | impl std::fmt::Debug for GlyphRun { |
| 83 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 84 | f.debug_struct("GlyphRun").field("text", &self.text).field("size", &self.size).field("glyphs", &self.glyphs).finish() |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | #[derive(Clone, Debug)] |
| 89 | pub enum FItem { |
| 90 | Glyphs(GlyphRun), |
| 91 | Line { to: P2, pen: Pen }, // a stroked segment from the item's position |
| 92 | Rect { w: f64, h: f64, fill: Paint, pen: Option<Pen> }, |
| 93 | Frame(MFrame), |
| 94 | Node { nodes: Vec<Node>, w: f64, h: f64 }, // laid-out content, top-left at the position |
| 95 | Tag(Tag), |
| 96 | } |
| 97 | |
| 98 | #[derive(Clone, Debug, Default)] |
| 99 | pub struct MFrame { |
| 100 | pub w: f64, |
| 101 | pub h: f64, |
| 102 | pub baseline: Option<f64>, |
| 103 | pub items: Vec<(P2, FItem)>, |
| 104 | } |
| 105 | |
| 106 | impl MFrame { |
| 107 | pub fn new(w: f64, h: f64) -> Self { Self { w, h, baseline: None, items: Vec::new() } } |
| 108 | |
| 109 | pub fn baseline(&self) -> f64 { self.baseline.unwrap_or(self.h) } |
| 110 | pub fn has_baseline(&self) -> bool { self.baseline.is_some() } |
| 111 | pub fn set_baseline(&mut self, b: f64) { self.baseline = Some(b); } |
| 112 | pub fn ascent(&self) -> f64 { self.baseline() } |
| 113 | pub fn descent(&self) -> f64 { self.h - self.baseline() } |
| 114 | |
| 115 | pub fn push(&mut self, at: P2, item: FItem) { self.items.push((at, item)); } |
| 116 | |
| 117 | pub fn push_frame(&mut self, at: P2, frame: MFrame) { |
| 118 | if frame.items.is_empty() { |
| 119 | return; |
| 120 | } |
| 121 | self.items.push((at, FItem::Frame(frame))); |
| 122 | } |
| 123 | |
| 124 | pub fn translate(&mut self, dx: f64, dy: f64) { |
| 125 | if dx == 0.0 && dy == 0.0 { |
| 126 | return; |
| 127 | } |
| 128 | if let Some(b) = &mut self.baseline { |
| 129 | *b += dy; |
| 130 | } |
| 131 | for (p, _) in self.items.iter_mut() { |
| 132 | p.x += dx; |
| 133 | p.y += dy; |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /// Resizes to `w` by `h`, moving the contents by the alignments (0 start, 0.5 centre, 1 end), and |
| 138 | /// returns how far they moved. |
| 139 | pub fn resize(&mut self, w: f64, h: f64, ax: f64, ay: f64) -> (f64, f64) { |
| 140 | let d = ((w - self.w) * ax, (h - self.h) * ay); |
| 141 | self.w = w; |
| 142 | self.h = h; |
| 143 | self.translate(d.0, d.1); |
| 144 | d |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // Lowering |
| 149 | |
| 150 | enum Prim { |
| 151 | Text { x: f64, y: f64, shaped: ShapedText }, |
| 152 | Node { x: f64, y: f64, w: f64, h: f64, nodes: Vec<Node> }, |
| 153 | Anchor { x: f64, id: crate::ledger::AnchorId }, |
| 154 | } |
| 155 | |
| 156 | /// The frame as one horizontal box on its baseline. |
| 157 | pub fn to_node(engine: &mut Engine, frame: &MFrame, span: Span) -> Outcome<Node> { |
| 158 | let mut prims = Vec::new(); |
| 159 | let mut ink = Vec::new(); |
| 160 | res!(flatten(engine, frame, 0.0, 0.0, &mut prims, &mut ink, span)); |
| 161 | let base = frame.baseline(); |
| 162 | let mut list = Vec::new(); |
| 163 | if !ink.is_empty() { |
| 164 | // One zero-width graphic whose frame is the whole box: its top is the box's top. |
| 165 | let dims = Dims::new(Sp::ZERO, Sp::from_pt(base), Sp::from_pt(frame.h - base)); |
| 166 | list.push(Node::Leaf(Leaf::graphic(Graphic::new(ink, dims)))); |
| 167 | } |
| 168 | // The glyphs stay in the frame's own order, which is Typst's: a row after its row, a base before its |
| 169 | // scripts, a numerator before its denominator, so the file's text reads as the equation does. The glue |
| 170 | // that seats each leaf therefore goes back as well as forward. |
| 171 | let mut cursor = 0.0; |
| 172 | for p in prims { |
| 173 | let x = px(&p); |
| 174 | if (x - cursor).abs() > 1e-9 { |
| 175 | list.push(Node::Glue(Glue::fixed(Sp::from_pt(x - cursor)))); |
| 176 | cursor = x; |
| 177 | } |
| 178 | match p { |
| 179 | Prim::Text { y, shaped, .. } => { |
| 180 | let leaf = Leaf::text_dims(shaped, Dims::new(Sp::ZERO, Sp::ZERO, Sp::ZERO)) |
| 181 | .with_shift(Sp::from_pt(y - base)) |
| 182 | .with_span(span.range()); |
| 183 | list.push(Node::Leaf(leaf)); |
| 184 | } |
| 185 | Prim::Node { y, w, h, nodes, .. } => { |
| 186 | let above = base - y; |
| 187 | let inner = Node::VBox(BoxNode::new(nodes, Dims::new(Sp::from_pt(w), Sp::from_pt(h), Sp::ZERO))); |
| 188 | list.push(Node::VBox(BoxNode::new(vec![inner], |
| 189 | Dims::new(Sp::from_pt(w), Sp::from_pt(above), Sp::from_pt(h - above))))); |
| 190 | cursor += w; |
| 191 | } |
| 192 | Prim::Anchor { id, .. } => list.push(Node::Anchor(id)), |
| 193 | } |
| 194 | } |
| 195 | if (frame.w - cursor).abs() > 1e-9 { |
| 196 | list.push(Node::Glue(Glue::fixed(Sp::from_pt(frame.w - cursor)))); |
| 197 | } |
| 198 | let dims = Dims::new(Sp::from_pt(frame.w), Sp::from_pt(base), Sp::from_pt(frame.h - base)); |
| 199 | Ok(Node::HBox(BoxNode::new(list, dims))) |
| 200 | } |
| 201 | |
| 202 | fn px(p: &Prim) -> f64 { |
| 203 | match p { |
| 204 | Prim::Text { x, .. } | Prim::Node { x, .. } | Prim::Anchor { x, .. } => *x, |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | fn flatten( |
| 209 | engine: &mut Engine, |
| 210 | frame: &MFrame, |
| 211 | ox: f64, |
| 212 | oy: f64, |
| 213 | prims: &mut Vec<Prim>, |
| 214 | ink: &mut Vec<DrawOp>, |
| 215 | span: Span, |
| 216 | ) |
| 217 | -> Outcome<()> |
| 218 | { |
| 219 | for (p, item) in &frame.items { |
| 220 | let x = ox + p.x; |
| 221 | let y = oy + p.y; |
| 222 | match item { |
| 223 | FItem::Glyphs(run) => prims.push(Prim::Text { x, y, shaped: res!(glyph_text(run)) }), |
| 224 | FItem::Line { to, pen } => { |
| 225 | let mut c = Curve::new(); |
| 226 | c.move_(P2::new(0.0, 0.0)); |
| 227 | c.line(*to); |
| 228 | res!(stroke_ink(engine, &c, pen, x, y, ink, span)); |
| 229 | } |
| 230 | FItem::Rect { w, h, fill, pen } => { |
| 231 | let c = Curve::rect(*w, *h); |
| 232 | if let Some(colour) = res!(paint_ink(engine, fill, span)) { |
| 233 | ink.push(DrawOp::Fill { path: res!(c.to_path(P2::new(x, y))), colour }); |
| 234 | } |
| 235 | if let Some(pen) = pen { |
| 236 | res!(stroke_ink(engine, &c, pen, x, y, ink, span)); |
| 237 | } |
| 238 | } |
| 239 | FItem::Frame(f) => res!(flatten(engine, f, x, y, prims, ink, span)), |
| 240 | FItem::Node { nodes, w, h } => prims.push(Prim::Node { x, y, w: *w, h: *h, nodes: nodes.clone() }), |
| 241 | FItem::Tag(Tag::Start(c)) => if let Some(loc) = c.location() { |
| 242 | prims.push(Prim::Anchor { x, id: loc.anchor() }); |
| 243 | }, |
| 244 | FItem::Tag(Tag::End(_)) => (), |
| 245 | } |
| 246 | } |
| 247 | Ok(()) |
| 248 | } |
| 249 | |
| 250 | fn stroke_ink(engine: &mut Engine, c: &Curve, pen: &Pen, x: f64, y: f64, ink: &mut Vec<DrawOp>, span: Span) -> Outcome<()> { |
| 251 | if pen.thickness <= 0.0 { |
| 252 | return Ok(()); |
| 253 | } |
| 254 | if let Some(colour) = res!(paint_ink(engine, &pen.paint, span)) { |
| 255 | let path = res!(c.to_path(P2::new(x, y))); |
| 256 | let p = res!(pen_of(pen)); |
| 257 | ink.push(DrawOp::Fill { path: res!(path.stroke(&p)), colour }); |
| 258 | } |
| 259 | Ok(()) |
| 260 | } |
| 261 | |
| 262 | // A glyph run as a text run of its own glyphs, whatever they are. A variant, an assembly part and a |
| 263 | // feature-selected form are glyphs of the font like any other: set as the font's glyph ids at their |
| 264 | // offsets they draw as the font draws them and keep the text they stand for, so the page's text and a |
| 265 | // PDF's /ToUnicode carry a script's digit, a stretched delimiter and an accent as characters, as Typst's |
| 266 | // do. A glyph for each character stands for that character; otherwise the run's first glyph stands for |
| 267 | // its whole text. |
| 268 | fn glyph_text(run: &GlyphRun) -> Outcome<ShapedText> { |
| 269 | let colour = match &run.fill { |
| 270 | Paint::Color(c) => c.to_ink(), |
| 271 | _ => Ink::BLACK, |
| 272 | }; |
| 273 | let starts: Vec<usize> = run.text.char_indices().map(|(i, _)| i).collect(); |
| 274 | let each = starts.len() == run.glyphs.len(); |
| 275 | let (mut px, mut py) = (0.0f64, 0.0f64); |
| 276 | let mut glyphs = Vec::with_capacity(run.glyphs.len()); |
| 277 | for (i, g) in run.glyphs.iter().enumerate() { |
| 278 | glyphs.push(Glyph { |
| 279 | id: g.id as u32, |
| 280 | face: 0, |
| 281 | x: ((px + g.x_offset) * run.size) as f32, |
| 282 | y: ((py + g.y_offset) * run.size) as f32, // up from the baseline |
| 283 | adv: (g.x_advance * run.size) as f32, |
| 284 | cluster: if each { starts[i] } else { 0 }, |
| 285 | safe_to_break: true, |
| 286 | }); |
| 287 | px += g.x_advance; |
| 288 | py += g.y_advance; |
| 289 | } |
| 290 | let vm = res!(run.font.font.metrics(run.size as f32)); |
| 291 | let dims = Dims::new(Sp::from_pt(px * run.size), Sp::from_pt(vm.ascent as f64), Sp::from_pt(vm.descent as f64)); |
| 292 | Ok(ShapedText::from_glyphs(run.font.font.clone(), run.size as f32, glyphs, run.text.clone(), colour, dims)) |
| 293 | } |