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