oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/layout.rs
26.2 KiB, 33 runs
created by r1870400018:63242, 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/*`, version 0.15.1). |
| 3 | // Modified for Austenite: ported to Hematite's types, IR and error handling. |
| 4 | // U6b owns this file. Schemas for the layout family (box, block, align, pad, stack, h, v, place, columns, |
| 5 | // colbreak, pagebreak, page), with Typst 0.15's defaults. `align` shows as its body under the alignment |
| 6 | // style and `page(..)[body]` constructs a page-bounded sequence, as Typst's do; every other element is a |
| 7 | // primitive flow lays out itself, so its `show` is `None`. |
| 8 | // |
| 9 | // Typst parses a few arguments that are no field of their element: `block(spacing:)`, `pad(x:, y:, rest:)` |
| 10 | // and `page(paper:)`. A constructor call spreads them into the real fields here. A `set` rule stores them |
| 11 | // as settable fields of their own, and flow resolves the real field from whichever of the two is nearer in |
| 12 | // the style chain, which is what Typst's spreading at parse time amounts to. |
| 13 | |
| 14 | use crate::eval::args::Args; |
| 15 | use crate::diag::DiagnosticKind; |
| 16 | use crate::eval::content::{ |
| 17 | Content, |
| 18 | ElemKind, |
| 19 | FieldDefault, |
| 20 | FieldId, |
| 21 | FieldSpec, |
| 22 | FieldType, |
| 23 | Fold, |
| 24 | }; |
| 25 | use crate::eval::lib::foundations::{ |
| 26 | keyword, |
| 27 | keyword_message, |
| 28 | }; |
| 29 | use crate::eval::lib::visual as vis; |
| 30 | use crate::eval::scope::Scope; |
| 31 | use crate::eval::styles::{ |
| 32 | self, |
| 33 | Property, |
| 34 | Style, |
| 35 | StyleChain, |
| 36 | Styles, |
| 37 | }; |
| 38 | use crate::eval::value::{ |
| 39 | Alignment, |
| 40 | Dict, |
| 41 | HAlign, |
| 42 | Length, |
| 43 | Type, |
| 44 | Value, |
| 45 | }; |
| 46 | use crate::eval::Engine; |
| 47 | |
| 48 | use oxedyne_fe2o3_core::prelude::*; |
| 49 | |
| 50 | native_fns! { |
| 51 | pub enum LayoutFn { |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Schemas |
| 56 | |
| 57 | const ANY: FieldType = FieldType::Any; |
| 58 | const BOOL: FieldType = FieldType::Of(Type::Bool); |
| 59 | const SPACING: FieldType = FieldType::OneOf(&[Type::Length, Type::Ratio, Type::Relative, Type::Fraction]); |
| 60 | |
| 61 | const BOX: &[FieldSpec] = &[ |
| 62 | FieldSpec::named("width", ANY, FieldDefault::Auto), |
| 63 | FieldSpec::named("height", ANY, FieldDefault::Auto), |
| 64 | FieldSpec::named("baseline", ANY, FieldDefault::Auto), |
| 65 | FieldSpec::named("fill", ANY, FieldDefault::None), |
| 66 | FieldSpec::named("stroke", ANY, FieldDefault::None).fold(Fold::Sides), |
| 67 | FieldSpec::named("radius", ANY, FieldDefault::Pt(0.0)).fold(Fold::Corners), |
| 68 | FieldSpec::named("inset", ANY, FieldDefault::Pt(0.0)).fold(Fold::Sides), |
| 69 | FieldSpec::named("outset", ANY, FieldDefault::Pt(0.0)).fold(Fold::Sides), |
| 70 | FieldSpec::named("clip", BOOL, FieldDefault::Bool(false)), |
| 71 | FieldSpec::named("body", FieldType::Content, FieldDefault::None).positional().unsettable(), |
| 72 | ]; |
| 73 | |
| 74 | // `spacing` is Typst's shorthand for both `above` and `below`; see the file header. The three have no |
| 75 | // static default: unset, the spacing is the paragraph spacing, which flow reads. |
| 76 | const BLOCK: &[FieldSpec] = &[ |
| 77 | FieldSpec::named("width", ANY, FieldDefault::Auto), |
| 78 | FieldSpec::named("height", ANY, FieldDefault::Auto), |
| 79 | FieldSpec::named("breakable", BOOL, FieldDefault::Bool(true)), |
| 80 | FieldSpec::named("fill", ANY, FieldDefault::None), |
| 81 | FieldSpec::named("stroke", ANY, FieldDefault::None).fold(Fold::Sides), |
| 82 | FieldSpec::named("radius", ANY, FieldDefault::Pt(0.0)).fold(Fold::Corners), |
| 83 | FieldSpec::named("inset", ANY, FieldDefault::Pt(0.0)).fold(Fold::Sides), |
| 84 | FieldSpec::named("outset", ANY, FieldDefault::Pt(0.0)).fold(Fold::Sides), |
| 85 | FieldSpec::named("spacing", ANY, FieldDefault::Computed), |
| 86 | FieldSpec::named("above", ANY, FieldDefault::Computed), |
| 87 | FieldSpec::named("below", ANY, FieldDefault::Computed), |
| 88 | FieldSpec::named("clip", BOOL, FieldDefault::Bool(false)), |
| 89 | FieldSpec::named("sticky", BOOL, FieldDefault::Bool(false)), |
| 90 | FieldSpec::named("body", FieldType::Content, FieldDefault::None).positional().unsettable(), |
| 91 | ]; |
| 92 | |
| 93 | // Alignment folds axis by axis (`set align(center)` then `align(horizon)` is centre-horizon); flow folds |
| 94 | // the chain's values itself, so the field is stored as set. Its default is `start + top`. |
| 95 | const ALIGN: &[FieldSpec] = &[ |
| 96 | FieldSpec::named("alignment", FieldType::Of(Type::Alignment), FieldDefault::Computed).positional(), |
| 97 | FieldSpec::required("body", FieldType::Content), |
| 98 | ]; |
| 99 | |
| 100 | // `x`, `y` and `rest` spread into the sides; see the file header. |
| 101 | const PAD: &[FieldSpec] = &[ |
| 102 | FieldSpec::named("left", ANY, FieldDefault::Pt(0.0)), |
| 103 | FieldSpec::named("top", ANY, FieldDefault::Pt(0.0)), |
| 104 | FieldSpec::named("right", ANY, FieldDefault::Pt(0.0)), |
| 105 | FieldSpec::named("bottom", ANY, FieldDefault::Pt(0.0)), |
| 106 | FieldSpec::named("x", ANY, FieldDefault::Computed), |
| 107 | FieldSpec::named("y", ANY, FieldDefault::Computed), |
| 108 | FieldSpec::named("rest", ANY, FieldDefault::Computed), |
| 109 | FieldSpec::required("body", FieldType::Content), |
| 110 | ]; |
| 111 | |
| 112 | const STACK: &[FieldSpec] = &[ |
| 113 | FieldSpec::named("dir", FieldType::Of(Type::Direction), FieldDefault::Computed), |
| 114 | FieldSpec::named("spacing", ANY, FieldDefault::None), |
| 115 | FieldSpec::named("children", ANY, FieldDefault::EmptyArray).variadic().unsettable(), |
| 116 | ]; |
| 117 | |
| 118 | const H: &[FieldSpec] = &[ |
| 119 | FieldSpec::required("amount", SPACING), |
| 120 | FieldSpec::named("weak", BOOL, FieldDefault::Bool(false)), |
| 121 | ]; |
| 122 | |
| 123 | // `attach` is Typst's internal marker for spacing that only survives straight after a paragraph. |
| 124 | const V: &[FieldSpec] = &[ |
| 125 | FieldSpec::required("amount", SPACING), |
| 126 | FieldSpec::named("weak", BOOL, FieldDefault::Bool(false)), |
| 127 | FieldSpec::named("attach", BOOL, FieldDefault::Bool(false)).unsettable(), |
| 128 | ]; |
| 129 | |
| 130 | // Keyword choices |
| 131 | const PLACE_SCOPE: &str = "\"column\" or \"parent\""; |
| 132 | const BREAK_TO: &str = "\"even\", \"odd\", or none"; |
| 133 | |
| 134 | const PLACE: &[FieldSpec] = &[ |
| 135 | FieldSpec::named("alignment", FieldType::OneOf(&[Type::Alignment, Type::Auto]), FieldDefault::Computed).positional(), |
| 136 | FieldSpec::named("scope", FieldType::Keyword(&[], PLACE_SCOPE), FieldDefault::Str("column")), |
| 137 | FieldSpec::named("float", BOOL, FieldDefault::Bool(false)), |
| 138 | FieldSpec::named("clearance", ANY, FieldDefault::Em(1.5)), |
| 139 | FieldSpec::named("dx", ANY, FieldDefault::Pt(0.0)), |
| 140 | FieldSpec::named("dy", ANY, FieldDefault::Pt(0.0)), |
| 141 | FieldSpec::required("body", FieldType::Content), |
| 142 | ]; |
| 143 | |
| 144 | const COLUMNS: &[FieldSpec] = &[ |
| 145 | FieldSpec::named("count", FieldType::Of(Type::Int), FieldDefault::Int(2)).positional(), |
| 146 | FieldSpec::named("gutter", ANY, FieldDefault::Ratio(0.04)), |
| 147 | FieldSpec::required("body", FieldType::Content), |
| 148 | ]; |
| 149 | |
| 150 | const COLBREAK: &[FieldSpec] = &[ |
| 151 | FieldSpec::named("weak", BOOL, FieldDefault::Bool(false)), |
| 152 | ]; |
| 153 | |
| 154 | // `boundary` marks the break realisation puts after a `set page` scope; it is never passed. |
| 155 | const PAGEBREAK: &[FieldSpec] = &[ |
| 156 | FieldSpec::named("weak", BOOL, FieldDefault::Bool(false)), |
| 157 | FieldSpec::named("to", ANY, FieldDefault::None), |
| 158 | FieldSpec::named("boundary", BOOL, FieldDefault::Bool(false)).unsettable(), |
| 159 | ]; |
| 160 | |
| 161 | // `paper` spreads into `width` and `height` (see the file header), so it precedes them: within one `set`, |
| 162 | // an explicit width or height is the nearer of the two. |
| 163 | const PAGE: &[FieldSpec] = &[ |
| 164 | FieldSpec::named("paper", ANY, FieldDefault::Str("a4")).positional(), // a keyword: `cast_field` checks it |
| 165 | FieldSpec::named("width", ANY, FieldDefault::Computed), |
| 166 | FieldSpec::named("height", ANY, FieldDefault::Computed), |
| 167 | FieldSpec::named("flipped", BOOL, FieldDefault::Bool(false)), |
| 168 | FieldSpec::named("margin", ANY, FieldDefault::Auto).fold(Fold::Sides), |
| 169 | FieldSpec::named("bleed", ANY, FieldDefault::Pt(0.0)).fold(Fold::Sides), |
| 170 | FieldSpec::named("binding", ANY, FieldDefault::Auto), |
| 171 | FieldSpec::named("columns", FieldType::Of(Type::Int), FieldDefault::Int(1)), |
| 172 | FieldSpec::named("fill", ANY, FieldDefault::Auto), |
| 173 | FieldSpec::named("numbering", ANY, FieldDefault::None), |
| 174 | FieldSpec::named("supplement", ANY, FieldDefault::Auto), |
| 175 | FieldSpec::named("number-align", ANY, FieldDefault::Computed), |
| 176 | FieldSpec::named("header", ANY, FieldDefault::Auto), |
| 177 | FieldSpec::named("header-ascent", ANY, FieldDefault::Ratio(0.3)), |
| 178 | FieldSpec::named("footer", ANY, FieldDefault::Auto), |
| 179 | FieldSpec::named("footer-descent", ANY, FieldDefault::Ratio(0.3)), |
| 180 | FieldSpec::named("background", ANY, FieldDefault::None), |
| 181 | FieldSpec::named("foreground", ANY, FieldDefault::None), |
| 182 | FieldSpec::required("body", FieldType::Content), |
| 183 | ]; |
| 184 | |
| 185 | pub fn fields(kind: ElemKind) -> &'static [FieldSpec] { |
| 186 | match kind { |
| 187 | ElemKind::Box => BOX, |
| 188 | ElemKind::Block => BLOCK, |
| 189 | ElemKind::Align => ALIGN, |
| 190 | ElemKind::Pad => PAD, |
| 191 | ElemKind::Stack => STACK, |
| 192 | ElemKind::H => H, |
| 193 | ElemKind::V => V, |
| 194 | ElemKind::Place => PLACE, |
| 195 | ElemKind::PlaceFlush => &[], |
| 196 | ElemKind::Columns => COLUMNS, |
| 197 | ElemKind::Colbreak => COLBREAK, |
| 198 | ElemKind::Pagebreak => PAGEBREAK, |
| 199 | ElemKind::Page => PAGE, |
| 200 | _ => &[], |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | /// The field's id in the element's schema. Every name passed here is one this file declares. |
| 205 | pub fn fid(kind: ElemKind, name: &str) -> Outcome<FieldId> { |
| 206 | kind.field_id(name).ok_or_else(|| err!( |
| 207 | "{} has no field `{}` in its schema.", kind.path(), name; Bug, Missing)) |
| 208 | } |
| 209 | |
| 210 | // Library |
| 211 | |
| 212 | pub fn define(_scope: &mut Scope) {} |
| 213 | |
| 214 | pub fn call(f: LayoutFn, _engine: &mut Engine, _args: Args) -> Outcome<Value> { |
| 215 | match f {} |
| 216 | } |
| 217 | |
| 218 | // Construction |
| 219 | |
| 220 | /// Spreads the shorthand arguments Typst parses into real fields, then leaves the element to the generic |
| 221 | /// schema walk; `page(..)[body]` alone builds something else, a page-bounded sequence. |
| 222 | pub fn construct(engine: &mut Engine, kind: ElemKind, args: &mut Args) -> Outcome<Option<Content>> { |
| 223 | match kind { |
| 224 | ElemKind::Page => construct_page(engine, args).map(Some), |
| 225 | ElemKind::H | ElemKind::V => { |
| 226 | // The amount is checked here for Typst's own message. |
| 227 | if let Some(a) = args.items.iter().find(|a| a.name.is_none()) { |
| 228 | if !SPACING.accepts(&a.value) { |
| 229 | let msg = fmt!("expected relative length or fraction, found {}", |
| 230 | a.value.ty().long_name()); |
| 231 | return Err(engine.error(DiagnosticKind::Type, a.span, msg)); |
| 232 | } |
| 233 | } |
| 234 | Ok(None) |
| 235 | }, |
| 236 | _ => { |
| 237 | res!(spread(kind, args)); |
| 238 | Ok(None) |
| 239 | }, |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | /// Rewrites the arguments Typst parses into other fields: `block(spacing:)` into whichever of `above` and |
| 244 | /// `below` is not given, `pad(x:, y:, rest:)` into the sides by Typst's precedence (a side, then its axis, |
| 245 | /// then `rest`). A `set` rule wants the same rewriting before its arguments become styles. |
| 246 | pub fn spread(kind: ElemKind, args: &mut Args) -> Outcome<()> { |
| 247 | let span = args.span; |
| 248 | match kind { |
| 249 | ElemKind::Block => { |
| 250 | if let Some(s) = res!(args.named::<Value>("spacing")) { |
| 251 | if !has_named(args, "above") { |
| 252 | args.push_named(span, "above", s.clone()); |
| 253 | } |
| 254 | if !has_named(args, "below") { |
| 255 | args.push_named(span, "below", s); |
| 256 | } |
| 257 | } |
| 258 | }, |
| 259 | ElemKind::Pad => { |
| 260 | let mut rest = res!(args.named::<Value>("rest")); |
| 261 | // `rest` is also the first positional, ahead of the body: `pad(1em)[..]`. |
| 262 | if rest.is_none() && args.items.iter().filter(|a| a.name.is_none()).count() > 1 { |
| 263 | if let Some(i) = args.items.iter().position(|a| a.name.is_none()) { |
| 264 | if matches!(args.items[i].value, Value::Length(_) | Value::Relative(_) | Value::Ratio(_)) { |
| 265 | rest = Some(args.items.remove(i).value); |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | let x = res!(args.named::<Value>("x")).or_else(|| rest.clone()); |
| 270 | let y = res!(args.named::<Value>("y")).or(rest); |
| 271 | for (side, v) in [("left", &x), ("right", &x), ("top", &y), ("bottom", &y)] { |
| 272 | if let Some(v) = v { |
| 273 | if !has_named(args, side) { |
| 274 | args.push_named(span, side, v.clone()); |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | }, |
| 279 | _ => (), |
| 280 | } |
| 281 | Ok(()) |
| 282 | } |
| 283 | |
| 284 | fn has_named(args: &Args, name: &str) -> bool { |
| 285 | args.items.iter().any(|a| a.name.as_deref() == Some(name)) |
| 286 | } |
| 287 | |
| 288 | /// `page(..)[body]`: no page element, but the body set apart on pages of its own under the page styles -- |
| 289 | /// a weak break before, a flush so the page is kept even when the body is empty, the body, and a boundary |
| 290 | /// break after, as Typst's constructor builds it. |
| 291 | fn construct_page(engine: &mut Engine, args: &mut Args) -> Outcome<Content> { |
| 292 | let span = args.span; |
| 293 | let body = match args.items.iter().rposition(|a| a.name.is_none()) { |
| 294 | Some(i) => { |
| 295 | let a = args.items.remove(i); |
| 296 | res!(a.value.cast::<Content>()) |
| 297 | }, |
| 298 | None => return Err(engine.error(DiagnosticKind::Type, span, "missing argument: body")), |
| 299 | }; |
| 300 | let styles = res!(styles::set_rule(engine, ElemKind::Page, std::mem::take(args))); |
| 301 | Ok(Content::sequence(vec![ |
| 302 | pagebreak(true, false), |
| 303 | Content::marker(ElemKind::PlaceFlush, span), |
| 304 | body, |
| 305 | pagebreak(true, true), |
| 306 | ]).styled(styles)) |
| 307 | } |
| 308 | |
| 309 | /// A page break as realisation and `page(..)` produce them. |
| 310 | pub fn pagebreak(weak: bool, boundary: bool) -> Content { |
| 311 | let mut fields = Vec::new(); |
| 312 | if let Some(id) = ElemKind::Pagebreak.field_id("weak") { |
| 313 | fields.push((id, Value::Bool(weak))); |
| 314 | } |
| 315 | if boundary { |
| 316 | if let Some(id) = ElemKind::Pagebreak.field_id("boundary") { |
| 317 | fields.push((id, Value::Bool(true))); |
| 318 | } |
| 319 | } |
| 320 | Content::new(ElemKind::Pagebreak, fields, crate::syntax::Span::detached()) |
| 321 | } |
| 322 | |
| 323 | // Casts |
| 324 | |
| 325 | /// Casts a field's value to Typst's type for it, for a constructor and for a `set` rule alike, with Typst's |
| 326 | /// wording when the value is refused. Every cast is idempotent: flow reads the stored value again. |
| 327 | pub fn cast_field(kind: ElemKind, name: &str, v: Value) -> Outcome<Value> { |
| 328 | use ElemKind as K; |
| 329 | match (kind, name) { |
| 330 | (K::Box, "width") | (K::Block, "height") => sizing(v), |
| 331 | (K::Box, "height") | (K::Block, "width") => smart_rel(v), |
| 332 | (K::Box, "baseline") => baseline(v), |
| 333 | (K::Box | K::Block, "fill") => vis::cast_fill(v), |
| 334 | (K::Box | K::Block, "stroke") => vis::cast_stroke_sides(v), |
| 335 | (K::Box | K::Block, "radius") => vis::cast_corners_rel(v), |
| 336 | (K::Box | K::Block, "inset") | (K::Box | K::Block, "outset") |
| 337 | => vis::cast_sides_rel(v), |
| 338 | (K::Block, "spacing") | (K::Block, "above") | (K::Block, "below") => match v { |
| 339 | Value::Auto => Ok(v), |
| 340 | other => spacing(other), |
| 341 | }, |
| 342 | (_, "clip") | (_, "breakable") | (_, "sticky") | (_, "weak") | (_, "float") | (_, "flipped") |
| 343 | | (_, "boundary") | (_, "attach") => Ok(Value::Bool(res!(v.cast::<bool>()))), |
| 344 | (K::Align, "alignment") => Ok(Value::Alignment(res!(v.cast::<Alignment>()))), |
| 345 | (K::Place, "alignment") => match v { |
| 346 | Value::Auto => Ok(v), |
| 347 | other => Ok(Value::Alignment(res!(other.cast::<Alignment>()))), |
| 348 | }, |
| 349 | (K::Pad, _) if name != "body" => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 350 | (K::Stack, "dir") => match v { |
| 351 | Value::Direction(_) => Ok(v), |
| 352 | other => Err(mismatch("direction", &other)), |
| 353 | }, |
| 354 | (K::Stack, "spacing") => match v { |
| 355 | Value::None => Ok(v), |
| 356 | other => spacing(other), |
| 357 | }, |
| 358 | (K::H | K::V, "amount") => spacing(v), |
| 359 | (K::Place, "scope") => Ok(Value::Str(res!(keyword(&v, &["column", "parent"], PLACE_SCOPE)))), |
| 360 | (K::Place, "clearance") => Ok(Value::Length(res!(vis::cast_length(v)))), |
| 361 | (K::Place, "dx") | (K::Place, "dy") => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 362 | (K::Columns, "count") | (K::Page, "columns") => { |
| 363 | let n = res!(v.cast::<i64>()); |
| 364 | if n <= 0 { |
| 365 | return Err(err!("number must be positive"; Input, Invalid)); |
| 366 | } |
| 367 | Ok(Value::Int(n)) |
| 368 | }, |
| 369 | (K::Columns, "gutter") => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 370 | (K::Pagebreak, "to") => match v { |
| 371 | Value::None => Ok(v), |
| 372 | other => Ok(Value::Str(res!(keyword(&other, &["even", "odd"], BREAK_TO)))), |
| 373 | }, |
| 374 | (K::Page, "paper") => match &v { |
| 375 | Value::Str(s) if paper(s).is_some() => Ok(v), |
| 376 | _ => { |
| 377 | // Typst names every paper it knows, in its table's order. |
| 378 | let names: Vec<String> = PAPERS.iter().map(|(n, _, _)| fmt!("\"{}\"", n)).collect(); |
| 379 | let (last, rest) = match names.split_last() { |
| 380 | Some(x) => x, |
| 381 | None => return Err(err!("unknown paper size"; Input, Invalid)), |
| 382 | }; |
| 383 | Err(err!("{}", keyword_message(&fmt!("{}, or {}", rest.join(", "), last), &v); Input, Invalid)) |
| 384 | }, |
| 385 | }, |
| 386 | (K::Page, "width") | (K::Page, "height") => match v { |
| 387 | Value::Auto => Ok(v), |
| 388 | other => Ok(Value::Length(res!(vis::cast_length(other)))), |
| 389 | }, |
| 390 | (K::Page, "margin") => margin(v), |
| 391 | (K::Page, "bleed") => vis::cast_sides_rel(v), |
| 392 | (K::Page, "binding") => match v { |
| 393 | Value::Auto => Ok(v), |
| 394 | Value::Alignment(Alignment { x: Some(HAlign::Left), y: None }) |
| 395 | | Value::Alignment(Alignment { x: Some(HAlign::Right), y: None }) => Ok(v), |
| 396 | Value::Alignment(_) => Err(err!("must be `left` or `right`"; Input, Invalid)), |
| 397 | other => Err(mismatch("alignment or auto", &other)), |
| 398 | }, |
| 399 | (K::Page, "fill") => match v { |
| 400 | Value::Auto => Ok(v), |
| 401 | other => vis::cast_fill(other), |
| 402 | }, |
| 403 | (K::Page, "numbering") => match v { |
| 404 | Value::None | Value::Str(_) | Value::Func(_) => Ok(v), |
| 405 | other => Err(mismatch("string, function, or none", &other)), |
| 406 | }, |
| 407 | (K::Page, "number-align") => Ok(Value::Alignment(res!(v.cast::<Alignment>()))), |
| 408 | (K::Page, "header-ascent") | (K::Page, "footer-descent") |
| 409 | => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 410 | (K::Page, "supplement") | (K::Page, "header") | (K::Page, "footer") => match v { |
| 411 | Value::Auto | Value::None => Ok(v), |
| 412 | other => Ok(Value::Content(res!(other.cast::<Content>()))), |
| 413 | }, |
| 414 | (K::Page, "background") | (K::Page, "foreground") => match v { |
| 415 | Value::None => Ok(v), |
| 416 | other => Ok(Value::Content(res!(other.cast::<Content>()))), |
| 417 | }, |
| 418 | _ => Ok(v), |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | fn mismatch(expected: &str, found: &Value) -> Error<ErrTag> { |
| 423 | err!("expected {}, found {}", expected, found.ty().long_name(); Input, Mismatch) |
| 424 | } |
| 425 | |
| 426 | // Typst's `Sizing`: `auto`, a relative length or a fraction. |
| 427 | fn sizing(v: Value) -> Outcome<Value> { |
| 428 | match v { |
| 429 | Value::Auto | Value::Fraction(_) => Ok(v), |
| 430 | Value::Relative(_) | Value::Length(_) | Value::Ratio(_) => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 431 | other => Err(mismatch("relative length, fraction, or auto", &other)), |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | fn smart_rel(v: Value) -> Outcome<Value> { |
| 436 | match v { |
| 437 | Value::Auto => Ok(v), |
| 438 | Value::Relative(_) | Value::Length(_) | Value::Ratio(_) => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 439 | other => Err(mismatch("relative length or auto", &other)), |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | // Typst's `Spacing`: a relative length or a fraction. |
| 444 | fn spacing(v: Value) -> Outcome<Value> { |
| 445 | match v { |
| 446 | Value::Fraction(_) => Ok(v), |
| 447 | Value::Relative(_) | Value::Length(_) | Value::Ratio(_) => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 448 | other => Err(mismatch("relative length or fraction", &other)), |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | // A box's baseline: an alignment or `auto` (where), a relative length (a shift), or both in a dictionary. |
| 453 | fn baseline(v: Value) -> Outcome<Value> { |
| 454 | match v { |
| 455 | Value::Auto | Value::Alignment(_) => Ok(v), |
| 456 | Value::Relative(_) | Value::Length(_) | Value::Ratio(_) => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 457 | Value::Dict(d) => { |
| 458 | let mut out = Dict::new(); |
| 459 | for (k, x) in d.iter() { |
| 460 | match k { |
| 461 | "at" => out.insert(k, match x { |
| 462 | Value::Auto | Value::Alignment(_) => x.clone(), |
| 463 | other => return Err(mismatch("alignment or auto", other)), |
| 464 | }), |
| 465 | "shift" => out.insert(k, Value::Relative(res!(vis::cast_rel(x.clone())))), |
| 466 | other => return Err(err!("unexpected key \"{}\", valid keys are \"at\" and \"shift\"", other; |
| 467 | Input, Invalid)), |
| 468 | } |
| 469 | } |
| 470 | Ok(Value::dict(out)) |
| 471 | }, |
| 472 | other => Err(mismatch("relative length, alignment, dictionary, or auto", &other)), |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | // A page margin: `auto`, one relative length, or a dictionary of sides that may each be `auto`, where |
| 477 | // `inside` and `outside` exclude `left` and `right`. |
| 478 | fn margin(v: Value) -> Outcome<Value> { |
| 479 | match v { |
| 480 | Value::Auto => Ok(v), |
| 481 | Value::Relative(_) | Value::Length(_) | Value::Ratio(_) => Ok(Value::Relative(res!(vis::cast_rel(v)))), |
| 482 | Value::Dict(d) => { |
| 483 | let two = d.contains("inside") || d.contains("outside"); |
| 484 | let one = d.contains("left") || d.contains("right"); |
| 485 | if two && one { |
| 486 | return Err(err!("`inside` and `outside` are mutually exclusive with `left` and `right`"; |
| 487 | Input, Invalid)); |
| 488 | } |
| 489 | let mut out = Dict::new(); |
| 490 | for (k, x) in d.iter() { |
| 491 | match k { |
| 492 | "left" | "top" | "right" | "bottom" | "inside" | "outside" | "x" | "y" | "rest" => { |
| 493 | let cast = match x { |
| 494 | Value::Auto => Value::Auto, |
| 495 | other => Value::Relative(res!(vis::cast_rel(other.clone()))), |
| 496 | }; |
| 497 | out.insert(k, cast); |
| 498 | }, |
| 499 | other => return Err(err!("unexpected key \"{}\", valid keys are \"left\", \"top\", \"right\", \ |
| 500 | \"bottom\", \"outside\", \"inside\", \"x\", \"y\", and \"rest\"", other; Input, Invalid)), |
| 501 | } |
| 502 | } |
| 503 | Ok(Value::dict(out)) |
| 504 | }, |
| 505 | other => Err(mismatch("relative length, auto, or dictionary", &other)), |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | // Show |
| 510 | |
| 511 | pub fn show(_engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Option<Content>> { |
| 512 | match elem.kind() { |
| 513 | // `align` is its body under the alignment style; flow aligns every block and line by it. |
| 514 | Some(ElemKind::Align) => { |
| 515 | let body = match elem.field("body") { |
| 516 | Some(v) => res!(v.clone().cast::<Content>()), |
| 517 | None => Content::empty(), |
| 518 | }; |
| 519 | let id = res!(fid(ElemKind::Align, "alignment")); |
| 520 | let value = match res!(styles.resolve(elem, id)) { |
| 521 | Some(v) => v, |
| 522 | None => return Ok(Some(body)), |
| 523 | }; |
| 524 | let set = Styles::from_style(Style::Property(Property::new(ElemKind::Align, id, value, elem.span()))); |
| 525 | Ok(Some(body.styled(set))) |
| 526 | }, |
| 527 | _ => Ok(None), |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | // Paper sizes |
| 532 | |
| 533 | /// The page's width and height as the chain sets them, each the nearer of its own setting and a `paper`, |
| 534 | /// which sets both, else A4's: a length or `auto`, unresolved. `flipped` does not swap them, as in Typst. |
| 535 | pub fn page_dims(styles: &StyleChain) -> (Value, Value) { |
| 536 | let ids = ( |
| 537 | ElemKind::Page.field_id("width"), |
| 538 | ElemKind::Page.field_id("height"), |
| 539 | ElemKind::Page.field_id("paper"), |
| 540 | ); |
| 541 | let (mut w, mut h): (Option<Value>, Option<Value>) = (None, None); |
| 542 | for s in styles.walk() { |
| 543 | let p = match s { |
| 544 | Style::Property(p) if p.elem == ElemKind::Page => p, |
| 545 | _ => continue, |
| 546 | }; |
| 547 | let field = Some(p.field); |
| 548 | if field == ids.2 { |
| 549 | if let Value::Str(name) = &p.value { |
| 550 | if let Some((pw, ph)) = paper(name) { |
| 551 | w = w.or(Some(Value::Length(Length::pt(pw * PT_PER_MM)))); |
| 552 | h = h.or(Some(Value::Length(Length::pt(ph * PT_PER_MM)))); |
| 553 | } |
| 554 | } |
| 555 | } else if field == ids.0 && w.is_none() { |
| 556 | w = Some(p.value.clone()); |
| 557 | } else if field == ids.1 && h.is_none() { |
| 558 | h = Some(p.value.clone()); |
| 559 | } |
| 560 | if w.is_some() && h.is_some() { |
| 561 | break; |
| 562 | } |
| 563 | } |
| 564 | let a4 = |mm: f64| Value::Length(Length::pt(mm * PT_PER_MM)); |
| 565 | (w.unwrap_or_else(|| a4(210.0)), h.unwrap_or_else(|| a4(297.0))) |
| 566 | } |
| 567 | |
| 568 | const PT_PER_MM: f64 = 72.0 / 25.4; |
| 569 | |
| 570 | /// A paper's width and height in millimetres, by its Typst name. |
| 571 | pub fn paper(name: &str) -> Option<(f64, f64)> { |
| 572 | let lower = name.to_lowercase(); |
| 573 | PAPERS.iter().find(|(n, _, _)| *n == lower).map(|(_, w, h)| (*w, *h)) |
| 574 | } |
| 575 | |
| 576 | // Typst 0.15.1's paper table, in millimetres. |
| 577 | const PAPERS: &[(&str, f64, f64)] = &[ |
| 578 | ("a0", 841.0, 1189.0), |
| 579 | ("a1", 594.0, 841.0), |
| 580 | ("a2", 420.0, 594.0), |
| 581 | ("a3", 297.0, 420.0), |
| 582 | ("a4", 210.0, 297.0), |
| 583 | ("a5", 148.0, 210.0), |
| 584 | ("a6", 105.0, 148.0), |
| 585 | ("a7", 74.0, 105.0), |
| 586 | ("a8", 52.0, 74.0), |
| 587 | ("a9", 37.0, 52.0), |
| 588 | ("a10", 26.0, 37.0), |
| 589 | ("a11", 18.0, 26.0), |
| 590 | ("iso-b1", 707.0, 1000.0), |
| 591 | ("iso-b2", 500.0, 707.0), |
| 592 | ("iso-b3", 353.0, 500.0), |
| 593 | ("iso-b4", 250.0, 353.0), |
| 594 | ("iso-b5", 176.0, 250.0), |
| 595 | ("iso-b6", 125.0, 176.0), |
| 596 | ("iso-b7", 88.0, 125.0), |
| 597 | ("iso-b8", 62.0, 88.0), |
| 598 | ("iso-c3", 324.0, 458.0), |
| 599 | ("iso-c4", 229.0, 324.0), |
| 600 | ("iso-c5", 162.0, 229.0), |
| 601 | ("iso-c6", 114.0, 162.0), |
| 602 | ("iso-c7", 81.0, 114.0), |
| 603 | ("iso-c8", 57.0, 81.0), |
| 604 | ("din-d3", 272.0, 385.0), |
| 605 | ("din-d4", 192.0, 272.0), |
| 606 | ("din-d5", 136.0, 192.0), |
| 607 | ("din-d6", 96.0, 136.0), |
| 608 | ("din-d7", 68.0, 96.0), |
| 609 | ("din-d8", 48.0, 68.0), |
| 610 | ("sis-g5", 169.0, 239.0), |
| 611 | ("sis-e5", 115.0, 220.0), |
| 612 | ("ansi-a", 216.0, 279.0), |
| 613 | ("ansi-b", 279.0, 432.0), |
| 614 | ("ansi-c", 432.0, 559.0), |
| 615 | ("ansi-d", 559.0, 864.0), |
| 616 | ("ansi-e", 864.0, 1118.0), |
| 617 | ("arch-a", 229.0, 305.0), |
| 618 | ("arch-b", 305.0, 457.0), |
| 619 | ("arch-c", 457.0, 610.0), |
| 620 | ("arch-d", 610.0, 914.0), |
| 621 | ("arch-e1", 762.0, 1067.0), |
| 622 | ("arch-e", 914.0, 1219.0), |
| 623 | ("jis-b0", 1030.0, 1456.0), |
| 624 | ("jis-b1", 728.0, 1030.0), |
| 625 | ("jis-b2", 515.0, 728.0), |
| 626 | ("jis-b3", 364.0, 515.0), |
| 627 | ("jis-b4", 257.0, 364.0), |
| 628 | ("jis-b5", 182.0, 257.0), |
| 629 | ("jis-b6", 128.0, 182.0), |
| 630 | ("jis-b7", 91.0, 128.0), |
| 631 | ("jis-b8", 64.0, 91.0), |
| 632 | ("jis-b9", 45.0, 64.0), |
| 633 | ("jis-b10", 32.0, 45.0), |
| 634 | ("jis-b11", 22.0, 32.0), |
| 635 | ("sac-d0", 764.0, 1064.0), |
| 636 | ("sac-d1", 532.0, 760.0), |
| 637 | ("sac-d2", 380.0, 528.0), |
| 638 | ("sac-d3", 264.0, 376.0), |
| 639 | ("sac-d4", 188.0, 260.0), |
| 640 | ("sac-d5", 130.0, 184.0), |
| 641 | ("sac-d6", 92.0, 126.0), |
| 642 | ("iso-id-1", 85.6, 53.98), |
| 643 | ("iso-id-2", 74.0, 105.0), |
| 644 | ("iso-id-3", 88.0, 125.0), |
| 645 | ("asia-f4", 210.0, 330.0), |
| 646 | ("jp-shiroku-ban-4", 264.0, 379.0), |
| 647 | ("jp-shiroku-ban-5", 189.0, 262.0), |
| 648 | ("jp-shiroku-ban-6", 127.0, 188.0), |
| 649 | ("jp-kiku-4", 227.0, 306.0), |
| 650 | ("jp-kiku-5", 151.0, 227.0), |
| 651 | ("jp-business-card", 91.0, 55.0), |
| 652 | ("cn-business-card", 90.0, 54.0), |
| 653 | ("eu-business-card", 85.0, 55.0), |
| 654 | ("fr-tellière", 340.0, 440.0), |
| 655 | ("fr-couronne-écriture", 360.0, 460.0), |
| 656 | ("fr-couronne-édition", 370.0, 470.0), |
| 657 | ("fr-raisin", 500.0, 650.0), |
| 658 | ("fr-carré", 450.0, 560.0), |
| 659 | ("fr-jésus", 560.0, 760.0), |
| 660 | ("uk-brief", 406.4, 342.9), |
| 661 | ("uk-draft", 254.0, 406.4), |
| 662 | ("uk-foolscap", 203.2, 330.2), |
| 663 | ("uk-quarto", 203.2, 254.0), |
| 664 | ("uk-crown", 508.0, 381.0), |
| 665 | ("uk-book-a", 111.0, 178.0), |
| 666 | ("uk-book-b", 129.0, 198.0), |
| 667 | ("us-letter", 215.9, 279.4), |
| 668 | ("us-legal", 215.9, 355.6), |
| 669 | ("us-tabloid", 279.4, 431.8), |
| 670 | ("us-executive", 184.15, 266.7), |
| 671 | ("us-foolscap-folio", 215.9, 342.9), |
| 672 | ("us-statement", 139.7, 215.9), |
| 673 | ("us-ledger", 431.8, 279.4), |
| 674 | ("us-oficio", 215.9, 340.36), |
| 675 | ("us-gov-letter", 203.2, 266.7), |
| 676 | ("us-gov-legal", 215.9, 330.2), |
| 677 | ("us-business-card", 88.9, 50.8), |
| 678 | ("us-digest", 139.7, 215.9), |
| 679 | ("us-trade", 152.4, 228.6), |
| 680 | ("newspaper-compact", 280.0, 430.0), |
| 681 | ("newspaper-berliner", 315.0, 470.0), |
| 682 | ("newspaper-broadsheet", 381.0, 578.0), |
| 683 | ("presentation-16-9", 297.0, 167.0625), |
| 684 | ("presentation-4-3", 280.0, 210.0), |
| 685 | ]; |
| 686 | |
| 687 | /// A layout field's default where the schema holds none (`Computed`) and Typst gives a value a read can show: the |
| 688 | /// page number's alignment, the spacing a block takes from its neighbours (`auto`, as the paragraph's own), the |
| 689 | /// alignment `align` and `place` take, and the direction a stack runs. |
| 690 | pub fn default_value(kind: ElemKind, name: &str) -> Option<Value> { |
| 691 | match (kind, name) { |
| 692 | (ElemKind::Page, "number-align") => Some(Value::Alignment(crate::eval::value::Alignment { |
| 693 | x: Some(crate::eval::value::HAlign::Center), |
| 694 | y: Some(crate::eval::value::VAlign::Bottom), |
| 695 | })), |
| 696 | (ElemKind::Block, "above") | (ElemKind::Block, "below") => Some(Value::Auto), |
| 697 | (ElemKind::Align, "alignment") => Some(Value::Alignment(crate::eval::value::Alignment { |
| 698 | x: Some(crate::eval::value::HAlign::Start), |
| 699 | y: Some(crate::eval::value::VAlign::Top), |
| 700 | })), |
| 701 | (ElemKind::Place, "alignment") => Some(Value::Alignment(crate::eval::value::Alignment { |
| 702 | x: Some(crate::eval::value::HAlign::Start), |
| 703 | y: None, |
| 704 | })), |
| 705 | (ElemKind::Stack, "dir") => Some(Value::Direction(crate::eval::value::Direction::Ttb)), |
| 706 | _ => kind.field_id(name).and_then(|id| kind.field_spec(id)).and_then(|s| s.default.to_value()), |
| 707 | } |
| 708 | } |