oxedyne/fe2o3/fe2o3_austenite/src/flow/visual.rs
69.7 KiB, 32 runs
created by r1870400018:63538, 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-layout `shapes.rs`, `transforms.rs`, `image.rs` and `repeat.rs`, version 0.15.1). |
| 3 | // Modified for Austenite: ported to Hematite's types, IR and error handling. |
| 4 | // U6d owns this file: images, shapes, curves and transforms into one atomic box each, over `image.rs`, |
| 5 | // `fe2o3_graphics` paths and `ir::TransformNode`/`ir::ClipNode`. |
| 6 | // |
| 7 | // Layout follows Typst 0.15's `typst-layout` (shapes.rs, transforms.rs, image.rs, repeat.rs) closely enough |
| 8 | // that the geometry can be checked against the `typst` oracle's SVG output shape for shape. Each element is |
| 9 | // laid out, as Typst lays it out, into a `Frame` of positioned items in points (y down), which is then |
| 10 | // lowered to IR: ink becomes one `Graphic` leaf, a laid-out body stays as nodes, and the two are overlaid |
| 11 | // in a vertical box whose layers back up over one another with negative glue. |
| 12 | // |
| 13 | // A transformed or clipped frame lowers to a `Node::Transform` or `Node::Clip` holding its material, which the |
| 14 | // driver places as a group; a raster's cover crop is still done on its pixels. |
| 15 | // |
| 16 | // An infinite region extent is `Sp(i32::MAX)` (anything from 2^30 up reads as infinite). |
| 17 | |
| 18 | use crate::diag::DiagnosticKind; |
| 19 | use crate::eval::content::{ |
| 20 | Content, |
| 21 | ElemKind, |
| 22 | }; |
| 23 | use crate::eval::lib::visual::{ |
| 24 | self as vis, |
| 25 | fid, |
| 26 | }; |
| 27 | use crate::eval::styles::StyleChain; |
| 28 | use crate::eval::value::{ |
| 29 | DashItem, |
| 30 | HAlign, |
| 31 | LineCap, |
| 32 | LineJoin, |
| 33 | Paint, |
| 34 | Relative, |
| 35 | Stroke, |
| 36 | VAlign, |
| 37 | Value, |
| 38 | }; |
| 39 | use crate::eval::Engine; |
| 40 | use crate::flow::Region; |
| 41 | use crate::image::{ |
| 42 | self as img, |
| 43 | Decoded, |
| 44 | }; |
| 45 | use crate::ir::{ |
| 46 | BoxNode, |
| 47 | ClipNode, |
| 48 | Dims, |
| 49 | DrawOp, |
| 50 | Glue, |
| 51 | Graphic, |
| 52 | LeafKind, |
| 53 | Leaf, |
| 54 | Node, |
| 55 | RasterImage, |
| 56 | Sp, |
| 57 | Transform, |
| 58 | TransformNode, |
| 59 | }; |
| 60 | use crate::syntax::Span; |
| 61 | |
| 62 | use oxedyne_fe2o3_core::prelude::*; |
| 63 | use oxedyne_fe2o3_graphics::{ |
| 64 | colour::Ink, |
| 65 | path::{ |
| 66 | Path, |
| 67 | PathBuilder, |
| 68 | Pt, |
| 69 | }, |
| 70 | stroke::{ |
| 71 | Cap, |
| 72 | Dash as PenDash, |
| 73 | Join, |
| 74 | Stroke as Pen, |
| 75 | }, |
| 76 | svg_doc::SvgOp, |
| 77 | transform::Transform as GTransform, |
| 78 | }; |
| 79 | |
| 80 | use std::sync::Arc; |
| 81 | |
| 82 | const INF_SP: i32 = 1 << 30; // region extents from here up are infinite |
| 83 | const STROKE_TOL: f32 = 0.01; // flattening tolerance of a stroke outline, points |
| 84 | const RAW_UNIT: f64 = 1.0 / 127.0; // Typst's raw length unit in points: a round cap's centre nudge |
| 85 | |
| 86 | // Geometry |
| 87 | |
| 88 | /// A point in points, y down. |
| 89 | #[derive(Clone, Copy, Debug, Default, PartialEq)] |
| 90 | pub struct P2 { |
| 91 | pub x: f64, |
| 92 | pub y: f64, |
| 93 | } |
| 94 | |
| 95 | impl P2 { |
| 96 | pub fn new(x: f64, y: f64) -> Self { Self { x, y } } |
| 97 | fn add(self, o: P2) -> P2 { P2::new(self.x + o.x, self.y + o.y) } |
| 98 | fn sub(self, o: P2) -> P2 { P2::new(self.x - o.x, self.y - o.y) } |
| 99 | fn mul(self, k: f64) -> P2 { P2::new(self.x * k, self.y * k) } |
| 100 | fn hypot(self) -> f64 { self.x.hypot(self.y) } |
| 101 | fn apply(self, t: &Transform) -> P2 { |
| 102 | P2::new(t.a * self.x + t.c * self.y + t.e, t.b * self.x + t.d * self.y + t.f) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// One step of a curve. Quadratics are raised to cubics as they are added, as Typst does. |
| 107 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 108 | pub enum Seg { |
| 109 | Move(P2), |
| 110 | Line(P2), |
| 111 | Cubic(P2, P2, P2), |
| 112 | Close, |
| 113 | } |
| 114 | |
| 115 | #[derive(Clone, Debug, Default, PartialEq)] |
| 116 | pub struct Curve(pub Vec<Seg>); |
| 117 | |
| 118 | impl Curve { |
| 119 | pub fn new() -> Self { Self::default() } |
| 120 | pub fn move_(&mut self, p: P2) { self.0.push(Seg::Move(p)); } |
| 121 | pub fn line(&mut self, p: P2) { self.0.push(Seg::Line(p)); } |
| 122 | pub fn cubic(&mut self, a: P2, b: P2, p: P2) { self.0.push(Seg::Cubic(a, b, p)); } |
| 123 | pub fn close(&mut self) { self.0.push(Seg::Close); } |
| 124 | pub fn is_empty(&self) -> bool { self.0.is_empty() } |
| 125 | |
| 126 | pub fn rect(w: f64, h: f64) -> Self { |
| 127 | let mut c = Curve::new(); |
| 128 | c.move_(P2::new(0.0, 0.0)); |
| 129 | c.line(P2::new(w, 0.0)); |
| 130 | c.line(P2::new(w, h)); |
| 131 | c.line(P2::new(0.0, h)); |
| 132 | c.close(); |
| 133 | c |
| 134 | } |
| 135 | |
| 136 | /// Typst's ellipse inscribed in a `w` by `h` box at the origin. |
| 137 | pub fn ellipse(w: f64, h: f64) -> Self { |
| 138 | let rx = w / 2.0; |
| 139 | let ry = h / 2.0; |
| 140 | let m = 0.551784; |
| 141 | let mx = m * rx; |
| 142 | let my = m * ry; |
| 143 | let p = |x: f64, y: f64| P2::new(x + rx, y + ry); |
| 144 | let mut c = Curve::new(); |
| 145 | c.move_(p(-rx, 0.0)); |
| 146 | c.cubic(p(-rx, -my), p(-mx, -ry), p(0.0, -ry)); |
| 147 | c.cubic(p(mx, -ry), p(rx, -my), p(rx, 0.0)); |
| 148 | c.cubic(p(rx, my), p(mx, ry), p(0.0, ry)); |
| 149 | c.cubic(p(-mx, ry), p(-rx, my), p(-rx, 0.0)); |
| 150 | c |
| 151 | } |
| 152 | |
| 153 | |
| 154 | /// The curve as a `fe2o3_graphics` path, offset by `at`. |
| 155 | pub fn to_path(&self, at: P2) -> Outcome<Path> { |
| 156 | let f = |p: P2| Pt::new((p.x + at.x) as f32, (p.y + at.y) as f32); |
| 157 | let mut b = PathBuilder::new(); |
| 158 | for s in &self.0 { |
| 159 | match *s { |
| 160 | Seg::Move(p) => b.move_to(f(p)), |
| 161 | Seg::Line(p) => b.line_to(f(p)), |
| 162 | Seg::Cubic(a, c, p) => b.cubic_to(f(a), f(c), f(p)), |
| 163 | Seg::Close => b.close(), |
| 164 | } |
| 165 | } |
| 166 | b.finish() |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 171 | pub enum FillRule { |
| 172 | NonZero, |
| 173 | EvenOdd, |
| 174 | } |
| 175 | |
| 176 | /// A stroke with every part decided, lengths in points: Typst's `FixedStroke`. |
| 177 | #[derive(Clone, Debug)] |
| 178 | pub struct FixedStroke { |
| 179 | pub paint: Paint, |
| 180 | pub thickness: f64, |
| 181 | pub cap: LineCap, |
| 182 | pub join: LineJoin, |
| 183 | pub dash: Option<(Vec<f64>, f64)>, // pattern and phase |
| 184 | pub miter_limit: f64, |
| 185 | } |
| 186 | |
| 187 | /// A curve with its fill and stroke. |
| 188 | #[derive(Clone, Debug)] |
| 189 | pub struct Shape { |
| 190 | pub curve: Curve, |
| 191 | pub fill: Option<Paint>, |
| 192 | pub fill_rule: FillRule, |
| 193 | pub stroke: Option<FixedStroke>, |
| 194 | } |
| 195 | |
| 196 | /// What a frame holds at a position. |
| 197 | #[derive(Clone, Debug)] |
| 198 | pub enum Item { |
| 199 | Shape(Shape), |
| 200 | Raster { image: Arc<RasterImage>, w: f64, h: f64 }, // fills (0, 0) to (w, h) from its position |
| 201 | Ops(Vec<DrawOp>), // ready ink, in the frame's own coordinates |
| 202 | Nodes { nodes: Vec<Node>, dims: Dims }, // laid-out content, its top-left at the position |
| 203 | Group { frame: Box<Frame>, transform: Transform, clip: Option<Curve> }, |
| 204 | } |
| 205 | |
| 206 | /// Typst's frame: a sized box of positioned items. `baseline` is from the top; none means the bottom. |
| 207 | #[derive(Clone, Debug, Default)] |
| 208 | pub struct Frame { |
| 209 | pub width: f64, |
| 210 | pub height: f64, |
| 211 | pub baseline: Option<f64>, |
| 212 | pub items: Vec<(P2, Item)>, |
| 213 | } |
| 214 | |
| 215 | impl Frame { |
| 216 | pub fn new(width: f64, height: f64) -> Self { Self { width, height, baseline: None, items: Vec::new() } } |
| 217 | |
| 218 | pub fn push(&mut self, at: P2, item: Item) { self.items.push((at, item)); } |
| 219 | |
| 220 | /// Puts items behind everything already in the frame. |
| 221 | pub fn prepend(&mut self, items: Vec<(P2, Item)>) { |
| 222 | let mut v = items; |
| 223 | v.append(&mut self.items); |
| 224 | self.items = v; |
| 225 | } |
| 226 | |
| 227 | pub fn translate(&mut self, d: P2) { |
| 228 | if d.x == 0.0 && d.y == 0.0 { |
| 229 | return; |
| 230 | } |
| 231 | if let Some(b) = &mut self.baseline { |
| 232 | *b += d.y; |
| 233 | } |
| 234 | for (p, _) in &mut self.items { |
| 235 | *p = p.add(d); |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | /// Moves the contents but not the baseline. |
| 240 | pub fn translate_visual(&mut self, d: P2) { |
| 241 | for (p, _) in &mut self.items { |
| 242 | *p = p.add(d); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | pub fn baseline(&self) -> f64 { self.baseline.unwrap_or(self.height) } |
| 247 | |
| 248 | /// Wraps the contents in a group drawn under `t`; the frame keeps its size. |
| 249 | pub fn transform(&mut self, t: Transform) { |
| 250 | if self.items.is_empty() { |
| 251 | return; |
| 252 | } |
| 253 | let inner = Frame { width: self.width, height: self.height, baseline: None, items: std::mem::take(&mut self.items) }; |
| 254 | self.items.push((P2::default(), Item::Group { frame: Box::new(inner), transform: t, clip: None })); |
| 255 | } |
| 256 | |
| 257 | pub fn clip(&mut self, c: Curve) { |
| 258 | if self.items.is_empty() { |
| 259 | return; |
| 260 | } |
| 261 | let inner = Frame { width: self.width, height: self.height, baseline: None, items: std::mem::take(&mut self.items) }; |
| 262 | self.items.push((P2::default(), Item::Group { frame: Box::new(inner), transform: Transform::identity(), clip: Some(c) })); |
| 263 | } |
| 264 | |
| 265 | /// Resizes to `target`, placing the contents by `align` (0 start, 0.5 centre, 1 end, per axis). |
| 266 | fn resize(&mut self, tw: f64, th: f64, ax: f64, ay: f64) { |
| 267 | let d = P2::new((tw - self.width) * ax, (th - self.height) * ay); |
| 268 | self.width = tw; |
| 269 | self.height = th; |
| 270 | self.translate(d); |
| 271 | } |
| 272 | |
| 273 | /// Drops this frame's own ink, keeping laid-out content (whose ink its own layout decides) and size. |
| 274 | fn hide(&mut self) { |
| 275 | self.items.retain(|(_, i)| matches!(i, Item::Nodes { .. } | Item::Group { .. })); |
| 276 | for (_, i) in &mut self.items { |
| 277 | if let Item::Group { frame, .. } = i { |
| 278 | frame.hide(); |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | /// The space an element's own layout sees: Typst's region, in points, possibly infinite. |
| 285 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 286 | pub struct Pod { |
| 287 | pub w: f64, |
| 288 | pub h: f64, |
| 289 | pub expand_x: bool, |
| 290 | pub expand_y: bool, |
| 291 | } |
| 292 | |
| 293 | impl Pod { |
| 294 | pub fn new(w: f64, h: f64, expand_x: bool, expand_y: bool) -> Self { Self { w, h, expand_x, expand_y } } |
| 295 | |
| 296 | fn finite(&self) -> bool { self.w.is_finite() && self.h.is_finite() } |
| 297 | |
| 298 | /// The pod as a flow region. |
| 299 | pub fn region(&self) -> Region { |
| 300 | let w = sp_of(self.w); |
| 301 | let h = sp_of(self.h); |
| 302 | Region { width: w, height: h, base: (w, h), expand_x: self.expand_x, expand_y: self.expand_y } |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | fn pt_of(sp: Sp) -> f64 { |
| 307 | if sp.0 >= INF_SP { f64::INFINITY } else { sp.to_pt() } |
| 308 | } |
| 309 | |
| 310 | fn sp_of(pt: f64) -> Sp { |
| 311 | if !pt.is_finite() || pt >= Sp(INF_SP).to_pt() { Sp(i32::MAX) } else { Sp::from_pt(pt) } |
| 312 | } |
| 313 | |
| 314 | // Style access |
| 315 | |
| 316 | /// The font size in points that resolves `em`: the chain's `text.size`, Typst's 11pt when none is set. |
| 317 | pub fn font_size(styles: &StyleChain) -> f64 { styles.font_size() } |
| 318 | |
| 319 | /// A relative length against a whole, as Typst's `relative_to`: a ratio of an infinite whole is zero, not |
| 320 | /// NaN, so `0% + 5pt` in an unbounded region is 5pt. |
| 321 | pub fn rel_to(r: Relative, whole: f64, fs: f64) -> f64 { |
| 322 | let part = r.rel.0 * whole; |
| 323 | (if part.is_finite() { part } else { 0.0 }) + r.abs.resolve(fs) |
| 324 | } |
| 325 | |
| 326 | struct Get<'a> { |
| 327 | elem: &'a Content, |
| 328 | styles: &'a StyleChain, |
| 329 | kind: ElemKind, |
| 330 | fs: f64, |
| 331 | } |
| 332 | |
| 333 | impl<'a> Get<'a> { |
| 334 | fn val(&self, name: &str) -> Outcome<Option<Value>> { |
| 335 | let id = res!(fid(self.kind, name)); |
| 336 | self.styles.resolve(self.elem, id) |
| 337 | } |
| 338 | |
| 339 | fn rel(&self, r: Relative, whole: f64) -> f64 { rel_to(r, whole, self.fs) } |
| 340 | |
| 341 | fn bool(&self, name: &str, default: bool) -> Outcome<bool> { |
| 342 | match res!(self.val(name)) { |
| 343 | Some(Value::Bool(b)) => Ok(b), |
| 344 | _ => Ok(default), |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | fn content(&self, name: &str) -> Outcome<Option<Content>> { |
| 349 | match res!(self.val(name)) { |
| 350 | None | Some(Value::None) => Ok(None), |
| 351 | Some(Value::Content(c)) => Ok(Some(c)), |
| 352 | Some(Value::Str(s)) => Ok(Some(Content::text(&s))), |
| 353 | Some(other) => Ok(Some(res!(other.cast::<Content>()))), |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | // Entry points |
| 359 | |
| 360 | /// A visual element as one box, placeable inline or as a block. Its body, if any, is laid out by |
| 361 | /// [`crate::flow::layout_block`]. |
| 362 | pub fn layout_visual( |
| 363 | engine: &mut Engine, |
| 364 | elem: &Content, |
| 365 | styles: &StyleChain, |
| 366 | region: Region, |
| 367 | ) |
| 368 | -> Outcome<Node> |
| 369 | { |
| 370 | let frame = res!(layout_frame(engine, elem, styles, region)); |
| 371 | frame_to_node(engine, &frame, elem.span()) |
| 372 | } |
| 373 | |
| 374 | /// The element laid out into a frame, its body through [`crate::flow::layout_block`]. |
| 375 | pub fn layout_frame( |
| 376 | engine: &mut Engine, |
| 377 | elem: &Content, |
| 378 | styles: &StyleChain, |
| 379 | region: Region, |
| 380 | ) |
| 381 | -> Outcome<Frame> |
| 382 | { |
| 383 | layout_frame_with(engine, elem, styles, region, &mut layout_body) |
| 384 | } |
| 385 | |
| 386 | /// Lays a body out in a pod as the flow does, and wraps the nodes as a frame. |
| 387 | pub fn layout_body(engine: &mut Engine, body: &Content, styles: &StyleChain, pod: Pod) -> Outcome<Frame> { |
| 388 | let nodes = res!(crate::flow::layout_block(engine, body, styles, pod.region())); |
| 389 | let dims = vlist_dims(&nodes); |
| 390 | let w = if pod.expand_x { pod.w } else { dims.width.to_pt() }; |
| 391 | let h = if pod.expand_y { pod.h } else { dims.vextent().to_pt() }; |
| 392 | let mut f = Frame::new(w, h); |
| 393 | f.baseline = first_baseline(&nodes).map(|b| b.to_pt()); |
| 394 | f.push(P2::default(), Item::Nodes { nodes, dims }); |
| 395 | Ok(f) |
| 396 | } |
| 397 | |
| 398 | /// As [`layout_frame`], with the routine that lays out a body passed in: what the element does around its |
| 399 | /// body is this file's, and how content becomes a frame is the caller's. |
| 400 | pub fn layout_frame_with<F>( |
| 401 | engine: &mut Engine, |
| 402 | elem: &Content, |
| 403 | styles: &StyleChain, |
| 404 | region: Region, |
| 405 | body: &mut F, |
| 406 | ) |
| 407 | -> Outcome<Frame> |
| 408 | where F: FnMut(&mut Engine, &Content, &StyleChain, Pod) -> Outcome<Frame> |
| 409 | { |
| 410 | let kind = match elem.kind() { |
| 411 | Some(k) => k, |
| 412 | None => return Err(err!("layout_visual was given a sequence, not an element."; Bug, Invalid)), |
| 413 | }; |
| 414 | let g = Get { elem, styles, kind, fs: font_size(styles) }; |
| 415 | let span = elem.span(); |
| 416 | // The body is laid out, however many times, at the element's place. |
| 417 | let place = elem.place(); |
| 418 | let mut at_place = |engine: &mut Engine, b: &Content, s: &StyleChain, pod: Pod| engine.within(place, |e| body(e, b, s, pod)); |
| 419 | let body = &mut at_place; |
| 420 | |
| 421 | // Every visual element is shown by Typst as a block whose single child is the element's layouter; the |
| 422 | // block's `width` and `height` (shapes and images have them) decide the pod. |
| 423 | let base_w = pt_of(region.base.0); |
| 424 | let base_h = pt_of(region.base.1); |
| 425 | let mut pod = Pod::new(pt_of(region.width), pt_of(region.height), false, false); |
| 426 | if kind.field_id("width").is_some() && kind != ElemKind::Hide { |
| 427 | if let Some(Value::Relative(r)) = res!(g.val("width")).map(|v| v).and_then(|v| cast_opt_rel(v)) { |
| 428 | pod.w = g.rel(r, base_w); |
| 429 | pod.expand_x = true; |
| 430 | } |
| 431 | match res!(g.val("height")) { |
| 432 | Some(Value::Fraction(_)) => pod.expand_y = true, |
| 433 | Some(v) => if let Some(Value::Relative(r)) = cast_opt_rel(v) { |
| 434 | pod.h = g.rel(r, base_h); |
| 435 | pod.expand_y = true; |
| 436 | }, |
| 437 | None => (), |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | let mut frame = match kind { |
| 442 | ElemKind::Line => res!(layout_line(&g, pod, span, engine)), |
| 443 | ElemKind::Polygon => res!(layout_polygon(&g, pod, span, engine)), |
| 444 | ElemKind::Curve => res!(layout_curve(&g, pod, span, engine)), |
| 445 | ElemKind::Rect | ElemKind::Square | ElemKind::Ellipse | ElemKind::Circle |
| 446 | => res!(layout_shape(engine, &g, pod, body)), |
| 447 | ElemKind::Image => res!(layout_image(engine, &g, pod)), |
| 448 | ElemKind::Move => res!(layout_move(engine, &g, pod, body)), |
| 449 | ElemKind::Rotate | ElemKind::Scale | ElemKind::Skew |
| 450 | => res!(layout_transform(engine, &g, pod, body)), |
| 451 | ElemKind::Repeat => res!(layout_repeat(engine, &g, pod, body)), |
| 452 | // `hide` is shown as its body under the `hidden` style before flow sees it; laid out directly, it |
| 453 | // is that body, hidden. |
| 454 | ElemKind::Hide => { |
| 455 | let b = match res!(g.content("body")) { |
| 456 | Some(b) => b, |
| 457 | None => Content::empty(), |
| 458 | }; |
| 459 | let mut f = res!(body(engine, &b, styles, pod)); |
| 460 | f.hide(); |
| 461 | f |
| 462 | }, |
| 463 | other => return Err(engine.error(DiagnosticKind::Unsupported, span, fmt!("{} is not a visual element flow can lay out", other.path()))), |
| 464 | }; |
| 465 | |
| 466 | // The block keeps the size it was given on an expanded axis. |
| 467 | if pod.expand_x && pod.w.is_finite() { |
| 468 | frame.width = pod.w; |
| 469 | } |
| 470 | if pod.expand_y && pod.h.is_finite() { |
| 471 | frame.height = pod.h; |
| 472 | } |
| 473 | if res!(vis::is_hidden(styles)) { |
| 474 | frame.hide(); |
| 475 | } |
| 476 | Ok(frame) |
| 477 | } |
| 478 | |
| 479 | fn cast_opt_rel(v: Value) -> Option<Value> { |
| 480 | match v { |
| 481 | Value::Auto | Value::None | Value::Fraction(_) => None, |
| 482 | other => vis::cast_rel(other).ok().map(Value::Relative), |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | // Strokes and paints |
| 487 | |
| 488 | // Typst's default stroke: 1pt black, butt caps, miter joins, miter limit 4. |
| 489 | fn default_stroke() -> FixedStroke { |
| 490 | FixedStroke { |
| 491 | paint: Paint::Color(black()), |
| 492 | thickness: 1.0, |
| 493 | cap: LineCap::Butt, |
| 494 | join: LineJoin::Miter, |
| 495 | dash: None, |
| 496 | miter_limit: 4.0, |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | fn black() -> crate::eval::value::Color { |
| 501 | crate::eval::value::Color { space: crate::eval::value::ColorSpace::Luma, c: [0.0, 0.0, 0.0, 0.0], alpha: 1.0 } |
| 502 | } |
| 503 | |
| 504 | /// A stroke's unset parts filled from Typst's default, lengths resolved at the font size. |
| 505 | pub fn fix_stroke(s: &Stroke, fs: f64) -> FixedStroke { |
| 506 | let d = default_stroke(); |
| 507 | let thickness = s.thickness.map(|l| l.resolve(fs)).unwrap_or(d.thickness); |
| 508 | let dash = match &s.dash { |
| 509 | Some(Some(dash)) => { |
| 510 | let pattern = dash.array.iter().map(|i| match i { |
| 511 | DashItem::Len(l) => l.resolve(fs), |
| 512 | DashItem::Dot => thickness, |
| 513 | }).collect::<Vec<_>>(); |
| 514 | // An empty array is the named "solid" pattern. |
| 515 | if pattern.is_empty() { None } else { Some((pattern, dash.phase.resolve(fs))) } |
| 516 | }, |
| 517 | _ => None, |
| 518 | }; |
| 519 | FixedStroke { |
| 520 | paint: s.paint.clone().unwrap_or(d.paint), |
| 521 | thickness, |
| 522 | cap: s.cap.unwrap_or(d.cap), |
| 523 | join: s.join.unwrap_or(d.join), |
| 524 | dash, |
| 525 | miter_limit: s.miter_limit.unwrap_or(d.miter_limit), |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | // `Smart<Option<Stroke>>` resolved against the fill: `auto` strokes only an unfilled shape. |
| 530 | fn smart_stroke(v: Option<Value>, filled: bool, fs: f64) -> Outcome<Option<FixedStroke>> { |
| 531 | match v { |
| 532 | None | Some(Value::Auto) => Ok(if filled { None } else { Some(default_stroke()) }), |
| 533 | Some(Value::None) => Ok(None), |
| 534 | Some(other) => Ok(Some(fix_stroke(&res!(vis::cast_stroke(other)), fs))), |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | fn fill_rule(g: &Get) -> Outcome<FillRule> { |
| 539 | match res!(g.val("fill-rule")) { |
| 540 | Some(Value::Str(s)) if s.as_str() == "even-odd" => Ok(FillRule::EvenOdd), |
| 541 | _ => Ok(FillRule::NonZero), |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | fn fill(g: &Get) -> Outcome<Option<Paint>> { |
| 546 | match res!(g.val("fill")) { |
| 547 | Some(v) => vis::fill_of(&v), |
| 548 | None => Ok(None), |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | fn point(g: &Get, v: &Value, pod: Pod) -> Outcome<P2> { |
| 553 | let (x, y) = res!(vis::point_of(v)); |
| 554 | Ok(P2::new(g.rel(x, pod.w), g.rel(y, pod.h))) |
| 555 | } |
| 556 | |
| 557 | // Line, polygon and curve |
| 558 | |
| 559 | fn layout_line(g: &Get, pod: Pod, span: Span, engine: &mut Engine) -> Outcome<Frame> { |
| 560 | let start = match res!(g.val("start")) { |
| 561 | Some(v) if !v.is_none() => res!(point(g, &v, pod)), |
| 562 | _ => P2::default(), |
| 563 | }; |
| 564 | let delta = match res!(g.val("end")) { |
| 565 | Some(v) if !v.is_none() => res!(point(g, &v, pod)).sub(start), |
| 566 | _ => { |
| 567 | let length = match res!(g.val("length")) { |
| 568 | Some(v) => res!(vis::cast_rel(v)), |
| 569 | None => Relative { rel: crate::eval::value::Ratio(0.0), abs: crate::eval::value::Length::pt(30.0) }, |
| 570 | }; |
| 571 | let angle = match res!(g.val("angle")) { |
| 572 | Some(v) => res!(vis::cast_angle(v)).0, |
| 573 | None => 0.0, |
| 574 | }; |
| 575 | // The length's two parts turn with the angle, each then resolved on its own axis. |
| 576 | let x = Relative { rel: crate::eval::value::Ratio(length.rel.0 * angle.cos()), |
| 577 | abs: crate::eval::value::Length { abs: length.abs.abs * angle.cos(), em: length.abs.em * angle.cos() } }; |
| 578 | let y = Relative { rel: crate::eval::value::Ratio(length.rel.0 * angle.sin()), |
| 579 | abs: crate::eval::value::Length { abs: length.abs.abs * angle.sin(), em: length.abs.em * angle.sin() } }; |
| 580 | P2::new(g.rel(x, pod.w), g.rel(y, pod.h)) |
| 581 | }, |
| 582 | }; |
| 583 | let stroke = match res!(g.val("stroke")) { |
| 584 | Some(v) if !v.is_auto() => fix_stroke(&res!(vis::cast_stroke(v)), g.fs), |
| 585 | _ => default_stroke(), |
| 586 | }; |
| 587 | let end = start.add(delta); |
| 588 | let w = start.x.max(end.x).max(0.0); |
| 589 | let h = start.y.max(end.y).max(0.0); |
| 590 | if !w.is_finite() || !h.is_finite() { |
| 591 | return Err(engine.error(DiagnosticKind::Type, span, "cannot create line with infinite length")); |
| 592 | } |
| 593 | let mut frame = Frame::new(w, h); |
| 594 | let mut c = Curve::new(); |
| 595 | c.move_(P2::default()); |
| 596 | c.line(delta); |
| 597 | frame.push(start, Item::Shape(Shape { curve: c, fill: None, fill_rule: FillRule::NonZero, stroke: Some(stroke) })); |
| 598 | Ok(frame) |
| 599 | } |
| 600 | |
| 601 | fn layout_polygon(g: &Get, pod: Pod, span: Span, engine: &mut Engine) -> Outcome<Frame> { |
| 602 | let mut pts = Vec::new(); |
| 603 | if let Some(Value::Array(a)) = res!(g.val("vertices")) { |
| 604 | for v in a.iter() { |
| 605 | pts.push(res!(point(g, v, pod))); |
| 606 | } |
| 607 | } |
| 608 | let w = pts.iter().fold(0.0f64, |m, p| m.max(p.x)); |
| 609 | let h = pts.iter().fold(0.0f64, |m, p| m.max(p.y)); |
| 610 | if !w.is_finite() || !h.is_finite() { |
| 611 | return Err(engine.error(DiagnosticKind::Type, span, "cannot create polygon with infinite size")); |
| 612 | } |
| 613 | let mut frame = Frame::new(w, h); |
| 614 | let first = match pts.first() { |
| 615 | Some(p) => *p, |
| 616 | None => return Ok(frame), |
| 617 | }; |
| 618 | let fill = res!(fill(g)); |
| 619 | let stroke = res!(smart_stroke(res!(g.val("stroke")), fill.is_some(), g.fs)); |
| 620 | let mut c = Curve::new(); |
| 621 | c.move_(first); |
| 622 | for p in &pts[1..] { |
| 623 | c.line(*p); |
| 624 | } |
| 625 | c.close(); |
| 626 | frame.push(P2::default(), Item::Shape(Shape { curve: c, fill, fill_rule: res!(fill_rule(g)), stroke })); |
| 627 | Ok(frame) |
| 628 | } |
| 629 | |
| 630 | // Typst's `CurveBuilder`: quads raised to cubics, `auto` controls mirrored from the previous segment, a |
| 631 | // smooth close drawn as a cubic back to the start, bounds grown by each point and cubic extremum. |
| 632 | struct CurveBuilder { |
| 633 | curve: Curve, |
| 634 | size: P2, |
| 635 | start_point: P2, |
| 636 | start_control_into: P2, |
| 637 | last_point: P2, |
| 638 | last_control_from: P2, |
| 639 | is_started: bool, |
| 640 | is_empty: bool, |
| 641 | } |
| 642 | |
| 643 | impl CurveBuilder { |
| 644 | fn new() -> Self { |
| 645 | Self { |
| 646 | curve: Curve::new(), size: P2::default(), start_point: P2::default(), |
| 647 | start_control_into: P2::default(), last_point: P2::default(), |
| 648 | last_control_from: P2::default(), is_started: false, is_empty: true, |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | fn expand(&mut self, p: P2) { |
| 653 | self.size.x = self.size.x.max(p.x); |
| 654 | self.size.y = self.size.y.max(p.y); |
| 655 | } |
| 656 | |
| 657 | fn move_(&mut self, p: P2) { |
| 658 | self.expand(p); |
| 659 | self.start_point = p; |
| 660 | self.start_control_into = p; |
| 661 | self.last_point = p; |
| 662 | self.last_control_from = p; |
| 663 | self.is_started = true; |
| 664 | self.is_empty = true; |
| 665 | } |
| 666 | |
| 667 | fn start_component(&mut self) { |
| 668 | self.curve.move_(self.start_point); |
| 669 | self.is_empty = false; |
| 670 | self.is_started = true; |
| 671 | } |
| 672 | |
| 673 | fn line(&mut self, p: P2) { |
| 674 | if self.is_empty { |
| 675 | self.start_component(); |
| 676 | self.start_control_into = self.start_point; |
| 677 | } |
| 678 | self.curve.line(p); |
| 679 | self.expand(p); |
| 680 | self.last_point = p; |
| 681 | self.last_control_from = p; |
| 682 | } |
| 683 | |
| 684 | fn quad(&mut self, control: P2, end: P2) { |
| 685 | let c1 = control_q2c(self.last_point, control); |
| 686 | let c2 = control_q2c(end, control); |
| 687 | self.cubic(c1, c2, end); |
| 688 | } |
| 689 | |
| 690 | fn cubic(&mut self, c1: P2, c2: P2, end: P2) { |
| 691 | if self.is_empty { |
| 692 | self.start_component(); |
| 693 | self.start_control_into = mirror_c(self.start_point, c1); |
| 694 | } |
| 695 | self.curve.cubic(c1, c2, end); |
| 696 | let (mx, my) = cubic_max(self.last_point, c1, c2, end); |
| 697 | self.size.x = self.size.x.max(mx); |
| 698 | self.size.y = self.size.y.max(my); |
| 699 | self.last_point = end; |
| 700 | self.last_control_from = mirror_c(end, c2); |
| 701 | } |
| 702 | |
| 703 | fn close(&mut self, smooth: bool) { |
| 704 | if self.is_started && !self.is_empty { |
| 705 | if smooth { |
| 706 | let (a, b, p) = (self.last_control_from, self.start_control_into, self.start_point); |
| 707 | self.cubic(a, b, p); |
| 708 | } |
| 709 | self.curve.close(); |
| 710 | self.last_point = self.start_point; |
| 711 | self.last_control_from = self.start_point; |
| 712 | } |
| 713 | self.is_started = false; |
| 714 | self.is_empty = true; |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | fn control_c2q(p: P2, c: P2) -> P2 { c.mul(1.5).sub(p.mul(0.5)) } |
| 719 | fn control_q2c(p: P2, c: P2) -> P2 { p.add(c.mul(2.0)).mul(1.0 / 3.0) } |
| 720 | fn mirror_c(p: P2, c: P2) -> P2 { p.mul(2.0).sub(c) } |
| 721 | |
| 722 | // The largest x and y a cubic reaches: its end points and the roots of its derivative within (0, 1). |
| 723 | fn cubic_max(p0: P2, p1: P2, p2: P2, p3: P2) -> (f64, f64) { |
| 724 | let axis = |a: f64, b: f64, c: f64, d: f64| -> f64 { |
| 725 | let mut m = a.max(d); |
| 726 | // B'(t)/3 = (b-a)(1-t)^2 + 2(c-b)(1-t)t + (d-c)t^2 = qa t^2 + qb t + qc. |
| 727 | let qa = (b - a) - 2.0 * (c - b) + (d - c); |
| 728 | let qb = 2.0 * ((c - b) - (b - a)); |
| 729 | let qc = b - a; |
| 730 | let mut roots = Vec::new(); |
| 731 | if qa.abs() < 1e-12 { |
| 732 | if qb.abs() > 1e-12 { |
| 733 | roots.push(-qc / qb); |
| 734 | } |
| 735 | } else { |
| 736 | let disc = qb * qb - 4.0 * qa * qc; |
| 737 | if disc >= 0.0 { |
| 738 | let s = disc.sqrt(); |
| 739 | roots.push((-qb + s) / (2.0 * qa)); |
| 740 | roots.push((-qb - s) / (2.0 * qa)); |
| 741 | } |
| 742 | } |
| 743 | for t in roots { |
| 744 | if t > 0.0 && t < 1.0 { |
| 745 | let u = 1.0 - t; |
| 746 | let v = u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d; |
| 747 | m = m.max(v); |
| 748 | } |
| 749 | } |
| 750 | m |
| 751 | }; |
| 752 | (axis(p0.x, p1.x, p2.x, p3.x), axis(p0.y, p1.y, p2.y, p3.y)) |
| 753 | } |
| 754 | |
| 755 | fn layout_curve(g: &Get, pod: Pod, span: Span, engine: &mut Engine) -> Outcome<Frame> { |
| 756 | let mut b = CurveBuilder::new(); |
| 757 | let comps = match res!(g.val("components")) { |
| 758 | Some(Value::Array(a)) => a, |
| 759 | _ => Arc::new(Vec::new()), |
| 760 | }; |
| 761 | for comp in comps.iter() { |
| 762 | let c = match comp { |
| 763 | Value::Content(c) => c, |
| 764 | _ => continue, |
| 765 | }; |
| 766 | let k = match c.kind() { |
| 767 | Some(k) => k, |
| 768 | None => continue, |
| 769 | }; |
| 770 | let cg = Get { elem: c, styles: g.styles, kind: k, fs: g.fs }; |
| 771 | let relative = if k == ElemKind::CurveClose { false } else { res!(cg.bool("relative", false)) }; |
| 772 | let at = |cg: &Get, name: &str, last: P2| -> Outcome<P2> { |
| 773 | let v = match res!(cg.val(name)) { |
| 774 | Some(v) => v, |
| 775 | None => return Err(err!("curve component is missing `{}`", name; Input, Missing)), |
| 776 | }; |
| 777 | let p = res!(point(cg, &v, pod)); |
| 778 | Ok(if relative { p.add(last) } else { p }) |
| 779 | }; |
| 780 | match k { |
| 781 | ElemKind::CurveMove => { |
| 782 | let p = res!(at(&cg, "start", b.last_point)); |
| 783 | b.move_(p); |
| 784 | }, |
| 785 | ElemKind::CurveLine => { |
| 786 | let p = res!(at(&cg, "end", b.last_point)); |
| 787 | b.line(p); |
| 788 | }, |
| 789 | ElemKind::CurveQuad => { |
| 790 | let end = res!(at(&cg, "end", b.last_point)); |
| 791 | let control = match res!(cg.val("control")) { |
| 792 | Some(Value::Auto) => control_c2q(b.last_point, b.last_control_from), |
| 793 | Some(Value::None) | None => end, |
| 794 | Some(_) => res!(at(&cg, "control", b.last_point)), |
| 795 | }; |
| 796 | b.quad(control, end); |
| 797 | }, |
| 798 | ElemKind::CurveCubic => { |
| 799 | let end = res!(at(&cg, "end", b.last_point)); |
| 800 | let c1 = match res!(cg.val("control-start")) { |
| 801 | Some(Value::Auto) => b.last_control_from, |
| 802 | Some(Value::None) | None => b.last_point, |
| 803 | Some(_) => res!(at(&cg, "control-start", b.last_point)), |
| 804 | }; |
| 805 | let c2 = match res!(cg.val("control-end")) { |
| 806 | Some(Value::None) | None => end, |
| 807 | Some(_) => res!(at(&cg, "control-end", b.last_point)), |
| 808 | }; |
| 809 | b.cubic(c1, c2, end); |
| 810 | }, |
| 811 | ElemKind::CurveClose => { |
| 812 | let smooth = !matches!(res!(cg.val("mode")), Some(Value::Str(s)) if s.as_str() == "straight"); |
| 813 | b.close(smooth); |
| 814 | }, |
| 815 | _ => (), |
| 816 | } |
| 817 | } |
| 818 | let (curve, size) = (b.curve, b.size); |
| 819 | let mut frame = Frame::new(size.x, size.y); |
| 820 | if curve.is_empty() { |
| 821 | return Ok(frame); |
| 822 | } |
| 823 | if !size.x.is_finite() || !size.y.is_finite() { |
| 824 | return Err(engine.error(DiagnosticKind::Type, span, "cannot create curve with infinite size")); |
| 825 | } |
| 826 | let fill = res!(fill(g)); |
| 827 | let stroke = res!(smart_stroke(res!(g.val("stroke")), fill.is_some(), g.fs)); |
| 828 | frame.push(P2::default(), Item::Shape(Shape { curve, fill, fill_rule: res!(fill_rule(g)), stroke })); |
| 829 | Ok(frame) |
| 830 | } |
| 831 | |
| 832 | // Rect, square, ellipse, circle |
| 833 | |
| 834 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 835 | enum ShapeKind { |
| 836 | Square, |
| 837 | Rect, |
| 838 | Circle, |
| 839 | Ellipse, |
| 840 | } |
| 841 | |
| 842 | impl ShapeKind { |
| 843 | fn is_round(self) -> bool { matches!(self, ShapeKind::Circle | ShapeKind::Ellipse) } |
| 844 | fn is_quadratic(self) -> bool { matches!(self, ShapeKind::Square | ShapeKind::Circle) } |
| 845 | } |
| 846 | |
| 847 | // Four sides (left, top, right, bottom) of relative lengths. A side the value leaves unset folds onto the |
| 848 | // field's default, as Typst folds `Sides<Option<..>>`: `inset: (x: 2pt)` keeps the 5pt default above and below. |
| 849 | fn sides_rel(g: &Get, name: &str) -> Outcome<[Relative; 4]> { |
| 850 | let default = match g.kind.field_id(name).and_then(|id| g.kind.field_spec(id)).and_then(|f| f.default.to_value()) { |
| 851 | Some(v) => res!(vis::cast_rel(v)), |
| 852 | None => Relative::default(), |
| 853 | }; |
| 854 | let mut out = [default; 4]; |
| 855 | if let Some(v) = res!(g.val(name)) { |
| 856 | let v = res!(vis::cast_sides_rel(v)); |
| 857 | for (k, s) in vis::sides_of(&v).iter().enumerate() { |
| 858 | if let Some(x) = s { |
| 859 | out[k] = res!(vis::cast_rel(x.clone())); |
| 860 | } |
| 861 | } |
| 862 | } |
| 863 | Ok(out) |
| 864 | } |
| 865 | |
| 866 | fn quadratic_size(pod: Pod) -> Option<f64> { |
| 867 | if pod.expand_x && pod.expand_y { |
| 868 | Some(pod.w.min(pod.h)) |
| 869 | } else if pod.expand_x { |
| 870 | Some(pod.w) |
| 871 | } else if pod.expand_y { |
| 872 | Some(pod.h) |
| 873 | } else { |
| 874 | None |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | fn layout_shape<F>(engine: &mut Engine, g: &Get, pod: Pod, body_fn: &mut F) -> Outcome<Frame> |
| 879 | where F: FnMut(&mut Engine, &Content, &StyleChain, Pod) -> Outcome<Frame> |
| 880 | { |
| 881 | let kind = match g.kind { |
| 882 | ElemKind::Square => ShapeKind::Square, |
| 883 | ElemKind::Circle => ShapeKind::Circle, |
| 884 | ElemKind::Ellipse => ShapeKind::Ellipse, |
| 885 | _ => ShapeKind::Rect, |
| 886 | }; |
| 887 | let body = res!(g.content("body")); |
| 888 | let mut frame; |
| 889 | if let Some(child) = body { |
| 890 | let mut inset = res!(sides_rel(g, "inset")); |
| 891 | if kind.is_round() { |
| 892 | // Round shapes pad their body further, so it sits inside the curve. |
| 893 | for s in &mut inset { |
| 894 | s.rel.0 += 0.5 - std::f64::consts::SQRT_2 / 4.0; |
| 895 | } |
| 896 | } |
| 897 | let has_inset = inset.iter().any(|s| s.rel.0 != 0.0 || s.abs.abs != 0.0 || s.abs.em != 0.0); |
| 898 | // Resolved against the region with Typst's summing: each axis's parts summed, then resolved. |
| 899 | let sum_x = Relative { rel: crate::eval::value::Ratio(inset[0].rel.0 + inset[2].rel.0), |
| 900 | abs: crate::eval::value::Length { abs: inset[0].abs.abs + inset[2].abs.abs, em: inset[0].abs.em + inset[2].abs.em } }; |
| 901 | let sum_y = Relative { rel: crate::eval::value::Ratio(inset[1].rel.0 + inset[3].rel.0), |
| 902 | abs: crate::eval::value::Length { abs: inset[1].abs.abs + inset[3].abs.abs, em: inset[1].abs.em + inset[3].abs.em } }; |
| 903 | let mut inner = pod; |
| 904 | if has_inset { |
| 905 | inner.w = pod.w - g.rel(sum_x, pod.w); |
| 906 | inner.h = pod.h - g.rel(sum_y, pod.h); |
| 907 | } |
| 908 | if kind.is_quadratic() { |
| 909 | let length = match quadratic_size(inner) { |
| 910 | Some(l) => l, |
| 911 | None => { |
| 912 | let f = res!(body_fn(engine, &child, g.styles, inner)); |
| 913 | f.width.max(f.height).min(inner.w.min(inner.h)) |
| 914 | }, |
| 915 | }; |
| 916 | inner = Pod::new(length, length, true, true); |
| 917 | } |
| 918 | frame = res!(body_fn(engine, &child, g.styles, inner)); |
| 919 | if has_inset { |
| 920 | // Typst's `pad::grow`: the padded size is what, padded again, gives the frame's size. |
| 921 | let pw = (frame.width + sum_x.abs.resolve(g.fs)) / (1.0 - sum_x.rel.0); |
| 922 | let ph = (frame.height + sum_y.abs.resolve(g.fs)) / (1.0 - sum_y.rel.0); |
| 923 | let left = g.rel(inset[0], pw); |
| 924 | let top = g.rel(inset[1], ph); |
| 925 | frame.width = pw; |
| 926 | frame.height = ph; |
| 927 | frame.translate(P2::new(left, top)); |
| 928 | } |
| 929 | } else { |
| 930 | // The default size a shape takes with no body and no forced size. |
| 931 | let dw = 45.0f64.min(pod.w); |
| 932 | let dh = 30.0f64.min(pod.h); |
| 933 | let (w, h) = if kind.is_quadratic() { |
| 934 | let l = quadratic_size(pod).unwrap_or(dw.min(dh)); |
| 935 | (l, l) |
| 936 | } else { |
| 937 | (if pod.expand_x { pod.w } else { dw }, if pod.expand_y { pod.h } else { dh }) |
| 938 | }; |
| 939 | frame = Frame::new(w, h); |
| 940 | } |
| 941 | |
| 942 | let fill = res!(fill(g)); |
| 943 | let outset = res!(sides_rel(g, "outset")); |
| 944 | if kind.is_round() { |
| 945 | let stroke = res!(smart_stroke(res!(g.val("stroke")), fill.is_some(), g.fs)); |
| 946 | if fill.is_some() || stroke.is_some() { |
| 947 | let l = g.rel(outset[0], frame.width); |
| 948 | let t = g.rel(outset[1], frame.height); |
| 949 | let r = g.rel(outset[2], frame.width); |
| 950 | let b = g.rel(outset[3], frame.height); |
| 951 | let shape = Shape { |
| 952 | curve: Curve::ellipse(frame.width + l + r, frame.height + t + b), |
| 953 | fill, |
| 954 | fill_rule: FillRule::NonZero, |
| 955 | stroke, |
| 956 | }; |
| 957 | frame.prepend(vec![(P2::new(-l, -t), Item::Shape(shape))]); |
| 958 | } |
| 959 | } else { |
| 960 | // Sides of strokes: `auto` strokes an unfilled rect all round; a set side left unset is unstroked. |
| 961 | let strokes: [Option<FixedStroke>; 4] = match res!(g.val("stroke")) { |
| 962 | None | Some(Value::Auto) => if fill.is_none() { |
| 963 | [Some(default_stroke()), Some(default_stroke()), Some(default_stroke()), Some(default_stroke())] |
| 964 | } else { |
| 965 | [None, None, None, None] |
| 966 | }, |
| 967 | Some(v) => { |
| 968 | let v = res!(vis::cast_stroke_sides(v)); |
| 969 | let parts = vis::sides_of(&v); |
| 970 | let mut out: [Option<FixedStroke>; 4] = [None, None, None, None]; |
| 971 | for k in 0..4 { |
| 972 | out[k] = match &parts[k] { |
| 973 | Some(Value::Stroke(s)) => Some(fix_stroke(s, g.fs)), |
| 974 | _ => None, |
| 975 | }; |
| 976 | } |
| 977 | out |
| 978 | }, |
| 979 | }; |
| 980 | let mut radius = [Relative::default(); 4]; |
| 981 | if let Some(v) = res!(g.val("radius")) { |
| 982 | let v = res!(vis::cast_corners_rel(v)); |
| 983 | for (k, c) in vis::corners_of(&v).iter().enumerate() { |
| 984 | if let Some(x) = c { |
| 985 | radius[k] = res!(vis::cast_rel(x.clone())); |
| 986 | } |
| 987 | } |
| 988 | } |
| 989 | if fill.is_some() || strokes.iter().any(Option::is_some) { |
| 990 | let l = g.rel(outset[0], frame.width); |
| 991 | let t = g.rel(outset[1], frame.height); |
| 992 | let r = g.rel(outset[2], frame.width); |
| 993 | let b = g.rel(outset[3], frame.height); |
| 994 | let size = P2::new(frame.width + l + r, frame.height + t + b); |
| 995 | let shapes = styled_rect(size, &radius, g.fs, fill, &strokes); |
| 996 | frame.prepend(shapes.into_iter().map(|s| (P2::new(-l, -t), Item::Shape(s))).collect()); |
| 997 | } |
| 998 | } |
| 999 | Ok(frame) |
| 1000 | } |
| 1001 | |
| 1002 | // Rectangles with radii and per-side strokes: Typst's `styled_rect`, `segmented_rect` and corner geometry. |
| 1003 | |
| 1004 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1005 | enum Corner { |
| 1006 | TopLeft, |
| 1007 | TopRight, |
| 1008 | BottomRight, |
| 1009 | BottomLeft, |
| 1010 | } |
| 1011 | |
| 1012 | impl Corner { |
| 1013 | fn idx(self) -> usize { |
| 1014 | match self { |
| 1015 | Corner::TopLeft => 0, |
| 1016 | Corner::TopRight => 1, |
| 1017 | Corner::BottomRight => 2, |
| 1018 | Corner::BottomLeft => 3, |
| 1019 | } |
| 1020 | } |
| 1021 | |
| 1022 | fn next_cw(self) -> Corner { |
| 1023 | match self { |
| 1024 | Corner::TopLeft => Corner::TopRight, |
| 1025 | Corner::TopRight => Corner::BottomRight, |
| 1026 | Corner::BottomRight => Corner::BottomLeft, |
| 1027 | Corner::BottomLeft => Corner::TopLeft, |
| 1028 | } |
| 1029 | } |
| 1030 | |
| 1031 | fn next_ccw(self) -> Corner { |
| 1032 | match self { |
| 1033 | Corner::TopLeft => Corner::BottomLeft, |
| 1034 | Corner::TopRight => Corner::TopLeft, |
| 1035 | Corner::BottomRight => Corner::TopRight, |
| 1036 | Corner::BottomLeft => Corner::BottomRight, |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | // The sides before and after the corner, clockwise, as indices into left, top, right, bottom. |
| 1041 | fn side_ccw(self) -> usize { |
| 1042 | match self { |
| 1043 | Corner::TopLeft => 0, |
| 1044 | Corner::TopRight => 1, |
| 1045 | Corner::BottomRight => 2, |
| 1046 | Corner::BottomLeft => 3, |
| 1047 | } |
| 1048 | } |
| 1049 | |
| 1050 | fn side_cw(self) -> usize { |
| 1051 | match self { |
| 1052 | Corner::TopLeft => 1, |
| 1053 | Corner::TopRight => 2, |
| 1054 | Corner::BottomRight => 3, |
| 1055 | Corner::BottomLeft => 0, |
| 1056 | } |
| 1057 | } |
| 1058 | } |
| 1059 | |
| 1060 | const ALL_CORNERS: [Corner; 4] = [Corner::TopLeft, Corner::TopRight, Corner::BottomRight, Corner::BottomLeft]; |
| 1061 | |
| 1062 | fn styled_rect(size: P2, radius: &[Relative; 4], fs: f64, fill: Option<Paint>, strokes: &[Option<FixedStroke>; 4]) -> Vec<Shape> { |
| 1063 | let uniform = strokes_uniform(strokes); |
| 1064 | let no_radius = radius.iter().all(|r| r.rel.0 == 0.0 && r.abs.abs == 0.0 && r.abs.em == 0.0); |
| 1065 | if uniform && no_radius { |
| 1066 | return vec![Shape { curve: Curve::rect(size.x, size.y), fill, fill_rule: FillRule::NonZero, stroke: strokes[1].clone() }]; |
| 1067 | } |
| 1068 | segmented_rect(size, radius, fs, fill, strokes) |
| 1069 | } |
| 1070 | |
| 1071 | fn stroke_same(a: &FixedStroke, b: &FixedStroke) -> bool { |
| 1072 | paint_same(&a.paint, &b.paint) && a.thickness == b.thickness && a.cap == b.cap && a.join == b.join |
| 1073 | && a.dash == b.dash && a.miter_limit == b.miter_limit |
| 1074 | } |
| 1075 | |
| 1076 | fn paint_same(a: &Paint, b: &Paint) -> bool { |
| 1077 | match (a, b) { |
| 1078 | (Paint::Color(x), Paint::Color(y)) => x == y, |
| 1079 | (Paint::Gradient(x), Paint::Gradient(y)) => x == y, |
| 1080 | (Paint::Tiling(x), Paint::Tiling(y)) => Arc::ptr_eq(x, y), |
| 1081 | _ => false, |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | fn strokes_uniform(s: &[Option<FixedStroke>; 4]) -> bool { |
| 1086 | s.iter().all(|x| match (x, &s[0]) { |
| 1087 | (None, None) => true, |
| 1088 | (Some(a), Some(b)) => stroke_same(a, b), |
| 1089 | _ => false, |
| 1090 | }) |
| 1091 | } |
| 1092 | |
| 1093 | // Half the stroke width of each side, `None` for an unstroked side, as Typst 0.15 keeps them: a rounded |
| 1094 | // corner next to an unstroked side borrows its neighbour's width when the radius has room, so the stroke |
| 1095 | // tapers into the curve with a proper cap rather than a sliver. |
| 1096 | struct ControlPoints { |
| 1097 | radius: f64, |
| 1098 | stroke_after: Option<f64>, |
| 1099 | stroke_before: Option<f64>, |
| 1100 | corner: Corner, |
| 1101 | size: P2, |
| 1102 | same: bool, |
| 1103 | } |
| 1104 | |
| 1105 | impl ControlPoints { |
| 1106 | fn rotate(&self, p: P2) -> P2 { |
| 1107 | let sx = self.size.x.signum(); |
| 1108 | let sy = self.size.y.signum(); |
| 1109 | match self.corner { |
| 1110 | Corner::TopLeft => P2::new(sx * p.x, sy * p.y), |
| 1111 | Corner::TopRight => P2::new(self.size.x - sx * p.y, sy * p.x), |
| 1112 | Corner::BottomRight => P2::new(self.size.x - sx * p.x, self.size.y - sy * p.y), |
| 1113 | Corner::BottomLeft => P2::new(sx * p.y, self.size.y - sy * p.x), |
| 1114 | } |
| 1115 | } |
| 1116 | fn reuse_after_for_cap(&self) -> Option<f64> { self.stroke_after.filter(|s| 2.0 * s < self.radius) } |
| 1117 | fn reuse_before_for_cap(&self) -> Option<f64> { self.stroke_before.filter(|s| 2.0 * s < self.radius) } |
| 1118 | fn wb(&self) -> f64 { self.stroke_before.or(self.reuse_after_for_cap()).unwrap_or(0.0) } |
| 1119 | fn wa(&self) -> f64 { self.stroke_after.or(self.reuse_before_for_cap()).unwrap_or(0.0) } |
| 1120 | fn outer(&self) -> P2 { self.rotate(P2::new(-self.wb(), -self.wa())) } |
| 1121 | fn center_outer(&self) -> P2 { |
| 1122 | let r = self.radius_outer(); |
| 1123 | self.rotate(P2::new(r - self.wb(), r - self.wa())) |
| 1124 | } |
| 1125 | fn center(&self) -> P2 { |
| 1126 | let r = self.radius(); |
| 1127 | self.rotate(P2::new(r, r)) |
| 1128 | } |
| 1129 | fn center_inner(&self) -> P2 { |
| 1130 | let r = self.radius_inner(); |
| 1131 | self.rotate(P2::new(self.wb() + r, self.wa() + r)) |
| 1132 | } |
| 1133 | fn radius_outer(&self) -> f64 { self.radius } |
| 1134 | fn radius(&self) -> f64 { (self.radius - self.wb().min(self.wa())).max(0.0) } |
| 1135 | fn radius_inner(&self) -> f64 { (self.radius - 2.0 * self.wb().max(self.wa())).max(0.0) } |
| 1136 | fn mid_outer(&self) -> P2 { |
| 1137 | let c_i = self.center_inner(); |
| 1138 | let c_o = self.center_outer(); |
| 1139 | let o = self.outer(); |
| 1140 | let r = self.radius_outer(); |
| 1141 | let a = (o.x - c_i.x).powi(2) + (o.y - c_i.y).powi(2); |
| 1142 | let b = 2.0 * (o.x - c_i.x) * (c_i.x - c_o.x) + 2.0 * (o.y - c_i.y) * (c_i.y - c_o.y); |
| 1143 | let c = (c_i.x - c_o.x).powi(2) + (c_i.y - c_o.y).powi(2) - r.powi(2); |
| 1144 | let t = (-b + (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a); |
| 1145 | c_i.add(o.sub(c_i).mul(t)) |
| 1146 | } |
| 1147 | fn mid(&self) -> P2 { |
| 1148 | let center = self.center(); |
| 1149 | let diff = self.outer().sub(center); |
| 1150 | center.add(diff.mul(self.radius() / diff.hypot())) |
| 1151 | } |
| 1152 | fn mid_inner(&self) -> P2 { |
| 1153 | let center = self.center_inner(); |
| 1154 | let diff = self.outer().sub(center); |
| 1155 | center.add(diff.mul(self.radius_inner() / diff.hypot())) |
| 1156 | } |
| 1157 | fn arc_outer(&self) -> bool { self.radius_outer() > 0.0 } |
| 1158 | fn arc(&self) -> bool { self.radius() > 0.0 } |
| 1159 | fn arc_inner(&self) -> bool { self.radius_inner() > 0.0 } |
| 1160 | fn start_outer(&self) -> P2 { self.rotate(P2::new(-self.wb(), self.radius_outer() - self.wa())) } |
| 1161 | fn start(&self) -> P2 { self.rotate(P2::new(0.0, self.radius())) } |
| 1162 | fn start_inner(&self) -> P2 { self.rotate(P2::new(self.wb(), self.wa() + self.radius_inner())) } |
| 1163 | fn end_outer(&self) -> P2 { self.rotate(P2::new(self.radius_outer() - self.wb(), -self.wa())) } |
| 1164 | fn end(&self) -> P2 { self.rotate(P2::new(self.radius(), 0.0)) } |
| 1165 | fn end_inner(&self) -> P2 { self.rotate(P2::new(self.wb() + self.radius_inner(), self.wa())) } |
| 1166 | |
| 1167 | // The cap where a stroke begins at this corner, its side before unstroked. |
| 1168 | fn start_cap(&self, curve: &mut Curve, cap: LineCap) { |
| 1169 | let small = self.reuse_after_for_cap().is_none(); |
| 1170 | if cap == LineCap::Butt || self.stroke_before.is_some() || (self.radius != 0.0 && small) { |
| 1171 | curve.line(self.mid_outer()); |
| 1172 | } else if cap == LineCap::Square { |
| 1173 | let (s, e) = (self.mid_inner(), self.mid_outer()); |
| 1174 | let off = line_normal(s, e).mul(self.wa()); |
| 1175 | curve.line(s.add(off)); |
| 1176 | curve.line(e.add(off)); |
| 1177 | curve.line(e); |
| 1178 | } else { |
| 1179 | let (s, e) = (self.mid_inner(), self.mid_outer()); |
| 1180 | let centre = s.add(e).mul(0.5).sub(line_normal(s, e).mul(RAW_UNIT)); |
| 1181 | curve.arc(s, centre, e); |
| 1182 | } |
| 1183 | } |
| 1184 | |
| 1185 | // The cap where a stroke ends at this corner, its side after unstroked. |
| 1186 | fn end_cap(&self, curve: &mut Curve, cap: LineCap) { |
| 1187 | let small = self.reuse_before_for_cap().is_none(); |
| 1188 | if cap == LineCap::Butt || self.stroke_after.is_some() || (self.radius != 0.0 && small) { |
| 1189 | curve.line(self.mid_inner()); |
| 1190 | } else if cap == LineCap::Square { |
| 1191 | let (s, e) = (self.mid_outer(), self.mid_inner()); |
| 1192 | let off = line_normal(s, e).mul(self.wb()); |
| 1193 | curve.line(s.add(off)); |
| 1194 | curve.line(e.add(off)); |
| 1195 | curve.line(e); |
| 1196 | } else { |
| 1197 | let (s, e) = (self.mid_outer(), self.mid_inner()); |
| 1198 | let centre = s.add(e).mul(0.5).sub(line_normal(s, e).mul(RAW_UNIT)); |
| 1199 | curve.arc(s, centre, e); |
| 1200 | } |
| 1201 | } |
| 1202 | } |
| 1203 | |
| 1204 | // The unit normal of the line from `a` to `b`, turned a quarter anticlockwise (y down: (x, y) to (y, -x)). |
| 1205 | fn line_normal(a: P2, b: P2) -> P2 { |
| 1206 | let d = b.sub(a); |
| 1207 | let n = P2::new(d.y, -d.x); |
| 1208 | let l = n.hypot(); |
| 1209 | if l == 0.0 { n } else { n.mul(1.0 / l) } |
| 1210 | } |
| 1211 | |
| 1212 | // The control points of a cubic approximating the circular arc from `start` to `end` about `center`. |
| 1213 | fn bezier_arc_control(start: P2, center: P2, end: P2) -> [P2; 2] { |
| 1214 | let a = start.sub(center); |
| 1215 | let b = end.sub(center); |
| 1216 | let q1 = a.x * a.x + a.y * a.y; |
| 1217 | let q2 = q1 + a.x * b.x + a.y * b.y; |
| 1218 | let k2 = (4.0 / 3.0) * ((2.0 * q1 * q2).sqrt() - q2) / (a.x * b.y - a.y * b.x); |
| 1219 | [ |
| 1220 | P2::new(center.x + a.x - k2 * a.y, center.y + a.y + k2 * a.x), |
| 1221 | P2::new(center.x + b.x + k2 * b.y, center.y + b.y - k2 * b.x), |
| 1222 | ] |
| 1223 | } |
| 1224 | |
| 1225 | impl Curve { |
| 1226 | fn arc(&mut self, start: P2, center: P2, end: P2) { |
| 1227 | let c = bezier_arc_control(start, center, end); |
| 1228 | self.cubic(c[0], c[1], end); |
| 1229 | } |
| 1230 | fn arc_move(&mut self, start: P2, center: P2, end: P2) { |
| 1231 | self.move_(start); |
| 1232 | self.arc(start, center, end); |
| 1233 | } |
| 1234 | fn arc_line(&mut self, start: P2, center: P2, end: P2) { |
| 1235 | self.line(start); |
| 1236 | self.arc(start, center, end); |
| 1237 | } |
| 1238 | } |
| 1239 | |
| 1240 | fn corners_control_points(size: P2, radius: &[f64; 4], strokes: &[Option<FixedStroke>; 4], widths: &[Option<f64>; 4]) -> [ControlPoints; 4] { |
| 1241 | ALL_CORNERS.map(|corner| ControlPoints { |
| 1242 | radius: radius[corner.idx()], |
| 1243 | stroke_before: widths[corner.side_ccw()], |
| 1244 | stroke_after: widths[corner.side_cw()], |
| 1245 | corner, |
| 1246 | size, |
| 1247 | same: match (&strokes[corner.side_ccw()], &strokes[corner.side_cw()]) { |
| 1248 | (Some(a), Some(b)) => { |
| 1249 | // A solid stroke is filled, so only its paint and dash matter; a dashed one is stroked |
| 1250 | // whole, so its cap and width must agree too. |
| 1251 | let solid = a.dash.is_none(); |
| 1252 | let filled_same = paint_same(&a.paint, &b.paint) && a.dash == b.dash; |
| 1253 | let stroked_same = a.cap == b.cap && a.thickness == b.thickness; |
| 1254 | filled_same && (solid || stroked_same) |
| 1255 | }, |
| 1256 | (None, None) => true, |
| 1257 | _ => false, |
| 1258 | }, |
| 1259 | }) |
| 1260 | } |
| 1261 | |
| 1262 | // Typst's `Option<Abs>::min`: `None` orders first. |
| 1263 | fn opt_min(a: Option<f64>, b: Option<f64>) -> Option<f64> { |
| 1264 | match (a, b) { |
| 1265 | (Some(x), Some(y)) => Some(x.min(y)), |
| 1266 | _ => None, |
| 1267 | } |
| 1268 | } |
| 1269 | |
| 1270 | fn segmented_rect(size: P2, radius: &[Relative; 4], fs: f64, fill: Option<Paint>, strokes: &[Option<FixedStroke>; 4]) -> Vec<Shape> { |
| 1271 | let mut res = Vec::new(); |
| 1272 | let widths = strokes.clone().map(|s| s.map(|s| s.thickness / 2.0)); |
| 1273 | let base = size.x.abs().min(size.y.abs()) / 2.0; |
| 1274 | // Each corner's largest radius: half the short side, plus the thinner of its two strokes. |
| 1275 | let corner_max = [ |
| 1276 | base + opt_min(widths[0], widths[1]).unwrap_or(0.0), |
| 1277 | base + opt_min(widths[1], widths[2]).unwrap_or(0.0), |
| 1278 | base + opt_min(widths[2], widths[3]).unwrap_or(0.0), |
| 1279 | base + opt_min(widths[3], widths[0]).unwrap_or(0.0), |
| 1280 | ]; |
| 1281 | let mut rad = [0.0f64; 4]; |
| 1282 | for k in 0..4 { |
| 1283 | rad[k] = rel_to(radius[k], corner_max[k] * 2.0, fs).min(corner_max[k]); |
| 1284 | } |
| 1285 | let corners = corners_control_points(size, &rad, strokes, &widths); |
| 1286 | let get = |c: Corner| &corners[c.idx()]; |
| 1287 | |
| 1288 | let mut stroke_insert = 0; |
| 1289 | if let Some(fill) = fill { |
| 1290 | let mut curve = Curve::new(); |
| 1291 | let c = get(Corner::TopLeft); |
| 1292 | if c.arc() { |
| 1293 | curve.arc_move(c.start(), c.center(), c.end()); |
| 1294 | } else { |
| 1295 | curve.move_(c.center()); |
| 1296 | } |
| 1297 | for corner in [Corner::TopRight, Corner::BottomRight, Corner::BottomLeft] { |
| 1298 | let c = get(corner); |
| 1299 | if c.arc() { |
| 1300 | curve.arc_line(c.start(), c.center(), c.end()); |
| 1301 | } else { |
| 1302 | curve.line(c.center()); |
| 1303 | } |
| 1304 | } |
| 1305 | curve.close(); |
| 1306 | res.push(Shape { curve, fill: Some(fill), fill_rule: FillRule::NonZero, stroke: None }); |
| 1307 | stroke_insert += 1; |
| 1308 | } |
| 1309 | |
| 1310 | let current = corners.iter().find(|c| !c.same).map(|c| c.corner); |
| 1311 | if let Some(mut current) = current { |
| 1312 | // Several segments: from a corner where the sides differ, clockwise round the others. |
| 1313 | let mut last = current; |
| 1314 | for _ in 0..4 { |
| 1315 | current = current.next_cw(); |
| 1316 | if get(current).same { |
| 1317 | continue; |
| 1318 | } |
| 1319 | let start = last; |
| 1320 | let end = current; |
| 1321 | last = current; |
| 1322 | let stroke = match &strokes[start.side_cw()] { |
| 1323 | Some(s) => s, |
| 1324 | None => continue, |
| 1325 | }; |
| 1326 | let start_cap = stroke.cap; |
| 1327 | let end_cap = match &strokes[end.side_ccw()] { |
| 1328 | Some(s) => s.cap, |
| 1329 | None => start_cap, |
| 1330 | }; |
| 1331 | let (shape, ontop) = segment(start, end, start_cap, end_cap, &corners, stroke); |
| 1332 | if ontop { |
| 1333 | res.push(shape); |
| 1334 | } else { |
| 1335 | res.insert(stroke_insert, shape); |
| 1336 | stroke_insert += 1; |
| 1337 | } |
| 1338 | } |
| 1339 | } else if let Some(stroke) = &strokes[1] { |
| 1340 | let (shape, _) = segment(Corner::TopLeft, Corner::TopLeft, stroke.cap, stroke.cap, &corners, stroke); |
| 1341 | res.push(shape); |
| 1342 | } |
| 1343 | res |
| 1344 | } |
| 1345 | |
| 1346 | /// The per-side strokes of a container's `stroke` field: a side with none, or a field that is `none` or `auto`, is |
| 1347 | /// unstroked. |
| 1348 | pub fn side_strokes(stroke: Option<Value>, fs: f64) -> Outcome<[Option<FixedStroke>; 4]> { |
| 1349 | let mut out: [Option<FixedStroke>; 4] = [None, None, None, None]; |
| 1350 | match stroke { |
| 1351 | None | Some(Value::None) | Some(Value::Auto) => (), |
| 1352 | Some(v) => { |
| 1353 | let v = res!(vis::cast_stroke_sides(v)); |
| 1354 | let parts = vis::sides_of(&v); |
| 1355 | for k in 0..4 { |
| 1356 | if let Some(Value::Stroke(s)) = &parts[k] { |
| 1357 | out[k] = Some(fix_stroke(s, fs)); |
| 1358 | } |
| 1359 | } |
| 1360 | }, |
| 1361 | } |
| 1362 | Ok(out) |
| 1363 | } |
| 1364 | |
| 1365 | /// Typst's `clip_rect`: the path a clipping container cuts its contents to, in the container's own frame. It |
| 1366 | /// is the container's rectangle grown by its `outset`, with the corners rounded by `radius`, and drawn at the |
| 1367 | /// inner edge of the stroke, so a stroke is never clipped away and nothing shows outside it. `outset` is |
| 1368 | /// `[left, top, right, bottom]` in points. |
| 1369 | pub fn clip_path( |
| 1370 | w: f64, |
| 1371 | h: f64, |
| 1372 | fs: f64, |
| 1373 | radius: Option<Value>, |
| 1374 | stroke: Option<Value>, |
| 1375 | outset: [f64; 4], |
| 1376 | ) |
| 1377 | -> Outcome<Path> |
| 1378 | { |
| 1379 | let strokes = res!(side_strokes(stroke, fs)); |
| 1380 | let mut rel = [Relative::default(); 4]; |
| 1381 | if let Some(v) = radius { |
| 1382 | let v = res!(vis::cast_corners_rel(v)); |
| 1383 | for (k, c) in vis::corners_of(&v).iter().enumerate() { |
| 1384 | if let Some(x) = c { |
| 1385 | rel[k] = res!(vis::cast_rel(x.clone())); |
| 1386 | } |
| 1387 | } |
| 1388 | } |
| 1389 | let size = P2::new(w + outset[0] + outset[2], h + outset[1] + outset[3]); |
| 1390 | let widths = strokes.clone().map(|s| s.map(|s| s.thickness / 2.0)); |
| 1391 | let base = size.x.abs().min(size.y.abs()) / 2.0; |
| 1392 | let corner_max = [ |
| 1393 | base + opt_min(widths[0], widths[1]).unwrap_or(0.0), |
| 1394 | base + opt_min(widths[1], widths[2]).unwrap_or(0.0), |
| 1395 | base + opt_min(widths[2], widths[3]).unwrap_or(0.0), |
| 1396 | base + opt_min(widths[3], widths[0]).unwrap_or(0.0), |
| 1397 | ]; |
| 1398 | let mut rad = [0.0f64; 4]; |
| 1399 | for k in 0..4 { |
| 1400 | rad[k] = rel_to(rel[k], corner_max[k] * 2.0, fs).min(corner_max[k]); |
| 1401 | } |
| 1402 | let corners = corners_control_points(size, &rad, &strokes, &widths); |
| 1403 | let mut curve = Curve::new(); |
| 1404 | let first = &corners[Corner::TopLeft.idx()]; |
| 1405 | if first.arc_inner() { |
| 1406 | curve.arc_move(first.start_inner(), first.center_inner(), first.end_inner()); |
| 1407 | } else { |
| 1408 | curve.move_(first.center_inner()); |
| 1409 | } |
| 1410 | for corner in [Corner::TopRight, Corner::BottomRight, Corner::BottomLeft] { |
| 1411 | let c = &corners[corner.idx()]; |
| 1412 | if c.arc_inner() { |
| 1413 | curve.arc_line(c.start_inner(), c.center_inner(), c.end_inner()); |
| 1414 | } else { |
| 1415 | curve.line(c.center_inner()); |
| 1416 | } |
| 1417 | } |
| 1418 | curve.close(); |
| 1419 | curve.to_path(P2::new(-outset[0], -outset[1])) |
| 1420 | } |
| 1421 | |
| 1422 | fn curve_segment(start: Corner, end: Corner, corners: &[ControlPoints; 4], curve: &mut Curve) { |
| 1423 | let c = &corners[start.idx()]; |
| 1424 | if start == end || !c.arc() { |
| 1425 | curve.move_(c.end()); |
| 1426 | } else { |
| 1427 | curve.arc_move(c.mid(), c.center(), c.end()); |
| 1428 | } |
| 1429 | let mut current = start.next_cw(); |
| 1430 | while current != end { |
| 1431 | let c = &corners[current.idx()]; |
| 1432 | if c.arc() { |
| 1433 | curve.arc_line(c.start(), c.center(), c.end()); |
| 1434 | } else { |
| 1435 | curve.line(c.end()); |
| 1436 | } |
| 1437 | current = current.next_cw(); |
| 1438 | } |
| 1439 | let c = &corners[end.idx()]; |
| 1440 | if !c.arc() { |
| 1441 | curve.line(c.start()); |
| 1442 | } else if start == end { |
| 1443 | curve.arc_line(c.start(), c.center(), c.end()); |
| 1444 | } else { |
| 1445 | curve.arc_line(c.start(), c.center(), c.mid()); |
| 1446 | } |
| 1447 | } |
| 1448 | |
| 1449 | fn segment( |
| 1450 | start: Corner, |
| 1451 | end: Corner, |
| 1452 | start_cap: LineCap, |
| 1453 | end_cap: LineCap, |
| 1454 | corners: &[ControlPoints; 4], |
| 1455 | stroke: &FixedStroke, |
| 1456 | ) |
| 1457 | -> (Shape, bool) |
| 1458 | { |
| 1459 | let fill_corner = |c: &ControlPoints| c.stroke_before != c.stroke_after || c.radius() < c.wb(); |
| 1460 | let fill_corners = || { |
| 1461 | if fill_corner(&corners[start.idx()]) || fill_corner(&corners[end.idx()]) { |
| 1462 | return true; |
| 1463 | } |
| 1464 | let mut current = start.next_cw(); |
| 1465 | while current != end { |
| 1466 | if fill_corner(&corners[current.idx()]) { |
| 1467 | return true; |
| 1468 | } |
| 1469 | current = current.next_cw(); |
| 1470 | } |
| 1471 | false |
| 1472 | }; |
| 1473 | let solid = stroke.dash.is_none(); |
| 1474 | let use_fill = solid && fill_corners(); |
| 1475 | let shape = if use_fill { |
| 1476 | fill_segment(start, end, start_cap, end_cap, corners, stroke) |
| 1477 | } else { |
| 1478 | let mut curve = Curve::new(); |
| 1479 | curve_segment(start, end, corners, &mut curve); |
| 1480 | Shape { curve, fill: None, fill_rule: FillRule::NonZero, stroke: Some(stroke.clone()) } |
| 1481 | }; |
| 1482 | (shape, use_fill) |
| 1483 | } |
| 1484 | |
| 1485 | fn fill_segment( |
| 1486 | start: Corner, |
| 1487 | end: Corner, |
| 1488 | start_cap: LineCap, |
| 1489 | end_cap: LineCap, |
| 1490 | corners: &[ControlPoints; 4], |
| 1491 | stroke: &FixedStroke, |
| 1492 | ) |
| 1493 | -> Shape |
| 1494 | { |
| 1495 | let mut curve = Curve::new(); |
| 1496 | if start == end { |
| 1497 | let c = &corners[start.idx()]; |
| 1498 | curve.move_(c.end_inner()); |
| 1499 | curve.line(c.end_outer()); |
| 1500 | } else { |
| 1501 | let c = &corners[start.idx()]; |
| 1502 | if c.arc_inner() { |
| 1503 | curve.arc_move(c.end_inner(), c.center_inner(), c.mid_inner()); |
| 1504 | } else { |
| 1505 | curve.move_(c.end_inner()); |
| 1506 | } |
| 1507 | c.start_cap(&mut curve, start_cap); |
| 1508 | if c.arc_outer() { |
| 1509 | curve.arc_line(c.mid_outer(), c.center_outer(), c.end_outer()); |
| 1510 | } |
| 1511 | } |
| 1512 | let mut current = start.next_cw(); |
| 1513 | while current != end { |
| 1514 | let c = &corners[current.idx()]; |
| 1515 | if c.arc_outer() { |
| 1516 | curve.arc_line(c.start_outer(), c.center_outer(), c.end_outer()); |
| 1517 | } else { |
| 1518 | curve.line(c.outer()); |
| 1519 | } |
| 1520 | current = current.next_cw(); |
| 1521 | } |
| 1522 | if start == end { |
| 1523 | let c = &corners[end.idx()]; |
| 1524 | if c.arc_outer() { |
| 1525 | curve.arc_line(c.start_outer(), c.center_outer(), c.end_outer()); |
| 1526 | } else { |
| 1527 | curve.line(c.outer()); |
| 1528 | curve.line(c.end_outer()); |
| 1529 | } |
| 1530 | if c.arc_inner() { |
| 1531 | curve.arc_line(c.end_inner(), c.center_inner(), c.start_inner()); |
| 1532 | } else { |
| 1533 | curve.line(c.center_inner()); |
| 1534 | } |
| 1535 | } else { |
| 1536 | let c = &corners[end.idx()]; |
| 1537 | if c.arc_outer() { |
| 1538 | curve.arc_line(c.start_outer(), c.center_outer(), c.mid_outer()); |
| 1539 | } else { |
| 1540 | curve.line(c.outer()); |
| 1541 | } |
| 1542 | c.end_cap(&mut curve, end_cap); |
| 1543 | if c.arc_inner() { |
| 1544 | curve.arc_line(c.mid_inner(), c.center_inner(), c.start_inner()); |
| 1545 | } |
| 1546 | } |
| 1547 | let mut current = end.next_ccw(); |
| 1548 | while current != start { |
| 1549 | let c = &corners[current.idx()]; |
| 1550 | if c.arc_inner() { |
| 1551 | curve.arc_line(c.end_inner(), c.center_inner(), c.start_inner()); |
| 1552 | } else { |
| 1553 | curve.line(c.center_inner()); |
| 1554 | } |
| 1555 | current = current.next_ccw(); |
| 1556 | } |
| 1557 | curve.close(); |
| 1558 | Shape { curve, fill: Some(stroke.paint.clone()), fill_rule: FillRule::NonZero, stroke: None } |
| 1559 | } |
| 1560 | |
| 1561 | // Images |
| 1562 | |
| 1563 | fn layout_image(engine: &mut Engine, g: &Get, pod: Pod) -> Outcome<Frame> { |
| 1564 | let span = g.elem.span(); |
| 1565 | let (data, ext) = match res!(g.val("source")) { |
| 1566 | Some(Value::Bytes(b)) => ((*b).clone(), None), |
| 1567 | Some(Value::Str(p)) => { |
| 1568 | let path = res!(crate::eval::import::resolve_path(engine, &p, span.file, span)); |
| 1569 | let ext = path.extension().and_then(|e| e.to_str()).map(|e| e.to_string()); |
| 1570 | (res!(crate::eval::import::read_file(engine, &path, span)), ext) |
| 1571 | }, |
| 1572 | _ => return Err(engine.error(DiagnosticKind::Type, span, "image source must be a path or bytes")), |
| 1573 | }; |
| 1574 | let format = match res!(g.val("format")) { |
| 1575 | Some(Value::Str(s)) => img::format_named(&s), |
| 1576 | _ => match ext.as_deref().map(img::format_named) { |
| 1577 | Some(Ok(f)) => Ok(f), |
| 1578 | _ => img::detect_format(&data), |
| 1579 | }, |
| 1580 | }; |
| 1581 | let format = match format { |
| 1582 | Ok(f) => f, |
| 1583 | Err(e) => return Err(engine.error(DiagnosticKind::Type, span, last_msg(&e))), |
| 1584 | }; |
| 1585 | let decoded = match img::decode(&data, format) { |
| 1586 | Ok(d) => d, |
| 1587 | Err(e) => return Err(engine.error(DiagnosticKind::Type, span, fmt!("failed to decode image ({})", last_msg(&e)))), |
| 1588 | }; |
| 1589 | let (nw, nh) = decoded.size_pt(); |
| 1590 | let px_ratio = nw / nh; |
| 1591 | let region_ratio = pod.w / pod.h; |
| 1592 | let wide = px_ratio > region_ratio; |
| 1593 | let (tw, th) = if pod.expand_x && pod.expand_y { |
| 1594 | (pod.w, pod.h) |
| 1595 | } else if pod.expand_x { |
| 1596 | (pod.w, pod.h.min(pod.w / px_ratio)) |
| 1597 | } else if pod.expand_y { |
| 1598 | (pod.w.min(pod.h * px_ratio), pod.h) |
| 1599 | } else { |
| 1600 | (nw.min(pod.w).min(pod.h * px_ratio), nh.min(pod.h).min(pod.w / px_ratio)) |
| 1601 | }; |
| 1602 | let fit = match res!(g.val("fit")) { |
| 1603 | Some(Value::Str(s)) => s.to_string(), |
| 1604 | _ => "cover".to_string(), |
| 1605 | }; |
| 1606 | let (fw, fh) = match fit.as_str() { |
| 1607 | "stretch" => (tw, th), |
| 1608 | _ => if wide == (fit == "contain") { (tw, tw / px_ratio) } else { (th * px_ratio, th) }, |
| 1609 | }; |
| 1610 | let mut frame = Frame::new(fw, fh); |
| 1611 | let cover_clip = fit == "cover" && (fw > tw + 1e-9 || fh > th + 1e-9); |
| 1612 | match decoded { |
| 1613 | Decoded::Raster { image, .. } => { |
| 1614 | if cover_clip { |
| 1615 | // The visible part of a covering raster is cropped from its pixels, so it needs no clip: the |
| 1616 | // crop is the centred window of the fitted image the target shows. |
| 1617 | let (cropped, cw, ch) = crop_centred(&image, fw, fh, tw, th); |
| 1618 | frame = Frame::new(tw, th); |
| 1619 | frame.push(P2::default(), Item::Raster { image: Arc::new(cropped), w: cw, h: ch }); |
| 1620 | return Ok(frame); |
| 1621 | } |
| 1622 | frame.push(P2::default(), Item::Raster { image: Arc::new(image), w: fw, h: fh }); |
| 1623 | }, |
| 1624 | Decoded::Vector { picture, .. } => { |
| 1625 | let sx = (fw / picture.width.max(1e-9) as f64) as f32; |
| 1626 | let sy = (fh / picture.height.max(1e-9) as f64) as f32; |
| 1627 | let ops = res!(svg_ops(engine, g.styles, picture.ops, GTransform::scale(sx, sy))); |
| 1628 | frame.push(P2::default(), Item::Ops(ops)); |
| 1629 | }, |
| 1630 | } |
| 1631 | frame.resize(tw, th, 0.5, 0.5); |
| 1632 | if cover_clip { |
| 1633 | frame.clip(Curve::rect(tw, th)); |
| 1634 | } |
| 1635 | Ok(frame) |
| 1636 | } |
| 1637 | |
| 1638 | // The centred window of a raster fitted at `fw` by `fh` that a `tw` by `th` target shows, as whole pixels, |
| 1639 | // and the size in points the kept pixels cover. |
| 1640 | fn crop_centred(image: &RasterImage, fw: f64, fh: f64, tw: f64, th: f64) -> (RasterImage, f64, f64) { |
| 1641 | let kx = image.width as f64 / fw; |
| 1642 | let ky = image.height as f64 / fh; |
| 1643 | let cw = ((tw * kx).round() as usize).clamp(1, image.width); |
| 1644 | let ch = ((th * ky).round() as usize).clamp(1, image.height); |
| 1645 | let x0 = (image.width - cw) / 2; |
| 1646 | let y0 = (image.height - ch) / 2; |
| 1647 | let mut rgba = Vec::with_capacity(cw * ch * 4); |
| 1648 | for y in y0..y0 + ch { |
| 1649 | let row = (y * image.width + x0) * 4; |
| 1650 | rgba.extend_from_slice(&image.rgba[row..row + cw * 4]); |
| 1651 | } |
| 1652 | (RasterImage { width: cw, height: ch, rgba, tone: image.tone }, tw, th) |
| 1653 | } |
| 1654 | |
| 1655 | // An SVG's ops under `t`: paths and rasters mapped, live text shaped under the element's styles. |
| 1656 | fn svg_ops(engine: &mut Engine, styles: &StyleChain, ops: Vec<SvgOp>, t: GTransform) -> Outcome<Vec<DrawOp>> { |
| 1657 | let mut out = Vec::with_capacity(ops.len()); |
| 1658 | for op in ops { |
| 1659 | match op { |
| 1660 | SvgOp::Fill { path, colour } => out.push(DrawOp::Fill { path: res!(path.transform(&t)), colour: colour.into() }), |
| 1661 | SvgOp::Stroke { path, colour, stroke } => { |
| 1662 | let outline = res!(path.stroke(&stroke)); |
| 1663 | out.push(DrawOp::Fill { path: res!(outline.transform(&t)), colour: colour.into() }); |
| 1664 | }, |
| 1665 | SvgOp::Text { text, local, x, y, size, anchor, colour, .. } => { |
| 1666 | let shaped = res!(crate::flow::text::shape(engine, &text, styles)); |
| 1667 | // The run is shaped at the chain's size and scaled to the SVG's own font size. |
| 1668 | let k = if shaped.size() > 0.0 { size / shaped.size() } else { 1.0 }; |
| 1669 | let advance = shaped.dims().width.to_pt() as f32 * k; |
| 1670 | let pen_x = match anchor { |
| 1671 | oxedyne_fe2o3_graphics::svg_doc::Anchor::Start => x, |
| 1672 | oxedyne_fe2o3_graphics::svg_doc::Anchor::Middle => x - advance / 2.0, |
| 1673 | oxedyne_fe2o3_graphics::svg_doc::Anchor::End => x - advance, |
| 1674 | }; |
| 1675 | for glyph in &shaped.run().glyphs { |
| 1676 | let o = res!(shaped.outline(glyph)); |
| 1677 | if o.is_empty() { |
| 1678 | continue; |
| 1679 | } |
| 1680 | let place = GTransform::scale(k, -k) |
| 1681 | .then(>ransform::translate(pen_x + glyph.x * k, y - glyph.y * k)) |
| 1682 | .then(&local) |
| 1683 | .then(&t); |
| 1684 | out.push(DrawOp::Fill { path: res!(o.transform(&place)), colour: colour.into() }); |
| 1685 | } |
| 1686 | }, |
| 1687 | SvgOp::Image { rgba, tone, iw, ih, x, y, w, h } => { |
| 1688 | let p0 = t.apply(Pt::new(x, y)); |
| 1689 | let p1 = t.apply(Pt::new(x + w, y + h)); |
| 1690 | out.push(DrawOp::Image { |
| 1691 | image: Arc::new(RasterImage { width: iw, height: ih, rgba, tone }), |
| 1692 | x: p0.x, |
| 1693 | y: p0.y, |
| 1694 | w: p1.x - p0.x, |
| 1695 | h: p1.y - p0.y, |
| 1696 | }); |
| 1697 | }, |
| 1698 | } |
| 1699 | } |
| 1700 | Ok(out) |
| 1701 | } |
| 1702 | |
| 1703 | // Transforms |
| 1704 | |
| 1705 | fn origin_fraction(h: HAlign, v: VAlign) -> (f64, f64) { |
| 1706 | let x = match h { |
| 1707 | HAlign::Start | HAlign::Left => 0.0, |
| 1708 | HAlign::Center => 0.5, |
| 1709 | HAlign::End | HAlign::Right => 1.0, |
| 1710 | }; |
| 1711 | let y = match v { |
| 1712 | VAlign::Top => 0.0, |
| 1713 | VAlign::Horizon => 0.5, |
| 1714 | VAlign::Bottom => 1.0, |
| 1715 | }; |
| 1716 | (x, y) |
| 1717 | } |
| 1718 | |
| 1719 | fn body_of(g: &Get) -> Outcome<Content> { |
| 1720 | Ok(res!(g.content("body")).unwrap_or_default()) |
| 1721 | } |
| 1722 | |
| 1723 | fn layout_move<F>(engine: &mut Engine, g: &Get, pod: Pod, body_fn: &mut F) -> Outcome<Frame> |
| 1724 | where F: FnMut(&mut Engine, &Content, &StyleChain, Pod) -> Outcome<Frame> |
| 1725 | { |
| 1726 | let body = res!(body_of(g)); |
| 1727 | let mut frame = res!(body_fn(engine, &body, g.styles, pod)); |
| 1728 | let dx = match res!(g.val("dx")) { Some(v) => res!(vis::cast_rel(v)), None => Relative::default() }; |
| 1729 | let dy = match res!(g.val("dy")) { Some(v) => res!(vis::cast_rel(v)), None => Relative::default() }; |
| 1730 | let d = P2::new(g.rel(dx, pod.w), g.rel(dy, pod.h)); |
| 1731 | // Typst moves the contents only: the size and the baseline stay where the body put them. |
| 1732 | frame.translate_visual(d); |
| 1733 | Ok(frame) |
| 1734 | } |
| 1735 | |
| 1736 | /// The corners of a `w` by `h` box under `t`: the offset that brings the image's top-left to the origin, |
| 1737 | /// and the size of its bounding box. |
| 1738 | fn bounding_box(w: f64, h: f64, t: &Transform) -> (P2, P2) { |
| 1739 | let pts = [P2::new(0.0, 0.0), P2::new(w, 0.0), P2::new(0.0, h), P2::new(w, h)] |
| 1740 | .map(|p| { |
| 1741 | // Typst's `transform_inf`: an infinite coordinate stays infinite rather than turning to NaN. |
| 1742 | let x = if p.x.is_infinite() || p.y.is_infinite() { p.x } else { p.apply(t).x }; |
| 1743 | let y = if p.x.is_infinite() || p.y.is_infinite() { p.y } else { p.apply(t).y }; |
| 1744 | P2::new(x, y) |
| 1745 | }); |
| 1746 | let min_x = pts.iter().fold(f64::INFINITY, |m, p| m.min(p.x)); |
| 1747 | let min_y = pts.iter().fold(f64::INFINITY, |m, p| m.min(p.y)); |
| 1748 | let max_x = pts.iter().fold(f64::NEG_INFINITY, |m, p| m.max(p.x)); |
| 1749 | let max_y = pts.iter().fold(f64::NEG_INFINITY, |m, p| m.max(p.y)); |
| 1750 | (P2::new(-min_x, -min_y), P2::new((max_x - min_x).abs(), (max_y - min_y).abs())) |
| 1751 | } |
| 1752 | |
| 1753 | fn skew(ax: f64, ay: f64) -> Transform { |
| 1754 | Transform { a: 1.0, b: ay.tan(), c: ax.tan(), d: 1.0, e: 0.0, f: 0.0 } |
| 1755 | } |
| 1756 | |
| 1757 | fn layout_transform<F>(engine: &mut Engine, g: &Get, pod: Pod, body_fn: &mut F) -> Outcome<Frame> |
| 1758 | where F: FnMut(&mut Engine, &Content, &StyleChain, Pod) -> Outcome<Frame> |
| 1759 | { |
| 1760 | let span = g.elem.span(); |
| 1761 | let body = res!(body_of(g)); |
| 1762 | let (h, v) = res!(vis::origin_of(res!(g.val("origin")))); |
| 1763 | let origin = origin_fraction(h, v); |
| 1764 | let reflow = res!(g.bool("reflow", false)); |
| 1765 | let (ts, size) = match g.kind { |
| 1766 | ElemKind::Rotate => { |
| 1767 | let angle = match res!(g.val("angle")) { |
| 1768 | Some(v) => res!(vis::cast_angle(v)).0, |
| 1769 | None => 0.0, |
| 1770 | }; |
| 1771 | let size = if pod.finite() { |
| 1772 | bounding_box(pod.w, pod.h, &Transform::rotate(-angle)).1 |
| 1773 | } else { |
| 1774 | P2::new(f64::INFINITY, f64::INFINITY) |
| 1775 | }; |
| 1776 | (Transform::rotate(angle), size) |
| 1777 | }, |
| 1778 | ElemKind::Skew => { |
| 1779 | let ax = match res!(g.val("ax")) { Some(v) => res!(vis::cast_angle(v)).0, None => 0.0 }; |
| 1780 | let ay = match res!(g.val("ay")) { Some(v) => res!(vis::cast_angle(v)).0, None => 0.0 }; |
| 1781 | let t = skew(ax, ay); |
| 1782 | let size = if pod.finite() { |
| 1783 | bounding_box(pod.w, pod.h, &t).1 |
| 1784 | } else { |
| 1785 | P2::new(f64::INFINITY, f64::INFINITY) |
| 1786 | }; |
| 1787 | (t, size) |
| 1788 | }, |
| 1789 | _ => { |
| 1790 | let (sx, sy) = res!(resolve_scale(engine, g, pod, &body, body_fn)); |
| 1791 | let size = P2::new( |
| 1792 | if pod.w.is_finite() { (pod.w / sx).abs() } else { pod.w }, |
| 1793 | if pod.h.is_finite() { (pod.h / sy).abs() } else { pod.h }, |
| 1794 | ); |
| 1795 | (Transform::scale(sx, sy), size) |
| 1796 | }, |
| 1797 | }; |
| 1798 | let _ = span; |
| 1799 | let mut frame = if reflow { |
| 1800 | let measured = res!(body_fn(engine, &body, g.styles, Pod::new(size.x, size.y, false, false))); |
| 1801 | res!(body_fn(engine, &body, g.styles, Pod::new(measured.width, measured.height, true, true))) |
| 1802 | } else { |
| 1803 | res!(body_fn(engine, &body, g.styles, pod)) |
| 1804 | }; |
| 1805 | let x = frame.width * origin.0; |
| 1806 | let y = frame.height * origin.1; |
| 1807 | let t = Transform::translate(x, y).then(&ts).then(&Transform::translate(-x, -y)); |
| 1808 | if reflow { |
| 1809 | // The baseline follows the transformed baseline's middle point for scaling (not mirrored) and |
| 1810 | // skewing; a rotation clears it, as its direction after turning is not clear. |
| 1811 | let keep = match g.kind { |
| 1812 | ElemKind::Rotate => false, |
| 1813 | ElemKind::Scale => ts.d >= 0.0, |
| 1814 | _ => true, |
| 1815 | }; |
| 1816 | let new_base = match (frame.baseline, keep) { |
| 1817 | (Some(b), true) => Some(P2::new(frame.width / 2.0, b).apply(&t).y), |
| 1818 | _ => None, |
| 1819 | }; |
| 1820 | let (offset, bb) = bounding_box(frame.width, frame.height, &t); |
| 1821 | frame.transform(t); |
| 1822 | frame.translate_visual(offset); |
| 1823 | frame.width = bb.x; |
| 1824 | frame.height = bb.y; |
| 1825 | match new_base { |
| 1826 | Some(b) => frame.baseline = Some(b + offset.y), |
| 1827 | None if !keep => frame.baseline = None, |
| 1828 | None => (), |
| 1829 | } |
| 1830 | } else { |
| 1831 | frame.transform(t); |
| 1832 | } |
| 1833 | Ok(frame) |
| 1834 | } |
| 1835 | |
| 1836 | fn resolve_scale<F>(engine: &mut Engine, g: &Get, pod: Pod, body: &Content, body_fn: &mut F) -> Outcome<(f64, f64)> |
| 1837 | where F: FnMut(&mut Engine, &Content, &StyleChain, Pod) -> Outcome<Frame> |
| 1838 | { |
| 1839 | let span = g.elem.span(); |
| 1840 | let x = res!(g.val("x")); |
| 1841 | let y = res!(g.val("y")); |
| 1842 | let needs_size = matches!(x, Some(Value::Length(_))) || matches!(y, Some(Value::Length(_))); |
| 1843 | let size = if needs_size { |
| 1844 | let f = res!(body_fn(engine, body, g.styles, Pod::new(pod.w, pod.h, false, false))); |
| 1845 | P2::new(f.width, f.height) |
| 1846 | } else { |
| 1847 | P2::default() |
| 1848 | }; |
| 1849 | let axis = |v: Option<Value>, whole: f64| -> Outcome<Option<f64>> { |
| 1850 | match v { |
| 1851 | Some(Value::Auto) => Ok(None), |
| 1852 | Some(Value::Ratio(r)) => Ok(Some(r.0)), |
| 1853 | Some(Value::Length(l)) => Ok(Some(l.resolve(g.fs) / whole)), |
| 1854 | None => Ok(Some(1.0)), |
| 1855 | Some(other) => Err(err!("expected ratio, length, or auto, found {}", other.ty().name(); |
| 1856 | Input, Mismatch)), |
| 1857 | } |
| 1858 | }; |
| 1859 | match (res!(axis(x, size.x)), res!(axis(y, size.y))) { |
| 1860 | (None, None) => Err(engine.error(DiagnosticKind::Type, span, "x and y cannot both be auto")), |
| 1861 | (Some(a), Some(b)) => Ok((a, b)), |
| 1862 | (None, Some(v)) | (Some(v), None) => Ok((v, v)), |
| 1863 | } |
| 1864 | } |
| 1865 | |
| 1866 | // Repeat |
| 1867 | |
| 1868 | fn layout_repeat<F>(engine: &mut Engine, g: &Get, pod: Pod, body_fn: &mut F) -> Outcome<Frame> |
| 1869 | where F: FnMut(&mut Engine, &Content, &StyleChain, Pod) -> Outcome<Frame> |
| 1870 | { |
| 1871 | let span = g.elem.span(); |
| 1872 | let body = res!(body_of(g)); |
| 1873 | let piece = res!(body_fn(engine, &body, g.styles, Pod::new(pod.w, pod.h, false, false))); |
| 1874 | let w_fill = pod.w; |
| 1875 | if !w_fill.is_finite() || !piece.height.is_finite() { |
| 1876 | return Err(engine.error(DiagnosticKind::Type, span, "repeat with no size restrictions")); |
| 1877 | } |
| 1878 | let mut frame = Frame::new(w_fill, piece.height); |
| 1879 | if piece.baseline.is_some() { |
| 1880 | frame.baseline = Some(piece.baseline()); |
| 1881 | } |
| 1882 | let mut gap = match res!(g.val("gap")) { |
| 1883 | Some(Value::Length(l)) => l.resolve(g.fs), |
| 1884 | _ => 0.0, |
| 1885 | }; |
| 1886 | let width = piece.width; |
| 1887 | let count = ((w_fill + gap) / (width + gap)).floor(); |
| 1888 | let remaining = (w_fill + gap) % (width + gap); |
| 1889 | let justify = res!(g.bool("justify", true)); |
| 1890 | if justify { |
| 1891 | gap += remaining / (count - 1.0); |
| 1892 | } |
| 1893 | let mut offset = 0.0; |
| 1894 | if count == 1.0 || !justify { |
| 1895 | offset += res!(align_x(g.styles)) * remaining; |
| 1896 | } |
| 1897 | if width > 0.0 { |
| 1898 | for _ in 0..(count.max(0.0) as usize).min(1000) { |
| 1899 | frame.push(P2::new(offset, 0.0), Item::Group { |
| 1900 | frame: Box::new(piece.clone()), |
| 1901 | transform: Transform::identity(), |
| 1902 | clip: None, |
| 1903 | }); |
| 1904 | offset += width + gap; |
| 1905 | } |
| 1906 | } |
| 1907 | Ok(frame) |
| 1908 | } |
| 1909 | |
| 1910 | // The horizontal alignment in force (`align`'s `alignment`), as a fraction: start is 0 in left-to-right text. |
| 1911 | fn align_x(styles: &StyleChain) -> Outcome<f64> { |
| 1912 | let v = match ElemKind::Align.field_id("alignment") { |
| 1913 | Some(id) => res!(styles.get(ElemKind::Align, id)), |
| 1914 | None => None, |
| 1915 | }; |
| 1916 | Ok(match v { |
| 1917 | Some(Value::Alignment(a)) => match a.x { |
| 1918 | Some(HAlign::Center) => 0.5, |
| 1919 | Some(HAlign::Right) | Some(HAlign::End) => 1.0, |
| 1920 | _ => 0.0, |
| 1921 | }, |
| 1922 | _ => 0.0, |
| 1923 | }) |
| 1924 | } |
| 1925 | |
| 1926 | // Lowering to IR |
| 1927 | |
| 1928 | /// A frame as one IR node: ink alone is one `Graphic` leaf; with laid-out content the layers are |
| 1929 | /// overlaid in a vertical box (see the file header). |
| 1930 | pub fn frame_to_node(engine: &mut Engine, frame: &Frame, span: Span) -> Outcome<Node> { |
| 1931 | let mut layers: Vec<Layer> = Vec::new(); |
| 1932 | res!(collect_layers(engine, frame, P2::default(), &mut layers, span)); |
| 1933 | let w = frame.width; |
| 1934 | let h = frame.height; |
| 1935 | let base = frame.baseline().clamp(0.0, h.max(0.0)); |
| 1936 | let dims = Dims::new(Sp::from_pt(w), Sp::from_pt(base), Sp::from_pt(h - base)); |
| 1937 | let only_ink = layers.iter().all(|l| matches!(l, Layer::Ink(_))); |
| 1938 | if only_ink { |
| 1939 | let mut ops = Vec::new(); |
| 1940 | for l in layers { |
| 1941 | if let Layer::Ink(o) = l { |
| 1942 | ops.extend(o); |
| 1943 | } |
| 1944 | } |
| 1945 | // The graphic's frame is the box's: y down from the top, the baseline `base` below it. |
| 1946 | return Ok(Node::Leaf(Leaf::graphic(Graphic::new(ops, dims)).with_span(span.range()))); |
| 1947 | } |
| 1948 | let full = Dims::new(Sp::from_pt(w), Sp::from_pt(h), Sp::ZERO); |
| 1949 | let mut list = Vec::new(); |
| 1950 | let n = layers.len(); |
| 1951 | for (i, l) in layers.into_iter().enumerate() { |
| 1952 | let layer = match l { |
| 1953 | Layer::Ink(ops) => Node::VBox(BoxNode::new(vec![ |
| 1954 | Node::Leaf(Leaf::graphic(Graphic::new(ops, full)).with_span(span.range())), |
| 1955 | ], full)), |
| 1956 | Layer::Nodes(at, nodes, d) => { |
| 1957 | let inner = Node::VBox(BoxNode::new(nodes, Dims::new(d.width, d.vextent(), Sp::ZERO))); |
| 1958 | Node::VBox(BoxNode::new(vec![ |
| 1959 | Node::Glue(Glue::fixed(Sp::from_pt(at.y))), |
| 1960 | Node::HBox(BoxNode::new(vec![ |
| 1961 | Node::Glue(Glue::fixed(Sp::from_pt(at.x))), |
| 1962 | inner, |
| 1963 | ], Dims::new(Sp::from_pt(at.x) + d.width, d.vextent(), Sp::ZERO))), |
| 1964 | ], full)) |
| 1965 | }, |
| 1966 | }; |
| 1967 | list.push(layer); |
| 1968 | if i + 1 < n { |
| 1969 | list.push(Node::Glue(Glue::fixed(-full.height))); |
| 1970 | } |
| 1971 | } |
| 1972 | Ok(Node::VBox(BoxNode::new(list, dims))) |
| 1973 | } |
| 1974 | |
| 1975 | enum Layer { |
| 1976 | Ink(Vec<DrawOp>), |
| 1977 | Nodes(P2, Vec<Node>, Dims), |
| 1978 | } |
| 1979 | |
| 1980 | fn push_ink(layers: &mut Vec<Layer>, ops: Vec<DrawOp>) { |
| 1981 | if let Some(Layer::Ink(v)) = layers.last_mut() { |
| 1982 | v.extend(ops); |
| 1983 | return; |
| 1984 | } |
| 1985 | layers.push(Layer::Ink(ops)); |
| 1986 | } |
| 1987 | |
| 1988 | fn collect_layers(engine: &mut Engine, frame: &Frame, at: P2, layers: &mut Vec<Layer>, span: Span) -> Outcome<()> { |
| 1989 | for (p, item) in &frame.items { |
| 1990 | let pos = at.add(*p); |
| 1991 | match item { |
| 1992 | Item::Shape(s) => { |
| 1993 | let ops = res!(shape_ops(engine, s, pos, span)); |
| 1994 | push_ink(layers, ops); |
| 1995 | }, |
| 1996 | Item::Raster { image, w, h } => push_ink(layers, vec![DrawOp::Image { |
| 1997 | image: image.clone(), |
| 1998 | x: pos.x as f32, |
| 1999 | y: pos.y as f32, |
| 2000 | w: *w as f32, |
| 2001 | h: *h as f32, |
| 2002 | }]), |
| 2003 | Item::Ops(ops) => { |
| 2004 | let t = GTransform::translate(pos.x as f32, pos.y as f32); |
| 2005 | let mut v = Vec::with_capacity(ops.len()); |
| 2006 | for op in ops { |
| 2007 | v.push(res!(op_transform(op, &t, span, engine))); |
| 2008 | } |
| 2009 | push_ink(layers, v); |
| 2010 | }, |
| 2011 | Item::Nodes { nodes, dims } => layers.push(Layer::Nodes(pos, nodes.clone(), *dims)), |
| 2012 | Item::Group { frame: inner, transform, clip } => { |
| 2013 | let identity = *transform == Transform::identity(); |
| 2014 | if identity && clip.is_none() { |
| 2015 | res!(collect_layers(engine, inner, pos, layers, span)); |
| 2016 | continue; |
| 2017 | } |
| 2018 | let node = res!(frame_to_node(engine, inner, span)); |
| 2019 | let t = Transform::translate(pos.x, pos.y).then(transform); |
| 2020 | let dims = Dims::new(Sp::from_pt(inner.width), Sp::from_pt(inner.height), Sp::ZERO); |
| 2021 | let mut out = match clip { |
| 2022 | Some(c) => { |
| 2023 | let path = res!(c.to_path(P2::default())); |
| 2024 | res!(wrap_clip(ClipNode { list: vec![node], dims, path: Some(path) })) |
| 2025 | }, |
| 2026 | None => node, |
| 2027 | }; |
| 2028 | if !identity || pos != P2::default() { |
| 2029 | out = res!(wrap_transform(engine, TransformNode { transform: t, list: vec![out], dims }, span)); |
| 2030 | } |
| 2031 | match out { |
| 2032 | Node::Leaf(Leaf { kind: LeafKind::Graphic(gr), .. }) => push_ink(layers, gr.ops.clone()), |
| 2033 | other => layers.push(Layer::Nodes(P2::default(), vec![other], dims)), |
| 2034 | } |
| 2035 | }, |
| 2036 | } |
| 2037 | } |
| 2038 | Ok(()) |
| 2039 | } |
| 2040 | |
| 2041 | /// Transformed material as a node: the transform node itself, which the driver places as a group. |
| 2042 | pub fn wrap_transform(_engine: &mut Engine, t: TransformNode, _span: Span) -> Outcome<Node> { |
| 2043 | Ok(Node::Transform(t)) |
| 2044 | } |
| 2045 | |
| 2046 | /// Clipped material as a node: the clip node itself, which the driver places as a clipping group. |
| 2047 | pub fn wrap_clip(c: ClipNode) -> Outcome<Node> { |
| 2048 | Ok(Node::Clip(c)) |
| 2049 | } |
| 2050 | |
| 2051 | fn op_transform(op: &DrawOp, t: >ransform, span: Span, engine: &mut Engine) -> Outcome<DrawOp> { |
| 2052 | Ok(match op { |
| 2053 | DrawOp::Fill { path, colour } => DrawOp::Fill { path: res!(path.transform(t)), colour: *colour }, |
| 2054 | DrawOp::Stroke { path, colour, width } => DrawOp::Stroke { |
| 2055 | path: res!(path.transform(t)), |
| 2056 | colour: *colour, |
| 2057 | width: *width * t.scale_factor(), |
| 2058 | }, |
| 2059 | DrawOp::Image { image, x, y, w, h } => { |
| 2060 | if t.b != 0.0 || t.c != 0.0 || t.a < 0.0 || t.d < 0.0 { |
| 2061 | return Err(engine.error(DiagnosticKind::Unsupported, span, |
| 2062 | "a raster image cannot yet be rotated, skewed or mirrored: the drawing layer places \ |
| 2063 | rasters upright")); |
| 2064 | } |
| 2065 | let p0 = t.apply(Pt::new(*x, *y)); |
| 2066 | let p1 = t.apply(Pt::new(*x + *w, *y + *h)); |
| 2067 | DrawOp::Image { image: image.clone(), x: p0.x, y: p0.y, w: p1.x - p0.x, h: p1.y - p0.y } |
| 2068 | }, |
| 2069 | }) |
| 2070 | } |
| 2071 | |
| 2072 | /// A shape's fill and stroke as draw ops at `at`. A stroke is outlined and filled, so caps, joins, dashes |
| 2073 | /// and the miter limit are drawn exactly whatever the emitter supports. |
| 2074 | pub fn shape_ops(engine: &mut Engine, s: &Shape, at: P2, span: Span) -> Outcome<Vec<DrawOp>> { |
| 2075 | let mut ops = Vec::new(); |
| 2076 | let path = res!(s.curve.to_path(at)); |
| 2077 | if let Some(p) = &s.fill { |
| 2078 | if let Some(colour) = res!(paint_ink(engine, p, span)) { |
| 2079 | let fill_path = match s.fill_rule { |
| 2080 | FillRule::EvenOdd => res!(path.even_odd_as_non_zero()), |
| 2081 | FillRule::NonZero => path.clone(), |
| 2082 | }; |
| 2083 | ops.push(DrawOp::Fill { path: fill_path, colour }); |
| 2084 | } |
| 2085 | } |
| 2086 | if let Some(st) = &s.stroke { |
| 2087 | if st.thickness > 0.0 { |
| 2088 | if let Some(colour) = res!(paint_ink(engine, &st.paint, span)) { |
| 2089 | let pen = res!(pen_of(st)); |
| 2090 | ops.push(DrawOp::Fill { path: res!(path.stroke(&pen)), colour }); |
| 2091 | } |
| 2092 | } |
| 2093 | } |
| 2094 | Ok(ops) |
| 2095 | } |
| 2096 | |
| 2097 | /// The `fe2o3_graphics` pen for a fixed stroke. |
| 2098 | pub fn pen_of(st: &FixedStroke) -> Outcome<Pen> { |
| 2099 | let mut pen = res!(Pen::new(st.thickness as f32)); |
| 2100 | pen = pen |
| 2101 | .with_cap(match st.cap { |
| 2102 | LineCap::Butt => Cap::Butt, |
| 2103 | LineCap::Round => Cap::Round, |
| 2104 | LineCap::Square => Cap::Square, |
| 2105 | }) |
| 2106 | .with_join(match st.join { |
| 2107 | LineJoin::Miter => Join::Miter, |
| 2108 | LineJoin::Round => Join::Round, |
| 2109 | LineJoin::Bevel => Join::Bevel, |
| 2110 | }) |
| 2111 | .with_miter_limit((st.miter_limit as f32).max(1.0)) |
| 2112 | .with_tolerance(STROKE_TOL); |
| 2113 | if let Some((pattern, phase)) = &st.dash { |
| 2114 | if pattern.iter().sum::<f64>() > 0.0 { |
| 2115 | pen = pen.with_dash(PenDash::new(pattern.iter().map(|x| *x as f32).collect()).with_offset(*phase as f32)); |
| 2116 | } |
| 2117 | } |
| 2118 | Ok(pen) |
| 2119 | } |
| 2120 | |
| 2121 | /// A paint as a flat ink in the colour's own space. A gradient is drawn in its middle stop's colour and a |
| 2122 | /// tiling not at all, each with a warning, because the drawing layer carries flat colours only. |
| 2123 | pub fn paint_ink(engine: &mut Engine, p: &Paint, span: Span) -> Outcome<Option<Ink>> { |
| 2124 | match p { |
| 2125 | Paint::Color(c) => Ok(Some(c.to_ink())), |
| 2126 | Paint::Gradient(g) => { |
| 2127 | engine.warn(DiagnosticKind::Unsupported, span, "gradients are drawn in one flat colour: the drawing layer has no shading"); |
| 2128 | match g.stops.get(g.stops.len() / 2) { |
| 2129 | Some((c, _)) => Ok(Some(c.to_ink())), |
| 2130 | None => Ok(None), |
| 2131 | } |
| 2132 | }, |
| 2133 | Paint::Tiling(_) => { |
| 2134 | engine.warn(DiagnosticKind::Unsupported, span, "tiling paint is not drawn: the drawing layer has no tiling"); |
| 2135 | Ok(None) |
| 2136 | }, |
| 2137 | } |
| 2138 | } |
| 2139 | |
| 2140 | // Node lists |
| 2141 | |
| 2142 | /// A vertical list's natural size: its widest box and the sum of its extents. |
| 2143 | pub fn vlist_dims(nodes: &[Node]) -> Dims { |
| 2144 | let mut w = Sp::ZERO; |
| 2145 | let mut h = Sp::ZERO; |
| 2146 | for n in nodes { |
| 2147 | let nw = match n { |
| 2148 | Node::HBox(b) | Node::VBox(b) => b.dims.width, |
| 2149 | Node::Leaf(l) => l.dims.width, |
| 2150 | _ => Sp::ZERO, |
| 2151 | }; |
| 2152 | if nw > w { |
| 2153 | w = nw; |
| 2154 | } |
| 2155 | h += n.vextent(); |
| 2156 | } |
| 2157 | Dims::new(w, h, Sp::ZERO) |
| 2158 | } |
| 2159 | |
| 2160 | /// The first baseline in a vertical list: the first line's, from the list's top. |
| 2161 | pub fn first_baseline(nodes: &[Node]) -> Option<Sp> { |
| 2162 | let mut y = Sp::ZERO; |
| 2163 | for n in nodes { |
| 2164 | match n { |
| 2165 | Node::HBox(b) => return Some(y + b.dims.height), |
| 2166 | Node::Leaf(l) => return Some(y + l.dims.height), |
| 2167 | Node::VBox(b) => if let Some(inner) = first_baseline(&b.list) { |
| 2168 | return Some(y + inner); |
| 2169 | }, |
| 2170 | _ => (), |
| 2171 | } |
| 2172 | y += n.vextent(); |
| 2173 | } |
| 2174 | None |
| 2175 | } |
| 2176 | |
| 2177 | // The innermost message of an error, which is what a diagnostic reports. |
| 2178 | fn last_msg(e: &Error<ErrTag>) -> String { |
| 2179 | match e.msgs().into_iter().last() { |
| 2180 | Some(m) => m, |
| 2181 | None => fmt!("{}", e), |
| 2182 | } |
| 2183 | } |