day_pieces/canvas.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The `canvas` immediate-mode drawing surface (record a `Draw` display list that backends
5//! replay natively; `day::motion` and `day::frame` drive per-frame animation), plus the general
6//! `Reactive<T>` (value / `Signal` / `Animated` / closure) abstraction that pieces accept for
7//! animatable inputs.
8
9use std::rc::Rc;
10
11use day_core::*;
12use day_reactive::Signal;
13use day_spec::props::*;
14use day_spec::{
15 Angle, CornerRadii, DrawOp, Event, ExportError, FillRule, Ink, Paint, PathSeg, Point, Rect,
16 Shape, Size, StrokeStyle, SystemColor, kinds,
17};
18
19use crate::*;
20
21// ---------------------------------------------------------------------------
22// Canvas (§11): record a display list reactively; backends replay natively.
23// ---------------------------------------------------------------------------
24
25#[derive(Default)]
26pub struct Draw {
27 ops: Vec<DrawOp>,
28}
29
30impl Draw {
31 /// An empty recorder, for a test that calls a draw function directly and asserts on what
32 /// it records: the same list the canvas replays.
33 #[must_use]
34 pub fn new() -> Self {
35 Draw::default()
36 }
37 /// What has been recorded so far, in order.
38 #[must_use]
39 pub fn ops(&self) -> &[DrawOp] {
40 &self.ops
41 }
42}
43
44/// Build a [`Shape::Path`]: several contours, straight or curved, with a fill rule.
45///
46/// ```ignore
47/// let ring = PathBuilder::new()
48/// .rule(FillRule::EvenOdd) // the inner circle cuts a hole
49/// .circle(center, 40.0)
50/// .circle(center, 24.0)
51/// .build();
52/// d.fill(ring, Color::BLUE);
53/// ```
54#[derive(Clone, Debug, Default)]
55#[must_use]
56pub struct PathBuilder {
57 segs: Vec<PathSeg>,
58 rule: FillRule,
59}
60
61impl PathBuilder {
62 pub fn new() -> Self {
63 Self::default()
64 }
65 /// Which points count as inside where contours overlap (default [`FillRule::NonZero`]).
66 pub fn rule(mut self, rule: FillRule) -> Self {
67 self.rule = rule;
68 self
69 }
70 /// Start a new contour.
71 pub fn move_to(mut self, p: Point) -> Self {
72 self.segs.push(PathSeg::Move(p));
73 self
74 }
75 pub fn line_to(mut self, p: Point) -> Self {
76 self.segs.push(PathSeg::Line(p));
77 self
78 }
79 /// Quadratic bezier through control point `c` to `p`.
80 pub fn quad_to(mut self, c: Point, p: Point) -> Self {
81 self.segs.push(PathSeg::Quad(c, p));
82 self
83 }
84 /// Cubic bezier with control points `c1`, `c2` to `p`.
85 pub fn cubic_to(mut self, c1: Point, c2: Point, p: Point) -> Self {
86 self.segs.push(PathSeg::Cubic(c1, c2, p));
87 self
88 }
89 /// Close the current contour back to its start.
90 pub fn close(mut self) -> Self {
91 self.segs.push(PathSeg::Close);
92 self
93 }
94 /// A whole circular contour, as four cubics.
95 ///
96 /// 0.5523 is the standard circle-from-beziers constant (`4/3·tan(π/8)`); the error against a
97 /// true circle is under a thousandth of the radius, which is well inside a pixel at any size
98 /// a UI draws.
99 /// Append a circular arc: `sweep_deg` of a circle of `radius` about `center`, starting at
100 /// `start_deg`. Degrees, `0` = the +x axis, positive sweeping clockwise, the same convention
101 /// [`Shape::Arc`] and [`PathBuilder::circle`] already use, so the crate has one.
102 ///
103 /// A *segment*, not a shape: the arc joins whatever came before it, which is what lets a
104 /// donut wedge, a rounded gauge or a pie slice with a hole be one closed path. Without it
105 /// every such figure is hand-rolled from cubics; `day-piece-charts` carried forty lines of
106 /// exactly this to draw a wedge.
107 ///
108 /// Emitted as cubics rather than as an arc op on the wire. Every rasterizer under Day has its
109 /// own rule for joining an arc to the line before it, and its own flattening tolerance; the
110 /// same beziers everywhere means the same pixels everywhere.
111 ///
112 /// A cubic cannot be a circle, so this is an approximation, and the quarter turns it splits
113 /// into are where that is cheapest: the radial error of a cubic quarter-circle peaks at
114 /// 2.7 × 10⁻⁴ of the radius, a quarter of a pixel on a circle a thousand points across, and
115 /// proportionally less on anything smaller. Splitting finer would halve nothing anyone can
116 /// see and double the segment count. It is the same tradeoff Core Graphics, cairo and every
117 /// SVG renderer make.
118 ///
119 /// Continues the current subpath when there is one, and starts a new one otherwise.
120 pub fn arc_to(mut self, center: Point, radius: f64, start: Angle, sweep: Angle) -> Self {
121 // Reach the arc's start: a line from wherever the path is, or a move if it is nowhere.
122 // `Close` ends a subpath, so a path that just closed is "nowhere" too.
123 let fresh = self.segs.last().is_none_or(|s| matches!(s, PathSeg::Close));
124 let first = day_spec::arc_point(center, radius, start);
125 self.segs.push(if fresh {
126 PathSeg::Move(first)
127 } else {
128 PathSeg::Line(first)
129 });
130 self.segs
131 .extend(day_spec::arc_cubics(center, radius, start, sweep));
132 self
133 }
134
135 pub fn circle(self, center: Point, radius: f64) -> Self {
136 const K: f64 = 0.552_284_749_8;
137 let (cx, cy, r, k) = (center.x, center.y, radius, radius * K);
138 self.move_to(Point::new(cx + r, cy))
139 .cubic_to(
140 Point::new(cx + r, cy + k),
141 Point::new(cx + k, cy + r),
142 Point::new(cx, cy + r),
143 )
144 .cubic_to(
145 Point::new(cx - k, cy + r),
146 Point::new(cx - r, cy + k),
147 Point::new(cx - r, cy),
148 )
149 .cubic_to(
150 Point::new(cx - r, cy - k),
151 Point::new(cx - k, cy - r),
152 Point::new(cx, cy - r),
153 )
154 .cubic_to(
155 Point::new(cx + k, cy - r),
156 Point::new(cx + r, cy - k),
157 Point::new(cx + r, cy),
158 )
159 .close()
160 }
161 /// A contour through `pts` as a Catmull-Rom spline converted to cubics: the smooth line a
162 /// chart wants through its data points, without the caller doing bezier arithmetic.
163 ///
164 /// The curve passes through every point (unlike a plain bezier fit), and the tangent at each
165 /// point follows its neighbors. `tension` 0.0 is a straight polyline and 1.0 is the
166 /// standard Catmull-Rom; values above about 1.2 overshoot visibly.
167 pub fn smooth_polyline(mut self, pts: &[Point], tension: f64) -> Self {
168 if pts.len() < 2 {
169 return match pts.first() {
170 Some(p) => self.move_to(*p),
171 None => self,
172 };
173 }
174 self.segs.push(PathSeg::Move(pts[0]));
175 let t = tension / 6.0;
176 for i in 0..pts.len() - 1 {
177 // The neighbors on each side, clamped at the ends so the first and last segments
178 // keep the same construction as the middle ones.
179 let p0 = pts[i.saturating_sub(1)];
180 let (p1, p2) = (pts[i], pts[i + 1]);
181 let p3 = pts[(i + 2).min(pts.len() - 1)];
182 self.segs.push(PathSeg::Cubic(
183 Point::new(p1.x + (p2.x - p0.x) * t, p1.y + (p2.y - p0.y) * t),
184 Point::new(p2.x - (p3.x - p1.x) * t, p2.y - (p3.y - p1.y) * t),
185 p2,
186 ));
187 }
188 self
189 }
190 /// Append a rectangle with its own radius on each corner, as one closed contour: the path
191 /// [`Shape::rounded_rect`] draws when its corners differ, for a figure that needs it as one
192 /// contour among several (a rounded frame with a hole cut out of it).
193 pub fn rounded_rect(mut self, rect: Rect, radii: CornerRadii) -> Self {
194 self.segs.extend(day_spec::rounded_rect_segs(rect, radii));
195 self
196 }
197
198 /// Finish, as a [`Shape`] ready for `fill`, `stroke` or `clip`.
199 pub fn build(self) -> Shape {
200 Shape::Path(day_spec::Path {
201 segs: self.segs,
202 rule: self.rule,
203 })
204 }
205}
206
207/// Canvas text styling (named fields per the API style rule, docs/api-style.md). Fill what you
208/// set and take the rest from `..Default::default()`: 12 points, the platform's text color,
209/// top-leading, the platform's own face.
210#[derive(Clone, Debug, PartialEq)]
211pub struct TextStyle {
212 /// Absolute canvas points, with no accessibility scale (docs/canvas.md "Text").
213 pub size: f64,
214 /// Any ink; a role or a light/dark pair re-records the drawing when the appearance changes.
215 pub color: Ink,
216 pub anchor: day_spec::TextAnchor,
217 /// Family, weight and slant (docs/fonts.md); the default is the platform's UI face.
218 pub font: day_spec::CanvasFont,
219}
220
221impl Default for TextStyle {
222 fn default() -> Self {
223 TextStyle {
224 size: 12.0,
225 color: Ink::system(SystemColor::Text),
226 anchor: day_spec::TextAnchor::LEADING,
227 font: day_spec::CanvasFont::default(),
228 }
229 }
230}
231
232/// A paint as a canvas records it: every ink resolved for the current appearance. Reading the
233/// palette is tracked, so a drawing that uses a role or a light/dark pair re-records when the
234/// appearance changes, and one with fixed colors only does not subscribe at all.
235fn recorded(paint: impl Into<Paint>) -> Paint {
236 let paint = paint.into();
237 if paint.is_dynamic() {
238 paint.resolve(&day_core::palette())
239 } else {
240 paint
241 }
242}
243
244/// An ink as a canvas records it (see [`recorded`]).
245fn recorded_ink(ink: impl Into<Ink>) -> Ink {
246 match ink.into() {
247 Ink::Fixed(c) => Ink::Fixed(c),
248 dynamic => Ink::Fixed(dynamic.resolve(&day_core::palette())),
249 }
250}
251
252impl Draw {
253 /// Fill a shape with any [`Paint`]: a [`Color`](day_spec::Color), a [`SystemColor`], an
254 /// [`Ink`], or a linear, radial or conic gradient, whose unit points resolve against the
255 /// shape's bounding box (docs/shapes.md §3.2). A role or a light/dark pair resolves for the
256 /// current appearance, and the drawing re-records when it changes.
257 pub fn fill(&mut self, shape: Shape, paint: impl Into<Paint>) {
258 self.ops.push(DrawOp::Fill(shape, recorded(paint)));
259 }
260 /// Stroke a shape with one ink at `width`, the everyday case.
261 pub fn stroke(&mut self, shape: Shape, color: impl Into<Ink>, width: f64) {
262 self.ops.push(DrawOp::Stroke(
263 shape,
264 Paint::Solid(recorded_ink(color)),
265 StrokeStyle::width(width),
266 ));
267 }
268 /// Stroke with a full [`StrokeStyle`] (dash, cap, join) and any paint, gradients included.
269 pub fn stroke_styled(&mut self, shape: Shape, paint: impl Into<Paint>, style: StrokeStyle) {
270 self.ops.push(DrawOp::Stroke(shape, recorded(paint), style));
271 }
272 /// Draw `shape` once at every position in `at`: one op for the whole batch.
273 ///
274 /// The template is authored around the origin and each copy is it translated by one point, so
275 /// a 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`. Order is drawing order.
276 ///
277 /// Reach for this the moment a drawing has more marks than it has kinds of mark. A scatter of
278 /// fifty thousand points drawn one `fill` at a time is fifty thousand ops to build, compare
279 /// and clone on every frame that re-records; as one stamp it is one op and a flat array of
280 /// coordinates, and a backend can put every copy into a single path (docs/canvas.md
281 /// "Stamping"). Every copy shares the shape, size and paint, so group by whatever varies.
282 pub fn stamp(&mut self, shape: Shape, at: Vec<Point>, paint: impl Into<Paint>) {
283 self.ops.push(DrawOp::Stamp(Box::new(day_spec::Stamp {
284 shape,
285 at,
286 paint: recorded(paint),
287 stroke: None,
288 })));
289 }
290
291 /// [`Draw::stamp`], stroking each copy instead of filling it.
292 pub fn stamp_styled(
293 &mut self,
294 shape: Shape,
295 at: Vec<Point>,
296 paint: impl Into<Paint>,
297 style: StrokeStyle,
298 ) {
299 self.ops.push(DrawOp::Stamp(Box::new(day_spec::Stamp {
300 shape,
301 at,
302 paint: recorded(paint),
303 stroke: Some(style),
304 })));
305 }
306
307 /// Draw a decoded image into `rect` (docs/images.md).
308 ///
309 /// Takes a decoded [`Bitmap`](day_core::Bitmap), not bytes: the draw closure re-records on
310 /// every tracked read, and a buffer here would be compared (and re-decoded) every frame.
311 /// Decode once with `day::decode_image`, hold the handle, and draw it as often as you like.
312 ///
313 /// ```ignore
314 /// let photo = day::decode_image(bytes).await?; // once
315 /// canvas(move |d, size| d.image(&photo, Rect::from_size(size)))
316 /// ```
317 ///
318 /// Needs [`Cap::ImageDecode`](day_spec::Cap::ImageDecode); a backend without it draws
319 /// nothing here, the same as for any op it does not know.
320 pub fn image(&mut self, image: &day_core::Bitmap, rect: day_spec::Rect) {
321 self.image_with_opacity(image, rect, 1.0);
322 }
323
324 /// [`Draw::image`] with an opacity in `0.0..=1.0` multiplying the image's own alpha.
325 pub fn image_with_opacity(
326 &mut self,
327 image: &day_core::Bitmap,
328 rect: day_spec::Rect,
329 opacity: f64,
330 ) {
331 self.ops.push(DrawOp::Image {
332 image: image.id(),
333 rect,
334 opacity: opacity.clamp(0.0, 1.0),
335 source: None,
336 });
337 }
338
339 /// Draw the `source` region of a decoded image into `rect` (docs/images.md "Drawing on a
340 /// canvas").
341 ///
342 /// `source` is in the bitmap's own PIXELS, not points: a sprite sheet lays its cells out in
343 /// pixels, and [`Bitmap::info`](day_core::Bitmap::info) says how many of them make a point.
344 /// The region is scaled into `rect` exactly as [`Draw::image`] scales the whole image. A
345 /// region reaching outside the bitmap is clamped to it, never an error, and an empty
346 /// intersection draws nothing.
347 ///
348 /// ```ignore
349 /// let sheet = day::decode_image(sprites).await?; // once
350 /// canvas(move |d, _| d.image_region(&sheet, icon.cell, Rect::new(10.0, 10.0, 24.0, 24.0)))
351 /// ```
352 pub fn image_region(
353 &mut self,
354 image: &day_core::Bitmap,
355 source: day_spec::Rect,
356 rect: day_spec::Rect,
357 ) {
358 self.image_region_with_opacity(image, source, rect, 1.0);
359 }
360
361 /// [`Draw::image_region`] with an opacity in `0.0..=1.0` multiplying the image's own alpha.
362 pub fn image_region_with_opacity(
363 &mut self,
364 image: &day_core::Bitmap,
365 source: day_spec::Rect,
366 rect: day_spec::Rect,
367 opacity: f64,
368 ) {
369 self.ops.push(DrawOp::Image {
370 image: image.id(),
371 rect,
372 opacity: opacity.clamp(0.0, 1.0),
373 source: Some(source),
374 });
375 }
376
377 /// Confine everything drawn afterwards to `shape`.
378 ///
379 /// The clip lasts until the enclosing [`Draw::restore`], so the usual shape is
380 /// `save` → `clip` → draw → `restore`; [`Draw::clipped`] does exactly that for you.
381 pub fn clip(&mut self, shape: Shape) {
382 self.ops.push(DrawOp::Clip(shape));
383 }
384 /// Draw `f` clipped to `shape`, restoring the previous clip afterwards.
385 pub fn clipped(&mut self, shape: Shape, f: impl FnOnce(&mut Draw)) {
386 self.save();
387 self.clip(shape);
388 f(self);
389 self.restore();
390 }
391 /// One line of text hung on `at` per the style's anchor (docs/canvas.md "Text"); measure it
392 /// first with `day::measure_text` when the drawing needs its extent.
393 pub fn text(&mut self, text: &str, at: Point, style: TextStyle) {
394 self.ops.push(DrawOp::Text {
395 text: text.to_owned(),
396 at,
397 size: style.size,
398 color: match style.color {
399 Ink::Fixed(c) => c,
400 dynamic => day_core::resolve(dynamic),
401 },
402 anchor: style.anchor,
403 font: style.font,
404 });
405 }
406 /// Cast `shadow` from everything drawn afterwards: each fill, stroke, text and image gets
407 /// its own (docs/canvas.md "Shadows"). `None` stops casting one.
408 ///
409 /// The shadow lasts until the enclosing [`Draw::restore`], like a clip;
410 /// [`Draw::shadowed`] saves, sets, draws and restores for you.
411 pub fn shadow(&mut self, shadow: impl Into<Option<day_spec::Shadow>>) {
412 let shadow = shadow.into().map(|s| day_spec::Shadow {
413 color: recorded_ink(s.color),
414 ..s
415 });
416 self.ops.push(DrawOp::Shadow(shadow));
417 }
418 /// Draw `f` with everything in it casting `shadow`, restoring the previous shadow
419 /// afterwards.
420 ///
421 /// ```ignore
422 /// d.shadowed(Shadow::new(Color::rgba(0.0, 0.0, 0.0, 0.3), 16.0).offset(0.0, 6.0), |d| {
423 /// d.fill(Shape::RoundedRect(card, 14.0), Color::WHITE);
424 /// });
425 /// ```
426 pub fn shadowed(&mut self, shadow: day_spec::Shadow, f: impl FnOnce(&mut Draw)) {
427 self.save();
428 self.shadow(shadow);
429 f(self);
430 self.restore();
431 }
432 /// Set how everything drawn afterwards combines with what the canvas already holds
433 /// (docs/canvas.md "Blend modes"). Lasts until the enclosing [`Draw::restore`];
434 /// [`Draw::blended`] scopes it for you.
435 pub fn blend(&mut self, mode: day_spec::BlendMode) {
436 self.ops.push(DrawOp::Blend(mode));
437 }
438 /// Draw `f` in blend mode `mode`, restoring the previous mode afterwards.
439 ///
440 /// ```ignore
441 /// d.fill(Shape::RoundedRect(ticket, 14.0), paper);
442 /// d.blended(BlendMode::Erase, |d| d.fill(Shape::Ellipse(hole), Color::BLACK));
443 /// ```
444 pub fn blended(&mut self, mode: day_spec::BlendMode, f: impl FnOnce(&mut Draw)) {
445 self.save();
446 self.blend(mode);
447 f(self);
448 self.restore();
449 }
450 /// Save the current transform, clip, shadow and blend mode; pair with [`Draw::restore`].
451 pub fn save(&mut self) {
452 self.ops.push(DrawOp::Save);
453 }
454 /// Restore the transform, clip, shadow and blend mode saved by the matching [`Draw::save`].
455 pub fn restore(&mut self) {
456 self.ops.push(DrawOp::Restore);
457 }
458 /// Multiply an affine onto the current transform (shape rotate/scale/offset, §11).
459 pub fn concat(&mut self, m: day_geometry::Affine) {
460 self.ops.push(DrawOp::Concat(m));
461 }
462 /// Draw within `m` applied to the CTM, restoring afterwards.
463 pub fn transformed(&mut self, m: day_geometry::Affine, f: impl FnOnce(&mut Draw)) {
464 self.save();
465 self.concat(m);
466 f(self);
467 self.restore();
468 }
469}
470
471/// Create + wire a reactive canvas leaf with a given flex: the draw closure re-records on any
472/// tracked read and on `FrameChanged`; replay is equality-gated by `DrawOp: PartialEq` (§4.2).
473/// Shared by [`canvas`] (intrinsic) and [`shape`] (grows to fill, §shapes).
474pub(crate) fn canvas_leaf(
475 cx: &mut BuildCx,
476 flex: Flex,
477 draw: impl Fn(&mut Draw, Size) + 'static,
478) -> RNode {
479 use day_reactive::{Trigger, bind};
480 let node = cx.leaf(kinds::CANVAS, &CanvasProps::default(), flex);
481 let trig = Trigger::new();
482 cx.on(node, move |ev| {
483 if matches!(ev, Event::FrameChanged(_)) {
484 trig.notify();
485 }
486 });
487 let draw = std::rc::Rc::new(draw);
488 let d2 = draw.clone();
489 bind(
490 move || {
491 trig.track();
492 let size = with_tree(|t| t.node_frame(node)).map_or(Size::new(0.0, 0.0), |f| f.size);
493 let mut d = Draw { ops: Vec::new() };
494 (d2)(&mut d, size);
495 d.ops
496 },
497 move |ops: &Vec<DrawOp>| {
498 with_tree(|t| t.replay(node, ops.clone()));
499 },
500 );
501 node
502}
503
504/// The drawing closure is a binding: signal reads re-record; layout size changes re-record
505/// (via `FrameChanged`); replay is equality-gated by `DrawOp`'s `PartialEq` (§4.2).
506pub fn canvas(draw: impl Fn(&mut Draw, Size) + 'static) -> impl Piece {
507 piece_fn(move |cx| canvas_leaf(cx, Flex::default(), draw))
508}
509
510// ---------------------------------------------------------------------------
511// Export (docs/canvas.md "Exporting"): the same draw function, replayed offscreen.
512// ---------------------------------------------------------------------------
513
514/// A recorded drawing at a fixed size: what a [`canvas`] would replay, kept for export.
515///
516/// Write the drawing once as a plain function and call it from the canvas and from export:
517///
518/// ```ignore
519/// fn draw_chart(d: &mut Draw, size: Size, series: &[f64]) { /* … */ }
520///
521/// canvas(move |d, size| draw_chart(d, size, &series.get())) // on screen
522/// let drawing = Drawing::record(Size::new(600.0, 400.0), |d, size| {
523/// draw_chart(d, size, &series.get_untracked())
524/// });
525/// day::task(async move {
526/// if let Ok(png) = drawing.to_png(2.0).await { /* save it */ }
527/// });
528/// ```
529///
530/// Rendering goes through the toolkit's own canvas painter (Core Graphics, cairo, `QPainter`,
531/// an android `Canvas`, …), so an export matches the screen. Probe [`canvas_exports`] before
532/// offering a command.
533#[derive(Clone, Debug, PartialEq)]
534pub struct Drawing {
535 size: Size,
536 ops: Vec<DrawOp>,
537}
538
539impl Drawing {
540 /// Run `draw` once, untracked, at `size` points. Signal reads inside it subscribe nothing,
541 /// so recording from a binding or a menu action is safe.
542 pub fn record(size: Size, draw: impl FnOnce(&mut Draw, Size)) -> Drawing {
543 let mut d = Draw::new();
544 day_reactive::untrack(|| draw(&mut d, size));
545 Drawing { size, ops: d.ops }
546 }
547
548 /// A drawing of ops recorded elsewhere, at `size` points.
549 #[must_use]
550 pub fn from_ops(size: Size, ops: Vec<DrawOp>) -> Drawing {
551 Drawing { size, ops }
552 }
553
554 /// The size the drawing was recorded at, in points.
555 pub fn size(&self) -> Size {
556 self.size
557 }
558
559 /// The recorded display list.
560 #[must_use]
561 pub fn ops(&self) -> &[DrawOp] {
562 &self.ops
563 }
564
565 /// Render to a bitmap of `size × scale` pixels whose `info().scale` is `scale`, so
566 /// `image(&bitmap)` shows it at the drawing's point size. Await it inside `day::task`.
567 ///
568 /// `Err(ExportError::Unsupported)` where the toolkit has no offscreen painter
569 /// ([`Cap::CanvasBitmap`](day_spec::Cap::CanvasBitmap)); `Err(ExportError::TooLarge)` above
570 /// 16,384 pixels a side or 64 megapixels.
571 #[must_use]
572 pub fn to_bitmap(&self, scale: f64) -> day_core::RenderBitmap {
573 day_core::render_bitmap(self.ops.clone(), self.size, scale)
574 }
575
576 /// Render to a bitmap and encode it as PNG: [`Drawing::to_bitmap`] then
577 /// [`Bitmap::encode`]. `Err(ExportError::Unsupported)` where either half is missing
578 /// ([`CanvasExports::png`] answers that up front).
579 ///
580 /// # Errors
581 ///
582 /// Resolves to the errors of [`Drawing::to_bitmap`], `ExportError::Unsupported` where the
583 /// toolkit cannot encode, or `ExportError::Failed` with the encoder's message.
584 pub fn to_png(
585 &self,
586 scale: f64,
587 ) -> impl std::future::Future<Output = Result<Vec<u8>, ExportError>> + 'static {
588 let render = self.to_bitmap(scale);
589 async move {
590 let bitmap = render.await?;
591 bitmap
592 .encode(day_spec::EncodeSpec::default())
593 .await
594 .map_err(|e| match e {
595 day_spec::ImageError::Unsupported | day_spec::ImageError::Encode => {
596 ExportError::Unsupported
597 }
598 other => ExportError::Failed(other.to_string()),
599 })
600 }
601 }
602
603 /// A one-page PDF the size of the drawing. `Err(ExportError::Unsupported)` where the
604 /// platform has no PDF writer ([`Cap::CanvasPdf`](day_spec::Cap::CanvasPdf)).
605 #[must_use]
606 pub fn to_pdf(&self) -> day_core::RenderPdf {
607 PdfDocument::new().page(self.clone()).render()
608 }
609}
610
611/// A PDF of one or more drawings, one per page; each page takes its drawing's size in PDF
612/// points (1/72 inch, the same unit as canvas points: US Letter is 612 × 792, A4 595 × 842).
613///
614/// ```ignore
615/// let mut doc = PdfDocument::new().title("Quarterly report");
616/// for region in ®ions {
617/// doc = doc.page(Drawing::record(LETTER, |d, size| draw_region(d, size, region)));
618/// }
619/// let pdf = doc.render().await?;
620/// ```
621#[derive(Clone, Debug, Default, PartialEq)]
622pub struct PdfDocument {
623 pages: Vec<Drawing>,
624 info: day_spec::PdfInfo,
625}
626
627impl PdfDocument {
628 /// An empty document; rendering it before adding a page answers `ExportError::Invalid`.
629 pub fn new() -> Self {
630 Self::default()
631 }
632
633 /// Append `drawing` as the next page, at the drawing's size.
634 #[must_use]
635 pub fn page(mut self, drawing: Drawing) -> Self {
636 self.pages.push(drawing);
637 self
638 }
639
640 /// The document title. Android's writer has no metadata API and ignores it.
641 #[must_use]
642 pub fn title(mut self, title: impl Into<String>) -> Self {
643 self.info.title = Some(title.into());
644 self
645 }
646
647 /// The document author. Android's writer ignores it, as it does the title.
648 #[must_use]
649 pub fn author(mut self, author: impl Into<String>) -> Self {
650 self.info.author = Some(author.into());
651 self
652 }
653
654 /// How many pages have been added.
655 #[must_use]
656 pub fn len(&self) -> usize {
657 self.pages.len()
658 }
659
660 /// Whether no page has been added yet.
661 #[must_use]
662 pub fn is_empty(&self) -> bool {
663 self.pages.is_empty()
664 }
665
666 /// Render the document through the platform's PDF writer. Await it inside `day::task`.
667 #[must_use]
668 pub fn render(self) -> day_core::RenderPdf {
669 let pages = self
670 .pages
671 .into_iter()
672 .map(|d| day_spec::PdfPage {
673 size: d.size,
674 ops: d.ops,
675 })
676 .collect();
677 day_core::render_pdf(pages, self.info)
678 }
679}
680
681// ---------------------------------------------------------------------------
682// Reactive<T>: a value, a Signal, or a closure; the generalization of IntoText/IntoFraction.
683// ---------------------------------------------------------------------------
684
685/// A parameter that is either a constant or a reactive source. `get()` is a tracked read, so any
686/// `Reactive` used inside a canvas draw closure makes that shape re-record when the source changes.
687pub enum Reactive<T: Clone + 'static> {
688 Const(T),
689 Dyn(Rc<dyn Fn() -> T>),
690}
691impl<T: Clone + 'static> Clone for Reactive<T> {
692 fn clone(&self) -> Self {
693 match self {
694 Reactive::Const(v) => Reactive::Const(v.clone()),
695 Reactive::Dyn(f) => Reactive::Dyn(f.clone()),
696 }
697 }
698}
699impl<T: Clone + 'static> Reactive<T> {
700 pub fn get(&self) -> T {
701 match self {
702 Reactive::Const(v) => v.clone(),
703 Reactive::Dyn(f) => f(),
704 }
705 }
706 pub fn get_untracked(&self) -> T {
707 match self {
708 Reactive::Const(v) => v.clone(),
709 Reactive::Dyn(f) => day_reactive::untrack(|| f()),
710 }
711 }
712}
713/// Disjoint-marker conversion (like [`IntoText`]): accepts `T`, `Signal<T>`, an
714/// `Animated<T>`, or `Fn() -> T`.
715pub trait IntoReactive<T: Clone + 'static, M> {
716 fn into_reactive(self) -> Reactive<T>;
717}
718impl<T: Clone + 'static> IntoReactive<T, StaticMark> for T {
719 fn into_reactive(self) -> Reactive<T> {
720 Reactive::Const(self)
721 }
722}
723impl<T: Clone + 'static> IntoReactive<T, SignalMark> for Signal<T> {
724 fn into_reactive(self) -> Reactive<T> {
725 Reactive::Dyn(Rc::new(move || self.get()))
726 }
727}
728impl<T: Clone + 'static, F: Fn() -> T + 'static> IntoReactive<T, FnMark> for F {
729 fn into_reactive(self) -> Reactive<T> {
730 Reactive::Dyn(Rc::new(self))
731 }
732}
733/// Marker for the [`IntoReactive`] impl of an animated value.
734pub struct AnimatedMark;
735/// An animated value (`day::motion::Animated`) is a reactive read of itself, so it goes
736/// straight into `.opacity(fade)`, `.translation(0.0, lift)` or `.background(tint)`.
737impl<T: day_core::tween::Lerp + 'static> IntoReactive<T, AnimatedMark>
738 for day_core::motion::Animated<T>
739{
740 fn into_reactive(self) -> Reactive<T> {
741 Reactive::Dyn(Rc::new(move || self.get()))
742 }
743}
744
745/// Marker for the [`IntoReactive`] impls that convert as they read: a [`Color`](day_spec::Color)
746/// where an [`Ink`](day_spec::Ink) is taken, a gradient where a [`Paint`](day_spec::Paint) is,
747/// a [`Radius`](crate::Radius) where a [`Corner`](crate::Corner) is, a [`Space`](crate::Space)
748/// where a length is. `S` names the source, so each conversion is its own impl and a constant,
749/// a signal and a closure of the source all work.
750pub struct IntoMark<S>(std::marker::PhantomData<S>);
751
752/// `IntoReactive<target>` for constants, signals and closures of each source type, converting
753/// with `Into`.
754macro_rules! reactive_into {
755 ($target:ty: $($source:ty),+ $(,)?) => {$(
756 impl IntoReactive<$target, IntoMark<$source>> for $source {
757 fn into_reactive(self) -> Reactive<$target> {
758 Reactive::Const(self.into())
759 }
760 }
761 impl IntoReactive<$target, IntoMark<Signal<$source>>> for Signal<$source> {
762 fn into_reactive(self) -> Reactive<$target> {
763 Reactive::Dyn(Rc::new(move || self.get().into()))
764 }
765 }
766 impl<F: Fn() -> $source + 'static> IntoReactive<$target, IntoMark<fn() -> $source>> for F {
767 fn into_reactive(self) -> Reactive<$target> {
768 Reactive::Dyn(Rc::new(move || self().into()))
769 }
770 }
771 )+};
772}
773
774reactive_into!(day_spec::Ink: day_spec::Color, day_spec::SystemColor);
775reactive_into!(
776 day_spec::Paint: day_spec::Color,
777 day_spec::SystemColor,
778 day_spec::Ink,
779 day_spec::LinearGradient,
780 day_spec::RadialGradient,
781 day_spec::ConicGradient,
782);
783reactive_into!(crate::Corner: f64, crate::Radius);
784reactive_into!(f64: crate::Space);
785reactive_into!(day_spec::Insets: f64, crate::Space);
786
787/// An animated color goes wherever an ink or a paint does: `.background(fade)`.
788impl IntoReactive<day_spec::Ink, IntoMark<day_core::motion::Animated<day_spec::Color>>>
789 for day_core::motion::Animated<day_spec::Color>
790{
791 fn into_reactive(self) -> Reactive<day_spec::Ink> {
792 Reactive::Dyn(Rc::new(move || self.get().into()))
793 }
794}
795impl IntoReactive<day_spec::Paint, IntoMark<day_core::motion::Animated<day_spec::Color>>>
796 for day_core::motion::Animated<day_spec::Color>
797{
798 fn into_reactive(self) -> Reactive<day_spec::Paint> {
799 Reactive::Dyn(Rc::new(move || self.get().into()))
800 }
801}
802impl IntoReactive<day_spec::Paint, IntoMark<day_core::motion::Animated<day_spec::Ink>>>
803 for day_core::motion::Animated<day_spec::Ink>
804{
805 fn into_reactive(self) -> Reactive<day_spec::Paint> {
806 Reactive::Dyn(Rc::new(move || self.get().into()))
807 }
808}
809
810// ---------------------------------------------------------------------------
811// Conformance cases (docs/testing.md)
812// ---------------------------------------------------------------------------
813
814/// The canvas's `#[day::test]` cases, next to its constructor.
815#[cfg(feature = "conformance")]
816pub(crate) mod conformance {
817 use day_core::conformance::{Case, Drive};
818 use day_reactive::Signal;
819 use day_spec::{Cap, Color, Role, Shape, kinds};
820
821 use crate::*;
822
823 /// A canvas with an explicit role, label and a value that follows a signal reports all
824 /// three natively, after the value changes too (the showcase gauge's shape). Its value is
825 /// also its text, so a drawn readout is checked with `assert_text` like a label.
826 #[day_macros::test(day_core)]
827 fn canvas_a11y_value() -> Case {
828 let level = Signal::new(40.0f64);
829 Case::new()
830 .proves(kinds::CANVAS)
831 .proves_modifier("a11y")
832 .page(move || {
833 column((
834 canvas(move |d, size| {
835 let w = size.width * level.get() / 100.0;
836 d.fill(
837 Shape::Rect(day_spec::Rect::new(0.0, 0.0, w, size.height)),
838 Color::rgb(0.2, 0.5, 0.9),
839 );
840 })
841 .a11y(move |a| {
842 a.role(Role::Meter)
843 .label("Level")
844 .value(move || format!("{:.0}", level.get()))
845 })
846 .id(day_core::id!(meter))
847 .frame(160.0, 24.0),
848 button("Raise")
849 .action(move || level.set(80.0))
850 .id(day_core::id!(raise)),
851 ))
852 .spacing(8.0)
853 })
854 .drive(|d: Drive| async move {
855 d.a11y_audit(Some("meter")).await?;
856 d.assert_text("meter", "40").await?;
857 d.tap("raise").await?;
858 d.a11y_audit(Some("meter")).await?;
859 d.assert_text("meter", "80").await
860 })
861 }
862
863 /// Native layout must not turn a canvas into a focus scope with no focusable children.
864 #[day_macros::test(day_core)]
865 fn canvas_focus_after_layout() -> Case {
866 Case::new()
867 .proves(kinds::CANVAS)
868 .proves_duty("focus")
869 .requires(Cap::Snapshot)
870 .page(|| {
871 column((
872 canvas(|d, size| {
873 d.fill(
874 Shape::Rect(day_spec::Rect::from_size(size)),
875 Color::hex(0x00ff_0000),
876 );
877 })
878 .frame(80.0, 60.0)
879 .id(day_core::id!(painted)),
880 canvas(|_, _| {}).frame(40.0, 40.0).id(day_core::id!(empty)),
881 ))
882 })
883 .drive(|d: Drive| async move {
884 // A real rendered frame, rather than a timing delay: requesting focus before
885 // ArkUI's first native layout hid its canvas host's loss of focusability.
886 d.shot("before-focus").await?;
887 d.sample_pixel("painted", 0.5, 0.5, "#ff0000").await?;
888 d.focus("painted").await?;
889 d.assert_focused("painted", true).await?;
890 d.sample_pixel("painted", 0.5, 0.5, "#ff0000").await?;
891 d.focus("empty").await?;
892 d.assert_focused("empty", true).await
893 })
894 }
895
896 /// Bitmap origins participate in the whole canvas transform, just like shape coordinates.
897 /// Reading the recorded rectangle alone cannot detect a native replay placing it elsewhere.
898 #[day_macros::test(day_core)]
899 fn canvas_image_transform_and_opacity() -> Case {
900 Case::new()
901 .proves(kinds::CANVAS)
902 .proves_cap(Cap::ImageDecode)
903 .requires(Cap::ImageDecode)
904 .requires(Cap::Snapshot)
905 .page(|| {
906 let bitmap = Signal::new(None::<day_core::Bitmap>);
907 day_core::decode_image_async(
908 std::sync::Arc::new(crate::image::conformance::RED_BLUE.to_vec()),
909 move |result| bitmap.set(Some(result.expect("decode the fixture PNG"))),
910 );
911 column((
912 canvas(move |d, size| {
913 d.fill(Shape::Rect(day_spec::Rect::from_size(size)), Color::WHITE);
914 if let Some(image) = bitmap.get() {
915 d.transformed(
916 day_spec::Affine::scale(2.0, 2.0)
917 .then(day_spec::Affine::rotate(day_spec::Angle::QUARTER))
918 .then(day_spec::Affine::translate(160.0, 20.0)),
919 |d| {
920 d.image_with_opacity(
921 &image,
922 day_spec::Rect::new(20.0, 10.0, 40.0, 20.0),
923 0.5,
924 );
925 },
926 );
927 }
928 })
929 .frame(200.0, 200.0)
930 .id(day_core::id!(canvas_image::painted)),
931 label(move || {
932 if bitmap.get().is_some() {
933 "ready"
934 } else {
935 "loading"
936 }
937 })
938 .id(day_core::id!(canvas_image::state)),
939 ))
940 })
941 .drive(|d: Drive| async move {
942 d.assert_text("canvas_image::state", "ready").await?;
943 // Rotated and doubled: x=100..140, red y=60..100, blue y=100..140.
944 d.sample_pixel("canvas_image::painted", 0.6, 0.4, "#ff8080")
945 .await?;
946 d.sample_pixel("canvas_image::painted", 0.6, 0.6, "#8080ff")
947 .await?;
948 d.sample_pixel("canvas_image::painted", 0.4, 0.5, "#ffffff")
949 .await?;
950 d.sample_pixel("canvas_image::painted", 0.6, 0.2, "#ffffff")
951 .await
952 })
953 }
954
955 /// A conic gradient turns clockwise from its start angle about the shape's center: with
956 /// four hard-edged quarters, each quadrant of the canvas is one color.
957 #[day_macros::test(day_core)]
958 fn canvas_conic_gradient() -> Case {
959 Case::new()
960 .proves(kinds::CANVAS)
961 .requires(Cap::Snapshot)
962 .page(|| {
963 canvas(|d, size| {
964 let quarter = |at: f64, color: u32| {
965 [(at, Color::hex(color)), (at + 0.25, Color::hex(color))]
966 };
967 let stops = [
968 quarter(0.0, 0x00ff_0000),
969 quarter(0.25, 0x0000_ff00),
970 quarter(0.5, 0x0000_00ff),
971 quarter(0.75, 0x00ff_ff00),
972 ]
973 .concat();
974 d.fill(
975 Shape::Rect(day_spec::Rect::from_size(size)),
976 day_spec::ConicGradient::centered(day_spec::Angle::ZERO, stops),
977 );
978 })
979 .frame(100.0, 100.0)
980 .id(day_core::id!(canvas_conic::painted))
981 })
982 .drive(|d: Drive| async move {
983 // 0° is +x and the sweep is clockwise, so the first quarter is bottom-right.
984 d.sample_pixel("canvas_conic::painted", 0.75, 0.75, "#ff0000")
985 .await?;
986 d.sample_pixel("canvas_conic::painted", 0.25, 0.75, "#00ff00")
987 .await?;
988 d.sample_pixel("canvas_conic::painted", 0.25, 0.25, "#0000ff")
989 .await?;
990 d.sample_pixel("canvas_conic::painted", 0.75, 0.25, "#ffff00")
991 .await
992 })
993 }
994
995 /// A shadow is cast by what is drawn while it is set, lands at its offset, is not moved by
996 /// the canvas transform, and ends with the scope that set it.
997 #[day_macros::test(day_core)]
998 fn canvas_shadow_offset_and_scope() -> Case {
999 Case::new()
1000 .proves(kinds::CANVAS)
1001 .requires(Cap::Snapshot)
1002 .page(|| {
1003 canvas(|d, size| {
1004 d.fill(Shape::Rect(day_spec::Rect::from_size(size)), Color::WHITE);
1005 // Drawn at half size under a doubling transform: the box lands on
1006 // (30, 20) to (70, 50), and its shadow 20 points below that, not 40.
1007 d.transformed(day_spec::Affine::scale(2.0, 2.0), |d| {
1008 d.shadowed(
1009 day_spec::Shadow::new(Color::hex(0x0000_0000), 2.0).offset(0.0, 20.0),
1010 |d| {
1011 d.fill(
1012 Shape::Rect(day_spec::Rect::new(15.0, 10.0, 20.0, 15.0)),
1013 Color::hex(0x0000_00ff),
1014 );
1015 },
1016 );
1017 });
1018 // After the scope: no shadow under this one.
1019 d.fill(
1020 Shape::Rect(day_spec::Rect::new(130.0, 20.0, 40.0, 30.0)),
1021 Color::hex(0x0000_00ff),
1022 );
1023 })
1024 .frame(200.0, 100.0)
1025 .id(day_core::id!(canvas_shadow::painted))
1026 })
1027 .drive(|d: Drive| async move {
1028 d.sample_pixel("canvas_shadow::painted", 0.25, 0.35, "#0000ff")
1029 .await?;
1030 d.sample_pixel("canvas_shadow::painted", 0.25, 0.6, "#000000")
1031 .await?;
1032 d.sample_pixel("canvas_shadow::painted", 0.25, 0.85, "#ffffff")
1033 .await?;
1034 d.sample_pixel("canvas_shadow::painted", 0.75, 0.35, "#0000ff")
1035 .await?;
1036 d.sample_pixel("canvas_shadow::painted", 0.75, 0.6, "#ffffff")
1037 .await
1038 })
1039 }
1040
1041 /// Multiply and add combine with what the canvas already holds, and the mode ends with the
1042 /// scope that set it.
1043 #[day_macros::test(day_core)]
1044 fn canvas_blend_multiply_and_add() -> Case {
1045 Case::new()
1046 .proves(kinds::CANVAS)
1047 .requires(Cap::Snapshot)
1048 .page(|| {
1049 canvas(|d, size| {
1050 let third = size.width / 3.0;
1051 let band = |i: f64| {
1052 Shape::Rect(day_spec::Rect::new(third * i, 0.0, third, size.height))
1053 };
1054 d.fill(Shape::Rect(day_spec::Rect::from_size(size)), Color::WHITE);
1055 // Yellow times cyan is green.
1056 d.fill(band(0.0), Color::hex(0x00ff_ff00));
1057 d.blended(day_spec::BlendMode::Multiply, |d| {
1058 d.fill(band(0.0), Color::hex(0x0000_ffff));
1059 });
1060 // Red plus blue is magenta.
1061 d.fill(band(1.0), Color::hex(0x00ff_0000));
1062 d.blended(day_spec::BlendMode::Add, |d| {
1063 d.fill(band(1.0), Color::hex(0x0000_00ff));
1064 });
1065 // Back to normal: blue simply covers yellow.
1066 d.fill(band(2.0), Color::hex(0x00ff_ff00));
1067 d.fill(band(2.0), Color::hex(0x0000_00ff));
1068 })
1069 .frame(150.0, 60.0)
1070 .id(day_core::id!(canvas_blend::painted))
1071 })
1072 .drive(|d: Drive| async move {
1073 d.sample_pixel("canvas_blend::painted", 0.16, 0.5, "#00ff00")
1074 .await?;
1075 d.sample_pixel("canvas_blend::painted", 0.5, 0.5, "#ff00ff")
1076 .await?;
1077 d.sample_pixel("canvas_blend::painted", 0.84, 0.5, "#0000ff")
1078 .await
1079 })
1080 }
1081
1082 /// Erase removes what the canvas has drawn and shows what lies behind the canvas, not a
1083 /// black or white hole.
1084 #[day_macros::test(day_core)]
1085 fn canvas_blend_erase_shows_behind() -> Case {
1086 Case::new()
1087 .proves(kinds::CANVAS)
1088 .requires(Cap::Snapshot)
1089 .page(|| {
1090 zstack((
1091 rectangle().fill(Color::hex(0x00ff_0000)),
1092 canvas(|d, size| {
1093 d.fill(Shape::Rect(day_spec::Rect::from_size(size)), Color::WHITE);
1094 d.blended(day_spec::BlendMode::Erase, |d| {
1095 d.fill(
1096 Shape::Ellipse(day_spec::Rect::new(
1097 size.width / 2.0 - 20.0,
1098 size.height / 2.0 - 20.0,
1099 40.0,
1100 40.0,
1101 )),
1102 Color::hex(0x0000_ff00),
1103 );
1104 });
1105 })
1106 .frame(100.0, 100.0),
1107 ))
1108 .id(day_core::id!(canvas_erase::ground))
1109 .frame(100.0, 100.0)
1110 })
1111 .drive(|d: Drive| async move {
1112 d.sample_pixel("canvas_erase::ground", 0.5, 0.5, "#ff0000")
1113 .await?;
1114 d.sample_pixel("canvas_erase::ground", 0.1, 0.1, "#ffffff")
1115 .await
1116 })
1117 }
1118
1119 /// The drawing the export cases render: red left half, blue right half, a white disc in
1120 /// the middle, and a dark bar across the bottom fifth. Solid colors, so a sample has one
1121 /// right answer on every toolkit.
1122 fn export_swatch(d: &mut Draw, size: day_spec::Size) {
1123 let (w, h) = (size.width, size.height);
1124 d.fill(
1125 Shape::Rect(day_spec::Rect::new(0.0, 0.0, w / 2.0, h)),
1126 Color::hex(0x00ff_0000),
1127 );
1128 d.fill(
1129 Shape::Rect(day_spec::Rect::new(w / 2.0, 0.0, w / 2.0, h)),
1130 Color::hex(0x0000_00ff),
1131 );
1132 d.fill(
1133 Shape::Ellipse(day_spec::Rect::new(
1134 w / 2.0 - 15.0,
1135 h / 2.0 - 15.0,
1136 30.0,
1137 30.0,
1138 )),
1139 Color::hex(0x00ff_ffff),
1140 );
1141 d.fill(
1142 Shape::Rect(day_spec::Rect::new(0.0, h * 0.8, w, h * 0.2)),
1143 Color::hex(0x0020_2020),
1144 );
1145 }
1146
1147 /// An exported bitmap shown beside the live canvas reads the same colors in the same places:
1148 /// the export path and the on-screen path paint with one painter, with the same origin and
1149 /// orientation (docs/canvas.md "Exporting").
1150 #[day_macros::test(day_core)]
1151 fn canvas_export_matches_screen() -> Case {
1152 let size = day_spec::Size::new(120.0, 80.0);
1153 Case::new()
1154 .proves(kinds::CANVAS)
1155 .proves_cap(Cap::CanvasBitmap)
1156 .requires(Cap::CanvasBitmap)
1157 .requires(Cap::Snapshot)
1158 .page(move || {
1159 let shown = Signal::new(None::<day_core::Bitmap>);
1160 day_core::render_bitmap_async(
1161 Drawing::record(size, export_swatch).ops().to_vec(),
1162 size,
1163 2.0,
1164 move |result| shown.set(result.ok()),
1165 );
1166 column((
1167 canvas(export_swatch)
1168 .frame(size.width, size.height)
1169 .id(day_core::id!(export::live)),
1170 keyed(
1171 move || shown.get(),
1172 move |bitmap| {
1173 image(bitmap)
1174 .stretch()
1175 .frame(size.width, size.height)
1176 .id(day_core::id!(export::rendered))
1177 },
1178 ),
1179 label(move || match shown.get() {
1180 Some(b) => {
1181 let info = b.info();
1182 format!(
1183 "{}x{}@{}",
1184 info.pixels.width, info.pixels.height, info.scale
1185 )
1186 }
1187 None => "rendering".to_string(),
1188 })
1189 .id(day_core::id!(export::state)),
1190 ))
1191 .spacing(8.0)
1192 })
1193 .shot("default")
1194 .drive(|d: Drive| async move {
1195 // 120 × 80 points at 2× is 240 × 160 pixels that draw back at 120 × 80 points.
1196 d.assert_text("export::state", "240x160@2").await?;
1197 d.assert_size("export::rendered", 120.0, 80.0).await?;
1198 for id in ["export::live", "export::rendered"] {
1199 d.sample_pixel(id, 0.15, 0.3, "#ff0000").await?;
1200 d.sample_pixel(id, 0.85, 0.3, "#0000ff").await?;
1201 d.sample_pixel(id, 0.5, 0.5, "#ffffff").await?;
1202 // The bar is at the bottom in both: a flipped export would put it on top.
1203 d.sample_pixel(id, 0.5, 0.92, "#202020").await?;
1204 d.sample_pixel(id, 0.15, 0.08, "#ff0000").await?;
1205 }
1206 Ok(())
1207 })
1208 }
1209
1210 /// Curved/path clips must retain their geometry and the transform at clipping time.
1211 /// The PNG round trip must preserve transparent pixels outside that geometry too.
1212 #[day_macros::test(day_core)]
1213 fn canvas_clip_transform_png() -> Case {
1214 fn swatch(d: &mut Draw, _: day_spec::Size) {
1215 use day_spec::{Point, Rect};
1216 // An empty data series must leave the transparent corners untouched.
1217 d.stamp(
1218 Shape::Rect(Rect::new(0.0, 0.0, 120.0, 100.0)),
1219 vec![],
1220 Color::BLACK,
1221 );
1222 d.transformed(day_geometry::Affine::translate(20.0, 10.0), |d| {
1223 d.clipped(Shape::Ellipse(Rect::new(0.0, 0.0, 80.0, 80.0)), |d| {
1224 d.fill(
1225 Shape::Rect(Rect::new(-20.0, -10.0, 160.0, 120.0)),
1226 Color::hex(0x00ff_0000),
1227 );
1228 let triangle = PathBuilder::new()
1229 .move_to(Point::new(40.0, 0.0))
1230 .line_to(Point::new(80.0, 80.0))
1231 .line_to(Point::new(0.0, 80.0))
1232 .close()
1233 .build();
1234 d.clipped(triangle, |d| {
1235 d.transformed(day_geometry::Affine::translate(-20.0, -10.0), |d| {
1236 d.fill(
1237 Shape::Rect(Rect::new(0.0, 0.0, 120.0, 100.0)),
1238 Color::hex(0x0000_00ff),
1239 );
1240 });
1241 });
1242 });
1243 });
1244 // Restoring must remove both clips and transforms.
1245 d.fill(
1246 Shape::Rect(day_spec::Rect::new(0.0, 90.0, 120.0, 10.0)),
1247 Color::hex(0x0000_ff00),
1248 );
1249 }
1250 Case::new()
1251 .proves(kinds::CANVAS)
1252 .proves_cap(Cap::ImageEncode)
1253 .requires(Cap::CanvasBitmap)
1254 .requires(Cap::ImageEncode)
1255 .requires(Cap::Snapshot)
1256 .page(|| {
1257 let decoded = Signal::new(None::<day_core::Bitmap>);
1258 let status = Signal::new("rendering".to_string());
1259 day_core::task(async move {
1260 let result = Drawing::record(day_spec::Size::new(120.0, 100.0), swatch)
1261 .to_png(2.0)
1262 .await;
1263 match result {
1264 Ok(bytes) => match day_core::decode_image(std::sync::Arc::new(bytes)).await
1265 {
1266 Ok(bitmap) => {
1267 decoded.set(Some(bitmap));
1268 status.set("ready".into());
1269 }
1270 Err(e) => status.set(format!("decode: {e}")),
1271 },
1272 Err(e) => status.set(format!("export: {e}")),
1273 }
1274 });
1275 column((
1276 canvas(swatch)
1277 .frame(120.0, 100.0)
1278 .id(day_core::id!(clip_png::live)),
1279 keyed(
1280 move || decoded.get(),
1281 |bitmap| {
1282 image(bitmap)
1283 .stretch()
1284 .frame(120.0, 100.0)
1285 .id(day_core::id!(clip_png::decoded))
1286 },
1287 ),
1288 label(move || status.get()).id(day_core::id!(clip_png::state)),
1289 ))
1290 .background(Color::WHITE)
1291 })
1292 .drive(|d: Drive| async move {
1293 d.assert_text("clip_png::state", "ready").await?;
1294 for id in ["clip_png::live", "clip_png::decoded"] {
1295 d.sample_pixel(id, 0.2, 0.14, "#ffffff").await?;
1296 d.sample_pixel(id, 0.24, 0.5, "#ff0000").await?;
1297 d.sample_pixel(id, 0.5, 0.6, "#0000ff").await?;
1298 d.sample_pixel(id, 0.1, 0.95, "#00ff00").await?;
1299 }
1300 Ok(())
1301 })
1302 }
1303
1304 /// A PDF where the platform has a writer, and `Unsupported` where it has none: the bytes are
1305 /// a PDF file, and a toolkit without the cap never pretends otherwise.
1306 #[day_macros::test(day_core)]
1307 fn canvas_pdf_document() -> Case {
1308 Case::headless().run(|t: Drive| async move {
1309 let page = |w, h| Drawing::record(day_spec::Size::new(w, h), export_swatch);
1310 let result = PdfDocument::new()
1311 .title("Conformance")
1312 .author("Day")
1313 .page(page(612.0, 792.0))
1314 .page(page(300.0, 200.0))
1315 .render()
1316 .await;
1317 if !canvas_exports().pdf {
1318 return t.check_eq(result.err(), Some(day_spec::ExportError::Unsupported));
1319 }
1320 let pdf = match result {
1321 Ok(pdf) => pdf,
1322 Err(e) => return t.check(false, &format!("the PDF did not render: {e}")),
1323 };
1324 t.check(
1325 pdf.starts_with(b"%PDF-"),
1326 "the bytes do not start with %PDF-",
1327 )?;
1328 let tail = String::from_utf8_lossy(&pdf[pdf.len().saturating_sub(64)..]).to_string();
1329 t.check(tail.contains("%%EOF"), "the PDF has no %%EOF trailer")?;
1330 // An empty document is not a PDF of two pages: each page carries its own content.
1331 t.check(
1332 pdf.len() > 400,
1333 &format!("a {} byte PDF is too small", pdf.len()),
1334 )
1335 })
1336 }
1337
1338 /// A rendered bitmap is a `Bitmap` like any decode: it reports the export scale and the
1339 /// rounded-up pixel size, and encodes to PNG where the toolkit encodes PNG.
1340 #[day_macros::test(day_core)]
1341 fn canvas_export_scale_and_png() -> Case {
1342 Case::headless().run(|t: Drive| async move {
1343 let drawing = Drawing::record(day_spec::Size::new(50.5, 20.0), export_swatch);
1344 let result = drawing.to_bitmap(3.0).await;
1345 if !canvas_exports().bitmap {
1346 return t.check_eq(result.err(), Some(day_spec::ExportError::Unsupported));
1347 }
1348 let bitmap = match result {
1349 Ok(b) => b,
1350 Err(e) => return t.check(false, &format!("the bitmap did not render: {e}")),
1351 };
1352 let info = bitmap.info();
1353 t.check_eq(info.pixels, day_spec::Size::new(152.0, 60.0))?;
1354 t.check_eq(info.scale, 3.0)?;
1355 if !canvas_exports().png() {
1356 return Ok(());
1357 }
1358 match drawing.to_png(1.0).await {
1359 Ok(png) => t.check_eq(
1360 day_spec::ImageFormat::sniff(&png),
1361 Some(day_spec::ImageFormat::Png),
1362 ),
1363 Err(e) => t.check(false, &format!("the PNG did not encode: {e}")),
1364 }
1365 })
1366 }
1367}
1368
1369#[cfg(test)]
1370mod arc_tests {
1371 use super::PathBuilder;
1372 use day_spec::{PathSeg, Point};
1373
1374 /// Walk a built path, sampling every cubic densely, and hand back the points.
1375 fn sample(segs: &[PathSeg], per_seg: usize) -> Vec<Point> {
1376 let mut out = Vec::new();
1377 let mut cur = Point::ZERO;
1378 for seg in segs {
1379 match seg {
1380 PathSeg::Move(p) | PathSeg::Line(p) => {
1381 cur = *p;
1382 out.push(cur);
1383 }
1384 PathSeg::Cubic(c1, c2, p) => {
1385 for i in 1..=per_seg {
1386 let t = i as f64 / per_seg as f64;
1387 let u = 1.0 - t;
1388 // de Casteljau, written out: the cubic Bernstein basis.
1389 out.push(Point::new(
1390 u * u * u * cur.x
1391 + 3.0 * u * u * t * c1.x
1392 + 3.0 * u * t * t * c2.x
1393 + t * t * t * p.x,
1394 u * u * u * cur.y
1395 + 3.0 * u * u * t * c1.y
1396 + 3.0 * u * t * t * c2.y
1397 + t * t * t * p.y,
1398 ));
1399 }
1400 cur = *p;
1401 }
1402 PathSeg::Quad(..) | PathSeg::Close => {}
1403 }
1404 }
1405 out
1406 }
1407
1408 /// The property that matters: every point of the emitted curve is on the circle. Pinning the
1409 /// control points instead would pin the construction rather than the result, and it is the
1410 /// result a rasterizer draws.
1411 #[test]
1412 fn an_arc_stays_on_its_circle() {
1413 let c = Point::new(100.0, 50.0);
1414 let r = 40.0;
1415 for sweep in [15.0_f64, 90.0, 180.0, 359.0, -90.0, -270.0] {
1416 let path = PathBuilder::new()
1417 .arc_to(
1418 c,
1419 r,
1420 day_spec::Angle::deg(30.0),
1421 day_spec::Angle::deg(sweep),
1422 )
1423 .build();
1424 let day_spec::Shape::Path(p) = path else {
1425 panic!("arc_to builds a path")
1426 };
1427 let worst = sample(&p.segs, 24)
1428 .iter()
1429 .map(|q| ((q.x - c.x).powi(2) + (q.y - c.y).powi(2)).sqrt() - r)
1430 .fold(0.0f64, |m, e| m.max(e.abs()));
1431 // The known peak for a cubic quarter-circle, with a little headroom. The assertion
1432 // uses the real figure rather than a loose one so that a future change that split the
1433 // sweep differently or got a handle length wrong is noticed here.
1434 assert!(worst < r * 2.8e-4, "sweep {sweep}: off by {worst}");
1435 // ...and it is that good rather than accidentally better: a construction that
1436 // silently started flattening to line segments would pass a one-sided bound.
1437 if sweep.abs() >= 90.0 {
1438 assert!(
1439 worst > r * 1e-6,
1440 "sweep {sweep}: suspiciously exact ({worst})"
1441 );
1442 }
1443 }
1444 }
1445
1446 /// Degrees, 0 = +x, positive clockwise, the same convention `Shape::Arc` and `circle` use.
1447 /// A wrong sign here is the kind of thing that only shows up as a donut drawn inside out.
1448 #[test]
1449 fn arc_endpoints_follow_the_clockwise_degree_convention() {
1450 let c = Point::new(0.0, 0.0);
1451 let near = |a: Point, b: Point| (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() < 1e-9;
1452 let ends = |start: f64, sweep: f64| {
1453 let day_spec::Shape::Path(p) = PathBuilder::new()
1454 .arc_to(
1455 c,
1456 10.0,
1457 day_spec::Angle::deg(start),
1458 day_spec::Angle::deg(sweep),
1459 )
1460 .build()
1461 else {
1462 panic!()
1463 };
1464 let pts = sample(&p.segs, 1);
1465 (*pts.first().unwrap(), *pts.last().unwrap())
1466 };
1467 // 0° is +x; a quarter turn clockwise lands on +y, which is down in canvas space.
1468 let (a, b) = ends(0.0, 90.0);
1469 assert!(near(a, Point::new(10.0, 0.0)), "{a:?}");
1470 assert!(near(b, Point::new(0.0, 10.0)), "{b:?}");
1471 // …and the same quarter counter-clockwise lands on -y.
1472 let (_, b) = ends(0.0, -90.0);
1473 assert!(near(b, Point::new(0.0, -10.0)), "{b:?}");
1474 }
1475
1476 /// A rounded rectangle is a contour of its own: a frame with a rounded hole is two of them,
1477 /// the inner one cut out by the even-odd rule.
1478 #[test]
1479 fn a_rounded_rect_contour_opens_and_closes_its_own_subpath() {
1480 use day_spec::{CornerRadii, FillRule, Rect};
1481 let day_spec::Shape::Path(p) = PathBuilder::new()
1482 .rule(FillRule::EvenOdd)
1483 .rounded_rect(Rect::new(0.0, 0.0, 40.0, 40.0), CornerRadii::uniform(8.0))
1484 .rounded_rect(Rect::new(10.0, 10.0, 20.0, 20.0), CornerRadii::top(4.0))
1485 .build()
1486 else {
1487 panic!("a path")
1488 };
1489 let moves = p
1490 .segs
1491 .iter()
1492 .filter(|s| matches!(s, PathSeg::Move(_)))
1493 .count();
1494 let closes = p
1495 .segs
1496 .iter()
1497 .filter(|s| matches!(s, PathSeg::Close))
1498 .count();
1499 assert_eq!((moves, closes), (2, 2));
1500 assert_eq!(p.rule, FillRule::EvenOdd);
1501 }
1502
1503 /// An arc joins what came before, which is why it is a segment and not a shape.
1504 #[test]
1505 fn an_arc_joins_the_current_subpath_but_starts_a_fresh_one_after_close() {
1506 let c = Point::new(0.0, 0.0);
1507 let segs = |b: PathBuilder| {
1508 let day_spec::Shape::Path(p) = b.build() else {
1509 panic!()
1510 };
1511 p.segs
1512 };
1513 // Nothing before it: the arc opens the subpath.
1514 let s = segs(PathBuilder::new().arc_to(
1515 c,
1516 5.0,
1517 day_spec::Angle::deg(0.0),
1518 day_spec::Angle::deg(90.0),
1519 ));
1520 std::assert_matches!(s[0], PathSeg::Move(_), "{:?}", s[0]);
1521 // Something before it: the arc is reached by a line, so the figure is one contour.
1522 let s = segs(PathBuilder::new().move_to(Point::new(9.0, 9.0)).arc_to(
1523 c,
1524 5.0,
1525 day_spec::Angle::deg(0.0),
1526 day_spec::Angle::deg(90.0),
1527 ));
1528 std::assert_matches!(s[1], PathSeg::Line(_), "{:?}", s[1]);
1529 // After a close there is no current point, so it opens a new subpath rather than drawing
1530 // a stray line back from wherever the last contour ended.
1531 let s = segs(
1532 PathBuilder::new()
1533 .move_to(Point::new(9.0, 9.0))
1534 .line_to(Point::new(1.0, 1.0))
1535 .close()
1536 .arc_to(
1537 c,
1538 5.0,
1539 day_spec::Angle::deg(0.0),
1540 day_spec::Angle::deg(90.0),
1541 ),
1542 );
1543 std::assert_matches!(s[3], PathSeg::Move(_), "{:?}", s[3]);
1544 // A degenerate arc still reaches its start point and emits no curve.
1545 let s = segs(PathBuilder::new().arc_to(
1546 c,
1547 5.0,
1548 day_spec::Angle::deg(0.0),
1549 day_spec::Angle::deg(0.0),
1550 ));
1551 assert_eq!(s.len(), 1);
1552 let s = segs(PathBuilder::new().arc_to(
1553 c,
1554 0.0,
1555 day_spec::Angle::deg(0.0),
1556 day_spec::Angle::deg(90.0),
1557 ));
1558 assert_eq!(s.len(), 1);
1559 }
1560}