use std::rc::Rc;
use crate::geometry::{Point, Rect, Size};
use crate::style::{Color, Gradient, Style};
use crate::tree::{Change, NodeId, NodeKind, Tree, borrow};
use crate::widgets::{Common, Element, ElementKind, Widget, visibility_methods};
const MOST_COMMANDS: usize = 16_384;
const MOST_COORDINATE: f32 = 1.0e6;
const MOST_DASHES: f32 = 100_000.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Paint {
Color(Color),
Gradient(Gradient),
}
impl From<Color> for Paint {
fn from(color: Color) -> Paint {
Paint::Color(color)
}
}
impl From<Gradient> for Paint {
fn from(gradient: Gradient) -> Paint {
Paint::Gradient(gradient)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PathCommand {
MoveTo(Point),
LineTo(Point),
QuadTo {
control: Point,
to: Point,
},
CubicTo {
first: Point,
second: Point,
to: Point,
},
Arc {
center: Point,
radius: f32,
start: f32,
sweep: f32,
},
Close,
}
#[derive(Clone, Debug, Default, PartialEq)]
#[must_use]
pub struct Path {
commands: Vec<PathCommand>,
}
impl Path {
pub fn new() -> Path {
Path::default()
}
pub fn move_to(self, to: Point) -> Path {
self.with(PathCommand::MoveTo(to))
}
pub fn line_to(self, to: Point) -> Path {
self.with(PathCommand::LineTo(to))
}
pub fn quad_to(self, control: Point, to: Point) -> Path {
self.with(PathCommand::QuadTo { control, to })
}
pub fn cubic_to(self, first: Point, second: Point, to: Point) -> Path {
self.with(PathCommand::CubicTo { first, second, to })
}
pub fn arc(self, center: Point, radius: f32, start: f32, sweep: f32) -> Path {
self.with(PathCommand::Arc {
center,
radius,
start,
sweep,
})
}
pub fn close(self) -> Path {
self.with(PathCommand::Close)
}
pub fn rect(rect: Rect) -> Path {
Path::new()
.move_to(Point::new(rect.x, rect.y))
.line_to(Point::new(rect.right(), rect.y))
.line_to(Point::new(rect.right(), rect.bottom()))
.line_to(Point::new(rect.x, rect.bottom()))
.close()
}
pub fn rounded_rect(rect: Rect, radius: f32) -> Path {
let r = radius.min(rect.width.min(rect.height) / 2.0);
if r.is_nan() || r <= 0.0 {
return Path::rect(rect);
}
let (left, top, right, bottom) = (rect.x, rect.y, rect.right(), rect.bottom());
Path::new()
.move_to(Point::new(left + r, top))
.arc(Point::new(right - r, top + r), r, -90.0, 90.0)
.arc(Point::new(right - r, bottom - r), r, 0.0, 90.0)
.arc(Point::new(left + r, bottom - r), r, 90.0, 90.0)
.arc(Point::new(left + r, top + r), r, 180.0, 90.0)
.close()
}
pub fn circle(center: Point, radius: f32) -> Path {
Path::new()
.move_to(Point::new(center.x + radius, center.y))
.arc(center, radius, 0.0, 360.0)
.close()
}
pub fn ellipse(center: Point, radius_x: f32, radius_y: f32) -> Path {
const KAPPA: f32 = 0.552_284_8;
let (x, y) = (center.x, center.y);
let (kx, ky) = (radius_x * KAPPA, radius_y * KAPPA);
let point = Point::new;
Path::new()
.move_to(point(x + radius_x, y))
.cubic_to(
point(x + radius_x, y + ky),
point(x + kx, y + radius_y),
point(x, y + radius_y),
)
.cubic_to(
point(x - kx, y + radius_y),
point(x - radius_x, y + ky),
point(x - radius_x, y),
)
.cubic_to(
point(x - radius_x, y - ky),
point(x - kx, y - radius_y),
point(x, y - radius_y),
)
.cubic_to(
point(x + kx, y - radius_y),
point(x + radius_x, y - ky),
point(x + radius_x, y),
)
.close()
}
pub fn commands(&self) -> &[PathCommand] {
&self.commands
}
fn with(mut self, command: PathCommand) -> Path {
self.commands.push(command);
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Cap {
#[default]
Butt,
Round,
Square,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Join {
#[default]
Miter,
Round,
Bevel,
}
#[derive(Clone, Debug, PartialEq)]
#[must_use]
pub struct Stroke {
pub width: f32,
pub paint: Paint,
pub cap: Cap,
pub join: Join,
pub dash: Vec<f32>,
pub dash_offset: f32,
}
impl Stroke {
pub fn new(width: f32, paint: impl Into<Paint>) -> Stroke {
Stroke {
width,
paint: paint.into(),
cap: Cap::default(),
join: Join::default(),
dash: Vec::new(),
dash_offset: 0.0,
}
}
pub fn cap(mut self, cap: Cap) -> Stroke {
self.cap = cap;
self
}
pub fn join(mut self, join: Join) -> Stroke {
self.join = join;
self
}
pub fn dash(mut self, pattern: &[f32], offset: f32) -> Stroke {
self.dash = pattern.to_vec();
self.dash_offset = offset;
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum CanvasOp {
Fill(Path, Paint),
Stroke(Path, Stroke),
}
pub struct Pen {
size: Size,
ops: Vec<CanvasOp>,
commands: usize,
dashes: f32,
skipped: Option<String>,
}
impl Pen {
fn new(size: Size) -> Pen {
Pen {
size,
ops: Vec::new(),
commands: 0,
dashes: 0.0,
skipped: None,
}
}
pub fn size(&self) -> Size {
self.size
}
pub fn fill(&mut self, path: &Path, paint: impl Into<Paint>) {
let commands = path.commands.len();
match check_path(path) {
Ok(()) => self.record(CanvasOp::Fill(path.clone(), paint.into()), commands, 0.0),
Err(reason) => self.skip(reason),
}
}
pub fn stroke(&mut self, path: &Path, stroke: &Stroke) {
if stroke.width == 0.0 {
return;
}
let checked = check_path(path).and_then(|()| check_stroke(path, stroke));
match checked {
Ok((dash, dashes)) => {
let commands = path.commands.len() + dash.len();
let stroke = Stroke {
dash,
..stroke.clone()
};
self.record(CanvasOp::Stroke(path.clone(), stroke), commands, dashes);
}
Err(reason) => self.skip(reason),
}
}
fn record(&mut self, op: CanvasOp, commands: usize, dashes: f32) {
if self.commands + commands > MOST_COMMANDS {
self.skip(format!(
"more than {MOST_COMMANDS} path commands and dash lengths in one run"
));
return;
}
if self.dashes + dashes > MOST_DASHES {
self.skip(format!("more than {MOST_DASHES} dashes in one run"));
return;
}
self.commands += commands;
self.dashes += dashes;
self.ops.push(op);
}
fn skip(&mut self, reason: String) {
self.skipped.get_or_insert(reason);
}
}
fn usable(n: f32) -> bool {
n.is_finite() && n.abs() <= MOST_COORDINATE
}
fn check_path(path: &Path) -> Result<(), String> {
for command in &path.commands {
let (points, numbers): (&[Point], &[f32]) = match command {
PathCommand::MoveTo(point) | PathCommand::LineTo(point) => (std::slice::from_ref(point), &[]),
PathCommand::QuadTo { control, to } => (&[*control, *to], &[]),
PathCommand::CubicTo { first, second, to } => (&[*first, *second, *to], &[]),
PathCommand::Arc {
center,
radius,
start,
sweep,
} => {
if *radius < 0.0 {
return Err(format!("an arc with a negative radius, {radius}"));
}
(std::slice::from_ref(center), &[*radius, *start, *sweep])
}
PathCommand::Close => (&[], &[]),
};
let all = points
.iter()
.flat_map(|p| [p.x, p.y])
.chain(numbers.iter().copied());
if let Some(bad) = all.into_iter().find(|&n| !usable(n)) {
return Err(format!(
"a path holding {bad}, which isn't a finite number within {MOST_COORDINATE}"
));
}
}
Ok(())
}
fn check_stroke(path: &Path, stroke: &Stroke) -> Result<(Vec<f32>, f32), String> {
if !(usable(stroke.width) && stroke.width > 0.0) {
return Err(format!("a stroke {} wide", stroke.width));
}
if stroke.dash.is_empty() {
return Ok((Vec::new(), 0.0));
}
if !usable(stroke.dash_offset) || stroke.dash.iter().any(|&n| !(usable(n) && n >= 0.0)) {
return Err(format!(
"a dash pattern {:?} at offset {}",
stroke.dash, stroke.dash_offset
));
}
let mut dash = stroke.dash.clone();
if dash.len() % 2 == 1 {
dash.extend_from_within(..);
}
let interval: f32 = dash.iter().sum();
let dashes = path_length(path) / interval * (dash.len() / 2) as f32;
if !(interval > 0.0 && dashes.is_finite()) {
return Err(format!("a dash pattern {:?}", stroke.dash));
}
Ok((dash, dashes))
}
fn path_length(path: &Path) -> f32 {
fn step(at: &mut Option<Point>, to: Point) -> f32 {
let from = at.replace(to).unwrap_or(to);
(to.x - from.x).hypot(to.y - from.y)
}
let (mut length, mut at, mut start) = (0.0, None, Point::default());
for command in &path.commands {
if at.is_none() {
let first = match *command {
PathCommand::MoveTo(point) | PathCommand::LineTo(point) => Some(point),
PathCommand::QuadTo { control, .. } => Some(control),
PathCommand::CubicTo { first, .. } => Some(first),
PathCommand::Arc {
center,
radius,
start,
..
} => {
let (sin, cos) = start.to_radians().sin_cos();
Some(Point::new(center.x + radius * cos, center.y + radius * sin))
}
PathCommand::Close => None,
};
if let Some(first) = first {
(at, start) = (Some(first), first);
}
}
length += match *command {
PathCommand::MoveTo(to) => {
(at, start) = (Some(to), to);
0.0
}
PathCommand::LineTo(to) => step(&mut at, to),
PathCommand::QuadTo { control, to } => step(&mut at, control) + step(&mut at, to),
PathCommand::CubicTo { first, second, to } => {
step(&mut at, first) + step(&mut at, second) + step(&mut at, to)
}
PathCommand::Arc {
center,
radius,
start: from,
sweep,
} => {
let point = |degrees: f32| {
let (sin, cos) = degrees.to_radians().sin_cos();
Point::new(center.x + radius * cos, center.y + radius * sin)
};
let sweep = sweep.clamp(-360.0, 360.0);
let line = step(&mut at, point(from));
at = Some(point(from + sweep));
line + radius * sweep.abs().to_radians()
}
PathCommand::Close => step(&mut at, start),
};
}
length
}
pub struct Canvas {
paint: Box<dyn FnMut(&mut Pen)>,
common: Common,
}
impl Canvas {
pub fn new(paint: impl FnMut(&mut Pen) + 'static) -> Canvas {
Canvas {
paint: Box::new(paint),
common: Common::default(),
}
}
pub fn style(mut self, style: impl crate::IntoProp<Style>) -> Canvas {
self.common.style = Some(style.into_prop());
self
}
visibility_methods!();
}
impl Widget for Canvas {
fn into_element(self: Box<Self>) -> Element {
Element {
name: "Canvas",
common: self.common,
kind: ElementKind::Canvas(self.paint),
children: Vec::new(),
}
}
}
#[derive(Default)]
pub(crate) struct CanvasNode {
pub(crate) ops: Vec<CanvasOp>,
}
impl Tree {
pub(crate) fn bind_canvas(&mut self, id: NodeId, mut paint: Box<dyn FnMut(&mut Pen)>) {
let Some(node) = self.node_mut(id) else {
return;
};
let cx = node.cx.clone();
let path = Rc::clone(&node.path);
let size = cx.signal(None::<Size>);
node.measure = Some(Rc::new(move |laid: Size| {
size.try_set(Some(laid));
}));
let tree = self.this.clone();
let label = format!("{path}.paint");
let mut logged = false;
cx.effect(move || {
let Some(size) = size.get() else {
return;
};
let mut pen = Pen::new(size);
paint(&mut pen);
let Pen { ops, skipped, .. } = pen;
if let Some(reason) = skipped
&& !std::mem::replace(&mut logged, true)
{
tracing::warn!(
"{path}.paint drew {reason}, so that drawing is skipped; later ones aren't logged"
);
}
let Some(tree) = tree.upgrade() else {
return;
};
borrow(&tree).update(id, |node| match &mut node.kind {
NodeKind::Canvas(canvas) if canvas.ops != ops => {
canvas.ops = ops;
Change::Paint
}
_ => Change::None,
});
})
.named(label);
}
}