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, with `frame_clock` for per-frame animation), plus the general `Reactive<T>`
6//! (value / `Signal` / closure) abstraction that pieces accept for animatable inputs.
7
8use std::cell::RefCell;
9use std::rc::Rc;
10
11use day_core::*;
12use day_reactive::{Scope, Signal};
13use day_spec::props::*;
14use day_spec::{
15 Color, CornerRadii, DrawOp, Event, ExportError, FillRule, Paint, PathSeg, Point, Rect, Shape,
16 Size, StrokeStyle, 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_deg: f64, sweep_deg: f64) -> 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_deg);
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_deg, sweep_deg));
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, black, top-leading, the
209/// 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 pub color: Color,
215 pub anchor: day_spec::TextAnchor,
216 /// Family, weight and slant (docs/fonts.md); the default is the platform's UI face.
217 pub font: day_spec::CanvasFont,
218}
219
220impl Default for TextStyle {
221 fn default() -> Self {
222 TextStyle {
223 size: 12.0,
224 color: Color::BLACK,
225 anchor: day_spec::TextAnchor::LEADING,
226 font: day_spec::CanvasFont::default(),
227 }
228 }
229}
230
231impl Draw {
232 /// Fill a shape with a solid color or a [`day_spec::LinearGradient`] (both convert to [`Paint`];
233 /// gradient unit points resolve against the shape's bounding box, docs/shapes.md §3.2).
234 pub fn fill(&mut self, shape: Shape, paint: impl Into<Paint>) {
235 self.ops.push(DrawOp::Fill(shape, paint.into()));
236 }
237 /// Stroke a shape with a solid color at `width`, the everyday case.
238 pub fn stroke(&mut self, shape: Shape, color: Color, width: f64) {
239 self.ops.push(DrawOp::Stroke(
240 shape,
241 Paint::Solid(color),
242 StrokeStyle::width(width),
243 ));
244 }
245 /// Stroke with a full [`StrokeStyle`] (dash, cap, join) and any paint, gradients included.
246 pub fn stroke_styled(&mut self, shape: Shape, paint: impl Into<Paint>, style: StrokeStyle) {
247 self.ops.push(DrawOp::Stroke(shape, paint.into(), style));
248 }
249 /// Draw `shape` once at every position in `at`: one op for the whole batch.
250 ///
251 /// The template is authored around the origin and each copy is it translated by one point, so
252 /// a 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`. Order is drawing order.
253 ///
254 /// Reach for this the moment a drawing has more marks than it has kinds of mark. A scatter of
255 /// fifty thousand points drawn one `fill` at a time is fifty thousand ops to build, compare
256 /// and clone on every frame that re-records; as one stamp it is one op and a flat array of
257 /// coordinates, and a backend can put every copy into a single path (docs/canvas.md
258 /// "Stamping"). Every copy shares the shape, size and paint, so group by whatever varies.
259 pub fn stamp(&mut self, shape: Shape, at: Vec<Point>, paint: impl Into<Paint>) {
260 self.ops.push(DrawOp::Stamp(Box::new(day_spec::Stamp {
261 shape,
262 at,
263 paint: paint.into(),
264 stroke: None,
265 })));
266 }
267
268 /// [`Draw::stamp`], stroking each copy instead of filling it.
269 pub fn stamp_styled(
270 &mut self,
271 shape: Shape,
272 at: Vec<Point>,
273 paint: impl Into<Paint>,
274 style: StrokeStyle,
275 ) {
276 self.ops.push(DrawOp::Stamp(Box::new(day_spec::Stamp {
277 shape,
278 at,
279 paint: paint.into(),
280 stroke: Some(style),
281 })));
282 }
283
284 /// Draw a decoded image into `rect` (docs/images.md).
285 ///
286 /// Takes a decoded [`Bitmap`](day_core::Bitmap), not bytes: the draw closure re-records on
287 /// every tracked read, and a buffer here would be compared (and re-decoded) every frame.
288 /// Decode once with `day::decode_image`, hold the handle, and draw it as often as you like.
289 ///
290 /// ```ignore
291 /// let photo = day::decode_image(bytes).await?; // once
292 /// canvas(move |d, size| d.image(&photo, Rect::from_size(size)))
293 /// ```
294 ///
295 /// Needs [`Cap::ImageDecode`](day_spec::Cap::ImageDecode); a backend without it draws
296 /// nothing here, the same as for any op it does not know.
297 pub fn image(&mut self, image: &day_core::Bitmap, rect: day_spec::Rect) {
298 self.image_with_opacity(image, rect, 1.0);
299 }
300
301 /// [`Draw::image`] with an opacity in `0.0..=1.0` multiplying the image's own alpha.
302 pub fn image_with_opacity(
303 &mut self,
304 image: &day_core::Bitmap,
305 rect: day_spec::Rect,
306 opacity: f64,
307 ) {
308 self.ops.push(DrawOp::Image {
309 image: image.id(),
310 rect,
311 opacity: opacity.clamp(0.0, 1.0),
312 source: None,
313 });
314 }
315
316 /// Draw the `source` region of a decoded image into `rect` (docs/images.md "Drawing on a
317 /// canvas").
318 ///
319 /// `source` is in the bitmap's own PIXELS, not points: a sprite sheet lays its cells out in
320 /// pixels, and [`Bitmap::info`](day_core::Bitmap::info) says how many of them make a point.
321 /// The region is scaled into `rect` exactly as [`Draw::image`] scales the whole image. A
322 /// region reaching outside the bitmap is clamped to it, never an error, and an empty
323 /// intersection draws nothing.
324 ///
325 /// ```ignore
326 /// let sheet = day::decode_image(sprites).await?; // once
327 /// canvas(move |d, _| d.image_region(&sheet, icon.cell, Rect::new(10.0, 10.0, 24.0, 24.0)))
328 /// ```
329 pub fn image_region(
330 &mut self,
331 image: &day_core::Bitmap,
332 source: day_spec::Rect,
333 rect: day_spec::Rect,
334 ) {
335 self.image_region_with_opacity(image, source, rect, 1.0);
336 }
337
338 /// [`Draw::image_region`] with an opacity in `0.0..=1.0` multiplying the image's own alpha.
339 pub fn image_region_with_opacity(
340 &mut self,
341 image: &day_core::Bitmap,
342 source: day_spec::Rect,
343 rect: day_spec::Rect,
344 opacity: f64,
345 ) {
346 self.ops.push(DrawOp::Image {
347 image: image.id(),
348 rect,
349 opacity: opacity.clamp(0.0, 1.0),
350 source: Some(source),
351 });
352 }
353
354 /// Confine everything drawn afterwards to `shape`.
355 ///
356 /// The clip lasts until the enclosing [`Draw::restore`], so the usual shape is
357 /// `save` → `clip` → draw → `restore`; [`Draw::clipped`] does exactly that for you.
358 pub fn clip(&mut self, shape: Shape) {
359 self.ops.push(DrawOp::Clip(shape));
360 }
361 /// Draw `f` clipped to `shape`, restoring the previous clip afterwards.
362 pub fn clipped(&mut self, shape: Shape, f: impl FnOnce(&mut Draw)) {
363 self.save();
364 self.clip(shape);
365 f(self);
366 self.restore();
367 }
368 /// One line of text hung on `at` per the style's anchor (docs/canvas.md "Text"); measure it
369 /// first with `day::measure_text` when the drawing needs its extent.
370 pub fn text(&mut self, text: &str, at: Point, style: TextStyle) {
371 self.ops.push(DrawOp::Text {
372 text: text.to_owned(),
373 at,
374 size: style.size,
375 color: style.color,
376 anchor: style.anchor,
377 font: style.font,
378 });
379 }
380 /// Save the current transform/clip; pair with [`Draw::restore`].
381 pub fn save(&mut self) {
382 self.ops.push(DrawOp::Save);
383 }
384 /// Restore the transform/clip saved by the matching [`Draw::save`].
385 pub fn restore(&mut self) {
386 self.ops.push(DrawOp::Restore);
387 }
388 /// Multiply an affine onto the current transform (shape rotate/scale/offset, §11).
389 pub fn concat(&mut self, m: day_geometry::Affine) {
390 self.ops.push(DrawOp::Concat(m));
391 }
392 /// Draw within `m` applied to the CTM, restoring afterwards.
393 pub fn transformed(&mut self, m: day_geometry::Affine, f: impl FnOnce(&mut Draw)) {
394 self.save();
395 self.concat(m);
396 f(self);
397 self.restore();
398 }
399}
400
401/// Create + wire a reactive canvas leaf with a given flex: the draw closure re-records on any
402/// tracked read and on `FrameChanged`; replay is equality-gated by `DrawOp: PartialEq` (§4.2).
403/// Shared by [`canvas`] (intrinsic) and [`shape`] (grows to fill, §shapes).
404pub(crate) fn canvas_leaf(
405 cx: &mut BuildCx,
406 flex: Flex,
407 draw: impl Fn(&mut Draw, Size) + 'static,
408) -> RNode {
409 use day_reactive::{Trigger, bind};
410 let node = cx.leaf(kinds::CANVAS, &CanvasProps::default(), flex);
411 let trig = Trigger::new();
412 cx.on(node, move |ev| {
413 if matches!(ev, Event::FrameChanged(_)) {
414 trig.notify();
415 }
416 });
417 let draw = std::rc::Rc::new(draw);
418 let d2 = draw.clone();
419 bind(
420 move || {
421 trig.track();
422 let size = with_tree(|t| t.node_frame(node)).map_or(Size::new(0.0, 0.0), |f| f.size);
423 let mut d = Draw { ops: Vec::new() };
424 (d2)(&mut d, size);
425 d.ops
426 },
427 move |ops: &Vec<DrawOp>| {
428 with_tree(|t| t.replay(node, ops.clone()));
429 },
430 );
431 node
432}
433
434/// The drawing closure is a binding: signal reads re-record; layout size changes re-record
435/// (via `FrameChanged`); replay is equality-gated by `DrawOp`'s `PartialEq` (§4.2).
436pub fn canvas(draw: impl Fn(&mut Draw, Size) + 'static) -> impl Piece {
437 piece_fn(move |cx| canvas_leaf(cx, Flex::default(), draw))
438}
439
440// ---------------------------------------------------------------------------
441// Export (docs/canvas.md "Exporting"): the same draw function, replayed offscreen.
442// ---------------------------------------------------------------------------
443
444/// A recorded drawing at a fixed size: what a [`canvas`] would replay, kept for export.
445///
446/// Write the drawing once as a plain function and call it from the canvas and from export:
447///
448/// ```ignore
449/// fn draw_chart(d: &mut Draw, size: Size, series: &[f64]) { /* … */ }
450///
451/// canvas(move |d, size| draw_chart(d, size, &series.get())) // on screen
452/// let drawing = Drawing::record(Size::new(600.0, 400.0), |d, size| {
453/// draw_chart(d, size, &series.get_untracked())
454/// });
455/// day::task(async move {
456/// if let Ok(png) = drawing.to_png(2.0).await { /* save it */ }
457/// });
458/// ```
459///
460/// Rendering goes through the toolkit's own canvas painter (Core Graphics, cairo, `QPainter`,
461/// an android `Canvas`, …), so an export matches the screen. Probe [`canvas_exports`] before
462/// offering a command.
463#[derive(Clone, Debug, PartialEq)]
464pub struct Drawing {
465 size: Size,
466 ops: Vec<DrawOp>,
467}
468
469impl Drawing {
470 /// Run `draw` once, untracked, at `size` points. Signal reads inside it subscribe nothing,
471 /// so recording from a binding or a menu action is safe.
472 pub fn record(size: Size, draw: impl FnOnce(&mut Draw, Size)) -> Drawing {
473 let mut d = Draw::new();
474 day_reactive::untrack(|| draw(&mut d, size));
475 Drawing { size, ops: d.ops }
476 }
477
478 /// A drawing of ops recorded elsewhere, at `size` points.
479 #[must_use]
480 pub fn from_ops(size: Size, ops: Vec<DrawOp>) -> Drawing {
481 Drawing { size, ops }
482 }
483
484 /// The size the drawing was recorded at, in points.
485 pub fn size(&self) -> Size {
486 self.size
487 }
488
489 /// The recorded display list.
490 #[must_use]
491 pub fn ops(&self) -> &[DrawOp] {
492 &self.ops
493 }
494
495 /// Render to a bitmap of `size × scale` pixels whose `info().scale` is `scale`, so
496 /// `image(&bitmap)` shows it at the drawing's point size. Await it inside `day::task`.
497 ///
498 /// `Err(ExportError::Unsupported)` where the toolkit has no offscreen painter
499 /// ([`Cap::CanvasBitmap`](day_spec::Cap::CanvasBitmap)); `Err(ExportError::TooLarge)` above
500 /// 16,384 pixels a side or 64 megapixels.
501 #[must_use]
502 pub fn to_bitmap(&self, scale: f64) -> day_core::RenderBitmap {
503 day_core::render_bitmap(self.ops.clone(), self.size, scale)
504 }
505
506 /// Render to a bitmap and encode it as PNG: [`Drawing::to_bitmap`] then
507 /// [`Bitmap::encode`]. `Err(ExportError::Unsupported)` where either half is missing
508 /// ([`CanvasExports::png`] answers that up front).
509 ///
510 /// # Errors
511 ///
512 /// Resolves to the errors of [`Drawing::to_bitmap`], `ExportError::Unsupported` where the
513 /// toolkit cannot encode, or `ExportError::Failed` with the encoder's message.
514 pub fn to_png(
515 &self,
516 scale: f64,
517 ) -> impl std::future::Future<Output = Result<Vec<u8>, ExportError>> + 'static {
518 let render = self.to_bitmap(scale);
519 async move {
520 let bitmap = render.await?;
521 bitmap
522 .encode(day_spec::EncodeSpec::default())
523 .await
524 .map_err(|e| match e {
525 day_spec::ImageError::Unsupported | day_spec::ImageError::Encode => {
526 ExportError::Unsupported
527 }
528 other => ExportError::Failed(other.to_string()),
529 })
530 }
531 }
532
533 /// A one-page PDF the size of the drawing. `Err(ExportError::Unsupported)` where the
534 /// platform has no PDF writer ([`Cap::CanvasPdf`](day_spec::Cap::CanvasPdf)).
535 #[must_use]
536 pub fn to_pdf(&self) -> day_core::RenderPdf {
537 PdfDocument::new().page(self.clone()).render()
538 }
539}
540
541/// A PDF of one or more drawings, one per page; each page takes its drawing's size in PDF
542/// points (1/72 inch, the same unit as canvas points: US Letter is 612 × 792, A4 595 × 842).
543///
544/// ```ignore
545/// let mut doc = PdfDocument::new().title("Quarterly report");
546/// for region in ®ions {
547/// doc = doc.page(Drawing::record(LETTER, |d, size| draw_region(d, size, region)));
548/// }
549/// let pdf = doc.render().await?;
550/// ```
551#[derive(Clone, Debug, Default, PartialEq)]
552pub struct PdfDocument {
553 pages: Vec<Drawing>,
554 info: day_spec::PdfInfo,
555}
556
557impl PdfDocument {
558 /// An empty document; rendering it before adding a page answers `ExportError::Invalid`.
559 pub fn new() -> Self {
560 Self::default()
561 }
562
563 /// Append `drawing` as the next page, at the drawing's size.
564 #[must_use]
565 pub fn page(mut self, drawing: Drawing) -> Self {
566 self.pages.push(drawing);
567 self
568 }
569
570 /// The document title. Android's writer has no metadata API and ignores it.
571 #[must_use]
572 pub fn title(mut self, title: impl Into<String>) -> Self {
573 self.info.title = Some(title.into());
574 self
575 }
576
577 /// The document author. Android's writer ignores it, as it does the title.
578 #[must_use]
579 pub fn author(mut self, author: impl Into<String>) -> Self {
580 self.info.author = Some(author.into());
581 self
582 }
583
584 /// How many pages have been added.
585 #[must_use]
586 pub fn len(&self) -> usize {
587 self.pages.len()
588 }
589
590 /// Whether no page has been added yet.
591 #[must_use]
592 pub fn is_empty(&self) -> bool {
593 self.pages.is_empty()
594 }
595
596 /// Render the document through the platform's PDF writer. Await it inside `day::task`.
597 #[must_use]
598 pub fn render(self) -> day_core::RenderPdf {
599 let pages = self
600 .pages
601 .into_iter()
602 .map(|d| day_spec::PdfPage {
603 size: d.size,
604 ops: d.ops,
605 })
606 .collect();
607 day_core::render_pdf(pages, self.info)
608 }
609}
610
611/// A frame clock (§8.4): an invisible, zero-size piece that calls `tick` every animation frame with
612/// the wall-clock delta since the previous frame, for as long as it is mounted. Drop it into the
613/// tree (e.g. behind a `canvas` in a `zstack`) to drive a game loop or self-driven animation: the
614/// tick mutates state `Signal`s, and a `canvas` reading them re-records that frame.
615///
616/// Shares `day::frame`'s per-window native display scheduler (docs/frames.md); Day has no
617/// timer fallback. Requests stop when the last consumer unmounts. This legacy piece retains
618/// a first delta of 1/60 s and a <=100 ms clamp; the general frame API exposes raw elapsed time
619/// and pause/resume handles. Inert on the mock backend.
620///
621/// ```ignore
622/// zstack((
623/// canvas(move |d, sz| draw(d, sz, state)).grow(Dimension::Both),
624/// frame_clock(move |dt| step(dt, state)),
625/// ))
626/// ```
627pub fn frame_clock(tick: impl FnMut(std::time::Duration) + 'static) -> impl Piece {
628 type TickSlot = Rc<RefCell<Option<Box<dyn FnMut(std::time::Duration)>>>>;
629 // Registered on first build (in the mounting scope) and removed when that scope is disposed.
630 let slot: TickSlot = Rc::new(RefCell::new(Some(Box::new(tick))));
631 piece_fn(move |cx| {
632 if let Some(cb) = slot.borrow_mut().take() {
633 let id = day_core::add_frame_consumer(cb);
634 Scope::current().on_cleanup(move || day_core::remove_frame_consumer(id));
635 }
636 label("").frame(0.0, 0.0).build(cx)
637 })
638}
639
640// ---------------------------------------------------------------------------
641// Reactive<T>: a value, a Signal, or a closure; the generalization of IntoText/IntoFraction.
642// ---------------------------------------------------------------------------
643
644/// A parameter that is either a constant or a reactive source. `get()` is a tracked read, so any
645/// `Reactive` used inside a canvas draw closure makes that shape re-record when the source changes.
646pub enum Reactive<T: Clone + 'static> {
647 Const(T),
648 Dyn(Rc<dyn Fn() -> T>),
649}
650impl<T: Clone + 'static> Clone for Reactive<T> {
651 fn clone(&self) -> Self {
652 match self {
653 Reactive::Const(v) => Reactive::Const(v.clone()),
654 Reactive::Dyn(f) => Reactive::Dyn(f.clone()),
655 }
656 }
657}
658impl<T: Clone + 'static> Reactive<T> {
659 pub fn get(&self) -> T {
660 match self {
661 Reactive::Const(v) => v.clone(),
662 Reactive::Dyn(f) => f(),
663 }
664 }
665 pub fn get_untracked(&self) -> T {
666 match self {
667 Reactive::Const(v) => v.clone(),
668 Reactive::Dyn(f) => day_reactive::untrack(|| f()),
669 }
670 }
671}
672/// Disjoint-marker conversion (like [`IntoText`]): accepts `T`, `Signal<T>`, or `Fn() -> T`.
673pub trait IntoReactive<T: Clone + 'static, M> {
674 fn into_reactive(self) -> Reactive<T>;
675}
676impl<T: Clone + 'static> IntoReactive<T, StaticMark> for T {
677 fn into_reactive(self) -> Reactive<T> {
678 Reactive::Const(self)
679 }
680}
681impl<T: Clone + 'static> IntoReactive<T, SignalMark> for Signal<T> {
682 fn into_reactive(self) -> Reactive<T> {
683 Reactive::Dyn(Rc::new(move || self.get()))
684 }
685}
686impl<T: Clone + 'static, F: Fn() -> T + 'static> IntoReactive<T, FnMark> for F {
687 fn into_reactive(self) -> Reactive<T> {
688 Reactive::Dyn(Rc::new(self))
689 }
690}
691
692// ---------------------------------------------------------------------------
693// Conformance cases (docs/testing.md)
694// ---------------------------------------------------------------------------
695
696/// The canvas's `#[day::test]` cases, next to its constructor.
697#[cfg(feature = "conformance")]
698pub(crate) mod conformance {
699 use day_core::conformance::{Case, Drive};
700 use day_reactive::Signal;
701 use day_spec::{Cap, Color, Role, Shape, kinds};
702
703 use crate::*;
704
705 /// A canvas with an explicit role, label and a value that follows a signal reports all
706 /// three natively, after the value changes too (the showcase gauge's shape). Its value is
707 /// also its text, so a drawn readout is checked with `assert_text` like a label.
708 #[day_macros::test(day_core)]
709 fn canvas_a11y_value() -> Case {
710 let level = Signal::new(40.0f64);
711 Case::new()
712 .proves(kinds::CANVAS)
713 .proves_modifier("a11y")
714 .page(move || {
715 column((
716 canvas(move |d, size| {
717 let w = size.width * level.get() / 100.0;
718 d.fill(
719 Shape::Rect(day_spec::Rect::new(0.0, 0.0, w, size.height)),
720 Color::rgb(0.2, 0.5, 0.9),
721 );
722 })
723 .a11y(move |a| {
724 a.role(Role::Meter)
725 .label("Level")
726 .value(move || format!("{:.0}", level.get()))
727 })
728 .id(day_core::id!(meter))
729 .frame(160.0, 24.0),
730 button("Raise")
731 .action(move || level.set(80.0))
732 .id(day_core::id!(raise)),
733 ))
734 .spacing(8.0)
735 })
736 .drive(|d: Drive| async move {
737 d.a11y_audit(Some("meter")).await?;
738 d.assert_text("meter", "40").await?;
739 d.tap("raise").await?;
740 d.a11y_audit(Some("meter")).await?;
741 d.assert_text("meter", "80").await
742 })
743 }
744
745 /// Native layout must not turn a canvas into a focus scope with no focusable children.
746 #[day_macros::test(day_core)]
747 fn canvas_focus_after_layout() -> Case {
748 Case::new()
749 .proves(kinds::CANVAS)
750 .proves_duty("focus")
751 .requires(Cap::Snapshot)
752 .page(|| {
753 column((
754 canvas(|d, size| {
755 d.fill(
756 Shape::Rect(day_spec::Rect::from_size(size)),
757 Color::hex(0x00ff_0000),
758 );
759 })
760 .frame(80.0, 60.0)
761 .id(day_core::id!(painted)),
762 canvas(|_, _| {}).frame(40.0, 40.0).id(day_core::id!(empty)),
763 ))
764 })
765 .drive(|d: Drive| async move {
766 // A real rendered frame, rather than a timing delay: requesting focus before
767 // ArkUI's first native layout hid its canvas host's loss of focusability.
768 d.shot("before-focus").await?;
769 d.sample_pixel("painted", 0.5, 0.5, "#ff0000").await?;
770 d.focus("painted").await?;
771 d.assert_focused("painted", true).await?;
772 d.sample_pixel("painted", 0.5, 0.5, "#ff0000").await?;
773 d.focus("empty").await?;
774 d.assert_focused("empty", true).await
775 })
776 }
777
778 /// Bitmap origins participate in the whole canvas transform, just like shape coordinates.
779 /// Reading the recorded rectangle alone cannot detect a native replay placing it elsewhere.
780 #[day_macros::test(day_core)]
781 fn canvas_image_transform_and_opacity() -> Case {
782 Case::new()
783 .proves(kinds::CANVAS)
784 .proves_cap(Cap::ImageDecode)
785 .requires(Cap::ImageDecode)
786 .requires(Cap::Snapshot)
787 .page(|| {
788 let bitmap = Signal::new(None::<day_core::Bitmap>);
789 day_core::decode_image_async(
790 std::sync::Arc::new(crate::image::conformance::RED_BLUE.to_vec()),
791 move |result| bitmap.set(Some(result.expect("decode the fixture PNG"))),
792 );
793 column((
794 canvas(move |d, size| {
795 d.fill(Shape::Rect(day_spec::Rect::from_size(size)), Color::WHITE);
796 if let Some(image) = bitmap.get() {
797 d.transformed(
798 day_spec::Affine::scale(2.0, 2.0)
799 .then(day_spec::Affine::rotate(std::f64::consts::FRAC_PI_2))
800 .then(day_spec::Affine::translate(160.0, 20.0)),
801 |d| {
802 d.image_with_opacity(
803 &image,
804 day_spec::Rect::new(20.0, 10.0, 40.0, 20.0),
805 0.5,
806 );
807 },
808 );
809 }
810 })
811 .frame(200.0, 200.0)
812 .id(day_core::id!(canvas_image::painted)),
813 label(move || {
814 if bitmap.get().is_some() {
815 "ready"
816 } else {
817 "loading"
818 }
819 })
820 .id(day_core::id!(canvas_image::state)),
821 ))
822 })
823 .drive(|d: Drive| async move {
824 d.assert_text("canvas_image::state", "ready").await?;
825 // Rotated and doubled: x=100..140, red y=60..100, blue y=100..140.
826 d.sample_pixel("canvas_image::painted", 0.6, 0.4, "#ff8080")
827 .await?;
828 d.sample_pixel("canvas_image::painted", 0.6, 0.6, "#8080ff")
829 .await?;
830 d.sample_pixel("canvas_image::painted", 0.4, 0.5, "#ffffff")
831 .await?;
832 d.sample_pixel("canvas_image::painted", 0.6, 0.2, "#ffffff")
833 .await
834 })
835 }
836
837 /// The drawing the export cases render: red left half, blue right half, a white disc in
838 /// the middle, and a dark bar across the bottom fifth. Solid colors, so a sample has one
839 /// right answer on every toolkit.
840 fn export_swatch(d: &mut Draw, size: day_spec::Size) {
841 let (w, h) = (size.width, size.height);
842 d.fill(
843 Shape::Rect(day_spec::Rect::new(0.0, 0.0, w / 2.0, h)),
844 Color::hex(0x00ff_0000),
845 );
846 d.fill(
847 Shape::Rect(day_spec::Rect::new(w / 2.0, 0.0, w / 2.0, h)),
848 Color::hex(0x0000_00ff),
849 );
850 d.fill(
851 Shape::Ellipse(day_spec::Rect::new(
852 w / 2.0 - 15.0,
853 h / 2.0 - 15.0,
854 30.0,
855 30.0,
856 )),
857 Color::hex(0x00ff_ffff),
858 );
859 d.fill(
860 Shape::Rect(day_spec::Rect::new(0.0, h * 0.8, w, h * 0.2)),
861 Color::hex(0x0020_2020),
862 );
863 }
864
865 /// An exported bitmap shown beside the live canvas reads the same colors in the same places:
866 /// the export path and the on-screen path paint with one painter, with the same origin and
867 /// orientation (docs/canvas.md "Exporting").
868 #[day_macros::test(day_core)]
869 fn canvas_export_matches_screen() -> Case {
870 let size = day_spec::Size::new(120.0, 80.0);
871 Case::new()
872 .proves(kinds::CANVAS)
873 .proves_cap(Cap::CanvasBitmap)
874 .requires(Cap::CanvasBitmap)
875 .requires(Cap::Snapshot)
876 .page(move || {
877 let shown = Signal::new(None::<day_core::Bitmap>);
878 day_core::render_bitmap_async(
879 Drawing::record(size, export_swatch).ops().to_vec(),
880 size,
881 2.0,
882 move |result| shown.set(result.ok()),
883 );
884 column((
885 canvas(export_swatch)
886 .frame(size.width, size.height)
887 .id(day_core::id!(export::live)),
888 keyed(
889 move || shown.get(),
890 move |bitmap| {
891 image(bitmap)
892 .stretch()
893 .frame(size.width, size.height)
894 .id(day_core::id!(export::rendered))
895 },
896 ),
897 label(move || match shown.get() {
898 Some(b) => {
899 let info = b.info();
900 format!(
901 "{}x{}@{}",
902 info.pixels.width, info.pixels.height, info.scale
903 )
904 }
905 None => "rendering".to_string(),
906 })
907 .id(day_core::id!(export::state)),
908 ))
909 .spacing(8.0)
910 })
911 .shot("default")
912 .drive(|d: Drive| async move {
913 // 120 × 80 points at 2× is 240 × 160 pixels that draw back at 120 × 80 points.
914 d.assert_text("export::state", "240x160@2").await?;
915 d.assert_size("export::rendered", 120.0, 80.0).await?;
916 for id in ["export::live", "export::rendered"] {
917 d.sample_pixel(id, 0.15, 0.3, "#ff0000").await?;
918 d.sample_pixel(id, 0.85, 0.3, "#0000ff").await?;
919 d.sample_pixel(id, 0.5, 0.5, "#ffffff").await?;
920 // The bar is at the bottom in both: a flipped export would put it on top.
921 d.sample_pixel(id, 0.5, 0.92, "#202020").await?;
922 d.sample_pixel(id, 0.15, 0.08, "#ff0000").await?;
923 }
924 Ok(())
925 })
926 }
927
928 /// Curved/path clips must retain their geometry and the transform at clipping time.
929 /// The PNG round trip must preserve transparent pixels outside that geometry too.
930 #[day_macros::test(day_core)]
931 fn canvas_clip_transform_png() -> Case {
932 fn swatch(d: &mut Draw, _: day_spec::Size) {
933 use day_spec::{Point, Rect};
934 // An empty data series must leave the transparent corners untouched.
935 d.stamp(
936 Shape::Rect(Rect::new(0.0, 0.0, 120.0, 100.0)),
937 vec![],
938 Color::BLACK,
939 );
940 d.transformed(day_geometry::Affine::translate(20.0, 10.0), |d| {
941 d.clipped(Shape::Ellipse(Rect::new(0.0, 0.0, 80.0, 80.0)), |d| {
942 d.fill(
943 Shape::Rect(Rect::new(-20.0, -10.0, 160.0, 120.0)),
944 Color::hex(0x00ff_0000),
945 );
946 let triangle = PathBuilder::new()
947 .move_to(Point::new(40.0, 0.0))
948 .line_to(Point::new(80.0, 80.0))
949 .line_to(Point::new(0.0, 80.0))
950 .close()
951 .build();
952 d.clipped(triangle, |d| {
953 d.transformed(day_geometry::Affine::translate(-20.0, -10.0), |d| {
954 d.fill(
955 Shape::Rect(Rect::new(0.0, 0.0, 120.0, 100.0)),
956 Color::hex(0x0000_00ff),
957 );
958 });
959 });
960 });
961 });
962 // Restoring must remove both clips and transforms.
963 d.fill(
964 Shape::Rect(day_spec::Rect::new(0.0, 90.0, 120.0, 10.0)),
965 Color::hex(0x0000_ff00),
966 );
967 }
968 Case::new()
969 .proves(kinds::CANVAS)
970 .proves_cap(Cap::ImageEncode)
971 .requires(Cap::CanvasBitmap)
972 .requires(Cap::ImageEncode)
973 .requires(Cap::Snapshot)
974 .page(|| {
975 let decoded = Signal::new(None::<day_core::Bitmap>);
976 let status = Signal::new("rendering".to_string());
977 day_core::task(async move {
978 let result = Drawing::record(day_spec::Size::new(120.0, 100.0), swatch)
979 .to_png(2.0)
980 .await;
981 match result {
982 Ok(bytes) => match day_core::decode_image(std::sync::Arc::new(bytes)).await
983 {
984 Ok(bitmap) => {
985 decoded.set(Some(bitmap));
986 status.set("ready".into());
987 }
988 Err(e) => status.set(format!("decode: {e}")),
989 },
990 Err(e) => status.set(format!("export: {e}")),
991 }
992 });
993 column((
994 canvas(swatch)
995 .frame(120.0, 100.0)
996 .id(day_core::id!(clip_png::live)),
997 keyed(
998 move || decoded.get(),
999 |bitmap| {
1000 image(bitmap)
1001 .stretch()
1002 .frame(120.0, 100.0)
1003 .id(day_core::id!(clip_png::decoded))
1004 },
1005 ),
1006 label(move || status.get()).id(day_core::id!(clip_png::state)),
1007 ))
1008 .background(Color::WHITE)
1009 })
1010 .drive(|d: Drive| async move {
1011 d.assert_text("clip_png::state", "ready").await?;
1012 for id in ["clip_png::live", "clip_png::decoded"] {
1013 d.sample_pixel(id, 0.2, 0.14, "#ffffff").await?;
1014 d.sample_pixel(id, 0.24, 0.5, "#ff0000").await?;
1015 d.sample_pixel(id, 0.5, 0.6, "#0000ff").await?;
1016 d.sample_pixel(id, 0.1, 0.95, "#00ff00").await?;
1017 }
1018 Ok(())
1019 })
1020 }
1021
1022 /// A PDF where the platform has a writer, and `Unsupported` where it has none: the bytes are
1023 /// a PDF file, and a toolkit without the cap never pretends otherwise.
1024 #[day_macros::test(day_core)]
1025 fn canvas_pdf_document() -> Case {
1026 Case::headless().run(|t: Drive| async move {
1027 let page = |w, h| Drawing::record(day_spec::Size::new(w, h), export_swatch);
1028 let result = PdfDocument::new()
1029 .title("Conformance")
1030 .author("Day")
1031 .page(page(612.0, 792.0))
1032 .page(page(300.0, 200.0))
1033 .render()
1034 .await;
1035 if !canvas_exports().pdf {
1036 return t.check_eq(result.err(), Some(day_spec::ExportError::Unsupported));
1037 }
1038 let pdf = match result {
1039 Ok(pdf) => pdf,
1040 Err(e) => return t.check(false, &format!("the PDF did not render: {e}")),
1041 };
1042 t.check(
1043 pdf.starts_with(b"%PDF-"),
1044 "the bytes do not start with %PDF-",
1045 )?;
1046 let tail = String::from_utf8_lossy(&pdf[pdf.len().saturating_sub(64)..]).to_string();
1047 t.check(tail.contains("%%EOF"), "the PDF has no %%EOF trailer")?;
1048 // An empty document is not a PDF of two pages: each page carries its own content.
1049 t.check(
1050 pdf.len() > 400,
1051 &format!("a {} byte PDF is too small", pdf.len()),
1052 )
1053 })
1054 }
1055
1056 /// A rendered bitmap is a `Bitmap` like any decode: it reports the export scale and the
1057 /// rounded-up pixel size, and encodes to PNG where the toolkit encodes PNG.
1058 #[day_macros::test(day_core)]
1059 fn canvas_export_scale_and_png() -> Case {
1060 Case::headless().run(|t: Drive| async move {
1061 let drawing = Drawing::record(day_spec::Size::new(50.5, 20.0), export_swatch);
1062 let result = drawing.to_bitmap(3.0).await;
1063 if !canvas_exports().bitmap {
1064 return t.check_eq(result.err(), Some(day_spec::ExportError::Unsupported));
1065 }
1066 let bitmap = match result {
1067 Ok(b) => b,
1068 Err(e) => return t.check(false, &format!("the bitmap did not render: {e}")),
1069 };
1070 let info = bitmap.info();
1071 t.check_eq(info.pixels, day_spec::Size::new(152.0, 60.0))?;
1072 t.check_eq(info.scale, 3.0)?;
1073 if !canvas_exports().png() {
1074 return Ok(());
1075 }
1076 match drawing.to_png(1.0).await {
1077 Ok(png) => t.check_eq(
1078 day_spec::ImageFormat::sniff(&png),
1079 Some(day_spec::ImageFormat::Png),
1080 ),
1081 Err(e) => t.check(false, &format!("the PNG did not encode: {e}")),
1082 }
1083 })
1084 }
1085}
1086
1087#[cfg(test)]
1088mod arc_tests {
1089 use super::PathBuilder;
1090 use day_spec::{PathSeg, Point};
1091
1092 /// Walk a built path, sampling every cubic densely, and hand back the points.
1093 fn sample(segs: &[PathSeg], per_seg: usize) -> Vec<Point> {
1094 let mut out = Vec::new();
1095 let mut cur = Point::ZERO;
1096 for seg in segs {
1097 match seg {
1098 PathSeg::Move(p) | PathSeg::Line(p) => {
1099 cur = *p;
1100 out.push(cur);
1101 }
1102 PathSeg::Cubic(c1, c2, p) => {
1103 for i in 1..=per_seg {
1104 let t = i as f64 / per_seg as f64;
1105 let u = 1.0 - t;
1106 // de Casteljau, written out: the cubic Bernstein basis.
1107 out.push(Point::new(
1108 u * u * u * cur.x
1109 + 3.0 * u * u * t * c1.x
1110 + 3.0 * u * t * t * c2.x
1111 + t * t * t * p.x,
1112 u * u * u * cur.y
1113 + 3.0 * u * u * t * c1.y
1114 + 3.0 * u * t * t * c2.y
1115 + t * t * t * p.y,
1116 ));
1117 }
1118 cur = *p;
1119 }
1120 PathSeg::Quad(..) | PathSeg::Close => {}
1121 }
1122 }
1123 out
1124 }
1125
1126 /// The property that matters: every point of the emitted curve is on the circle. Pinning the
1127 /// control points instead would pin the construction rather than the result, and it is the
1128 /// result a rasterizer draws.
1129 #[test]
1130 fn an_arc_stays_on_its_circle() {
1131 let c = Point::new(100.0, 50.0);
1132 let r = 40.0;
1133 for sweep in [15.0, 90.0, 180.0, 359.0, -90.0, -270.0] {
1134 let path = PathBuilder::new().arc_to(c, r, 30.0, sweep).build();
1135 let day_spec::Shape::Path(p) = path else {
1136 panic!("arc_to builds a path")
1137 };
1138 let worst = sample(&p.segs, 24)
1139 .iter()
1140 .map(|q| ((q.x - c.x).powi(2) + (q.y - c.y).powi(2)).sqrt() - r)
1141 .fold(0.0f64, |m, e| m.max(e.abs()));
1142 // The known peak for a cubic quarter-circle, with a little headroom. The assertion
1143 // uses the real figure rather than a loose one so that a future change that split the
1144 // sweep differently or got a handle length wrong is noticed here.
1145 assert!(worst < r * 2.8e-4, "sweep {sweep}: off by {worst}");
1146 // ...and it is that good rather than accidentally better: a construction that
1147 // silently started flattening to line segments would pass a one-sided bound.
1148 if sweep.abs() >= 90.0 {
1149 assert!(
1150 worst > r * 1e-6,
1151 "sweep {sweep}: suspiciously exact ({worst})"
1152 );
1153 }
1154 }
1155 }
1156
1157 /// Degrees, 0 = +x, positive clockwise, the same convention `Shape::Arc` and `circle` use.
1158 /// A wrong sign here is the kind of thing that only shows up as a donut drawn inside out.
1159 #[test]
1160 fn arc_endpoints_follow_the_clockwise_degree_convention() {
1161 let c = Point::new(0.0, 0.0);
1162 let near = |a: Point, b: Point| (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() < 1e-9;
1163 let ends = |start: f64, sweep: f64| {
1164 let day_spec::Shape::Path(p) = PathBuilder::new().arc_to(c, 10.0, start, sweep).build()
1165 else {
1166 panic!()
1167 };
1168 let pts = sample(&p.segs, 1);
1169 (*pts.first().unwrap(), *pts.last().unwrap())
1170 };
1171 // 0° is +x; a quarter turn clockwise lands on +y, which is down in canvas space.
1172 let (a, b) = ends(0.0, 90.0);
1173 assert!(near(a, Point::new(10.0, 0.0)), "{a:?}");
1174 assert!(near(b, Point::new(0.0, 10.0)), "{b:?}");
1175 // …and the same quarter counter-clockwise lands on -y.
1176 let (_, b) = ends(0.0, -90.0);
1177 assert!(near(b, Point::new(0.0, -10.0)), "{b:?}");
1178 }
1179
1180 /// A rounded rectangle is a contour of its own: a frame with a rounded hole is two of them,
1181 /// the inner one cut out by the even-odd rule.
1182 #[test]
1183 fn a_rounded_rect_contour_opens_and_closes_its_own_subpath() {
1184 use day_spec::{CornerRadii, FillRule, Rect};
1185 let day_spec::Shape::Path(p) = PathBuilder::new()
1186 .rule(FillRule::EvenOdd)
1187 .rounded_rect(Rect::new(0.0, 0.0, 40.0, 40.0), CornerRadii::uniform(8.0))
1188 .rounded_rect(Rect::new(10.0, 10.0, 20.0, 20.0), CornerRadii::top(4.0))
1189 .build()
1190 else {
1191 panic!("a path")
1192 };
1193 let moves = p
1194 .segs
1195 .iter()
1196 .filter(|s| matches!(s, PathSeg::Move(_)))
1197 .count();
1198 let closes = p
1199 .segs
1200 .iter()
1201 .filter(|s| matches!(s, PathSeg::Close))
1202 .count();
1203 assert_eq!((moves, closes), (2, 2));
1204 assert_eq!(p.rule, FillRule::EvenOdd);
1205 }
1206
1207 /// An arc joins what came before, which is why it is a segment and not a shape.
1208 #[test]
1209 fn an_arc_joins_the_current_subpath_but_starts_a_fresh_one_after_close() {
1210 let c = Point::new(0.0, 0.0);
1211 let segs = |b: PathBuilder| {
1212 let day_spec::Shape::Path(p) = b.build() else {
1213 panic!()
1214 };
1215 p.segs
1216 };
1217 // Nothing before it: the arc opens the subpath.
1218 let s = segs(PathBuilder::new().arc_to(c, 5.0, 0.0, 90.0));
1219 std::assert_matches!(s[0], PathSeg::Move(_), "{:?}", s[0]);
1220 // Something before it: the arc is reached by a line, so the figure is one contour.
1221 let s = segs(
1222 PathBuilder::new()
1223 .move_to(Point::new(9.0, 9.0))
1224 .arc_to(c, 5.0, 0.0, 90.0),
1225 );
1226 std::assert_matches!(s[1], PathSeg::Line(_), "{:?}", s[1]);
1227 // After a close there is no current point, so it opens a new subpath rather than drawing
1228 // a stray line back from wherever the last contour ended.
1229 let s = segs(
1230 PathBuilder::new()
1231 .move_to(Point::new(9.0, 9.0))
1232 .line_to(Point::new(1.0, 1.0))
1233 .close()
1234 .arc_to(c, 5.0, 0.0, 90.0),
1235 );
1236 std::assert_matches!(s[3], PathSeg::Move(_), "{:?}", s[3]);
1237 // A degenerate arc still reaches its start point and emits no curve.
1238 let s = segs(PathBuilder::new().arc_to(c, 5.0, 0.0, 0.0));
1239 assert_eq!(s.len(), 1);
1240 let s = segs(PathBuilder::new().arc_to(c, 0.0, 0.0, 90.0));
1241 assert_eq!(s.len(), 1);
1242 }
1243}