Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/grid.rs

16.6 KiB, 3 runs

created by r1870400018:63238, 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// U6c owns this file. Schemas for grid and table and their cells, headers, footers and lines. `grid.cell`
2// and `table.cell` fields are what the per-cell fill/stroke/align closures resolve against.
3//
4// Typst normalises at construction, and so does this: `columns: 3` is stored as three `auto`s, `gutter`
5// is not a field but the fallback for both `column-gutter` and `row-gutter`, and a child that is not a
6// cell, header, footer or line is wrapped in the family's own cell -- so `it.children` reads as Typst's.
7
8use crate::diag::DiagnosticKind;
9use crate::eval::args::Args;
10use crate::eval::content::{
11 Content,
12 ElemKind,
13 FieldDefault,
14 FieldId,
15 FieldSpec,
16 FieldType,
17};
18use crate::eval::scope::Scope;
19use crate::eval::styles::{
20 Property,
21 Style,
22 StyleChain,
23 Styles,
24};
25use crate::eval::value::{
26 Alignment,
27 Color,
28 ColorSpace,
29 HAlign,
30 Length,
31 Ratio,
32 Relative,
33 Stroke,
34 Type,
35 Paint,
36 VAlign,
37 Value,
38};
39use crate::eval::Engine;
40use crate::syntax::Span;
41
42use oxedyne_fe2o3_core::prelude::*;
43
44use std::sync::Arc;
45
46native_fns! {
47 pub enum GridFn {
48 }
49}
50
51pub fn define(_scope: &mut Scope) {}
52
53pub fn call(f: GridFn, _engine: &mut Engine, _args: Args) -> Outcome<Value> {
54 match f {}
55}
56
57const ANY: FieldType = FieldType::Any;
58
59// Grid and table: one schema, the defaults of `inset` and `stroke` differ and are computed.
60static GRID_FIELDS: [FieldSpec; 9] = [
61 FieldSpec::named("columns", ANY, FieldDefault::EmptyArray),
62 FieldSpec::named("rows", ANY, FieldDefault::EmptyArray),
63 FieldSpec::named("column-gutter", ANY, FieldDefault::EmptyArray),
64 FieldSpec::named("row-gutter", ANY, FieldDefault::EmptyArray),
65 FieldSpec::named("inset", ANY, FieldDefault::Computed),
66 FieldSpec::named("align", ANY, FieldDefault::Auto),
67 FieldSpec::named("fill", ANY, FieldDefault::None),
68 FieldSpec::named("stroke", ANY, FieldDefault::Computed),
69 FieldSpec::named("children", ANY, FieldDefault::EmptyArray).variadic().unsettable(),
70];
71
72static CELL_FIELDS: [FieldSpec; 10] = [
73 FieldSpec::required("body", FieldType::Content),
74 FieldSpec::named("x", ANY, FieldDefault::Auto),
75 FieldSpec::named("y", ANY, FieldDefault::Auto),
76 FieldSpec::named("colspan", FieldType::Of(Type::Int), FieldDefault::Int(1)),
77 FieldSpec::named("rowspan", FieldType::Of(Type::Int), FieldDefault::Int(1)),
78 FieldSpec::named("inset", ANY, FieldDefault::Auto),
79 FieldSpec::named("align", ANY, FieldDefault::Auto),
80 FieldSpec::named("fill", ANY, FieldDefault::Auto),
81 FieldSpec::named("stroke", ANY, FieldDefault::Computed),
82 FieldSpec::named("breakable", ANY, FieldDefault::Auto),
83];
84
85static HEADER_FIELDS: [FieldSpec; 3] = [
86 FieldSpec::named("repeat", FieldType::Of(Type::Bool), FieldDefault::Bool(true)),
87 FieldSpec::named("level", FieldType::Of(Type::Int), FieldDefault::Int(1)),
88 FieldSpec::named("children", ANY, FieldDefault::EmptyArray).variadic().unsettable(),
89];
90
91static FOOTER_FIELDS: [FieldSpec; 2] = [
92 FieldSpec::named("repeat", FieldType::Of(Type::Bool), FieldDefault::Bool(true)),
93 FieldSpec::named("children", ANY, FieldDefault::EmptyArray).variadic().unsettable(),
94];
95
96static HLINE_FIELDS: [FieldSpec; 5] = [
97 FieldSpec::named("y", ANY, FieldDefault::Auto),
98 FieldSpec::named("start", FieldType::Of(Type::Int), FieldDefault::Int(0)),
99 FieldSpec::named("end", ANY, FieldDefault::None),
100 FieldSpec::named("stroke", ANY, FieldDefault::Computed),
101 FieldSpec::named("position", ANY, FieldDefault::Computed),
102];
103
104static VLINE_FIELDS: [FieldSpec; 5] = [
105 FieldSpec::named("x", ANY, FieldDefault::Auto),
106 FieldSpec::named("start", FieldType::Of(Type::Int), FieldDefault::Int(0)),
107 FieldSpec::named("end", ANY, FieldDefault::None),
108 FieldSpec::named("stroke", ANY, FieldDefault::Computed),
109 FieldSpec::named("position", ANY, FieldDefault::Computed),
110];
111
112pub fn fields(kind: ElemKind) -> &'static [FieldSpec] {
113 match kind {
114 ElemKind::Grid | ElemKind::Table => &GRID_FIELDS,
115 ElemKind::GridCell | ElemKind::TableCell => &CELL_FIELDS,
116 ElemKind::GridHeader | ElemKind::TableHeader => &HEADER_FIELDS,
117 ElemKind::GridFooter | ElemKind::TableFooter => &FOOTER_FIELDS,
118 ElemKind::GridHLine | ElemKind::TableHLine => &HLINE_FIELDS,
119 ElemKind::GridVLine | ElemKind::TableVLine => &VLINE_FIELDS,
120 _ => &[],
121 }
122}
123
124/// Field ids of the grid family, fixed by the schemas above.
125pub mod fid {
126 use crate::eval::content::FieldId;
127
128 // grid, table
129 pub const COLUMNS: FieldId = FieldId(0);
130 pub const ROWS: FieldId = FieldId(1);
131 pub const COL_GUTTER: FieldId = FieldId(2);
132 pub const ROW_GUTTER: FieldId = FieldId(3);
133 pub const INSET: FieldId = FieldId(4);
134 pub const ALIGN: FieldId = FieldId(5);
135 pub const FILL: FieldId = FieldId(6);
136 pub const STROKE: FieldId = FieldId(7);
137 pub const CHILDREN: FieldId = FieldId(8);
138 // cells
139 pub const BODY: FieldId = FieldId(0);
140 pub const X: FieldId = FieldId(1);
141 pub const Y: FieldId = FieldId(2);
142 pub const COLSPAN: FieldId = FieldId(3);
143 pub const ROWSPAN: FieldId = FieldId(4);
144 pub const CELL_INSET: FieldId = FieldId(5);
145 pub const CELL_ALIGN: FieldId = FieldId(6);
146 pub const CELL_FILL: FieldId = FieldId(7);
147 pub const CELL_STROKE: FieldId = FieldId(8);
148 pub const BREAKABLE: FieldId = FieldId(9);
149 // headers and footers
150 pub const REPEAT: FieldId = FieldId(0);
151 pub const LEVEL: FieldId = FieldId(1);
152 pub const HEAD_CHILDREN: FieldId = FieldId(2);
153 pub const FOOT_CHILDREN: FieldId = FieldId(1);
154 // lines: `y` for an hline, `x` for a vline
155 pub const LINE_AT: FieldId = FieldId(0);
156 pub const LINE_START: FieldId = FieldId(1);
157 pub const LINE_END: FieldId = FieldId(2);
158 pub const LINE_STROKE: FieldId = FieldId(3);
159 pub const LINE_POS: FieldId = FieldId(4);
160}
161
162/// The `1pt + black` stroke Typst gives a table and every line by default.
163pub fn default_line_stroke() -> Value {
164 Value::Stroke(Arc::new(Stroke {
165 paint: Some(Paint::Color(Color { space: ColorSpace::Luma, c: [0.0, 0.0, 0.0, 0.0], alpha: 1.0 })),
166 thickness: Some(Length::pt(1.0)),
167 ..Stroke::default()
168 }))
169}
170
171/// A field's default where the schema holds `Computed`: Typst's value, exactly as `repr` shows it.
172pub fn computed_default(kind: ElemKind, field: FieldId) -> Option<Value> {
173 use fid::*;
174 match (kind, field) {
175 (ElemKind::Grid, INSET) | (ElemKind::Grid, STROKE) => Some(Value::dict(Default::default())),
176 (ElemKind::Table, INSET) => Some(Value::Relative(Relative { rel: Ratio(0.0), abs: Length::pt(5.0) })),
177 (ElemKind::Table, STROKE) => Some(default_line_stroke()),
178 (ElemKind::GridCell, CELL_STROKE) | (ElemKind::TableCell, CELL_STROKE)
179 => Some(Value::dict(Default::default())),
180 (ElemKind::GridHLine, LINE_STROKE) | (ElemKind::TableHLine, LINE_STROKE)
181 | (ElemKind::GridVLine, LINE_STROKE) | (ElemKind::TableVLine, LINE_STROKE)
182 => Some(default_line_stroke()),
183 (ElemKind::GridHLine, LINE_POS) | (ElemKind::TableHLine, LINE_POS)
184 => Some(Value::Alignment(Alignment { x: None, y: Some(VAlign::Top) })),
185 (ElemKind::GridVLine, LINE_POS) | (ElemKind::TableVLine, LINE_POS)
186 => Some(Value::Alignment(Alignment { x: Some(HAlign::Start), y: None })),
187 _ => None,
188 }
189}
190
191/// A field as a read shows it where nothing sets it: [`computed_default`], with a line's stroke as Typst holds it,
192/// a stroke whose paint and thickness are both `auto` (it reads as `1pt + black`), where layout draws
193/// [`default_line_stroke`].
194pub fn read_default(kind: ElemKind, field: FieldId) -> Option<Value> {
195 match computed_default(kind, field) {
196 Some(Value::Stroke(_)) => Some(Value::Stroke(Arc::new(Stroke::default()))),
197 other => other,
198 }
199}
200
201/// A field in force for an element in hand: its own value, a `set` rule's, or the default, computed
202/// defaults included.
203pub fn resolve(styles: &StyleChain, elem: &Content, field: FieldId) -> Outcome<Value> {
204 if let Some(v) = res!(styles.resolve(elem, field)) {
205 return Ok(v);
206 }
207 Ok(match elem.kind() {
208 Some(k) => computed_default(k, field).unwrap_or(Value::None),
209 None => Value::None,
210 })
211}
212
213/// Does the grid family hold this element as a child of a grid or table?
214pub fn is_grid_child(kind: ElemKind) -> bool { kind.family() == crate::eval::content::Family::Grid }
215
216/// The family's own kinds: (cell, header, footer, hline, vline) of a grid or of a table.
217pub fn family_of(kind: ElemKind) -> (ElemKind, ElemKind, ElemKind, ElemKind, ElemKind) {
218 match kind {
219 ElemKind::Table | ElemKind::TableCell | ElemKind::TableHeader | ElemKind::TableFooter
220 | ElemKind::TableHLine | ElemKind::TableVLine => (
221 ElemKind::TableCell, ElemKind::TableHeader, ElemKind::TableFooter,
222 ElemKind::TableHLine, ElemKind::TableVLine),
223 _ => (
224 ElemKind::GridCell, ElemKind::GridHeader, ElemKind::GridFooter,
225 ElemKind::GridHLine, ElemKind::GridVLine),
226 }
227}
228
229/// The track sizings of `columns`, `rows` and the gutters, normalised as Typst stores them: an integer is
230/// that many `auto`s, a single sizing is a one-element array, an array is checked element by element.
231fn track_sizings(engine: &mut Engine, span: Span, name: &str, v: Value) -> Outcome<Value> {
232 let one = |v: &Value| matches!(v,
233 Value::Auto | Value::Length(_) | Value::Ratio(_) | Value::Relative(_) | Value::Fraction(_));
234 match v {
235 Value::Int(n) if n >= 0 => Ok(Value::array(vec![Value::Auto; n as usize])),
236 Value::Array(a) => {
237 for item in a.iter() {
238 if !one(item) {
239 return Err(engine.error(DiagnosticKind::Type, span, fmt!(
240 "expected auto, relative length, or fraction, found {}", item.ty().name())));
241 }
242 }
243 Ok(Value::Array(a))
244 }
245 v if one(&v) => Ok(Value::array(vec![v])),
246 other => Err(engine.error(DiagnosticKind::Type, span, fmt!(
247 "{}: expected integer, auto, relative length, fraction, or array of the latter three, found {}",
248 name, other.ty().name()))),
249 }
250}
251
252/// Gutters are relative lengths in Typst's stored form (`2pt` is kept as `0% + 2pt`); a fraction stays one.
253fn gutter_sizings(engine: &mut Engine, span: Span, name: &str, v: Value) -> Outcome<Value> {
254 let v = res!(track_sizings(engine, span, name, v));
255 match v {
256 Value::Array(a) => Ok(Value::array(a.iter().map(|g| match g {
257 Value::Length(l) => Value::Relative(Relative { rel: Ratio(0.0), abs: *l }),
258 Value::Ratio(r) => Value::Relative(Relative { rel: *r, abs: Length::zero() }),
259 other => other.clone(),
260 }).collect())),
261 other => Ok(other),
262 }
263}
264
265/// Wraps a child that is not one of the family's own elements into the family's cell, and refuses a grid
266/// element inside a table and the reverse, with Typst's wording.
267fn wrap_child(
268 engine: &mut Engine,
269 span: Span,
270 parent: ElemKind,
271 v: Value,
272 in_part: bool,
273)
274 -> Outcome<Value>
275{
276 let (cell, header, footer, _, _) = family_of(parent);
277 let content = res!(cell_content(v));
278 if let Some(k) = content.kind() {
279 if is_grid_child(k) && k != ElemKind::Grid && k != ElemKind::Table {
280 let own = family_of(k).0 == cell;
281 if !own {
282 let (what, other) = match cell {
283 ElemKind::TableCell => ("table", "grid"),
284 _ => ("grid", "table"),
285 };
286 return Err(engine.error_hint(DiagnosticKind::Type, span,
287 fmt!("cannot use `{}.{}` as a {} cell", other, k.name(), what),
288 fmt!("use `{}.{}` instead", what, k.name())));
289 }
290 if in_part && (k == header || k == footer) {
291 return Err(engine.error(DiagnosticKind::Type, span, fmt!("cannot place a {} within another header or footer", k.path())));
292 }
293 return Ok(Value::Content(content));
294 }
295 }
296 Ok(Value::Content(Content::new(cell, vec![(fid::BODY, Value::Content(content))], span)))
297}
298
299/// A child as content: what Typst displays as content becomes a cell's body.
300fn cell_content(v: Value) -> Outcome<Content> {
301 match v {
302 Value::Content(c) => Ok(c),
303 Value::None => Ok(Content::empty()),
304 Value::Str(s) => Ok(Content::text(&s)),
305 Value::Int(i) => Ok(Content::text(&fmt!("{}", i))),
306 Value::Float(f) => Ok(Content::text(&fmt!("{}", f))),
307 Value::Symbol(s) => Ok(Content::symbol(&crate::eval::ops::symbol_text(&s))),
308 other => Err(err!("expected content, found {}", other.ty().name(); Input, Mismatch)),
309 }
310}
311
312pub fn construct(engine: &mut Engine, kind: ElemKind, args: &mut Args) -> Outcome<Option<Content>> {
313 let span = args.span;
314 match kind {
315 ElemKind::Grid | ElemKind::Table => {
316 let mut fields: Vec<(FieldId, Value)> = Vec::new();
317 if let Some(v) = res!(args.named::<Value>("columns")) {
318 fields.push((fid::COLUMNS, res!(track_sizings(engine, span, "columns", v))));
319 }
320 if let Some(v) = res!(args.named::<Value>("rows")) {
321 fields.push((fid::ROWS, res!(track_sizings(engine, span, "rows", v))));
322 }
323 let gutter = res!(args.named::<Value>("gutter"));
324 let cg = res!(args.named::<Value>("column-gutter")).or_else(|| gutter.clone());
325 let rg = res!(args.named::<Value>("row-gutter")).or(gutter);
326 if let Some(v) = cg {
327 fields.push((fid::COL_GUTTER, res!(gutter_sizings(engine, span, "column-gutter", v))));
328 }
329 if let Some(v) = rg {
330 fields.push((fid::ROW_GUTTER, res!(gutter_sizings(engine, span, "row-gutter", v))));
331 }
332 for (id, name) in [(fid::INSET, "inset"), (fid::ALIGN, "align"), (fid::FILL, "fill"), (fid::STROKE, "stroke")] {
333 if let Some(v) = res!(args.named::<Value>(name)) {
334 fields.push((id, v));
335 }
336 }
337 let mut children = Vec::new();
338 for v in res!(args.all::<Value>()) {
339 children.push(res!(wrap_child(engine, span, kind, v, false)));
340 }
341 fields.push((fid::CHILDREN, Value::array(children)));
342 res!(std::mem::take(args).finish());
343 Ok(Some(Content::new(kind, fields, span)))
344 }
345 ElemKind::GridHeader | ElemKind::TableHeader | ElemKind::GridFooter | ElemKind::TableFooter => {
346 let is_head = matches!(kind, ElemKind::GridHeader | ElemKind::TableHeader);
347 let mut fields: Vec<(FieldId, Value)> = Vec::new();
348 if let Some(v) = res!(args.named::<Value>("repeat")) {
349 fields.push((fid::REPEAT, v));
350 }
351 if is_head {
352 if let Some(v) = res!(args.named::<Value>("level")) {
353 match v {
354 Value::Int(n) if n >= 1 => fields.push((fid::LEVEL, v)),
355 _ => return Err(engine.error(DiagnosticKind::Type, span, "number must be positive")),
356 }
357 }
358 }
359 let mut children = Vec::new();
360 for v in res!(args.all::<Value>()) {
361 let c = res!(wrap_child(engine, span, kind, v, true));
362 children.push(c);
363 }
364 let at = if is_head { fid::HEAD_CHILDREN } else { fid::FOOT_CHILDREN };
365 fields.push((at, Value::array(children)));
366 res!(std::mem::take(args).finish());
367 Ok(Some(Content::new(kind, fields, span)))
368 }
369 ElemKind::GridCell | ElemKind::TableCell => {
370 // The generic walk, then Typst's range checks on the spans.
371 for name in ["colspan", "rowspan"] {
372 if let Some(Value::Int(n)) = args.items.iter().find(|a| a.name.as_deref() == Some(name)).map(|a| &a.value) {
373 if *n < 1 {
374 return Err(engine.error(DiagnosticKind::Type, span, "number must be positive"));
375 }
376 }
377 }
378 Ok(None)
379 }
380 _ => Ok(None),
381 }
382}
383
384/// A cell realises as Typst's does: its body padded by the resolved inset, under the resolved alignment.
385/// Grids, tables, headers, footers and lines are primitives the grid flow lays out itself.
386pub fn show(engine: &mut Engine, elem: &Content, _styles: &StyleChain) -> Outcome<Option<Content>> {
387 match elem.kind() {
388 Some(ElemKind::GridCell | ElemKind::TableCell) => (),
389 _ => return Ok(None),
390 }
391 let span = elem.span();
392 let mut body = match elem.get(fid::BODY) {
393 Some(v) => res!(cell_content(v.clone())),
394 None => Content::empty(),
395 };
396 if let Some(Value::Dict(d)) = elem.get(fid::CELL_INSET) {
397 let zero = |v: Option<&Value>| match v {
398 None | Some(Value::None) => true,
399 Some(Value::Length(l)) => l.abs == 0.0 && l.em == 0.0,
400 Some(Value::Relative(r)) => r.rel.0 == 0.0 && r.abs.abs == 0.0 && r.abs.em == 0.0,
401 Some(Value::Ratio(r)) => r.0 == 0.0,
402 Some(_) => false,
403 };
404 if !["left", "top", "right", "bottom"].iter().all(|k| zero(d.get(k))) {
405 let mut fields = Vec::new();
406 for k in ["left", "top", "right", "bottom"] {
407 if let Some(v) = d.get(k) {
408 let id = res!(layout_field(engine, span, ElemKind::Pad, k));
409 fields.push((id, v.clone()));
410 }
411 }
412 let id = res!(layout_field(engine, span, ElemKind::Pad, "body"));
413 fields.push((id, Value::Content(body)));
414 body = Content::new(ElemKind::Pad, fields, span);
415 }
416 }
417 if let Some(Value::Alignment(a)) = elem.get(fid::CELL_ALIGN) {
418 let field = res!(layout_field(engine, span, ElemKind::Align, "alignment"));
419 body = body.styled(Styles::from_style(Style::Property(Property {
420 elem: ElemKind::Align, field, value: Value::Alignment(*a), span, liftable: false, outside: false,
421 })));
422 }
423 Ok(Some(body))
424}
425
426/// A field of a layout element the cell realises into; the layout family's schema is U6b's.
427fn layout_field(engine: &mut Engine, span: Span, kind: ElemKind, name: &str) -> Outcome<FieldId> {
428 match kind.field_id(name) {
429 Some(id) => Ok(id),
430 None => Err(engine.error(DiagnosticKind::Type, span, fmt!("{} has no field `{}`, which a grid cell needs", kind.path(), name))),
431 }
432}