1use std::rc::Rc;
6
7use crate::geometry::{Point, Rect, Size};
8use crate::style::{Color, Gradient, Style};
9use crate::tree::{Change, NodeId, NodeKind, Tree, borrow};
10use crate::widgets::{Common, Element, ElementKind, Widget, visibility_methods};
11
12const MOST_COMMANDS: usize = 16_384;
16
17const MOST_COORDINATE: f32 = 1.0e6;
21
22const MOST_DASHES: f32 = 100_000.0;
26
27#[derive(Clone, Copy, Debug, PartialEq)]
30pub enum Paint {
31 Color(Color),
33 Gradient(Gradient),
35}
36
37impl From<Color> for Paint {
38 fn from(color: Color) -> Paint {
39 Paint::Color(color)
40 }
41}
42
43impl From<Gradient> for Paint {
44 fn from(gradient: Gradient) -> Paint {
45 Paint::Gradient(gradient)
46 }
47}
48
49#[derive(Clone, Copy, Debug, PartialEq)]
51pub enum PathCommand {
52 MoveTo(Point),
54 LineTo(Point),
56 QuadTo {
58 control: Point,
60 to: Point,
62 },
63 CubicTo {
66 first: Point,
68 second: Point,
70 to: Point,
72 },
73 Arc {
77 center: Point,
79 radius: f32,
81 start: f32,
83 sweep: f32,
86 },
87 Close,
89}
90
91#[derive(Clone, Debug, Default, PartialEq)]
107#[must_use]
108pub struct Path {
109 commands: Vec<PathCommand>,
110}
111
112impl Path {
113 pub fn new() -> Path {
115 Path::default()
116 }
117
118 pub fn move_to(self, to: Point) -> Path {
120 self.with(PathCommand::MoveTo(to))
121 }
122
123 pub fn line_to(self, to: Point) -> Path {
125 self.with(PathCommand::LineTo(to))
126 }
127
128 pub fn quad_to(self, control: Point, to: Point) -> Path {
130 self.with(PathCommand::QuadTo { control, to })
131 }
132
133 pub fn cubic_to(self, first: Point, second: Point, to: Point) -> Path {
136 self.with(PathCommand::CubicTo { first, second, to })
137 }
138
139 pub fn arc(self, center: Point, radius: f32, start: f32, sweep: f32) -> Path {
145 self.with(PathCommand::Arc {
146 center,
147 radius,
148 start,
149 sweep,
150 })
151 }
152
153 pub fn close(self) -> Path {
155 self.with(PathCommand::Close)
156 }
157
158 pub fn rect(rect: Rect) -> Path {
160 Path::new()
161 .move_to(Point::new(rect.x, rect.y))
162 .line_to(Point::new(rect.right(), rect.y))
163 .line_to(Point::new(rect.right(), rect.bottom()))
164 .line_to(Point::new(rect.x, rect.bottom()))
165 .close()
166 }
167
168 pub fn rounded_rect(rect: Rect, radius: f32) -> Path {
171 let r = radius.min(rect.width.min(rect.height) / 2.0);
172 if r.is_nan() || r <= 0.0 {
173 return Path::rect(rect);
174 }
175 let (left, top, right, bottom) = (rect.x, rect.y, rect.right(), rect.bottom());
176 Path::new()
177 .move_to(Point::new(left + r, top))
178 .arc(Point::new(right - r, top + r), r, -90.0, 90.0)
179 .arc(Point::new(right - r, bottom - r), r, 0.0, 90.0)
180 .arc(Point::new(left + r, bottom - r), r, 90.0, 90.0)
181 .arc(Point::new(left + r, top + r), r, 180.0, 90.0)
182 .close()
183 }
184
185 pub fn circle(center: Point, radius: f32) -> Path {
187 Path::new()
188 .move_to(Point::new(center.x + radius, center.y))
189 .arc(center, radius, 0.0, 360.0)
190 .close()
191 }
192
193 pub fn ellipse(center: Point, radius_x: f32, radius_y: f32) -> Path {
196 const KAPPA: f32 = 0.552_284_8;
199 let (x, y) = (center.x, center.y);
200 let (kx, ky) = (radius_x * KAPPA, radius_y * KAPPA);
201 let point = Point::new;
202 Path::new()
203 .move_to(point(x + radius_x, y))
204 .cubic_to(
205 point(x + radius_x, y + ky),
206 point(x + kx, y + radius_y),
207 point(x, y + radius_y),
208 )
209 .cubic_to(
210 point(x - kx, y + radius_y),
211 point(x - radius_x, y + ky),
212 point(x - radius_x, y),
213 )
214 .cubic_to(
215 point(x - radius_x, y - ky),
216 point(x - kx, y - radius_y),
217 point(x, y - radius_y),
218 )
219 .cubic_to(
220 point(x + kx, y - radius_y),
221 point(x + radius_x, y - ky),
222 point(x + radius_x, y),
223 )
224 .close()
225 }
226
227 pub fn commands(&self) -> &[PathCommand] {
229 &self.commands
230 }
231
232 fn with(mut self, command: PathCommand) -> Path {
233 self.commands.push(command);
234 self
235 }
236}
237
238#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
240pub enum Cap {
241 #[default]
243 Butt,
244 Round,
246 Square,
248}
249
250#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
252pub enum Join {
253 #[default]
256 Miter,
257 Round,
259 Bevel,
261}
262
263#[derive(Clone, Debug, PartialEq)]
274#[must_use]
275pub struct Stroke {
276 pub width: f32,
278 pub paint: Paint,
280 pub cap: Cap,
282 pub join: Join,
284 pub dash: Vec<f32>,
288 pub dash_offset: f32,
290}
291
292impl Stroke {
293 pub fn new(width: f32, paint: impl Into<Paint>) -> Stroke {
295 Stroke {
296 width,
297 paint: paint.into(),
298 cap: Cap::default(),
299 join: Join::default(),
300 dash: Vec::new(),
301 dash_offset: 0.0,
302 }
303 }
304
305 pub fn cap(mut self, cap: Cap) -> Stroke {
307 self.cap = cap;
308 self
309 }
310
311 pub fn join(mut self, join: Join) -> Stroke {
313 self.join = join;
314 self
315 }
316
317 pub fn dash(mut self, pattern: &[f32], offset: f32) -> Stroke {
321 self.dash = pattern.to_vec();
322 self.dash_offset = offset;
323 self
324 }
325}
326
327#[derive(Clone, Debug, PartialEq)]
329pub enum CanvasOp {
330 Fill(Path, Paint),
332 Stroke(Path, Stroke),
334}
335
336pub struct Pen {
339 size: Size,
340 ops: Vec<CanvasOp>,
341 commands: usize,
342 dashes: f32,
344 skipped: Option<String>,
346}
347
348impl Pen {
349 fn new(size: Size) -> Pen {
350 Pen {
351 size,
352 ops: Vec::new(),
353 commands: 0,
354 dashes: 0.0,
355 skipped: None,
356 }
357 }
358
359 pub fn size(&self) -> Size {
361 self.size
362 }
363
364 pub fn fill(&mut self, path: &Path, paint: impl Into<Paint>) {
367 let commands = path.commands.len();
368 match check_path(path) {
369 Ok(()) => self.record(CanvasOp::Fill(path.clone(), paint.into()), commands, 0.0),
370 Err(reason) => self.skip(reason),
371 }
372 }
373
374 pub fn stroke(&mut self, path: &Path, stroke: &Stroke) {
376 if stroke.width == 0.0 {
377 return;
378 }
379 let checked = check_path(path).and_then(|()| check_stroke(path, stroke));
380 match checked {
381 Ok((dash, dashes)) => {
382 let commands = path.commands.len() + dash.len();
383 let stroke = Stroke {
384 dash,
385 ..stroke.clone()
386 };
387 self.record(CanvasOp::Stroke(path.clone(), stroke), commands, dashes);
388 }
389 Err(reason) => self.skip(reason),
390 }
391 }
392
393 fn record(&mut self, op: CanvasOp, commands: usize, dashes: f32) {
394 if self.commands + commands > MOST_COMMANDS {
395 self.skip(format!(
396 "more than {MOST_COMMANDS} path commands and dash lengths in one run"
397 ));
398 return;
399 }
400 if self.dashes + dashes > MOST_DASHES {
401 self.skip(format!("more than {MOST_DASHES} dashes in one run"));
402 return;
403 }
404 self.commands += commands;
405 self.dashes += dashes;
406 self.ops.push(op);
407 }
408
409 fn skip(&mut self, reason: String) {
410 self.skipped.get_or_insert(reason);
411 }
412}
413
414fn usable(n: f32) -> bool {
416 n.is_finite() && n.abs() <= MOST_COORDINATE
417}
418
419fn check_path(path: &Path) -> Result<(), String> {
422 for command in &path.commands {
423 let (points, numbers): (&[Point], &[f32]) = match command {
424 PathCommand::MoveTo(point) | PathCommand::LineTo(point) => (std::slice::from_ref(point), &[]),
425 PathCommand::QuadTo { control, to } => (&[*control, *to], &[]),
426 PathCommand::CubicTo { first, second, to } => (&[*first, *second, *to], &[]),
427 PathCommand::Arc {
428 center,
429 radius,
430 start,
431 sweep,
432 } => {
433 if *radius < 0.0 {
434 return Err(format!("an arc with a negative radius, {radius}"));
435 }
436 (std::slice::from_ref(center), &[*radius, *start, *sweep])
437 }
438 PathCommand::Close => (&[], &[]),
439 };
440 let all = points
441 .iter()
442 .flat_map(|p| [p.x, p.y])
443 .chain(numbers.iter().copied());
444 if let Some(bad) = all.into_iter().find(|&n| !usable(n)) {
445 return Err(format!(
446 "a path holding {bad}, which isn't a finite number within {MOST_COORDINATE}"
447 ));
448 }
449 }
450 Ok(())
451}
452
453fn check_stroke(path: &Path, stroke: &Stroke) -> Result<(Vec<f32>, f32), String> {
457 if !(usable(stroke.width) && stroke.width > 0.0) {
458 return Err(format!("a stroke {} wide", stroke.width));
459 }
460 if stroke.dash.is_empty() {
461 return Ok((Vec::new(), 0.0));
462 }
463 if !usable(stroke.dash_offset) || stroke.dash.iter().any(|&n| !(usable(n) && n >= 0.0)) {
464 return Err(format!(
465 "a dash pattern {:?} at offset {}",
466 stroke.dash, stroke.dash_offset
467 ));
468 }
469 let mut dash = stroke.dash.clone();
470 if dash.len() % 2 == 1 {
471 dash.extend_from_within(..);
472 }
473 let interval: f32 = dash.iter().sum();
474 let dashes = path_length(path) / interval * (dash.len() / 2) as f32;
475 if !(interval > 0.0 && dashes.is_finite()) {
476 return Err(format!("a dash pattern {:?}", stroke.dash));
477 }
478 Ok((dash, dashes))
479}
480
481fn path_length(path: &Path) -> f32 {
484 fn step(at: &mut Option<Point>, to: Point) -> f32 {
486 let from = at.replace(to).unwrap_or(to);
487 (to.x - from.x).hypot(to.y - from.y)
488 }
489 let (mut length, mut at, mut start) = (0.0, None, Point::default());
490 for command in &path.commands {
491 if at.is_none() {
494 let first = match *command {
495 PathCommand::MoveTo(point) | PathCommand::LineTo(point) => Some(point),
496 PathCommand::QuadTo { control, .. } => Some(control),
497 PathCommand::CubicTo { first, .. } => Some(first),
498 PathCommand::Arc {
499 center,
500 radius,
501 start,
502 ..
503 } => {
504 let (sin, cos) = start.to_radians().sin_cos();
505 Some(Point::new(center.x + radius * cos, center.y + radius * sin))
506 }
507 PathCommand::Close => None,
508 };
509 if let Some(first) = first {
510 (at, start) = (Some(first), first);
511 }
512 }
513 length += match *command {
514 PathCommand::MoveTo(to) => {
515 (at, start) = (Some(to), to);
516 0.0
517 }
518 PathCommand::LineTo(to) => step(&mut at, to),
519 PathCommand::QuadTo { control, to } => step(&mut at, control) + step(&mut at, to),
520 PathCommand::CubicTo { first, second, to } => {
521 step(&mut at, first) + step(&mut at, second) + step(&mut at, to)
522 }
523 PathCommand::Arc {
524 center,
525 radius,
526 start: from,
527 sweep,
528 } => {
529 let point = |degrees: f32| {
530 let (sin, cos) = degrees.to_radians().sin_cos();
531 Point::new(center.x + radius * cos, center.y + radius * sin)
532 };
533 let sweep = sweep.clamp(-360.0, 360.0);
534 let line = step(&mut at, point(from));
535 at = Some(point(from + sweep));
536 line + radius * sweep.abs().to_radians()
537 }
538 PathCommand::Close => step(&mut at, start),
539 };
540 }
541 length
542}
543
544pub struct Canvas {
572 paint: Box<dyn FnMut(&mut Pen)>,
573 common: Common,
574}
575
576impl Canvas {
577 pub fn new(paint: impl FnMut(&mut Pen) + 'static) -> Canvas {
579 Canvas {
580 paint: Box::new(paint),
581 common: Common::default(),
582 }
583 }
584
585 pub fn style(mut self, style: impl crate::IntoProp<Style>) -> Canvas {
588 self.common.style = Some(style.into_prop());
589 self
590 }
591
592 visibility_methods!();
593}
594
595impl Widget for Canvas {
596 fn into_element(self: Box<Self>) -> Element {
597 Element {
598 name: "Canvas",
599 common: self.common,
600 kind: ElementKind::Canvas(self.paint),
601 children: Vec::new(),
602 }
603 }
604}
605
606#[derive(Default)]
608pub(crate) struct CanvasNode {
609 pub(crate) ops: Vec<CanvasOp>,
610}
611
612impl Tree {
613 pub(crate) fn bind_canvas(&mut self, id: NodeId, mut paint: Box<dyn FnMut(&mut Pen)>) {
617 let Some(node) = self.node_mut(id) else {
618 return;
619 };
620 let cx = node.cx.clone();
621 let path = Rc::clone(&node.path);
622 let size = cx.signal(None::<Size>);
624 node.measure = Some(Rc::new(move |laid: Size| {
625 size.try_set(Some(laid));
626 }));
627 let tree = self.this.clone();
628 let label = format!("{path}.paint");
629 let mut logged = false;
630 cx.effect(move || {
631 let Some(size) = size.get() else {
632 return;
633 };
634 let mut pen = Pen::new(size);
635 paint(&mut pen);
637 let Pen { ops, skipped, .. } = pen;
638 if let Some(reason) = skipped
639 && !std::mem::replace(&mut logged, true)
640 {
641 tracing::warn!(
642 "{path}.paint drew {reason}, so that drawing is skipped; later ones aren't logged"
643 );
644 }
645 let Some(tree) = tree.upgrade() else {
646 return;
647 };
648 borrow(&tree).update(id, |node| match &mut node.kind {
649 NodeKind::Canvas(canvas) if canvas.ops != ops => {
650 canvas.ops = ops;
651 Change::Paint
652 }
653 _ => Change::None,
654 });
655 })
656 .named(label);
657 }
658}