Skip to main content

crabshell_ui/
canvas.rs

1//! [`Canvas`], a widget a config draws on with paths, and the plain data
2//! it records: [`Path`], [`Paint`] and [`Stroke`]. ui only records the
3//! drawing; `crabshell-render` draws it.
4
5use 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
12/// The most path commands and dash lengths one run of a paint closure
13/// keeps, so a runaway loop can't eat memory: 16,384 is eight lines
14/// across a 2048-pixel-wide graph, a point a pixel, at about 0.5 MiB.
15const MOST_COMMANDS: usize = 16_384;
16
17/// The largest number a canvas takes as a coordinate, radius, width or
18/// dash, in logical pixels. Past it a number is a mistake, and the
19/// renderer's arithmetic would lose it.
20const MOST_COORDINATE: f32 = 1.0e6;
21
22/// The most dashes one run of a paint closure may cut its strokes into,
23/// as far as their lengths can be told before they are drawn. Each tile
24/// a stroke crosses cuts it again.
25const MOST_DASHES: f32 = 100_000.0;
26
27/// How a [`Canvas`] paints a path: in one color, or in a gradient laid
28/// over the canvas's box, as a style's is.
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub enum Paint {
31  /// One color.
32  Color(Color),
33  /// A gradient across the canvas's box.
34  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/// One step of a [`Path`], in logical pixels from the canvas's top-left.
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub enum PathCommand {
52  /// Starts a new piece at the point.
53  MoveTo(Point),
54  /// A straight line to the point.
55  LineTo(Point),
56  /// A quadratic curve to `to`, bent toward `control`.
57  QuadTo {
58    /// Its control point.
59    control: Point,
60    /// Where it ends.
61    to: Point,
62  },
63  /// A cubic curve to `to`, leaving toward `first` and arriving from
64  /// `second`.
65  CubicTo {
66    /// The control point it leaves toward.
67    first: Point,
68    /// The control point it arrives from.
69    second: Point,
70    /// Where it ends.
71    to: Point,
72  },
73  /// An arc of a circle, from `start` degrees through `sweep` degrees,
74  /// clockwise from 3 o'clock, with a line to its start from where the
75  /// path is.
76  Arc {
77    /// The circle's middle.
78    center: Point,
79    /// The circle's radius.
80    radius: f32,
81    /// Where it starts, in degrees clockwise from 3 o'clock.
82    start: f32,
83    /// How far it goes, in degrees: clockwise when positive, at most a
84    /// whole turn either way.
85    sweep: f32,
86  },
87  /// A straight line back to where the piece started, closing it.
88  Close,
89}
90
91/// A shape to fill or stroke on a [`Canvas`], built from lines, curves
92/// and arcs in logical pixels from the canvas's top-left corner. It is
93/// plain data, so it can be built once outside the paint closure.
94///
95/// ```
96/// use crabshell_ui::{Path, Point, Rect};
97///
98/// let tick = Path::new()
99///     .move_to(Point::new(2.0, 8.0))
100///     .line_to(Point::new(6.0, 12.0))
101///     .line_to(Point::new(14.0, 4.0));
102/// // A quarter of a ring from 12 o'clock, as a progress ring at 25%.
103/// let progress = Path::new().arc(Point::new(20.0, 20.0), 16.0, -90.0, 90.0);
104/// let card = Path::rounded_rect(Rect::new(0.0, 0.0, 40.0, 40.0), 8.0);
105/// ```
106#[derive(Clone, Debug, Default, PartialEq)]
107#[must_use]
108pub struct Path {
109  commands: Vec<PathCommand>,
110}
111
112impl Path {
113  /// An empty path.
114  pub fn new() -> Path {
115    Path::default()
116  }
117
118  /// Starts a new piece at `to`.
119  pub fn move_to(self, to: Point) -> Path {
120    self.with(PathCommand::MoveTo(to))
121  }
122
123  /// Adds a straight line to `to`.
124  pub fn line_to(self, to: Point) -> Path {
125    self.with(PathCommand::LineTo(to))
126  }
127
128  /// Adds a quadratic curve to `to`, bent toward `control`.
129  pub fn quad_to(self, control: Point, to: Point) -> Path {
130    self.with(PathCommand::QuadTo { control, to })
131  }
132
133  /// Adds a cubic curve to `to`, leaving toward `first` and arriving from
134  /// `second`.
135  pub fn cubic_to(self, first: Point, second: Point, to: Point) -> Path {
136    self.with(PathCommand::CubicTo { first, second, to })
137  }
138
139  /// Adds an arc of the circle around `center`, from `start` degrees
140  /// through `sweep` degrees, clockwise from 3 o'clock, as an HTML
141  /// canvas's `arc` goes: a negative sweep runs counterclockwise, and a
142  /// sweep past a whole turn is one. A line joins it to where the path
143  /// was; on an empty path it starts a piece.
144  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  /// Closes the piece with a straight line back to its start.
154  pub fn close(self) -> Path {
155    self.with(PathCommand::Close)
156  }
157
158  /// A rectangle.
159  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  /// A rectangle with circular corners of `radius`, at most half its
169  /// shorter side.
170  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  /// A circle around `center`.
186  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  /// An ellipse around `center`, `radius_x` wide and `radius_y` tall on
194  /// each side.
195  pub fn ellipse(center: Point, radius_x: f32, radius_y: f32) -> Path {
196    // How far a cubic curve's control points sit along the tangents to
197    // follow a quarter circle closely.
198    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  /// The steps, in order.
228  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/// How a stroke's open ends look.
239#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
240pub enum Cap {
241  /// Cut square at the end. The default.
242  #[default]
243  Butt,
244  /// A half circle past the end.
245  Round,
246  /// A half square past the end.
247  Square,
248}
249
250/// How a stroke turns its corners.
251#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
252pub enum Join {
253  /// A sharp point, cut flat where it would reach past 4 widths. The
254  /// default.
255  #[default]
256  Miter,
257  /// A round corner.
258  Round,
259  /// A corner cut flat.
260  Bevel,
261}
262
263/// How a [`Canvas`] draws along a path: its width in logical pixels, its
264/// paint, its ends, its corners and its dashes.
265///
266/// ```
267/// use crabshell_ui::{Cap, Color, Join, Stroke};
268///
269/// let ring = Stroke::new(4.0, Color::hex("#89b4fa")).cap(Cap::Round);
270/// let grid = Stroke::new(1.0, Color::rgba(255, 255, 255, 40)).dash(&[4.0, 2.0], 0.0);
271/// let line = Stroke::new(2.0, Color::hex("#a6e3a1")).join(Join::Round);
272/// ```
273#[derive(Clone, Debug, PartialEq)]
274#[must_use]
275pub struct Stroke {
276  /// How wide it is. 0 draws nothing.
277  pub width: f32,
278  /// What it is painted with.
279  pub paint: Paint,
280  /// How its open ends look.
281  pub cap: Cap,
282  /// How it turns corners.
283  pub join: Join,
284  /// The lengths of its dashes and the gaps between them, in turn, or
285  /// empty for a solid line. An odd list is repeated, as an HTML
286  /// canvas's `setLineDash` does.
287  pub dash: Vec<f32>,
288  /// How far into the dash pattern the stroke starts.
289  pub dash_offset: f32,
290}
291
292impl Stroke {
293  /// A solid stroke `width` wide, with butt ends and miter corners.
294  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  /// Sets how its open ends look, dashes' included.
306  pub fn cap(mut self, cap: Cap) -> Stroke {
307    self.cap = cap;
308    self
309  }
310
311  /// Sets how it turns corners.
312  pub fn join(mut self, join: Join) -> Stroke {
313    self.join = join;
314    self
315  }
316
317  /// Dashes it: `pattern` holds the lengths of dashes and the gaps
318  /// between them, in turn, and `offset` is how far into it the stroke
319  /// starts.
320  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/// One drawing a paint closure recorded, for the renderer.
328#[derive(Clone, Debug, PartialEq)]
329pub enum CanvasOp {
330  /// The inside of a path, by the nonzero winding rule.
331  Fill(Path, Paint),
332  /// Along a path.
333  Stroke(Path, Stroke),
334}
335
336/// What a [`Canvas`]'s paint closure draws with. Each run starts with a
337/// clean canvas, and what it draws replaces the last run's drawing.
338pub struct Pen {
339  size: Size,
340  ops: Vec<CanvasOp>,
341  commands: usize,
342  /// How many dashes its strokes are cut into, at most.
343  dashes: f32,
344  /// Why the first drawing it skipped was skipped.
345  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  /// The canvas's size in logical pixels, from its last layout.
360  pub fn size(&self) -> Size {
361    self.size
362  }
363
364  /// Fills the inside of `path` with `paint`, a [`Color`] or a
365  /// [`Gradient`] laid over the canvas's box.
366  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  /// Draws along `path` with `stroke`.
375  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
414/// Whether `n` is a number a canvas takes.
415fn usable(n: f32) -> bool {
416  n.is_finite() && n.abs() <= MOST_COORDINATE
417}
418
419/// Refuses a path with a number that isn't finite, is past
420/// [`MOST_COORDINATE`], or is a negative radius.
421fn 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
453/// Refuses a stroke whose width or dashes the renderer can't draw, and
454/// gives its dash pattern with an even number of lengths and at most how
455/// many dashes it cuts its path into.
456fn 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
481/// At least the length of `path`: the lengths of its control polygons
482/// and arcs.
483fn path_length(path: &Path) -> f32 {
484  /// The distance from `at` to `to`, which becomes where the path is.
485  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    // As drawn, a path that doesn't start with a move starts a piece at
492    // the first point of its first command.
493    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
544/// A box a config draws on with paths, arcs, curves and dashed strokes,
545/// for progress rings, graphs and audio visualizers.
546///
547/// The paint closure gets a [`Pen`] and runs when the canvas is first
548/// laid out, when its laid-out size changes, and when a signal it read
549/// changes; each run replaces the drawing, and repaints only the
550/// canvas's box. Coordinates are logical pixels from the canvas's
551/// top-left, and the drawing is cut to its box and rounded corners. Size
552/// it with its style's `width` and `height`, or let its parent stretch
553/// it, as any box. A panic in the closure is logged with the canvas's
554/// path, such as `PanelWindow[DP-1]/Row/Canvas[2].paint`, and the last
555/// drawing stays.
556///
557/// ```
558/// use crabshell_ui::{Canvas, Cap, Color, Path, Point, Stroke, Style};
559///
560/// # let cx = crabshell_ui::Cx::new(crabshell_reactive::Runtime::current().new_owner());
561/// let charge = cx.signal(0.6_f32);
562/// let ring = Canvas::new(move |pen| {
563///     let size = pen.size();
564///     let middle = Point::new(size.width / 2.0, size.height / 2.0);
565///     let radius = size.width.min(size.height) / 2.0 - 3.0;
566///     let arc = Path::new().arc(middle, radius, -90.0, 360.0 * charge.get());
567///     pen.stroke(&arc, &Stroke::new(4.0, Color::hex("#a6e3a1")).cap(Cap::Round));
568/// })
569/// .style(Style::new().width(24.0).height(24.0));
570/// ```
571pub struct Canvas {
572  paint: Box<dyn FnMut(&mut Pen)>,
573  common: Common,
574}
575
576impl Canvas {
577  /// A canvas `paint` draws on.
578  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  /// Sets the style: its `width` and `height` size the canvas, and its
586  /// background and border are drawn under the drawing.
587  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/// What a canvas node holds: the last run's drawing.
607#[derive(Default)]
608pub(crate) struct CanvasNode {
609  pub(crate) ops: Vec<CanvasOp>,
610}
611
612impl Tree {
613  /// Runs `paint` in an effect under the canvas's owner once the canvas
614  /// has a size, and again whenever that size or a signal it read
615  /// changes, storing what it drew.
616  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    // `None` until the first layout says how large it is.
623    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      // The user's closure runs before the tree is borrowed.
636      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}