Oregami
Repositories/oxedyne/fe2o3

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

45.8 KiB, 43 runs

created by r1870400018:63496, 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 `visualize/*`, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4// U6d owns this file. Schemas for images, shapes, curves and transforms, and the `stroke`, `tiling` and
5// `polygon.regular` constructors. Every visual element but `hide` is a primitive flow lays out itself
6// (`flow::visual`), so `show` is `None` for them; `hide` shows as its body under the `hidden` style.
7//
8// A field's value is cast to Typst's own type when the element is built, so `fields()` and field access
9// see what Typst shows (`rect(width: 1pt).width` is `0% + 1pt`, a sides dictionary is expanded). A value
10// that arrives through `set` is raw, so flow casts again on reading; every cast here is idempotent.
11
12use crate::diag::DiagnosticKind;
13use crate::eval::args::Args;
14use crate::eval::content::{
15 Content,
16 ElemKind,
17 FieldDefault,
18 FieldId,
19 FieldSpec,
20 FieldType,
21 Fold,
22};
23use crate::eval::lib::foundations::keyword;
24use crate::eval::styles::{
25 Property,
26 Style,
27 StyleChain,
28 Styles,
29};
30use crate::eval::value::{
31 Alignment,
32 Angle,
33 Dash,
34 DashItem,
35 Dict,
36 HAlign,
37 Length,
38 LineCap,
39 LineJoin,
40 Paint,
41 Ratio,
42 Relative,
43 RelativeTo,
44 Stroke,
45 Tiling,
46 Type,
47 VAlign,
48 Value,
49};
50use crate::eval::Engine;
51use crate::syntax::Span;
52
53use oxedyne_fe2o3_core::prelude::*;
54
55use std::sync::Arc;
56
57native_fns! {
58 pub enum VisualFn {
59 Stroke => "stroke",
60 Tiling => "tiling",
61 PolygonRegular => "regular",
62 }
63}
64
65// Schemas
66
67const ANY: FieldType = FieldType::Any;
68
69const RECT: &[FieldSpec] = &[
70 FieldSpec::named("width", ANY, FieldDefault::Auto),
71 FieldSpec::named("height", ANY, FieldDefault::Auto),
72 FieldSpec::named("fill", ANY, FieldDefault::None),
73 FieldSpec::named("stroke", ANY, FieldDefault::Auto).fold(Fold::Custom),
74 FieldSpec::named("radius", ANY, FieldDefault::Pt(0.0)).fold(Fold::Custom),
75 FieldSpec::named("inset", ANY, FieldDefault::Pt(5.0)).fold(Fold::Custom),
76 FieldSpec::named("outset", ANY, FieldDefault::Pt(0.0)).fold(Fold::Custom),
77 FieldSpec::named("body", FieldType::Content, FieldDefault::None).positional(),
78];
79
80// Square has rect's fields; `size` is an argument only, spread into width and height.
81const SQUARE: &[FieldSpec] = RECT;
82
83const ELLIPSE: &[FieldSpec] = &[
84 FieldSpec::named("width", ANY, FieldDefault::Auto),
85 FieldSpec::named("height", ANY, FieldDefault::Auto),
86 FieldSpec::named("fill", ANY, FieldDefault::None),
87 FieldSpec::named("stroke", ANY, FieldDefault::Auto).fold(Fold::Custom),
88 FieldSpec::named("inset", ANY, FieldDefault::Pt(5.0)).fold(Fold::Custom),
89 FieldSpec::named("outset", ANY, FieldDefault::Pt(0.0)).fold(Fold::Custom),
90 FieldSpec::named("body", FieldType::Content, FieldDefault::None).positional(),
91];
92
93// Circle has ellipse's fields; `radius` is an argument only, spread into width and height.
94const CIRCLE: &[FieldSpec] = ELLIPSE;
95
96const LINE: &[FieldSpec] = &[
97 FieldSpec::named("start", ANY, FieldDefault::Computed),
98 FieldSpec::named("end", ANY, FieldDefault::None),
99 FieldSpec::named("length", ANY, FieldDefault::Pt(30.0)),
100 FieldSpec::named("angle", ANY, FieldDefault::Computed),
101 FieldSpec::named("stroke", ANY, FieldDefault::Computed).fold(Fold::Custom),
102];
103
104const POLYGON: &[FieldSpec] = &[
105 FieldSpec::named("fill", ANY, FieldDefault::None),
106 FieldSpec::named("fill-rule", ANY, FieldDefault::Str("non-zero")),
107 FieldSpec::named("stroke", ANY, FieldDefault::Auto).fold(Fold::Custom),
108 FieldSpec::named("vertices", ANY, FieldDefault::EmptyArray).variadic().unsettable(),
109];
110
111const CURVE: &[FieldSpec] = &[
112 FieldSpec::named("fill", ANY, FieldDefault::None),
113 FieldSpec::named("fill-rule", ANY, FieldDefault::Str("non-zero")),
114 FieldSpec::named("stroke", ANY, FieldDefault::Auto).fold(Fold::Custom),
115 FieldSpec::named("components", ANY, FieldDefault::EmptyArray).variadic().unsettable(),
116];
117
118const CURVE_MOVE: &[FieldSpec] = &[
119 FieldSpec::required("start", ANY),
120 FieldSpec::named("relative", FieldType::Of(Type::Bool), FieldDefault::Bool(false)),
121];
122
123const CURVE_LINE: &[FieldSpec] = &[
124 FieldSpec::required("end", ANY),
125 FieldSpec::named("relative", FieldType::Of(Type::Bool), FieldDefault::Bool(false)),
126];
127
128const CURVE_QUAD: &[FieldSpec] = &[
129 FieldSpec::required("control", ANY),
130 FieldSpec::required("end", ANY),
131 FieldSpec::named("relative", FieldType::Of(Type::Bool), FieldDefault::Bool(false)),
132];
133
134const CURVE_CUBIC: &[FieldSpec] = &[
135 FieldSpec::required("control-start", ANY),
136 FieldSpec::required("control-end", ANY),
137 FieldSpec::required("end", ANY),
138 FieldSpec::named("relative", FieldType::Of(Type::Bool), FieldDefault::Bool(false)),
139];
140
141const CURVE_CLOSE: &[FieldSpec] = &[
142 FieldSpec::named("mode", ANY, FieldDefault::Str("smooth")),
143];
144
145const MOVE: &[FieldSpec] = &[
146 FieldSpec::named("dx", ANY, FieldDefault::Pt(0.0)),
147 FieldSpec::named("dy", ANY, FieldDefault::Pt(0.0)),
148 FieldSpec::required("body", FieldType::Content),
149];
150
151/// A visual field's default where the schema holds none (`Computed`) and Typst gives a value a read can show: the
152/// turn of a rotation or skew (none), the point they and a scale turn about (the centre), a line's start and
153/// angle, and its stroke as Typst holds a default one, with paint and thickness both `auto`.
154pub fn default_value(kind: ElemKind, name: &str) -> Option<Value> {
155 use crate::eval::value::{Alignment, Angle, HAlign, Length, Ratio, Relative, Stroke, VAlign};
156 match (kind, name) {
157 (ElemKind::Rotate, "angle") | (ElemKind::Skew, "ax") | (ElemKind::Skew, "ay") | (ElemKind::Line, "angle")
158 => Some(Value::Angle(Angle(0.0))),
159 (ElemKind::Rotate, "origin") | (ElemKind::Scale, "origin") | (ElemKind::Skew, "origin")
160 => Some(Value::Alignment(Alignment { x: Some(HAlign::Center), y: Some(VAlign::Horizon) })),
161 (ElemKind::Line, "start") => {
162 let origin = Value::Relative(Relative { rel: Ratio(0.0), abs: Length::pt(0.0) });
163 Some(Value::array(vec![origin.clone(), origin]))
164 },
165 (ElemKind::Line, "stroke") => Some(Value::Stroke(std::sync::Arc::new(Stroke::default()))),
166 _ => kind.field_id(name).and_then(|id| kind.field_spec(id)).and_then(|s| s.default.to_value()),
167 }
168}
169
170const ROTATE: &[FieldSpec] = &[
171 FieldSpec::named("angle", ANY, FieldDefault::Computed).positional(),
172 FieldSpec::named("origin", ANY, FieldDefault::Computed).fold(Fold::Custom),
173 FieldSpec::named("reflow", FieldType::Of(Type::Bool), FieldDefault::Bool(false)),
174 FieldSpec::required("body", FieldType::Content),
175];
176
177const SCALE: &[FieldSpec] = &[
178 FieldSpec::named("x", ANY, FieldDefault::Ratio(1.0)),
179 FieldSpec::named("y", ANY, FieldDefault::Ratio(1.0)),
180 FieldSpec::named("origin", ANY, FieldDefault::Computed).fold(Fold::Custom),
181 FieldSpec::named("reflow", FieldType::Of(Type::Bool), FieldDefault::Bool(false)),
182 FieldSpec::required("body", FieldType::Content),
183];
184
185const SKEW: &[FieldSpec] = &[
186 FieldSpec::named("ax", ANY, FieldDefault::Computed),
187 FieldSpec::named("ay", ANY, FieldDefault::Computed),
188 FieldSpec::named("origin", ANY, FieldDefault::Computed).fold(Fold::Custom),
189 FieldSpec::named("reflow", FieldType::Of(Type::Bool), FieldDefault::Bool(false)),
190 FieldSpec::required("body", FieldType::Content),
191];
192
193// `hidden` is Typst's internal ghost field: set as a style on the body by `hide`'s show, never passed.
194const HIDE: &[FieldSpec] = &[
195 FieldSpec::required("body", FieldType::Content),
196 FieldSpec::named("hidden", FieldType::Of(Type::Bool), FieldDefault::Bool(false)).unsettable(),
197];
198
199const REPEAT: &[FieldSpec] = &[
200 FieldSpec::required("body", FieldType::Content),
201 FieldSpec::named("gap", ANY, FieldDefault::Pt(0.0)),
202 FieldSpec::named("justify", FieldType::Of(Type::Bool), FieldDefault::Bool(true)),
203];
204
205const IMAGE: &[FieldSpec] = &[
206 FieldSpec::required("source", ANY),
207 FieldSpec::named("format", ANY, FieldDefault::Auto),
208 FieldSpec::named("width", ANY, FieldDefault::Auto),
209 FieldSpec::named("height", ANY, FieldDefault::Auto),
210 FieldSpec::named("alt", ANY, FieldDefault::None),
211 FieldSpec::named("page", FieldType::Of(Type::Int), FieldDefault::Int(1)),
212 FieldSpec::named("fit", ANY, FieldDefault::Str("cover")),
213 FieldSpec::named("scaling", ANY, FieldDefault::Auto),
214 FieldSpec::named("icc", ANY, FieldDefault::Auto),
215];
216
217pub fn fields(kind: ElemKind) -> &'static [FieldSpec] {
218 match kind {
219 ElemKind::Image => IMAGE,
220 ElemKind::Line => LINE,
221 ElemKind::Rect => RECT,
222 ElemKind::Square => SQUARE,
223 ElemKind::Circle => CIRCLE,
224 ElemKind::Ellipse => ELLIPSE,
225 ElemKind::Polygon => POLYGON,
226 ElemKind::Curve => CURVE,
227 ElemKind::CurveMove => CURVE_MOVE,
228 ElemKind::CurveLine => CURVE_LINE,
229 ElemKind::CurveQuad => CURVE_QUAD,
230 ElemKind::CurveCubic => CURVE_CUBIC,
231 ElemKind::CurveClose => CURVE_CLOSE,
232 ElemKind::Move => MOVE,
233 ElemKind::Scale => SCALE,
234 ElemKind::Rotate => ROTATE,
235 ElemKind::Skew => SKEW,
236 ElemKind::Hide => HIDE,
237 ElemKind::Repeat => REPEAT,
238 // Typst 0.15 has no `path` element: `path` is the file-path type, which the drawing element's name
239 // was given to. The kind stays in U0's closed list and has no fields.
240 ElemKind::Path => &[],
241 _ => &[],
242 }
243}
244
245/// The field's id in the element's schema. Every name passed here is one this file declares.
246pub fn fid(kind: ElemKind, name: &str) -> Outcome<FieldId> {
247 kind.field_id(name).ok_or_else(|| err!(
248 "{} has no field `{}` in its schema.", kind.path(), name; Bug, Missing))
249}
250
251// Library
252
253/// A native function reached through an element function, as `polygon.regular` is.
254pub fn scoped(kind: ElemKind, name: &str) -> Option<VisualFn> {
255 match (kind, name) {
256 (ElemKind::Polygon, "regular") => Some(VisualFn::PolygonRegular),
257 _ => None,
258 }
259}
260
261pub fn call(f: VisualFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
262 let span = args.span;
263 let out = match f {
264 VisualFn::Stroke => stroke_constructor(&mut args),
265 VisualFn::Tiling => tiling_constructor(&mut args),
266 VisualFn::PolygonRegular => polygon_regular(&mut args, span),
267 };
268 match out {
269 Ok(v) => match args.finish() {
270 Ok(()) => Ok(v),
271 Err(e) => Err(engine.error(DiagnosticKind::Type, span, err_text(&e))),
272 },
273 Err(e) => Err(engine.error(DiagnosticKind::Type, span, err_text(&e))),
274 }
275}
276
277// The innermost message of an error made by a cast, which is what the diagnostic reports.
278fn err_text(e: &Error<ErrTag>) -> String {
279 match e.msgs().into_iter().last() {
280 Some(m) => m,
281 None => fmt!("{}", e),
282 }
283}
284
285fn stroke_constructor(args: &mut Args) -> Outcome<Value> {
286 if let Some(v) = res!(args.eat::<Value>()) {
287 return Ok(Value::Stroke(Arc::new(res!(cast_stroke(v)))));
288 }
289 let mut s = Stroke::default();
290 if let Some(v) = res!(args.named::<Value>("paint")) {
291 s.paint = res!(smart(v, cast_paint_some));
292 }
293 if let Some(v) = res!(args.named::<Value>("thickness")) {
294 s.thickness = res!(smart(v, cast_length));
295 }
296 if let Some(v) = res!(args.named::<Value>("cap")) {
297 s.cap = res!(smart(v, cast_cap));
298 }
299 if let Some(v) = res!(args.named::<Value>("join")) {
300 s.join = res!(smart(v, cast_join));
301 }
302 if let Some(v) = res!(args.named::<Value>("dash")) {
303 s.dash = res!(smart(v, cast_dash));
304 }
305 if let Some(v) = res!(args.named::<Value>("miter-limit")) {
306 s.miter_limit = res!(smart(v, |v| v.cast::<f64>()));
307 }
308 Ok(Value::Stroke(Arc::new(s)))
309}
310
311fn tiling_constructor(args: &mut Args) -> Outcome<Value> {
312 let size = match res!(args.named::<Value>("size")) {
313 None | Some(Value::Auto) => None,
314 Some(v) => Some(res!(length_pair(v, "size"))),
315 };
316 let spacing = match res!(args.named::<Value>("spacing")) {
317 None => (Length::zero(), Length::zero()),
318 Some(v) => res!(length_pair(v, "spacing")),
319 };
320 let relative = match res!(args.named::<Value>("relative")) {
321 None | Some(Value::Auto) => RelativeTo::Auto,
322 Some(v) => res!(cast_relative_to(v)),
323 };
324 let body = res!(args.expect::<Content>("body"));
325 Ok(Value::Tiling(Arc::new(Tiling { body, size, spacing, relative })))
326}
327
328fn polygon_regular(args: &mut Args, span: Span) -> Outcome<Value> {
329 let fill = res!(args.named::<Value>("fill"));
330 let stroke = res!(args.named::<Value>("stroke"));
331 let size = match res!(args.named::<Value>("size")) {
332 Some(v) => res!(cast_length(v)),
333 None => Length::em(1.0),
334 };
335 let n = match res!(args.named::<Value>("vertices")) {
336 Some(v) => res!(v.cast::<i64>()),
337 None => 3,
338 };
339 if n < 0 {
340 return Err(err!("number must be at least zero"; Input, Range));
341 }
342 // Each coordinate is the radius times a factor, so the minima that normalise the polygon into its
343 // box are taken on the factors, which keeps an `em` size unresolved as Typst keeps it.
344 let nf = n as f64;
345 let angle = |i: f64| 2.0 * std::f64::consts::PI * i / nf + std::f64::consts::PI * (0.5 - 1.0 / nf);
346 let mut min_x = 1.0f64;
347 let mut min_y = 1.0f64;
348 for v in 0..=n {
349 let a = angle(v as f64);
350 min_x = min_x.min(a.cos() + 1.0);
351 min_y = min_y.min(a.sin() + 1.0);
352 }
353 let r = Length { abs: size.abs / 2.0, em: size.em / 2.0 };
354 let mut verts = Vec::new();
355 for v in 0..=n {
356 let a = angle(v as f64);
357 let fx = a.cos() + 1.0 - min_x;
358 let fy = a.sin() + 1.0 - min_y;
359 verts.push(Value::array(vec![
360 Value::Relative(rel_of(Length { abs: r.abs * fx, em: r.em * fx })),
361 Value::Relative(rel_of(Length { abs: r.abs * fy, em: r.em * fy })),
362 ]));
363 }
364 let kind = ElemKind::Polygon;
365 let mut fields = Vec::new();
366 if let Some(v) = fill {
367 fields.push((res!(fid(kind, "fill")), res!(cast_fill(v))));
368 }
369 if let Some(v) = stroke {
370 fields.push((res!(fid(kind, "stroke")), res!(cast_smart_stroke(v))));
371 }
372 fields.push((res!(fid(kind, "vertices")), Value::array(verts)));
373 Ok(Value::Content(Content::new(kind, fields, span)))
374}
375
376// Construction
377
378pub fn construct(engine: &mut Engine, kind: ElemKind, args: &mut Args) -> Outcome<Option<Content>> {
379 let span = args.span;
380 let built = match kind {
381 ElemKind::Rect | ElemKind::Square | ElemKind::Ellipse | ElemKind::Circle
382 => build_shape(kind, args),
383 ElemKind::Line => build_line(args),
384 ElemKind::Polygon => build_polygon(args),
385 ElemKind::Curve => build_curve(args),
386 ElemKind::CurveMove => build_component(kind, args, &["start"]),
387 ElemKind::CurveLine => build_component(kind, args, &["end"]),
388 ElemKind::CurveQuad => build_component(kind, args, &["control", "end"]),
389 ElemKind::CurveCubic => build_component(kind, args, &["control-start", "control-end", "end"]),
390 ElemKind::CurveClose => build_close(args),
391 ElemKind::Move => build_move(args),
392 ElemKind::Rotate => build_rotate(args),
393 ElemKind::Scale => build_scale(args),
394 ElemKind::Skew => build_skew(args),
395 ElemKind::Hide => build_body_only(kind, args),
396 ElemKind::Repeat => build_repeat(args),
397 ElemKind::Image => build_image(engine, args),
398 ElemKind::Path => Err(err!(
399 "Typst 0.15 has no `path` drawing element; use `curve` instead"; Input, Invalid)),
400 _ => return Ok(None),
401 };
402 let fields = match built {
403 Ok(f) => f,
404 Err(e) => return Err(engine.error(DiagnosticKind::Type, span, err_text(&e))),
405 };
406 if let Err(e) = std::mem::take(args).finish() {
407 return Err(engine.error(DiagnosticKind::Type, span, err_text(&e)));
408 }
409 Ok(Some(Content::new(kind, fields, span)))
410}
411
412type Fields = Vec<(FieldId, Value)>;
413
414// Takes a named argument and casts it into the field of the same name.
415fn take_named(fields: &mut Fields, kind: ElemKind, args: &mut Args, name: &str) -> Outcome<()> {
416 if let Some(v) = res!(args.named::<Value>(name)) {
417 fields.push((res!(fid(kind, name)), res!(cast_field(kind, name, v))));
418 }
419 Ok(())
420}
421
422// Keyword choices
423const CLOSE_MODE: &str = "\"smooth\" or \"straight\"";
424const IMAGE_FORMAT: &str = "\"png\", \"jpg\", \"gif\", \"webp\", dictionary, \"svg\", \"pdf\", or auto";
425const IMAGE_FIT: &str = "\"cover\", \"contain\", or \"stretch\"";
426const IMAGE_SCALING: &str = "\"smooth\", \"pixelated\", or auto";
427const FILL_RULE: &str = "\"non-zero\" or \"even-odd\"";
428const CAP: &str = "\"butt\", \"round\", \"square\", or auto";
429const JOIN: &str = "\"miter\", \"round\", \"bevel\", or auto";
430pub const RELATIVE_TO: &str = "\"self\", \"parent\", or auto";
431
432/// Casts a value into a visual element's field as Typst casts it. The constructors and `set` rules
433/// both cast through here, so a value `set` accepts is one construction accepts.
434pub fn cast_field(kind: ElemKind, name: &str, v: Value) -> Outcome<Value> {
435 use ElemKind as K;
436 match (kind, name) {
437 (_, "width") => cast_smart_rel(v),
438 (_, "height") => cast_sizing(v),
439 (_, "fill") => cast_fill(v),
440 (_, "fill-rule") => cast_fill_rule(v),
441 (K::Rect | K::Square, "stroke") => cast_stroke_sides(v),
442 (K::Line, "stroke") => Ok(Value::Stroke(Arc::new(res!(cast_stroke(v))))),
443 (_, "stroke") => cast_smart_stroke(v),
444 (_, "radius") => cast_corners_rel(v),
445 (_, "inset") | (_, "outset") => cast_sides_rel(v),
446 (K::Line, "start") => cast_point(v),
447 (K::Line, "end") => if v.is_none() { Ok(v) } else { cast_point(v) },
448 (K::Line, "length") => Ok(Value::Relative(res!(cast_rel(v)))),
449 (K::Line, "angle") | (K::Rotate, "angle") | (K::Skew, "ax") | (K::Skew, "ay")
450 => Ok(Value::Angle(res!(cast_angle(v)))),
451 (K::Move, "dx") | (K::Move, "dy") => Ok(Value::Relative(res!(cast_rel(v)))),
452 (K::Scale, "x") | (K::Scale, "y") => cast_scale_amount(v),
453 (_, "origin") => Ok(Value::Alignment(res!(v.cast::<Alignment>()))),
454 (_, "reflow") | (_, "relative") | (_, "justify")
455 => Ok(Value::Bool(res!(v.cast::<bool>()))),
456 (K::Repeat, "gap") => Ok(Value::Length(res!(cast_length(v)))),
457 (K::CurveClose, "mode") => Ok(Value::Str(res!(keyword(&v, &["smooth", "straight"], CLOSE_MODE)))),
458 (K::Image, "format") => match v {
459 Value::Auto => Ok(v),
460 other => Ok(Value::Str(res!(keyword(&other, &["png", "jpg", "gif", "webp", "svg", "pdf"], IMAGE_FORMAT)))),
461 },
462 (K::Image, "alt") => match v {
463 Value::None => Ok(v),
464 other => Ok(Value::str(res!(other.cast::<String>()))),
465 },
466 (K::Image, "page") => Ok(Value::Int(res!(v.cast::<i64>()))),
467 (K::Image, "fit") => Ok(Value::Str(res!(keyword(&v, &["cover", "contain", "stretch"], IMAGE_FIT)))),
468 (K::Image, "scaling") => match v {
469 Value::Auto => Ok(v),
470 other => Ok(Value::Str(res!(keyword(&other, &["smooth", "pixelated"], IMAGE_SCALING)))),
471 },
472 _ => Ok(v),
473 }
474}
475
476fn build_shape(kind: ElemKind, args: &mut Args) -> Outcome<Fields> {
477 let mut f = Vec::new();
478 let round = matches!(kind, ElemKind::Ellipse | ElemKind::Circle);
479 // The external sizing arguments come first, as Typst parses them: `square(size:)` and
480 // `circle(radius:)` set width and height together and take precedence over them.
481 let (w, h) = match kind {
482 ElemKind::Square => match res!(args.named::<Value>("size")) {
483 Some(Value::Auto) => {
484 let _ = res!(args.named::<Value>("width"));
485 let _ = res!(args.named::<Value>("height"));
486 (Some(Value::Auto), Some(Value::Auto))
487 },
488 Some(v) => {
489 let r = Value::Relative(rel_of(res!(cast_length(v))));
490 let _ = res!(args.named::<Value>("width"));
491 let _ = res!(args.named::<Value>("height"));
492 (Some(r.clone()), Some(r))
493 },
494 None => (res!(args.named::<Value>("width")), res!(args.named::<Value>("height"))),
495 },
496 ElemKind::Circle => match res!(args.named::<Value>("radius")) {
497 Some(v) => {
498 let l = res!(cast_length(v));
499 let r = Value::Relative(rel_of(Length { abs: l.abs * 2.0, em: l.em * 2.0 }));
500 let _ = res!(args.named::<Value>("width"));
501 let _ = res!(args.named::<Value>("height"));
502 (Some(r.clone()), Some(r))
503 },
504 None => (res!(args.named::<Value>("width")), res!(args.named::<Value>("height"))),
505 },
506 _ => (res!(args.named::<Value>("width")), res!(args.named::<Value>("height"))),
507 };
508 if let Some(v) = w {
509 f.push((res!(fid(kind, "width")), res!(cast_field(kind, "width", v))));
510 }
511 if let Some(v) = h {
512 f.push((res!(fid(kind, "height")), res!(cast_field(kind, "height", v))));
513 }
514 res!(take_named(&mut f, kind, args, "fill"));
515 if round {
516 res!(take_named(&mut f, kind, args, "stroke"));
517 } else {
518 res!(take_named(&mut f, kind, args, "stroke"));
519 res!(take_named(&mut f, kind, args, "radius"));
520 }
521 res!(take_named(&mut f, kind, args, "inset"));
522 res!(take_named(&mut f, kind, args, "outset"));
523 if let Some(v) = res!(args.eat::<Value>()) {
524 f.push((res!(fid(kind, "body")), res!(cast_opt_content(v))));
525 }
526 Ok(f)
527}
528
529fn build_line(args: &mut Args) -> Outcome<Fields> {
530 let kind = ElemKind::Line;
531 let mut f = Vec::new();
532 res!(take_named(&mut f, kind, args, "start"));
533 res!(take_named(&mut f, kind, args, "end"));
534 res!(take_named(&mut f, kind, args, "length"));
535 res!(take_named(&mut f, kind, args, "angle"));
536 res!(take_named(&mut f, kind, args, "stroke"));
537 Ok(f)
538}
539
540fn build_polygon(args: &mut Args) -> Outcome<Fields> {
541 let kind = ElemKind::Polygon;
542 let mut f = Vec::new();
543 res!(take_named(&mut f, kind, args, "fill"));
544 res!(take_named(&mut f, kind, args, "fill-rule"));
545 res!(take_named(&mut f, kind, args, "stroke"));
546 let mut verts = Vec::new();
547 for v in res!(args.all::<Value>()) {
548 verts.push(res!(cast_point(v)));
549 }
550 f.push((res!(fid(kind, "vertices")), Value::array(verts)));
551 Ok(f)
552}
553
554fn build_curve(args: &mut Args) -> Outcome<Fields> {
555 let kind = ElemKind::Curve;
556 let mut f = Vec::new();
557 res!(take_named(&mut f, kind, args, "fill"));
558 res!(take_named(&mut f, kind, args, "fill-rule"));
559 res!(take_named(&mut f, kind, args, "stroke"));
560 let mut comps = Vec::new();
561 for v in res!(args.all::<Value>()) {
562 let ok = match &v {
563 Value::Content(c) => matches!(c.kind(), Some(ElemKind::CurveMove) | Some(ElemKind::CurveLine)
564 | Some(ElemKind::CurveQuad) | Some(ElemKind::CurveCubic) | Some(ElemKind::CurveClose)),
565 _ => false,
566 };
567 if !ok {
568 return Err(err!("expected curve component, found {}", v.ty().long_name(); Input, Mismatch));
569 }
570 comps.push(v);
571 }
572 f.push((res!(fid(kind, "components")), Value::array(comps)));
573 Ok(f)
574}
575
576// A curve component: its required points in order, then `relative`. A quad's control may be `auto` or
577// `none`; a cubic's start control may be `auto` or `none` and its end control `none`.
578fn build_component(kind: ElemKind, args: &mut Args, points: &[&str]) -> Outcome<Fields> {
579 let mut f = Vec::new();
580 for name in points {
581 let v = res!(args.expect::<Value>(name));
582 let cast = match (kind, *name) {
583 (ElemKind::CurveQuad, "control") | (ElemKind::CurveCubic, "control-start") => match v {
584 Value::Auto | Value::None => v,
585 other => res!(cast_point(other)),
586 },
587 (ElemKind::CurveCubic, "control-end") => match v {
588 Value::None => v,
589 other => res!(cast_point(other)),
590 },
591 _ => res!(cast_point(v)),
592 };
593 f.push((res!(fid(kind, name)), cast));
594 }
595 res!(take_named(&mut f, kind, args, "relative"));
596 Ok(f)
597}
598
599fn build_close(args: &mut Args) -> Outcome<Fields> {
600 let kind = ElemKind::CurveClose;
601 let mut f = Vec::new();
602 res!(take_named(&mut f, kind, args, "mode"));
603 Ok(f)
604}
605
606fn take_body(f: &mut Fields, kind: ElemKind, args: &mut Args) -> Outcome<()> {
607 let body = res!(args.expect::<Value>("body"));
608 f.push((res!(fid(kind, "body")), res!(cast_content(body))));
609 Ok(())
610}
611
612fn take_origin_reflow(f: &mut Fields, kind: ElemKind, args: &mut Args) -> Outcome<()> {
613 res!(take_named(f, kind, args, "origin"));
614 res!(take_named(f, kind, args, "reflow"));
615 Ok(())
616}
617
618fn build_move(args: &mut Args) -> Outcome<Fields> {
619 let kind = ElemKind::Move;
620 let mut f = Vec::new();
621 res!(take_named(&mut f, kind, args, "dx"));
622 res!(take_named(&mut f, kind, args, "dy"));
623 res!(take_body(&mut f, kind, args));
624 Ok(f)
625}
626
627fn build_rotate(args: &mut Args) -> Outcome<Fields> {
628 let kind = ElemKind::Rotate;
629 let mut f = Vec::new();
630 // The angle is positional but optional: the first positional argument that is an angle.
631 let named = res!(args.named::<Value>("angle"));
632 let pos = res!(args.find::<Value>(|v| matches!(v, Value::Angle(_))));
633 if let Some(v) = pos.or(named) {
634 f.push((res!(fid(kind, "angle")), res!(cast_field(kind, "angle", v))));
635 }
636 res!(take_origin_reflow(&mut f, kind, args));
637 res!(take_body(&mut f, kind, args));
638 Ok(f)
639}
640
641fn build_scale(args: &mut Args) -> Outcome<Fields> {
642 let kind = ElemKind::Scale;
643 let mut f = Vec::new();
644 // `factor` is external: a positional ratio or length (or `auto`) that sets both axes unless an axis
645 // is given by name.
646 let factor = res!(args.find::<Value>(|v| matches!(v,
647 Value::Ratio(_) | Value::Length(_) | Value::Auto)));
648 let x = res!(args.named::<Value>("x")).or_else(|| factor.clone());
649 let y = res!(args.named::<Value>("y")).or(factor);
650 if let Some(v) = x {
651 f.push((res!(fid(kind, "x")), res!(cast_field(kind, "x", v))));
652 }
653 if let Some(v) = y {
654 f.push((res!(fid(kind, "y")), res!(cast_field(kind, "y", v))));
655 }
656 res!(take_origin_reflow(&mut f, kind, args));
657 res!(take_body(&mut f, kind, args));
658 Ok(f)
659}
660
661fn build_skew(args: &mut Args) -> Outcome<Fields> {
662 let kind = ElemKind::Skew;
663 let mut f = Vec::new();
664 res!(take_named(&mut f, kind, args, "ax"));
665 res!(take_named(&mut f, kind, args, "ay"));
666 res!(take_origin_reflow(&mut f, kind, args));
667 res!(take_body(&mut f, kind, args));
668 Ok(f)
669}
670
671fn build_body_only(kind: ElemKind, args: &mut Args) -> Outcome<Fields> {
672 let mut f = Vec::new();
673 res!(take_body(&mut f, kind, args));
674 Ok(f)
675}
676
677fn build_repeat(args: &mut Args) -> Outcome<Fields> {
678 let kind = ElemKind::Repeat;
679 let mut f = Vec::new();
680 res!(take_body(&mut f, kind, args));
681 res!(take_named(&mut f, kind, args, "gap"));
682 res!(take_named(&mut f, kind, args, "justify"));
683 Ok(f)
684}
685
686fn build_image(engine: &mut Engine, args: &mut Args) -> Outcome<Fields> {
687 let kind = ElemKind::Image;
688 let span = args.span;
689 let mut f = Vec::new();
690 let at = args.items.iter().find(|a| a.name.is_none()).map(|a| a.span).unwrap_or(span);
691 let source = res!(args.expect::<Value>("source")).symbol_as_str();
692 match &source {
693 // A path is resolved and the file checked now, as Typst reads it when the element is built, so a
694 // missing file is reported at the argument that names it.
695 Value::Str(p) => {
696 let path = res!(crate::eval::import::resolve_path(engine, p, at.file, at));
697 res!(crate::eval::import::require_file(engine, &path, at));
698 },
699 Value::Bytes(_) => (),
700 other => return Err(err!("expected string or bytes, found {}", other.ty().long_name(); Input, Mismatch)),
701 }
702 f.push((res!(fid(kind, "source")), source));
703 res!(take_named(&mut f, kind, args, "format"));
704 res!(take_named(&mut f, kind, args, "width"));
705 res!(take_named(&mut f, kind, args, "height"));
706 res!(take_named(&mut f, kind, args, "alt"));
707 res!(take_named(&mut f, kind, args, "page"));
708 res!(take_named(&mut f, kind, args, "fit"));
709 res!(take_named(&mut f, kind, args, "scaling"));
710 res!(take_named(&mut f, kind, args, "icc"));
711 Ok(f)
712}
713
714// Show
715
716pub fn show(engine: &mut Engine, elem: &Content, _styles: &StyleChain) -> Outcome<Option<Content>> {
717 match elem.kind() {
718 // Typst's `hide`: the body under the `hidden` style, which every layout of ink honours by laying
719 // the content out and drawing none of it.
720 Some(ElemKind::Hide) => {
721 let body = match elem.field("body") {
722 Some(v) => res!(cast_content(v.clone()).and_then(|v| v.cast::<Content>())),
723 None => Content::empty(),
724 };
725 let id = res!(fid(ElemKind::Hide, "hidden"));
726 let styles = Styles::from_style(Style::Property(Property {
727 elem: ElemKind::Hide,
728 field: id,
729 value: Value::Bool(true),
730 span: elem.span(),
731 liftable: false,
732 outside: false,
733 }));
734 let _ = engine;
735 Ok(Some(body.styled(styles)))
736 },
737 _ => Ok(None),
738 }
739}
740
741/// Is content under these styles hidden by an enclosing `hide`? Every producer of ink asks this and
742/// lays the content out without drawing it.
743pub fn is_hidden(styles: &StyleChain) -> Outcome<bool> {
744 match ElemKind::Hide.field_id("hidden") {
745 Some(id) => Ok(matches!(res!(styles.get(ElemKind::Hide, id)), Some(Value::Bool(true)))),
746 None => Ok(false),
747 }
748}
749
750// Folding
751
752/// Folds a `Fold::Custom` field of a visual element: `inner` (the nearer value) over `outer`. Strokes fold
753/// part by part (`stroke: red` over `stroke: 2pt` is a red 2pt stroke), sides and corners side by side,
754/// and an origin axis by axis; `auto` and a plain value replace.
755pub fn fold(kind: ElemKind, field: &str, inner: Value, outer: Value) -> Outcome<Value> {
756 match field {
757 "stroke" => match kind {
758 ElemKind::Rect | ElemKind::Square => fold_sides(inner, outer, cast_stroke_sides, fold_opt_stroke),
759 ElemKind::Line => fold_stroke_values(inner, outer),
760 _ => fold_opt_stroke(inner, outer),
761 },
762 "radius" => fold_corners(inner, outer),
763 "inset" | "outset" => fold_sides(inner, outer, cast_sides_rel, |i, _| Ok(i)),
764 "origin" => {
765 let i = res!(inner.cast::<Alignment>());
766 let o = match outer {
767 Value::Alignment(a) => a,
768 _ => Alignment::default(),
769 };
770 Ok(Value::Alignment(Alignment { x: i.x.or(o.x), y: i.y.or(o.y) }))
771 },
772 _ => Ok(inner),
773 }
774}
775
776// Two `Smart<Option<Stroke>>` values: strokes fold, `auto` or `none` inner replaces.
777fn fold_opt_stroke(inner: Value, outer: Value) -> Outcome<Value> {
778 match (&inner, &outer) {
779 (Value::Auto, _) | (Value::None, _) => Ok(inner),
780 (_, Value::Auto) | (_, Value::None) => Ok(res!(cast_smart_stroke(inner))),
781 _ => fold_stroke_values(inner, outer),
782 }
783}
784
785fn fold_stroke_values(inner: Value, outer: Value) -> Outcome<Value> {
786 let i = res!(cast_stroke(inner));
787 let o = res!(cast_stroke(outer));
788 Ok(Value::Stroke(Arc::new(Stroke {
789 paint: i.paint.or(o.paint),
790 thickness: i.thickness.or(o.thickness),
791 cap: i.cap.or(o.cap),
792 join: i.join.or(o.join),
793 dash: i.dash.or(o.dash),
794 miter_limit: i.miter_limit.or(o.miter_limit),
795 })))
796}
797
798fn fold_sides<C, F>(inner: Value, outer: Value, cast: C, each: F) -> Outcome<Value>
799 where
800 C: Fn(Value) -> Outcome<Value>,
801 F: Fn(Value, Value) -> Outcome<Value>,
802{
803 if inner.is_auto() || outer.is_auto() {
804 return cast(inner);
805 }
806 let i = sides_of(&res!(cast(inner)));
807 let o = sides_of(&res!(cast(outer)));
808 let mut out = [None, None, None, None];
809 for k in 0..4 {
810 out[k] = match (i[k].clone(), o[k].clone()) {
811 (Some(a), Some(b)) => Some(res!(each(a, b))),
812 (Some(a), None) => Some(a),
813 (None, b) => b,
814 };
815 }
816 Ok(sides_value(out))
817}
818
819fn fold_corners(inner: Value, outer: Value) -> Outcome<Value> {
820 let i = corners_of(&res!(cast_corners_rel(inner)));
821 let o = corners_of(&res!(cast_corners_rel(outer)));
822 let mut out = [None, None, None, None];
823 for k in 0..4 {
824 out[k] = i[k].clone().or_else(|| o[k].clone());
825 }
826 Ok(corners_value(out))
827}
828
829// Casts
830
831fn mismatch(expected: &str, found: &Value) -> Error<ErrTag> {
832 err!("expected {}, found {}", expected, found.ty().long_name(); Input, Mismatch)
833}
834
835fn rel_of(l: Length) -> Relative { Relative { rel: Ratio(0.0), abs: l } }
836
837fn smart<T, F>(v: Value, f: F) -> Outcome<Option<T>>
838 where F: Fn(Value) -> Outcome<T>
839{
840 match v {
841 Value::Auto => Ok(None),
842 other => Ok(Some(res!(f(other)))),
843 }
844}
845
846pub fn cast_length(v: Value) -> Outcome<Length> {
847 match v {
848 Value::Length(l) => Ok(l),
849 other => Err(mismatch("length", &other)),
850 }
851}
852
853pub fn cast_rel(v: Value) -> Outcome<Relative> {
854 match v {
855 Value::Relative(r) => Ok(r),
856 Value::Length(l) => Ok(rel_of(l)),
857 Value::Ratio(r) => Ok(Relative { rel: r, abs: Length::zero() }),
858 other => Err(mismatch("relative length", &other)),
859 }
860}
861
862pub fn cast_angle(v: Value) -> Outcome<Angle> {
863 match v {
864 Value::Angle(a) => Ok(a),
865 other => Err(mismatch("angle", &other)),
866 }
867}
868
869fn cast_smart_rel(v: Value) -> Outcome<Value> {
870 match v {
871 Value::Auto => Ok(v),
872 other => Ok(Value::Relative(res!(cast_rel(other)))),
873 }
874}
875
876// Typst's `Sizing`: `auto`, a relative length or a fraction.
877fn cast_sizing(v: Value) -> Outcome<Value> {
878 match v {
879 Value::Auto | Value::Fraction(_) => Ok(v),
880 Value::Relative(_) | Value::Length(_) | Value::Ratio(_)
881 => Ok(Value::Relative(res!(cast_rel(v)))),
882 other => Err(mismatch("relative length, fraction, or auto", &other)),
883 }
884}
885
886fn cast_scale_amount(v: Value) -> Outcome<Value> {
887 match v {
888 Value::Auto | Value::Ratio(_) | Value::Length(_) => Ok(v),
889 other => Err(mismatch("ratio, length, or auto", &other)),
890 }
891}
892
893/// A point: an array of exactly two relative lengths, stored as two `Relative`s.
894pub fn cast_point(v: Value) -> Outcome<Value> {
895 match v {
896 Value::Array(a) => {
897 if a.len() != 2 {
898 return Err(err!("point array must contain exactly two entries"; Input, Invalid));
899 }
900 Ok(Value::array(vec![
901 Value::Relative(res!(cast_rel(a[0].clone()))),
902 Value::Relative(res!(cast_rel(a[1].clone()))),
903 ]))
904 },
905 other => Err(mismatch("array", &other)),
906 }
907}
908
909/// A point's two coordinates, from a value `cast_point` accepts.
910pub fn point_of(v: &Value) -> Outcome<(Relative, Relative)> {
911 match res!(cast_point(v.clone())) {
912 Value::Array(a) if a.len() == 2 => Ok((res!(cast_rel(a[0].clone())), res!(cast_rel(a[1].clone())))),
913 _ => Err(err!("point array must contain exactly two entries"; Input, Invalid)),
914 }
915}
916
917fn cast_content(v: Value) -> Outcome<Value> {
918 match v {
919 Value::Content(_) => Ok(v),
920 Value::Str(s) => Ok(Value::Content(Content::text(&s))),
921 Value::Int(i) => Ok(Value::Content(Content::text(&fmt!("{}", i)))),
922 Value::Float(x) => Ok(Value::Content(Content::text(&fmt!("{}", x)))),
923 Value::Symbol(_) => Ok(v),
924 Value::None => Ok(Value::Content(Content::empty())),
925 other => Err(mismatch("content", &other)),
926 }
927}
928
929fn cast_opt_content(v: Value) -> Outcome<Value> {
930 match v {
931 Value::None => Ok(v),
932 other => cast_content(other),
933 }
934}
935
936fn cast_paint_some(v: Value) -> Outcome<Paint> {
937 match v {
938 Value::Color(c) => Ok(Paint::Color(c)),
939 Value::Gradient(g) => Ok(Paint::Gradient(g)),
940 Value::Tiling(t) => Ok(Paint::Tiling(t)),
941 other => Err(mismatch("color, gradient, or tiling", &other)),
942 }
943}
944
945/// A paint as a value, the inverse of the paint cast.
946pub fn paint_value(p: &Paint) -> Value {
947 match p {
948 Paint::Color(c) => Value::Color(*c),
949 Paint::Gradient(g) => Value::Gradient(g.clone()),
950 Paint::Tiling(t) => Value::Tiling(t.clone()),
951 }
952}
953
954/// `fill`: `none` or a paint.
955pub fn cast_fill(v: Value) -> Outcome<Value> {
956 match v {
957 Value::None => Ok(v),
958 other => match res!(cast_paint_some(other.clone()).map_err(|_| mismatch("color, gradient, tiling, or none", &other))) {
959 p => Ok(paint_value(&p)),
960 },
961 }
962}
963
964pub fn fill_of(v: &Value) -> Outcome<Option<Paint>> {
965 match v {
966 Value::None | Value::Auto => Ok(None),
967 other => Ok(Some(res!(cast_paint_some(other.clone())))),
968 }
969}
970
971fn cast_fill_rule(v: Value) -> Outcome<Value> {
972 Ok(Value::Str(res!(keyword(&v, &["non-zero", "even-odd"], FILL_RULE))))
973}
974
975fn cast_cap(v: Value) -> Outcome<LineCap> {
976 match res!(keyword(&v, &["butt", "round", "square"], CAP)).as_str() {
977 "butt" => Ok(LineCap::Butt),
978 "round" => Ok(LineCap::Round),
979 _ => Ok(LineCap::Square),
980 }
981}
982
983fn cast_join(v: Value) -> Outcome<LineJoin> {
984 match res!(keyword(&v, &["miter", "round", "bevel"], JOIN)).as_str() {
985 "miter" => Ok(LineJoin::Miter),
986 "round" => Ok(LineJoin::Round),
987 _ => Ok(LineJoin::Bevel),
988 }
989}
990
991fn dash_item(v: Value) -> Outcome<DashItem> {
992 match v {
993 Value::Length(l) => Ok(DashItem::Len(l)),
994 Value::Str(s) if *s == "dot" => Ok(DashItem::Dot),
995 other => Err(mismatch("length or \"dot\"", &other)),
996 }
997}
998
999/// A dash pattern: `none`, a named pattern (TikZ's names), an array of lengths and `"dot"`, or a
1000/// dictionary of `array` and `phase`. `Some(None)` is an explicit solid line.
1001fn cast_dash(v: Value) -> Outcome<Option<Dash>> {
1002 let pt = |p: f64| DashItem::Len(Length::pt(p));
1003 let dot = DashItem::Dot;
1004 let named = |array: Vec<DashItem>| Ok(Some(Dash { array, phase: Length::zero() }));
1005 match v {
1006 Value::None => Ok(None),
1007 Value::Str(s) => match s.as_str() {
1008 "solid" => named(Vec::new()),
1009 "dotted" => named(vec![dot, pt(2.0)]),
1010 "densely-dotted" => named(vec![dot, pt(1.0)]),
1011 "loosely-dotted" => named(vec![dot, pt(4.0)]),
1012 "dashed" => named(vec![pt(3.0), pt(3.0)]),
1013 "densely-dashed" => named(vec![pt(3.0), pt(2.0)]),
1014 "loosely-dashed" => named(vec![pt(3.0), pt(6.0)]),
1015 "dash-dotted" => named(vec![pt(3.0), pt(2.0), dot, pt(2.0)]),
1016 "densely-dash-dotted" => named(vec![pt(3.0), pt(1.0), dot, pt(1.0)]),
1017 "loosely-dash-dotted" => named(vec![pt(3.0), pt(4.0), dot, pt(4.0)]),
1018 _ => Err(err!("expected \"solid\", \"dotted\", \"densely-dotted\", \"loosely-dotted\", \
1019 \"dashed\", \"densely-dashed\", \"loosely-dashed\", \"dash-dotted\", \
1020 \"densely-dash-dotted\", \"loosely-dash-dotted\", array, dictionary, dash, or none";
1021 Input, Invalid)),
1022 },
1023 Value::Array(a) => {
1024 let mut array = Vec::new();
1025 for x in a.iter() {
1026 array.push(res!(dash_item(x.clone())));
1027 }
1028 Ok(Some(Dash { array, phase: Length::zero() }))
1029 },
1030 Value::Dict(d) => {
1031 let mut array = Vec::new();
1032 match d.get("array") {
1033 Some(Value::Array(a)) => for x in a.iter() {
1034 array.push(res!(dash_item(x.clone())));
1035 },
1036 Some(other) => return Err(mismatch("array", other)),
1037 None => return Err(err!("dictionary does not contain key \"array\""; Input, Missing)),
1038 }
1039 let phase = match d.get("phase") {
1040 Some(v) => res!(cast_length(v.clone())),
1041 None => Length::zero(),
1042 };
1043 for k in d.keys() {
1044 if k != "array" && k != "phase" {
1045 return Err(err!("unexpected key \"{}\", valid keys are \"array\" and \"phase\"", k;
1046 Input, Invalid));
1047 }
1048 }
1049 Ok(Some(Dash { array, phase }))
1050 },
1051 other => Err(mismatch("string, array, dictionary, or none", &other)),
1052 }
1053}
1054
1055/// Typst's stroke cast: a length, a paint, a dictionary of parts, or a stroke. Unset parts stay unset so
1056/// strokes fold.
1057pub fn cast_stroke(v: Value) -> Outcome<Stroke> {
1058 match v {
1059 Value::Stroke(s) => Ok((*s).clone()),
1060 Value::Length(l) => Ok(Stroke { thickness: Some(l), ..Stroke::default() }),
1061 Value::Color(c) => Ok(Stroke { paint: Some(Paint::Color(c)), ..Stroke::default() }),
1062 Value::Gradient(g) => Ok(Stroke { paint: Some(Paint::Gradient(g)), ..Stroke::default() }),
1063 Value::Tiling(t) => Ok(Stroke { paint: Some(Paint::Tiling(t)), ..Stroke::default() }),
1064 Value::Dict(d) => {
1065 let mut s = Stroke::default();
1066 for (k, v) in d.iter() {
1067 let v = v.clone();
1068 match k {
1069 "paint" => s.paint = res!(smart(v, cast_paint_some)),
1070 "thickness" => s.thickness = res!(smart(v, cast_length)),
1071 "cap" => s.cap = res!(smart(v, cast_cap)),
1072 "join" => s.join = res!(smart(v, cast_join)),
1073 "dash" => s.dash = res!(smart(v, cast_dash)),
1074 "miter-limit" => s.miter_limit = res!(smart(v, |v| v.cast::<f64>())),
1075 other => return Err(err!("unexpected key \"{}\", valid keys are \"paint\", \
1076 \"thickness\", \"cap\", \"join\", \"dash\", and \"miter-limit\"", other;
1077 Input, Invalid)),
1078 }
1079 }
1080 Ok(s)
1081 },
1082 other => Err(mismatch("length, color, gradient, tiling, dictionary, or stroke", &other)),
1083 }
1084}
1085
1086/// `Smart<Option<Stroke>>`: `auto`, `none`, or a stroke.
1087pub fn cast_smart_stroke(v: Value) -> Outcome<Value> {
1088 match v {
1089 Value::Auto | Value::None => Ok(v),
1090 other => Ok(Value::Stroke(Arc::new(res!(cast_stroke(other))))),
1091 }
1092}
1093
1094fn cast_opt_stroke(v: Value) -> Outcome<Value> {
1095 match v {
1096 Value::None => Ok(v),
1097 other => Ok(Value::Stroke(Arc::new(res!(cast_stroke(other))))),
1098 }
1099}
1100
1101fn cast_opt_rel(v: Value) -> Outcome<Value> {
1102 Ok(Value::Relative(res!(cast_rel(v))))
1103}
1104
1105// Sides and corners
1106
1107const SIDES: [&str; 4] = ["left", "top", "right", "bottom"];
1108const CORNERS: [&str; 4] = ["top-left", "top-right", "bottom-right", "bottom-left"];
1109
1110// Collapses four set parts to one value when they agree, as Typst's `Sides`/`Corners` do on output.
1111fn uniform(parts: &[Option<Value>; 4]) -> Option<Value> {
1112 let first = match &parts[0] {
1113 Some(v) => v,
1114 None => return None,
1115 };
1116 for p in parts.iter().skip(1) {
1117 match p {
1118 Some(v) if same(first, v) => (),
1119 _ => return None,
1120 }
1121 }
1122 Some(first.clone())
1123}
1124
1125// Structural equality over the values sides and corners hold.
1126fn same(a: &Value, b: &Value) -> bool {
1127 match (a, b) {
1128 (Value::None, Value::None) => true,
1129 (Value::Auto, Value::Auto) => true,
1130 (Value::Relative(x), Value::Relative(y)) => x == y,
1131 (Value::Length(x), Value::Length(y)) => x == y,
1132 (Value::Stroke(x), Value::Stroke(y)) => Arc::ptr_eq(x, y) || stroke_eq(x, y),
1133 _ => false,
1134 }
1135}
1136
1137fn stroke_eq(a: &Stroke, b: &Stroke) -> bool {
1138 let paint = match (&a.paint, &b.paint) {
1139 (None, None) => true,
1140 (Some(Paint::Color(x)), Some(Paint::Color(y))) => x == y,
1141 (Some(Paint::Gradient(x)), Some(Paint::Gradient(y))) => x == y,
1142 (Some(Paint::Tiling(x)), Some(Paint::Tiling(y))) => Arc::ptr_eq(x, y),
1143 _ => false,
1144 };
1145 paint && a.thickness == b.thickness && a.cap == b.cap && a.join == b.join
1146 && a.dash == b.dash && a.miter_limit == b.miter_limit
1147}
1148
1149fn sides_value(parts: [Option<Value>; 4]) -> Value {
1150 if let Some(v) = uniform(&parts) {
1151 return v;
1152 }
1153 let mut d = Dict::new();
1154 for (k, p) in SIDES.iter().zip(parts) {
1155 if let Some(v) = p {
1156 d.insert(k, v);
1157 }
1158 }
1159 Value::dict(d)
1160}
1161
1162fn corners_value(parts: [Option<Value>; 4]) -> Value {
1163 if let Some(v) = uniform(&parts) {
1164 return v;
1165 }
1166 let mut d = Dict::new();
1167 for (k, p) in CORNERS.iter().zip(parts) {
1168 if let Some(v) = p {
1169 d.insert(k, v);
1170 }
1171 }
1172 Value::dict(d)
1173}
1174
1175/// The four sides (left, top, right, bottom) of a normalised sides value; unset sides are `None`.
1176pub fn sides_of(v: &Value) -> [Option<Value>; 4] {
1177 match v {
1178 Value::Dict(d) => SIDES.map(|k| d.get(k).cloned()),
1179 other => [Some(other.clone()), Some(other.clone()), Some(other.clone()), Some(other.clone())],
1180 }
1181}
1182
1183/// The four corners (top-left, top-right, bottom-right, bottom-left) of a normalised corners value.
1184pub fn corners_of(v: &Value) -> [Option<Value>; 4] {
1185 match v {
1186 Value::Dict(d) => CORNERS.map(|k| d.get(k).cloned()),
1187 other => [Some(other.clone()), Some(other.clone()), Some(other.clone()), Some(other.clone())],
1188 }
1189}
1190
1191// A sides dictionary: `rest`, then `x`/`y`, then the named sides, each more specific key winning.
1192fn expand_sides<F>(d: &Dict, cast: &F) -> Outcome<[Option<Value>; 4]>
1193 where F: Fn(Value) -> Outcome<Value>
1194{
1195 for k in d.keys() {
1196 if !matches!(k, "left" | "top" | "right" | "bottom" | "x" | "y" | "rest") {
1197 return Err(err!("unexpected key \"{}\", valid keys are \"left\", \"top\", \"right\", \
1198 \"bottom\", \"x\", \"y\", and \"rest\"", k; Input, Invalid));
1199 }
1200 }
1201 let get = |k: &str| -> Outcome<Option<Value>> {
1202 match d.get(k) {
1203 Some(v) => Ok(Some(res!(cast(v.clone())))),
1204 None => Ok(None),
1205 }
1206 };
1207 let rest = res!(get("rest"));
1208 let x = res!(get("x")).or_else(|| rest.clone());
1209 let y = res!(get("y")).or_else(|| rest.clone());
1210 Ok([
1211 res!(get("left")).or_else(|| x.clone()),
1212 res!(get("top")).or_else(|| y.clone()),
1213 res!(get("right")).or(x),
1214 res!(get("bottom")).or(y),
1215 ])
1216}
1217
1218fn expand_corners<F>(d: &Dict, cast: &F) -> Outcome<[Option<Value>; 4]>
1219 where F: Fn(Value) -> Outcome<Value>
1220{
1221 for k in d.keys() {
1222 if !matches!(k, "top-left" | "top-right" | "bottom-right" | "bottom-left"
1223 | "left" | "top" | "right" | "bottom" | "rest")
1224 {
1225 return Err(err!("unexpected key \"{}\", valid keys are \"top-left\", \"top-right\", \
1226 \"bottom-right\", \"bottom-left\", \"left\", \"top\", \"right\", \"bottom\", and \"rest\"", k;
1227 Input, Invalid));
1228 }
1229 }
1230 let get = |k: &str| -> Outcome<Option<Value>> {
1231 match d.get(k) {
1232 Some(v) => Ok(Some(res!(cast(v.clone())))),
1233 None => Ok(None),
1234 }
1235 };
1236 let rest = res!(get("rest"));
1237 let left = res!(get("left")).or_else(|| rest.clone());
1238 let top = res!(get("top")).or_else(|| rest.clone());
1239 let right = res!(get("right")).or_else(|| rest.clone());
1240 let bottom = res!(get("bottom")).or_else(|| rest.clone());
1241 Ok([
1242 res!(get("top-left")).or_else(|| top.clone()).or_else(|| left.clone()),
1243 res!(get("top-right")).or_else(|| top.clone()).or_else(|| right.clone()),
1244 res!(get("bottom-right")).or_else(|| bottom.clone()).or_else(|| right.clone()),
1245 res!(get("bottom-left")).or_else(|| bottom.clone()).or_else(|| left.clone()),
1246 ])
1247}
1248
1249const SIDE_KEYS: [&str; 7] = ["left", "top", "right", "bottom", "x", "y", "rest"];
1250const CORNER_KEYS: [&str; 9] = ["top-left", "top-right", "bottom-right", "bottom-left",
1251 "left", "top", "right", "bottom", "rest"];
1252
1253// As Typst casts `Sides`: a dictionary naming any side key is sides (other keys then an error), an empty
1254// one sets no side, and anything else, a stroke dictionary included, is one value for all four.
1255// A sides value. A plain value that fails the part cast is reported against everything the field
1256// accepts, `expected`, as Typst reports a failed cast to `Sides<..>`.
1257fn cast_sides<F>(v: Value, cast: F, expected: &str) -> Outcome<Value>
1258 where F: Fn(Value) -> Outcome<Value>
1259{
1260 match v {
1261 Value::Dict(d) if d.is_empty() => Ok(Value::dict(Dict::new())),
1262 Value::Dict(d) if d.keys().any(|k| SIDE_KEYS.contains(&k)) => Ok(sides_value(res!(expand_sides(&d, &cast)))),
1263 other => match cast(other.clone()) {
1264 Ok(v) => Ok(v),
1265 Err(_) => Err(mismatch(expected, &other)),
1266 },
1267 }
1268}
1269
1270/// `inset`/`outset`: a relative length or a sides dictionary of them.
1271pub fn cast_sides_rel(v: Value) -> Outcome<Value> { cast_sides(v, cast_opt_rel, "relative length or dictionary") }
1272
1273/// A rect's `stroke`: `auto`, or a stroke (or `none`) or a sides dictionary of them.
1274pub fn cast_stroke_sides(v: Value) -> Outcome<Value> {
1275 match v {
1276 Value::Auto => Ok(v),
1277 other => cast_sides(other, cast_opt_stroke,
1278 "length, color, gradient, tiling, dictionary, stroke, none, or auto"),
1279 }
1280}
1281
1282/// `radius`: a relative length or a corners dictionary of them.
1283pub fn cast_corners_rel(v: Value) -> Outcome<Value> {
1284 match v {
1285 Value::Dict(d) if d.is_empty() => Ok(Value::dict(Dict::new())),
1286 Value::Dict(d) if d.keys().any(|k| CORNER_KEYS.contains(&k)) => Ok(corners_value(res!(expand_corners(&d, &cast_opt_rel)))),
1287 other => match cast_opt_rel(other.clone()) {
1288 Ok(v) => Ok(v),
1289 Err(_) => Err(mismatch("relative length or dictionary", &other)),
1290 },
1291 }
1292}
1293
1294fn cast_relative_to(v: Value) -> Outcome<RelativeTo> {
1295 match res!(keyword(&v, &["self", "parent"], RELATIVE_TO)).as_str() {
1296 "self" => Ok(RelativeTo::SelfBox),
1297 _ => Ok(RelativeTo::Parent),
1298 }
1299}
1300
1301fn length_pair(v: Value, what: &str) -> Outcome<(Length, Length)> {
1302 match v {
1303 Value::Array(a) if a.len() == 2 => Ok((res!(cast_length(a[0].clone())), res!(cast_length(a[1].clone())))),
1304 _ => Err(err!("{} must be an array of two lengths", what; Input, Invalid)),
1305 }
1306}
1307
1308/// An alignment's axes with Typst's transform default filling the absent one: centre and horizon.
1309pub fn origin_of(v: Option<Value>) -> Outcome<(HAlign, VAlign)> {
1310 let a = match v {
1311 Some(Value::Alignment(a)) => a,
1312 Some(Value::None) | None => Alignment::default(),
1313 Some(other) => return Err(mismatch("alignment", &other)),
1314 };
1315 Ok((a.x.unwrap_or(HAlign::Center), a.y.unwrap_or(VAlign::Horizon)))
1316}