1use std::rc::Rc;
9
10use day_core::*;
11use day_spec::{Angle, Event, Ink, Paint, Point, Rect, Shape, Size, UnitPoint};
12
13use crate::*;
14
15use day_geometry::Affine;
21pub use day_spec::{DragPhase, GestureKind};
22
23#[derive(Clone, Debug, PartialEq)]
25pub enum ShapeKind {
26 Rectangle,
27 RoundedRectangle {
28 corner: Corner,
29 },
30 Circle,
31 Ellipse,
32 Capsule,
33 Arc {
35 start: Angle,
36 sweep: Angle,
37 },
38 Line {
41 from: UnitPoint,
42 to: UnitPoint,
43 },
44 Polygon {
47 points: Rc<[UnitPoint]>,
48 },
49}
50
51#[derive(Clone, Copy, Debug, PartialEq)]
55pub enum Corner {
56 Fixed(f64),
57 Fraction(f64),
58}
59impl From<f64> for Corner {
60 fn from(v: f64) -> Self {
61 Corner::Fixed(v)
62 }
63}
64impl From<Radius> for Corner {
65 fn from(r: Radius) -> Self {
66 Corner::Fixed(r.points())
67 }
68}
69impl Default for Corner {
70 fn default() -> Self {
72 Corner::Fixed(0.0)
73 }
74}
75impl Corner {
76 pub const CAPSULE: Corner = Corner::Fraction(1.0);
78
79 #[must_use]
81 pub fn points(self, size: Size) -> f64 {
82 let cap = (size.width.min(size.height) / 2.0).max(0.0);
83 match self {
84 Corner::Fixed(v) => v.clamp(0.0, cap),
85 Corner::Fraction(f) => f.clamp(0.0, 1.0) * cap,
86 }
87 }
88 #[must_use]
90 pub fn is_relative(self) -> bool {
91 matches!(self, Corner::Fraction(_))
92 }
93 fn resolve(self, rect: Rect) -> f64 {
94 self.points(rect.size)
95 }
96}
97impl ShapeKind {
98 fn geometry(self, rect: Rect) -> Shape {
100 match self {
101 ShapeKind::Rectangle => Shape::Rect(rect),
102 ShapeKind::RoundedRectangle { corner } => {
103 Shape::RoundedRect(rect, corner.resolve(rect))
104 }
105 ShapeKind::Ellipse => Shape::Ellipse(rect),
106 ShapeKind::Capsule => {
107 Shape::RoundedRect(rect, rect.size.width.min(rect.size.height) / 2.0)
108 }
109 ShapeKind::Circle => {
110 let d = rect.size.width.min(rect.size.height);
111 let c = rect.center();
112 Shape::Ellipse(Rect::new(c.x - d / 2.0, c.y - d / 2.0, d, d))
113 }
114 ShapeKind::Arc { start, sweep } => Shape::Arc { rect, start, sweep },
115 ShapeKind::Line { from, to } => Shape::Line(from.resolve(rect), to.resolve(rect)),
116 ShapeKind::Polygon { points } => {
117 Shape::Polygon(points.iter().map(|p| p.resolve(rect)).collect())
118 }
119 }
120 }
121 fn contains(self, rect: Rect, p: Point) -> bool {
123 fn in_rect(r: Rect, p: Point) -> bool {
124 p.x >= r.min_x() && p.x <= r.max_x() && p.y >= r.min_y() && p.y <= r.max_y()
125 }
126 fn in_ellipse(r: Rect, p: Point) -> bool {
127 if r.size.width <= 0.0 || r.size.height <= 0.0 {
128 return false;
129 }
130 let c = r.center();
131 let dx = (p.x - c.x) / (r.size.width / 2.0);
132 let dy = (p.y - c.y) / (r.size.height / 2.0);
133 dx * dx + dy * dy <= 1.0
134 }
135 fn in_polygon(pts: &[Point], p: Point) -> bool {
137 if pts.len() < 3 {
138 return false;
139 }
140 let mut inside = false;
141 let mut j = pts.len() - 1;
142 for i in 0..pts.len() {
143 let (a, b) = (pts[i], pts[j]);
144 if (a.y > p.y) != (b.y > p.y) {
145 let x = a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x);
146 if p.x < x {
147 inside = !inside;
148 }
149 }
150 j = i;
151 }
152 inside
153 }
154 match self.geometry(rect) {
155 Shape::Ellipse(r) => in_ellipse(r, p),
156 Shape::Rect(r) | Shape::RoundedRect(r, _) => in_rect(r, p),
157 Shape::Polygon(pts) => in_polygon(&pts, p),
158 _ => in_rect(rect, p), }
160 }
161}
162
163#[derive(Clone, Copy, Debug, PartialEq)]
177#[non_exhaustive]
178pub struct Drag {
179 pub phase: DragPhase,
180 pub location: Point,
181 pub translation: Point,
182 pub velocity: Point,
186}
187
188impl Drag {
189 #[must_use]
191 pub fn new(phase: DragPhase, location: Point, translation: Point) -> Drag {
192 Drag {
193 phase,
194 location,
195 translation,
196 velocity: Point::ZERO,
197 }
198 }
199
200 #[must_use]
202 pub fn with_velocity(mut self, velocity: Point) -> Drag {
203 self.velocity = velocity;
204 self
205 }
206
207 #[must_use]
209 pub fn start(&self) -> Point {
210 Point::new(
211 self.location.x - self.translation.x,
212 self.location.y - self.translation.y,
213 )
214 }
215
216 #[must_use]
218 pub fn speed(&self) -> f64 {
219 self.velocity.x.hypot(self.velocity.y)
220 }
221}
222
223#[derive(Clone, Copy, Debug, PartialEq)]
227#[non_exhaustive]
228pub struct Pinch {
229 pub phase: DragPhase,
230 pub scale: f64,
231 pub location: Point,
232}
233
234impl Pinch {
235 #[must_use]
237 pub fn new(phase: DragPhase, scale: f64, location: Point) -> Pinch {
238 Pinch {
239 phase,
240 scale,
241 location,
242 }
243 }
244}
245
246#[derive(Clone, Copy, Debug, PartialEq)]
249#[non_exhaustive]
250pub struct Rotate {
251 pub phase: DragPhase,
252 pub rotation: Angle,
255 pub location: Point,
257}
258
259impl Rotate {
260 #[must_use]
262 pub fn new(phase: DragPhase, rotation: Angle, location: Point) -> Rotate {
263 Rotate {
264 phase,
265 rotation,
266 location,
267 }
268 }
269}
270
271#[derive(Clone, Copy, Debug, PartialEq)]
276#[non_exhaustive]
277pub struct Pan {
278 pub phase: DragPhase,
279 pub delta: Point,
280 pub location: Point,
281 pub velocity: Point,
283}
284
285impl Pan {
286 #[must_use]
288 pub fn new(phase: DragPhase, delta: Point, location: Point) -> Pan {
289 Pan {
290 phase,
291 delta,
292 location,
293 velocity: Point::ZERO,
294 }
295 }
296
297 #[must_use]
299 pub fn with_velocity(mut self, velocity: Point) -> Pan {
300 self.velocity = velocity;
301 self
302 }
303}
304
305#[derive(Clone)]
308struct ShapeSpec {
309 kind: Reactive<ShapeKind>,
310 fill: Option<Reactive<Paint>>,
311 stroke: Option<(Reactive<Ink>, Reactive<f64>)>,
312 inset: Reactive<f64>,
313 rotation: Reactive<Angle>,
314 scale: Reactive<f64>,
315 translation: (Reactive<f64>, Reactive<f64>),
316 at: Option<Rect>,
318}
319
320#[must_use]
322pub struct ShapePiece {
323 spec: ShapeSpec,
324 on_tap: Option<Rc<dyn Fn()>>,
325 on_drag: Option<Rc<dyn Fn(Drag)>>,
326}
327
328pub fn shape<M>(kind: impl IntoReactive<ShapeKind, M>) -> ShapePiece {
330 ShapePiece {
331 spec: ShapeSpec {
332 kind: kind.into_reactive(),
333 fill: None,
334 stroke: None,
335 inset: Reactive::Const(0.0),
336 rotation: Reactive::Const(Angle::ZERO),
337 scale: Reactive::Const(1.0),
338 translation: (Reactive::Const(0.0), Reactive::Const(0.0)),
339 at: None,
340 },
341 on_tap: None,
342 on_drag: None,
343 }
344}
345pub fn rectangle() -> ShapePiece {
347 shape(ShapeKind::Rectangle)
348}
349pub fn circle() -> ShapePiece {
350 shape(ShapeKind::Circle)
351}
352pub fn ellipse() -> ShapePiece {
353 shape(ShapeKind::Ellipse)
354}
355pub fn capsule() -> ShapePiece {
356 shape(ShapeKind::Capsule)
357}
358pub fn rounded_rectangle(corner: impl Into<Corner>) -> ShapePiece {
359 shape(ShapeKind::RoundedRectangle {
360 corner: corner.into(),
361 })
362}
363pub fn arc(start: Angle, sweep: Angle) -> ShapePiece {
365 shape(ShapeKind::Arc { start, sweep })
366}
367pub fn line(from: (f64, f64), to: (f64, f64)) -> ShapePiece {
369 shape(ShapeKind::Line {
370 from: UnitPoint::new(from.0, from.1),
371 to: UnitPoint::new(to.0, to.1),
372 })
373}
374pub fn polygon(points: impl IntoIterator<Item = (f64, f64)>) -> ShapePiece {
376 shape(ShapeKind::Polygon {
377 points: points
378 .into_iter()
379 .map(|(x, y)| UnitPoint::new(x, y))
380 .collect(),
381 })
382}
383
384#[day_macros::builder(ShapePieceBuilder)]
385impl ShapePiece {
386 pub fn fill<M>(mut self, paint: impl IntoReactive<Paint, M>) -> Self {
391 self.spec.fill = Some(paint.into_reactive());
392 self
393 }
394 pub fn stroke<M1, M2>(
395 mut self,
396 color: impl IntoReactive<Ink, M1>,
397 width: impl IntoReactive<f64, M2>,
398 ) -> Self {
399 self.spec.stroke = Some((color.into_reactive(), width.into_reactive()));
400 self
401 }
402 pub fn inset<M>(mut self, v: impl IntoReactive<f64, M>) -> Self {
404 self.spec.inset = v.into_reactive();
405 self
406 }
407 pub fn rotation<M>(mut self, angle: impl IntoReactive<Angle, M>) -> Self {
410 self.spec.rotation = angle.into_reactive();
411 self
412 }
413 pub fn scale<M>(mut self, s: impl IntoReactive<f64, M>) -> Self {
415 self.spec.scale = s.into_reactive();
416 self
417 }
418 pub fn translation<M1, M2>(
421 mut self,
422 x: impl IntoReactive<f64, M1>,
423 y: impl IntoReactive<f64, M2>,
424 ) -> Self {
425 self.spec.translation = (x.into_reactive(), y.into_reactive());
426 self
427 }
428 pub fn at(mut self, fx: f64, fy: f64, fw: f64, fh: f64) -> Self {
432 self.spec.at = Some(Rect::new(fx, fy, fw, fh));
433 self
434 }
435 pub fn on_tap(mut self, f: impl Fn() + 'static) -> Self {
437 self.on_tap = Some(Rc::new(f));
438 self
439 }
440 pub fn on_drag(mut self, f: impl Fn(Drag) + 'static) -> Self {
442 self.on_drag = Some(Rc::new(f));
443 self
444 }
445}
446
447fn shape_transform(rect: Rect, rotation: Angle, scale: f64, ox: f64, oy: f64) -> Affine {
449 let c = rect.center();
450 Affine::translate(-c.x, -c.y)
451 .then(Affine::scale(scale, scale))
452 .then(Affine::rotate(rotation))
453 .then(Affine::translate(c.x, c.y))
454 .then(Affine::translate(ox, oy))
455}
456
457fn resolve_at(at: Option<Rect>, bounds: Rect) -> Rect {
459 match at {
460 Some(u) => Rect::new(
461 bounds.origin.x + u.origin.x * bounds.size.width,
462 bounds.origin.y + u.origin.y * bounds.size.height,
463 u.size.width * bounds.size.width,
464 u.size.height * bounds.size.height,
465 ),
466 None => bounds,
467 }
468}
469
470fn record_shape(spec: &ShapeSpec, d: &mut Draw, bounds: Rect) {
473 let bounds = resolve_at(spec.at, bounds);
474 let kind = spec.kind.get();
475 let open = matches!(kind, ShapeKind::Line { .. } | ShapeKind::Polygon { .. });
482 let stroke_half = if open {
483 0.0
484 } else {
485 spec.stroke.as_ref().map_or(0.0, |(_, w)| w.get() / 2.0)
486 };
487 let rect = bounds.inset(spec.inset.get() + stroke_half);
488 if !open && (rect.size.width <= 0.0 || rect.size.height <= 0.0) {
489 return;
490 }
491 let geom = kind.geometry(rect);
492 let m = shape_transform(
493 rect,
494 spec.rotation.get(),
495 spec.scale.get(),
496 spec.translation.0.get(),
497 spec.translation.1.get(),
498 );
499 let transformed = !m.is_identity();
500 if transformed {
501 d.save();
502 d.concat(m);
503 }
504 if !matches!(geom, Shape::Line(..))
505 && let Some(fill) = &spec.fill
506 {
507 d.fill(geom.clone(), fill.get());
508 }
509 if let Some((c, w)) = &spec.stroke {
510 d.stroke(geom, c.get(), w.get());
511 }
512 if transformed {
513 d.restore();
514 }
515}
516
517fn shape_flex() -> Flex {
519 Flex {
520 grow_w: true,
521 grow_h: true,
522 ..Default::default()
523 }
524}
525
526pub fn shape_group(shapes: impl IntoIterator<Item = ShapePiece>) -> impl Piece {
530 let specs: Vec<ShapeSpec> = shapes.into_iter().map(|s| s.spec).collect();
531 piece_fn(move |cx| {
532 canvas_leaf(cx, shape_flex(), move |d, size| {
533 let bounds = Rect::from_size(size);
534 for spec in &specs {
535 record_shape(spec, d, bounds);
536 }
537 })
538 })
539}
540
541pub fn shape_group_fn(shapes: impl Fn(Size) -> Vec<ShapePiece> + 'static) -> impl Piece {
545 piece_fn(move |cx| {
546 canvas_leaf(cx, shape_flex(), move |d, size| {
547 let bounds = Rect::from_size(size);
548 for piece in shapes(size) {
549 record_shape(&piece.spec, d, bounds);
550 }
551 })
552 })
553}
554
555impl Piece for ShapePiece {
556 fn build(self, cx: &mut BuildCx) -> RNode {
557 let ShapePiece {
558 spec,
559 on_tap,
560 on_drag,
561 } = self;
562
563 let draw_spec = spec.clone();
564 let node = canvas_leaf(cx, shape_flex(), move |d, size| {
565 record_shape(&draw_spec, d, Rect::from_size(size));
566 });
567
568 if let Some(on_tap) = on_tap {
571 with_tree(|t| t.enable_gesture(node, GestureKind::Tap));
572 cx.on(node, move |ev| {
573 if let Event::Tap(p) = ev
574 && let Some(f) = with_tree(|t| t.node_frame(node))
575 {
576 let bounds = resolve_at(spec.at, Rect::from_size(f.size));
577 let rect = bounds.inset(spec.inset.get_untracked());
578 let m = shape_transform(
579 rect,
580 spec.rotation.get_untracked(),
581 spec.scale.get_untracked(),
582 spec.translation.0.get_untracked(),
583 spec.translation.1.get_untracked(),
584 );
585 let local = m.invert_apply(*p).unwrap_or(*p);
586 if spec.kind.get_untracked().contains(rect, local) {
587 on_tap();
588 }
589 }
590 });
591 }
592 if let Some(on_drag) = on_drag {
593 with_tree(|t| t.enable_gesture(node, GestureKind::Drag));
594 cx.on(node, move |ev| {
595 if let Event::Drag {
596 phase,
597 location,
598 translation,
599 } = ev
600 {
601 let velocity =
602 day_core::gesture::velocity(day_core::rnode_to_id(node), GestureKind::Drag);
603 on_drag(Drag::new(*phase, *location, *translation).with_velocity(velocity));
604 }
605 });
606 }
607 node
608 }
609}
610
611#[cfg(feature = "conformance")]
619pub(crate) mod conformance {
620 use day_core::Piece;
621 use day_core::conformance::{Case, Drive};
622 use day_spec::{Cap, Color};
623
624 use crate::*;
625
626 fn on_white(s: ShapePiece) -> impl Piece {
628 zstack((rectangle().fill(Color::WHITE), s))
629 .id(day_core::id!(ground))
630 .frame(80.0, 80.0)
631 }
632
633 #[day_macros::test(day_core)]
635 fn shape_fill() -> Case {
636 Case::new()
637 .proves_duty("snapshot_window")
638 .proves_duty("prepare_snapshot")
639 .proves_cap(Cap::Snapshot)
640 .requires(Cap::Snapshot)
641 .page(|| on_white(rectangle().fill(Color::rgb(1.0, 0.0, 0.0))))
642 .drive(|d: Drive| async move {
643 d.sample_pixel("ground", 0.5, 0.5, "#ff0000").await?;
644 d.sample_pixel("ground", 0.05, 0.05, "#ff0000").await
645 })
646 }
647
648 #[day_macros::test(day_core)]
650 fn shape_circle() -> Case {
651 Case::new()
652 .requires(Cap::Snapshot)
653 .page(|| on_white(circle().fill(Color::rgb(0.0, 0.0, 1.0))))
654 .shot("default")
655 .drive(|d: Drive| async move {
656 d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
657 d.sample_pixel("ground", 0.04, 0.04, "#ffffff").await
658 })
659 }
660
661 #[day_macros::test(day_core)]
663 fn shape_rounded() -> Case {
664 Case::new()
665 .requires(Cap::Snapshot)
666 .page(|| on_white(rounded_rectangle(30.0).fill(Color::rgb(0.0, 0.0, 1.0))))
667 .drive(|d: Drive| async move {
668 d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
669 d.sample_pixel("ground", 0.03, 0.03, "#ffffff").await?;
670 d.sample_pixel("ground", 0.5, 0.03, "#0000ff").await
671 })
672 }
673
674 #[day_macros::test(day_core)]
676 fn shape_group_places() -> Case {
677 Case::new()
678 .requires(Cap::Snapshot)
679 .page(|| {
680 shape_group([
681 rectangle()
682 .fill(Color::rgb(1.0, 0.0, 0.0))
683 .at(0.0, 0.0, 0.5, 1.0),
684 rectangle()
685 .fill(Color::rgb(0.0, 0.0, 1.0))
686 .at(0.5, 0.0, 0.5, 1.0),
687 ])
688 .id(day_core::id!(group))
689 .frame(80.0, 40.0)
690 })
691 .drive(|d: Drive| async move {
692 d.sample_pixel("group", 0.25, 0.5, "#ff0000").await?;
693 d.sample_pixel("group", 0.75, 0.5, "#0000ff").await
694 })
695 }
696}