Oregami
Repositories/oxedyne/fe2o3

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

9.6 KiB, 1 run

created by r1870400018:63554, 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/` element fields and their defaults, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4//! Reading and writing the styles maths layout depends on: the equation's internal fields (size,
5//! cramped, alphabet, boldness, italics, script scale) and the text, paragraph and alignment properties
6//! other units own, each read by its Typst field name with Typst's default when unset.
7
8use crate::eval::content::{
9 ElemKind,
10 FieldId,
11};
12use crate::eval::styles::{
13 Property,
14 Style,
15 StyleChain,
16 Styles,
17};
18use crate::eval::value::{
19 Alignment,
20 Color,
21 ColorSpace,
22 HAlign,
23 Length,
24 Paint,
25 Value,
26};
27use crate::fonts::FaceVariant;
28use crate::math::style::{
29 MathSize,
30 MathVariant,
31};
32use crate::syntax::Span;
33
34use oxedyne_fe2o3_core::prelude::*;
35use oxedyne_fe2o3_font::shape::Feature;
36
37fn fid(kind: ElemKind, name: &str) -> Option<FieldId> { kind.field_id(name) }
38
39/// The value of `kind.name` in force, or `None` when unset and the schema has no static default.
40pub fn get(styles: &StyleChain, kind: ElemKind, name: &str) -> Outcome<Option<Value>> {
41 match fid(kind, name) {
42 Some(id) => styles.get(kind, id),
43 None => Ok(None),
44 }
45}
46
47// An equation internal field: its schema folds by replacement, so the innermost set value wins and no
48// fold can fail.
49fn own(styles: &StyleChain, name: &str) -> Option<Value> {
50 let id = fid(ElemKind::Equation, name)?;
51 styles.values(ElemKind::Equation, id).first().map(|v| (*v).clone())
52}
53
54/// A property style for `kind.name`, or `None` when the schema lacks the field.
55pub fn property(kind: ElemKind, name: &str, value: Value) -> Option<Style> {
56 fid(kind, name).map(|id| Style::Property(Property::new(kind, id, value, Span::detached())))
57}
58
59/// The chain with the given properties pushed innermost.
60pub fn chain_with(styles: &StyleChain, props: Vec<Option<Style>>) -> StyleChain {
61 let v: Vec<Style> = props.into_iter().flatten().collect();
62 styles.chain(&Styles::from_vec(v))
63}
64
65// Equation internals
66
67pub fn size(styles: &StyleChain) -> MathSize {
68 match own(styles, "size") {
69 Some(Value::Str(s)) => MathSize::from_name(&s).unwrap_or(MathSize::Text),
70 _ => MathSize::Text,
71 }
72}
73
74pub fn set_size(size: MathSize) -> Option<Style> {
75 property(ElemKind::Equation, "size", Value::str(size.name()))
76}
77
78pub fn cramped(styles: &StyleChain) -> bool {
79 matches!(own(styles, "cramped"), Some(Value::Bool(true)))
80}
81
82pub fn set_cramped(v: bool) -> Option<Style> { property(ElemKind::Equation, "cramped", Value::Bool(v)) }
83
84/// Are dotless letter forms asked for (the base of a top accent)?
85pub fn dtls(styles: &StyleChain) -> bool {
86 matches!(own(styles, "dtls"), Some(Value::Bool(true)))
87}
88
89pub fn bold(styles: &StyleChain) -> bool {
90 matches!(own(styles, "bold"), Some(Value::Bool(true)))
91}
92
93pub fn italic(styles: &StyleChain) -> Option<bool> {
94 match own(styles, "italic") {
95 Some(Value::Bool(b)) => Some(b),
96 _ => None,
97 }
98}
99
100pub fn variant(styles: &StyleChain) -> Option<MathVariant> {
101 match own(styles, "variant") {
102 Some(Value::Str(s)) => MathVariant::from_name(&s),
103 _ => None,
104 }
105}
106
107pub fn script_scale(styles: &StyleChain) -> (i16, i16) {
108 match own(styles, "script-scale") {
109 Some(Value::Array(a)) => match (a.first(), a.get(1)) {
110 (Some(Value::Int(x)), Some(Value::Int(y))) => (*x as i16, *y as i16),
111 _ => (70, 50),
112 },
113 _ => (70, 50),
114 }
115}
116
117pub fn set_script_scale(a: i16, b: i16) -> Option<Style> {
118 property(ElemKind::Equation, "script-scale", Value::array(vec![Value::Int(a as i64), Value::Int(b as i64)]))
119}
120
121/// The superscript's size: one step down, bottoming out at script-script.
122pub fn for_superscript(styles: &StyleChain) -> Option<Style> {
123 set_size(match size(styles) {
124 MathSize::Display | MathSize::Text => MathSize::Script,
125 MathSize::Script | MathSize::ScriptScript => MathSize::ScriptScript,
126 })
127}
128
129pub fn for_subscript(styles: &StyleChain) -> Vec<Option<Style>> {
130 vec![for_superscript(styles), set_cramped(true)]
131}
132
133pub fn for_numerator(styles: &StyleChain) -> Option<Style> {
134 set_size(match size(styles) {
135 MathSize::Display => MathSize::Text,
136 MathSize::Text => MathSize::Script,
137 MathSize::Script | MathSize::ScriptScript => MathSize::ScriptScript,
138 })
139}
140
141pub fn for_denominator(styles: &StyleChain) -> Vec<Option<Style>> {
142 vec![for_numerator(styles), set_cramped(true)]
143}
144
145// Text
146
147/// The font size scripts scale from, `text.size` in points, before the maths script factor.
148pub fn text_size(styles: &StyleChain) -> f64 { styles.font_size() }
149
150/// The resolved text size: `text.size` scaled by the script percentage the maths size calls for.
151pub fn font_size(styles: &StyleChain) -> f64 {
152 let (s, ss) = script_scale(styles);
153 let factor = match size(styles) {
154 MathSize::Display | MathSize::Text => 1.0,
155 MathSize::Script => s as f64 / 100.0,
156 MathSize::ScriptScript => ss as f64 / 100.0,
157 };
158 factor * text_size(styles)
159}
160
161/// A length in points against the resolved maths font size.
162pub fn resolve(styles: &StyleChain, l: Length) -> f64 { l.resolve(font_size(styles)) }
163
164pub fn black() -> Paint {
165 Paint::Color(Color { space: ColorSpace::Luma, c: [0.0, 0.0, 0.0, 0.0], alpha: 1.0 })
166}
167
168pub fn fill(styles: &StyleChain) -> Outcome<Paint> {
169 Ok(match res!(get(styles, ElemKind::Text, "fill")) {
170 Some(Value::Color(c)) => Paint::Color(c),
171 Some(Value::Gradient(g)) => Paint::Gradient(g),
172 Some(Value::Tiling(t)) => Paint::Tiling(t),
173 _ => black(),
174 })
175}
176
177/// The family list `text.font` names. Unset, it is the maths face the equation's own show-set rule names,
178/// not the document's default, so an equation is set in maths whatever the text schema supplies.
179pub fn families(styles: &StyleChain) -> Outcome<Vec<String>> {
180 fn push(v: &Value, out: &mut Vec<String>) {
181 match v {
182 Value::Str(s) => out.push(s.to_string()),
183 Value::Dict(d) => if let Some(Value::Str(s)) = d.get("name") {
184 out.push(s.to_string());
185 },
186 Value::Array(a) => for x in a.iter() {
187 push(x, out);
188 },
189 _ => (),
190 }
191 }
192 let mut out = Vec::new();
193 match res!(get(styles, ElemKind::Text, "font")) {
194 Some(v) => push(&v, &mut out),
195 None => out.push("new computer modern math".to_string()),
196 }
197 Ok(out)
198}
199
200pub fn fallback(styles: &StyleChain) -> Outcome<bool> {
201 Ok(!matches!(res!(get(styles, ElemKind::Text, "fallback")), Some(Value::Bool(false))))
202}
203
204/// The font variant the styles ask of a face: style, weight and stretch, as Typst's `variant(styles)`.
205pub fn face_variant(styles: &StyleChain) -> Outcome<FaceVariant> {
206 crate::flow::text::variant(styles)
207}
208
209/// `text.baseline`: a shift of the glyphs, positive downward.
210pub fn baseline(styles: &StyleChain) -> Outcome<f64> {
211 Ok(match res!(get(styles, ElemKind::Text, "baseline")) {
212 Some(Value::Length(l)) => resolve(styles, l),
213 _ => 0.0,
214 })
215}
216
217pub fn stroke(styles: &StyleChain) -> Outcome<Option<crate::eval::value::Stroke>> {
218 Ok(res!(get(styles, ElemKind::Text, "stroke")).and_then(|v| crate::eval::styles::to_stroke(&v)))
219}
220
221/// The OpenType features maths text is shaped with: the script-style alternates by size, and whatever
222/// `text.features` adds.
223pub fn features(styles: &StyleChain) -> Outcome<Vec<Feature>> {
224 let mut out = Vec::new();
225 if matches!(res!(get(styles, ElemKind::Text, "kerning")), Some(Value::Bool(false))) {
226 out.push(Feature { tag: *b"kern", value: 0 });
227 }
228 match size(styles) {
229 MathSize::Script => out.push(Feature { tag: *b"ssty", value: 1 }),
230 MathSize::ScriptScript => out.push(Feature { tag: *b"ssty", value: 2 }),
231 _ => (),
232 }
233 match res!(get(styles, ElemKind::Text, "features")) {
234 Some(Value::Array(a)) => for v in a.iter() {
235 if let Value::Str(s) = v {
236 if let Some(tag) = tag_of(s) {
237 out.push(Feature { tag, value: 1 });
238 }
239 }
240 },
241 Some(Value::Dict(d)) => for (k, v) in d.iter() {
242 if let (Some(tag), Value::Int(n)) = (tag_of(k), v) {
243 out.push(Feature { tag, value: *n as u32 });
244 }
245 },
246 _ => (),
247 }
248 Ok(out)
249}
250
251fn tag_of(s: &str) -> Option<[u8; 4]> {
252 let b = s.as_bytes();
253 if b.len() != 4 {
254 return None;
255 }
256 Some([b[0], b[1], b[2], b[3]])
257}
258
259/// Where a text edge sits.
260#[derive(Clone, Copy, Debug, PartialEq)]
261pub enum Edge {
262 Ascender,
263 CapHeight,
264 XHeight,
265 Baseline,
266 Descender,
267 Bounds,
268 Length(f64),
269}
270
271fn edge(styles: &StyleChain, name: &str, default: Edge) -> Outcome<Edge> {
272 Ok(match res!(get(styles, ElemKind::Text, name)) {
273 Some(Value::Str(s)) => match s.as_str() {
274 "ascender" => Edge::Ascender,
275 "cap-height" => Edge::CapHeight,
276 "x-height" => Edge::XHeight,
277 "baseline" => Edge::Baseline,
278 "descender" => Edge::Descender,
279 "bounds" => Edge::Bounds,
280 _ => default,
281 },
282 Some(Value::Length(l)) => Edge::Length(resolve(styles, l)),
283 _ => default,
284 })
285}
286
287pub fn top_edge(styles: &StyleChain) -> Outcome<Edge> { edge(styles, "top-edge", Edge::CapHeight) }
288pub fn bottom_edge(styles: &StyleChain) -> Outcome<Edge> { edge(styles, "bottom-edge", Edge::Baseline) }
289
290// Paragraph and alignment
291
292/// `par.leading` in points: Typst's 0.65em.
293pub fn leading(styles: &StyleChain) -> Outcome<f64> {
294 Ok(match res!(get(styles, ElemKind::Par, "leading")) {
295 Some(Value::Length(l)) => l.resolve(text_size(styles)),
296 _ => 0.65 * text_size(styles),
297 })
298}
299
300/// The horizontal alignment in force, `start` when unset.
301pub fn align_x(styles: &StyleChain) -> Outcome<Option<HAlign>> {
302 Ok(match res!(get(styles, ElemKind::Align, "alignment")) {
303 Some(Value::Alignment(Alignment { x, .. })) => x,
304 _ => None,
305 })
306}
307
308/// Is `block.breakable` on?
309pub fn breakable(styles: &StyleChain) -> Outcome<bool> {
310 Ok(!matches!(res!(get(styles, ElemKind::Block, "breakable")), Some(Value::Bool(false))))
311}