Oregami
Repositories/oxedyne/fe2o3

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

15.9 KiB, 1 run

created by r1870400018:63548, 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 `math/ir/item.rs`, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4//! The maths IR: an equation's realised elements resolved into items (glyphs, fractions, scripts,
5//! fences, tables) with their classes, sizes and spacing decided, ready for layout. A port of Typst
6//! 0.15's `typst-library/src/math/ir/item.rs`; items own their children, and the few properties layout
7//! adjusts in place (a glyph's stretch) sit in cells.
8
9use crate::eval::realise::Tag;
10use crate::eval::styles::StyleChain;
11use crate::eval::value::Relative;
12use crate::eval::content::Content;
13use crate::math::class::MathClass;
14use crate::math::style::MathSize;
15use crate::math::props;
16use crate::syntax::Span;
17
18use std::cell::Cell;
19use std::rc::Rc;
20
21/// A relative length with its length part resolved to points: Typst's `Rel<Abs>`.
22#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub struct Rel {
24 pub rel: f64,
25 pub abs: f64,
26}
27
28impl Rel {
29 pub fn one() -> Self { Self { rel: 1.0, abs: 0.0 } }
30 pub fn new(rel: f64, abs: f64) -> Self { Self { rel, abs } }
31
32 /// The length against a whole; a ratio of an infinite whole counts for nothing.
33 pub fn relative_to(&self, whole: f64) -> f64 {
34 let part = self.rel * whole;
35 (if part.is_finite() { part } else { 0.0 }) + self.abs
36 }
37
38 pub fn of(r: &Relative, font_size: f64) -> Self {
39 Self { rel: r.rel.0, abs: r.abs.resolve(font_size) }
40 }
41}
42
43/// Is a relative length exactly 100%?
44pub fn is_one(r: &Relative) -> bool {
45 r.rel.0 == 1.0 && r.abs.abs == 0.0 && r.abs.em == 0.0
46}
47
48/// When attachments go above and below rather than to the side.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum Limits {
51 Never,
52 Display,
53 Always,
54}
55
56impl Limits {
57 pub fn for_char_with_class(c: char, class: Option<MathClass>) -> Self {
58 match class {
59 Some(MathClass::Large) => if is_integral_char(c) { Limits::Never } else { Limits::Display },
60 Some(MathClass::Relation) => Limits::Always,
61 _ => Limits::Never,
62 }
63 }
64
65 pub fn for_class(class: MathClass) -> Self {
66 match class {
67 MathClass::Large => Limits::Display,
68 MathClass::Relation => Limits::Always,
69 _ => Limits::Never,
70 }
71 }
72
73 pub fn active(&self, styles: &StyleChain) -> bool {
74 match self {
75 Limits::Always => true,
76 Limits::Display => props::size(styles) == MathSize::Display,
77 Limits::Never => false,
78 }
79 }
80}
81
82fn is_integral_char(c: char) -> bool {
83 ('\u{222b}'..='\u{2233}').contains(&c) || ('\u{2a0b}'..='\u{2a1c}').contains(&c)
84}
85
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum Position {
88 Above,
89 Below,
90}
91
92/// Which way a row of cells alternates alignment: right, left, right, ... or not at all.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub enum Alternator {
95 None,
96 Left,
97 Right,
98}
99
100impl Alternator {
101 /// The current alignment, advancing to the next.
102 pub fn next(&mut self) -> Alternator {
103 let r = *self;
104 *self = match self {
105 Alternator::None => Alternator::None,
106 Alternator::Left => Alternator::Right,
107 Alternator::Right => Alternator::Left,
108 };
109 r
110 }
111}
112
113/// Horizontal alignment resolved to start, centre or end.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum Fixed {
116 Start,
117 Center,
118 End,
119}
120
121impl Fixed {
122 /// The offset to align something of `extent` within free space.
123 pub fn position(self, free: f64) -> f64 {
124 match self {
125 Fixed::Start => 0.0,
126 Fixed::Center => free / 2.0,
127 Fixed::End => free,
128 }
129 }
130}
131
132/// How far to stretch along one axis.
133#[derive(Clone, Copy, Debug, PartialEq)]
134pub struct StretchInfo {
135 pub target: Rel,
136 buffer: Option<Rel>,
137 pub explicit: bool,
138 pub requested_target: Option<Relative>,
139 pub short_fall: f64, // ems
140 pub relative_to: Option<f64>,
141 pub font_size: Option<f64>,
142}
143
144impl StretchInfo {
145 pub fn new(target: Rel, short_fall: f64) -> Self {
146 Self { target, buffer: None, explicit: false, requested_target: None, short_fall, relative_to: None,
147 font_size: None }
148 }
149
150 pub fn from_size(size: &Relative, short_fall: f64, font_size: f64) -> Self {
151 Self {
152 target: Rel::of(size, font_size),
153 buffer: None,
154 explicit: false,
155 requested_target: if is_one(size) { None } else { Some(*size) },
156 short_fall,
157 relative_to: None,
158 font_size: None,
159 }
160 }
161
162 // Typst's `MulAssign`: stack a further request onto this one.
163 fn mul(&mut self, rhs: StretchInfo) {
164 if let Some(b) = self.buffer {
165 self.target = Rel::new(self.target.rel * b.rel, b.rel * self.target.abs + b.abs);
166 }
167 self.buffer = Some(rhs.target);
168 if let Some(req) = rhs.requested_target {
169 self.requested_target = Some(match self.requested_target {
170 None => req,
171 Some(t) => {
172 let abs = crate::eval::value::Length {
173 abs: req.rel.0 * t.abs.abs + req.abs.abs,
174 em: req.rel.0 * t.abs.em + req.abs.em,
175 };
176 Relative { rel: crate::eval::value::Ratio(t.rel.0 * req.rel.0), abs }
177 }
178 });
179 }
180 self.explicit = self.explicit || rhs.explicit;
181 self.short_fall = rhs.short_fall;
182 }
183}
184
185impl Default for StretchInfo {
186 fn default() -> Self { Self::new(Rel::one(), 0.0) }
187}
188
189#[derive(Clone, Copy, Debug, Default, PartialEq)]
190pub struct Stretch {
191 pub x: Option<StretchInfo>,
192 pub y: Option<StretchInfo>,
193}
194
195impl Stretch {
196 pub fn new() -> Self { Self::default() }
197
198 pub fn with_x(mut self, info: StretchInfo) -> Self { self.x = Some(info); self }
199 pub fn with_y(mut self, info: StretchInfo) -> Self { self.y = Some(info); self }
200
201 fn axis_mut(&mut self, vertical: bool) -> &mut Option<StretchInfo> {
202 if vertical { &mut self.y } else { &mut self.x }
203 }
204
205 fn axis(&self, vertical: bool) -> Option<StretchInfo> {
206 if vertical { self.y } else { self.x }
207 }
208
209 pub fn update(mut self, mut info: StretchInfo) -> Self {
210 info.explicit = true;
211 match &mut self.x {
212 Some(v) => v.mul(info),
213 None => self.x = Some(info),
214 }
215 match &mut self.y {
216 Some(v) => v.mul(info),
217 None => self.y = Some(info),
218 }
219 self
220 }
221
222 pub fn relative_to(mut self, rel: f64, vertical: bool) -> Self {
223 if let Some(info) = self.axis_mut(vertical) {
224 if info.relative_to.is_none() {
225 info.relative_to = Some(rel);
226 }
227 }
228 self
229 }
230
231 pub fn font_size(mut self, size: f64, vertical: bool) -> Self {
232 if let Some(info) = self.axis_mut(vertical) {
233 if info.font_size.is_none() {
234 info.font_size = Some(size);
235 }
236 }
237 self
238 }
239
240 /// The request along an axis with any buffered request folded in.
241 pub fn resolve(mut self, vertical: bool) -> Option<StretchInfo> {
242 if let Some(info) = self.axis_mut(vertical) {
243 if let Some(b) = info.buffer {
244 if info.relative_to.is_some() {
245 info.target = b;
246 } else {
247 info.target = Rel::new(info.target.rel * b.rel, b.rel * info.target.abs + b.abs);
248 }
249 }
250 }
251 self.axis(vertical)
252 }
253
254 pub fn is_explicit(self, vertical: bool) -> bool {
255 self.axis(vertical).map(|i| i.explicit).unwrap_or(false)
256 }
257}
258
259/// An item and the per-item layout decisions made before layout.
260#[derive(Clone, Copy, Debug)]
261pub struct Props {
262 pub limits: Limits,
263 pub class: Option<MathClass>,
264 pub size: MathSize,
265 pub cramped: bool,
266 pub ignorant: bool, // transparent to spacing (a tag, a placed element)
267 pub spaced: bool, // takes a source space either side
268 pub lspace: Option<f64>, // ems
269 pub rspace: Option<f64>,
270 pub align_form_infix: bool,
271 pub span: Span,
272}
273
274impl Props {
275 pub fn new(styles: &StyleChain, class: Option<MathClass>, span: Span) -> Self {
276 Self {
277 limits: Limits::Never,
278 class,
279 size: props::size(styles),
280 cramped: props::cramped(styles),
281 ignorant: false,
282 spaced: false,
283 lspace: None,
284 rspace: None,
285 align_form_infix: false,
286 span,
287 }
288 }
289
290 pub fn class(&self) -> MathClass { self.class.unwrap_or(MathClass::Normal) }
291}
292
293pub struct Glyph {
294 pub text: String,
295 pub class: MathClass,
296 pub stretch: Cell<Stretch>,
297 pub mid_stretched: Cell<Option<bool>>,
298 pub flac: Cell<bool>,
299}
300
301pub struct Scripts {
302 pub base: Item,
303 pub t: Option<Item>,
304 pub b: Option<Item>,
305 pub tl: Option<Item>,
306 pub bl: Option<Item>,
307 pub tr: Option<Item>,
308 pub br: Option<Item>,
309}
310
311/// A matrix augmentation: line offsets and the stroke, all resolved.
312#[derive(Clone, Debug, Default)]
313pub struct Augment {
314 pub hline: Vec<i64>,
315 pub vline: Vec<i64>,
316 pub stroke: Option<crate::eval::value::Stroke>,
317}
318
319pub struct Table {
320 pub cells: Vec<Vec<Row>>,
321 pub gap: (Rel, Rel), // column, row
322 pub augment: Option<Augment>,
323 pub align: Fixed,
324 pub alternator: Alternator,
325}
326
327pub struct Cancel {
328 pub base: Item,
329 pub length: Rel,
330 pub stroke: crate::math::frame::Pen,
331 pub cross: bool,
332 pub invert_first_line: bool,
333 pub angle: crate::eval::value::Value, // auto, an angle, or a function
334}
335
336/// The body of a fenced item: its own, or one segment of a multiline fence whose delimiters are all
337/// sized against every segment together.
338pub enum FencedBody {
339 Owned(Item),
340 Shared { index: usize, sizing: Rc<SharedSizing> },
341}
342
343impl FencedBody {
344 pub fn item(&self) -> &Item {
345 match self {
346 FencedBody::Owned(i) => i,
347 FencedBody::Shared { index, sizing } => match sizing.items.get(*index) {
348 Some(i) => i,
349 None => &sizing.empty,
350 },
351 }
352 }
353}
354
355pub struct SharedSizing {
356 pub items: Vec<Item>,
357 pub relative_to: Cell<Option<f64>>,
358 pub styles: StyleChain,
359 empty: Item,
360}
361
362impl SharedSizing {
363 pub fn new(items: Vec<Item>, styles: StyleChain) -> Rc<Self> {
364 Rc::new(Self { items, relative_to: Cell::new(None), styles, empty: Item::Space })
365 }
366}
367
368pub enum Kind {
369 Group(Vec<Item>),
370 Multiline { rows: Vec<Row>, centered: bool },
371 Radical { radicand: Item, index: Option<Item>, sqrt: Item },
372 Fenced { open: Option<Item>, close: Option<Item>, body: FencedBody, balanced: bool },
373 Fraction { num: Item, denom: Item, line: bool, padding: f64 },
374 Skewed { num: Item, denom: Item, slash: Item },
375 Table(Box<Table>),
376 Scripts(Box<Scripts>),
377 Accent { base: Item, accent: Item, position: Position, dotless: bool, exact: bool },
378 Cancel(Box<Cancel>),
379 Line { base: Item, position: Position },
380 Primes(usize),
381 Text(String),
382 Number(String),
383 Glyph(Glyph),
384 External(Content),
385}
386
387pub struct Comp {
388 pub kind: Kind,
389 pub props: Props,
390 pub styles: StyleChain,
391}
392
393/// A row split at alignment points into columns, each one item.
394pub struct Row(pub Vec<Item>);
395
396impl Row {
397 pub fn len(&self) -> usize { self.0.len() }
398 pub fn is_empty(&self) -> bool { self.0.is_empty() }
399
400 pub fn pad_to(&mut self, n: usize, styles: &StyleChain) {
401 while self.0.len() < n {
402 self.0.push(Item::wrap(Vec::new(), styles));
403 }
404 }
405}
406
407pub enum Item {
408 Comp(Box<Comp>),
409 Spacing(f64, bool), // points, weak
410 Space,
411 Tag(Tag),
412}
413
414/// An item, or a linebreak or alignment point still to be resolved into rows and columns.
415pub enum Raw {
416 Item(Item),
417 Linebreak,
418 Align,
419}
420
421impl Raw {
422 pub fn is_ignorant(&self) -> bool {
423 match self {
424 Raw::Item(i) => i.is_ignorant(),
425 _ => false,
426 }
427 }
428
429 pub fn into_item(self) -> Option<Item> {
430 match self {
431 Raw::Item(i) => Some(i),
432 _ => None,
433 }
434 }
435}
436
437impl Item {
438 pub fn comp(kind: Kind, props: Props, styles: StyleChain) -> Item {
439 Item::Comp(Box::new(Comp { kind, props, styles }))
440 }
441
442 /// One item as it is, several as a group.
443 pub fn wrap(mut items: Vec<Item>, styles: &StyleChain) -> Item {
444 if items.len() == 1 {
445 if let Some(i) = items.pop() {
446 return i;
447 }
448 }
449 Item::comp(Kind::Group(items), Props::new(styles, None, Span::detached()), styles.clone())
450 }
451
452 pub fn limits(&self) -> Limits {
453 match self {
454 Item::Comp(c) => c.props.limits,
455 _ => Limits::Never,
456 }
457 }
458
459 pub fn class(&self) -> MathClass { self.raw_class().unwrap_or(MathClass::Normal) }
460
461 pub fn raw_class(&self) -> Option<MathClass> {
462 match self {
463 Item::Comp(c) => c.props.class,
464 Item::Spacing(..) | Item::Space => Some(MathClass::Space),
465 Item::Tag(_) => Some(MathClass::Special),
466 }
467 }
468
469 /// The class the item presents on its right: a fence with a closing delimiter closes.
470 pub fn rclass(&self) -> MathClass {
471 if let Item::Comp(c) = self {
472 if let Kind::Fenced { close: Some(_), .. } = &c.kind {
473 if c.props.class.is_none() {
474 return MathClass::Closing;
475 }
476 }
477 }
478 self.class()
479 }
480
481 pub fn lclass(&self) -> MathClass {
482 if let Item::Comp(c) = self {
483 if let Kind::Fenced { open: Some(_), .. } = &c.kind {
484 if c.props.class.is_none() {
485 return MathClass::Opening;
486 }
487 }
488 }
489 self.class()
490 }
491
492 pub fn size(&self) -> Option<MathSize> {
493 match self {
494 Item::Comp(c) => Some(c.props.size),
495 _ => None,
496 }
497 }
498
499 pub fn is_spaced(&self) -> bool {
500 if self.class() == MathClass::Fence {
501 return true;
502 }
503 match self {
504 Item::Comp(c) => c.props.spaced && matches!(c.props.class(), MathClass::Normal | MathClass::Alphabetic),
505 _ => false,
506 }
507 }
508
509 pub fn is_ignorant(&self) -> bool {
510 match self {
511 Item::Comp(c) => c.props.ignorant,
512 Item::Tag(_) => true,
513 _ => false,
514 }
515 }
516
517 pub fn span(&self) -> Span {
518 match self {
519 Item::Comp(c) => c.props.span,
520 _ => Span::detached(),
521 }
522 }
523
524 pub fn styles(&self) -> Option<&StyleChain> {
525 match self {
526 Item::Comp(c) => Some(&c.styles),
527 _ => None,
528 }
529 }
530
531 fn glyph(&self) -> Option<&Glyph> {
532 match self {
533 Item::Comp(c) => match &c.kind {
534 Kind::Glyph(g) => Some(g),
535 _ => None,
536 },
537 _ => None,
538 }
539 }
540
541 pub fn mid_stretched(&self) -> Option<bool> {
542 self.glyph().and_then(|g| g.mid_stretched.get())
543 }
544
545 pub fn is_multiline(&self) -> bool {
546 matches!(self, Item::Comp(c) if matches!(c.kind, Kind::Multiline { .. }))
547 }
548
549 /// A group's items, or the item itself.
550 pub fn as_slice(&self) -> &[Item] {
551 if let Item::Comp(c) = self {
552 if let Kind::Group(items) = &c.kind {
553 return items;
554 }
555 }
556 std::slice::from_ref(self)
557 }
558
559 pub fn set_limits(&mut self, limits: Limits) {
560 if let Item::Comp(c) = self {
561 c.props.limits = limits;
562 }
563 }
564
565 pub fn set_class(&mut self, class: MathClass) {
566 if let Item::Comp(c) = self {
567 c.props.class = Some(class);
568 }
569 }
570
571 pub fn set_explicit_class(&mut self, class: MathClass) {
572 self.set_class(class);
573 if let Item::Comp(c) = self {
574 let display = c.props.size == MathSize::Display;
575 if let Kind::Glyph(g) = &mut c.kind {
576 g.class = class;
577 if class == MathClass::Large && display && !g.stretch.get().is_explicit(true) {
578 let s = g.stretch.get().with_y(StretchInfo::default());
579 g.stretch.set(s);
580 }
581 }
582 }
583 }
584
585 pub fn set_lspace(&mut self, space: Option<f64>) {
586 if let Item::Comp(c) = self {
587 if c.props.lspace.is_none() {
588 c.props.lspace = space;
589 }
590 }
591 }
592
593 pub fn set_rspace(&mut self, space: Option<f64>) {
594 if let Item::Comp(c) = self {
595 if c.props.rspace.is_none() {
596 c.props.rspace = space;
597 }
598 }
599 }
600
601 pub fn with_multiline_centering(mut self) -> Self {
602 if let Item::Comp(c) = &mut self {
603 if let Kind::Multiline { centered, .. } = &mut c.kind {
604 *centered = true;
605 }
606 }
607 self
608 }
609
610 pub fn set_mid_stretched(&self, v: Option<bool>) {
611 if let Some(g) = self.glyph() {
612 g.mid_stretched.set(v);
613 }
614 }
615
616 /// Replaces the stretch request, marking it explicit.
617 pub fn set_stretch(&self, mut stretch: Stretch) {
618 if let Some(i) = &mut stretch.x {
619 i.explicit = true;
620 }
621 if let Some(i) = &mut stretch.y {
622 i.explicit = true;
623 }
624 self.replace_stretch(stretch);
625 }
626
627 pub fn replace_stretch(&self, stretch: Stretch) {
628 if let Some(g) = self.glyph() {
629 g.stretch.set(stretch);
630 }
631 }
632
633 pub fn set_y_stretch(&self, mut info: StretchInfo) {
634 if let Some(g) = self.glyph() {
635 info.explicit = true;
636 g.stretch.set(g.stretch.get().with_y(info));
637 }
638 }
639
640 pub fn update_stretch(&self, info: StretchInfo) {
641 if let Some(g) = self.glyph() {
642 g.stretch.set(g.stretch.get().update(info));
643 }
644 }
645
646 pub fn set_stretch_relative_to(&self, rel: f64, vertical: bool) {
647 if let Some(g) = self.glyph() {
648 g.stretch.set(g.stretch.get().relative_to(rel, vertical));
649 }
650 }
651
652 pub fn set_stretch_font_size(&self, size: f64, vertical: bool) {
653 if let Some(g) = self.glyph() {
654 g.stretch.set(g.stretch.get().font_size(size, vertical));
655 }
656 }
657
658 pub fn set_flac(&self) {
659 if let Some(g) = self.glyph() {
660 g.flac.set(true);
661 }
662 }
663}