Skip to main content

nsh_core/js/
canvas.rs

1//! The canvas's operations (`CV_*`): how a recorded drawing is read
2//! ([`decode`], [`CanvasOp`]'s and [`PathOp`]'s `#[derive(JsOps)]` with the
3//! arguments' readers here) and the part of the 2D context that only
4//! records them, generated from the same variants: the methods that push
5//! their code and arguments, and the drawing-state properties that push
6//! their code and value (`nsh-js` `canvas.rs` records natively from the
7//! same specs; [`typescript`] gives their declarations).
8
9codes! { CODES:
10    CV_SAVE = 0,
11    CV_RESTORE = 1,
12    CV_TRANSLATE = 2,
13    CV_SCALE = 3,
14    CV_ROTATE = 4,
15    CV_TRANSFORM = 5,
16    CV_SET_TRANSFORM = 6,
17    CV_BEGIN_PATH = 7,
18    CV_MOVE_TO = 8,
19    CV_LINE_TO = 9,
20    CV_QUAD_TO = 10,
21    CV_CUBIC_TO = 11,
22    CV_ARC = 12,
23    CV_ARC_TO = 13,
24    CV_ELLIPSE = 14,
25    CV_RECT = 15,
26    CV_ROUND_RECT = 16,
27    CV_CLOSE = 17,
28    CV_FILL = 18,
29    CV_STROKE = 19,
30    CV_CLIP = 20,
31    CV_FILL_RECT = 21,
32    CV_STROKE_RECT = 22,
33    CV_CLEAR_RECT = 23,
34    CV_FILL_STYLE = 24,
35    CV_STROKE_STYLE = 25,
36    CV_LINE_WIDTH = 26,
37    CV_LINE_CAP = 27,
38    CV_LINE_JOIN = 28,
39    CV_MITER_LIMIT = 29,
40    CV_LINE_DASH = 30,
41    CV_LINE_DASH_OFFSET = 31,
42    CV_GLOBAL_ALPHA = 32,
43    CV_COMPOSITE = 33,
44    CV_SHADOW_COLOR = 34,
45    CV_SHADOW_BLUR = 35,
46    CV_SHADOW_OFFSET = 36,
47    CV_FONT = 37,
48    CV_TEXT_ALIGN = 38,
49    CV_TEXT_BASELINE = 39,
50    CV_FILL_TEXT = 40,
51    CV_STROKE_TEXT = 41,
52    CV_DRAW_IMAGE = 42,
53    CV_FONT_VARIANT_NUMERIC = 43,
54    /// SVG path data, parsed natively (`new Path2D("M0 0 L10 10")`)
55    CV_SVG_PATH = 50,
56}
57
58use std::sync::Arc;
59
60use super::{
61    host::{HostInput, HostList, HostValue},
62    ops::{JsOps, OpArg, OpMethod, OpReader, OpsError, host_value},
63};
64use crate::{
65    canvas::{
66        CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
67        Composite, Drawing, FillRule, GradientShape, LineCap, LineJoin, Num, Paint, Path, PathOp,
68        parse_svg_path,
69    },
70    element::TsTypes,
71    geometry::{Bounds, Percentage, Points, Radians, ScaledPixels, point, size},
72    style::{Color, FontVariant},
73};
74
75/// Reads drawing `list[start..end]` (what a `draw` callback recorded).
76pub fn decode<L: HostList<Item: HostInput>>(
77    list: &L,
78    start: usize,
79    end: usize,
80) -> Result<Drawing, OpsError> {
81    let mut drawing = Drawing::default();
82    let mut r = OpReader::new(list, start, end);
83    while r.more() {
84        let code = r.code()?;
85        match CanvasOp::decode(code, &mut r, &mut drawing)? {
86            Some(Some(op)) => drawing.ops.push(op),
87            Some(None) => {}
88            None => return Err(OpsError::Unknown(code)),
89        }
90    }
91    Ok(drawing)
92}
93
94/// A constant, or an animated value the canvas reads while it draws (a slot
95/// of the drawing); anything else is 0.
96impl OpArg<Drawing> for Num {
97    #[inline]
98    fn read<L: HostList<Item: HostInput>>(
99        r: &mut OpReader<'_, L>,
100        drawing: &mut Drawing,
101    ) -> Result<Option<Self>, OpsError> {
102        let v = r.arg()?;
103        if let Some(n) = v.as_number() {
104            return Ok(Some(Num::Const(n as f32)));
105        }
106        Ok(Some(match v.animated_node() {
107            Some(node) => Num::Slot(drawing.slot(node)),
108            None => Num::Const(0.0),
109        }))
110    }
111
112    fn ts(_: &mut TsTypes) -> String {
113        "CanvasNumber".into()
114    }
115}
116
117/// A `Path2D`'s recorded list, or (anything else) the current path.
118impl OpArg<Drawing> for Option<Path> {
119    fn read<L: HostList<Item: HostInput>>(
120        r: &mut OpReader<'_, L>,
121        drawing: &mut Drawing,
122    ) -> Result<Option<Self>, OpsError> {
123        let Some(list) = r.arg()?.as_list() else {
124            return Ok(Some(None));
125        };
126        let mut ops = Vec::new();
127        let mut path = OpReader::all(&list);
128        while path.more() {
129            let code = path.code()?;
130            if code == CV_SVG_PATH {
131                ops.extend(parse_svg_path(&path.arg()?.as_string().unwrap_or_default()));
132                continue;
133            }
134            match PathOp::decode(code, &mut path, drawing)? {
135                Some(Some(op)) => ops.push(op),
136                Some(None) => {}
137                None => return Err(OpsError::Misplaced(code)),
138            }
139        }
140        Ok(Some(Some(ops.into())))
141    }
142
143    fn ts(_: &mut TsTypes) -> String {
144        "Path2D".into()
145    }
146}
147
148/// A color, an animated value interpolating colors, or a gradient
149/// (`[kind, ...geometry, [offset, color, ...]]`); anything else drops the
150/// operation.
151impl OpArg<Drawing> for Paint {
152    fn read<L: HostList<Item: HostInput>>(
153        r: &mut OpReader<'_, L>,
154        drawing: &mut Drawing,
155    ) -> Result<Option<Self>, OpsError> {
156        let v = r.arg()?;
157        if let Some(s) = v.as_string() {
158            return Ok(Color::parse(&s).map(Paint::Color));
159        }
160        if let Some(node) = v.animated_node() {
161            return Ok(Some(Paint::Slot(drawing.slot(node))));
162        }
163        let Some(list) = v.as_list() else {
164            return Ok(None);
165        };
166        let n = |i: usize| list.item(i).and_then(|x| x.as_number()).unwrap_or(0.0) as f32;
167        let p = |i: usize| Points(n(i));
168        let at = |i: usize| point(p(i), p(i + 1));
169        let (shape, stops_at) = match list.item(0).and_then(|k| k.as_number()) {
170            Some(0.0) => (
171                GradientShape::Linear {
172                    start: at(1),
173                    end: at(3),
174                },
175                5,
176            ),
177            Some(1.0) => (
178                GradientShape::Radial {
179                    start: at(1),
180                    start_radius: p(3),
181                    end: at(4),
182                    end_radius: p(6),
183                },
184                7,
185            ),
186            Some(2.0) => (
187                GradientShape::Conic {
188                    start_angle: Radians(n(1)),
189                    center: at(2),
190                },
191                4,
192            ),
193            _ => return Ok(None),
194        };
195        let mut stops = Vec::new();
196        if let Some(raw) = list.item(stops_at).and_then(|s| s.as_list()) {
197            let mut i = 0;
198            while i + 1 < raw.len() {
199                let offset = raw.item(i).and_then(|o| o.as_number()).unwrap_or(0.0) as f32;
200                let color = raw
201                    .item(i + 1)
202                    .and_then(|c| c.as_string())
203                    .and_then(|c| Color::parse(&c));
204                if let Some(color) = color {
205                    stops.push((Percentage(offset.clamp(0.0, 1.0)), color));
206                }
207                i += 2;
208            }
209        }
210        // Stops apply in offset order (equal offsets keep their order).
211        stops.sort_by(|a, b| a.0.0.total_cmp(&b.0.0));
212        Ok(Some(Paint::Gradient(Arc::new(CanvasGradient {
213            shape,
214            stops,
215        }))))
216    }
217
218    fn ts(_: &mut TsTypes) -> String {
219        "CanvasPaint".into()
220    }
221}
222
223/// A URL or `asset:/` URI; without one the operation is dropped.
224impl OpArg<Drawing> for CanvasImage {
225    fn read<L: HostList<Item: HostInput>>(
226        r: &mut OpReader<'_, L>,
227        _: &mut Drawing,
228    ) -> Result<Option<Self>, OpsError> {
229        let uri = r.arg()?.as_string().unwrap_or_default();
230        Ok((!uri.is_empty()).then(|| CanvasImage { uri: uri.into() }))
231    }
232
233    fn ts(_: &mut TsTypes) -> String {
234        "string".into()
235    }
236}
237
238/// `drawImage`'s source rectangle `[sx, sy, sw, sh]`, or the whole image.
239impl OpArg<Drawing> for Option<Bounds<ScaledPixels>> {
240    fn read<L: HostList<Item: HostInput>>(
241        r: &mut OpReader<'_, L>,
242        _: &mut Drawing,
243    ) -> Result<Option<Self>, OpsError> {
244        let Some(v) = r.arg()?.as_list() else {
245            return Ok(Some(None));
246        };
247        let mut out = [0f32; 4];
248        for (i, o) in out.iter_mut().enumerate().take(v.len()) {
249            *o = v.item(i).and_then(|n| n.as_number()).unwrap_or(0.0) as f32;
250        }
251        let [x, y, w, h] = out.map(ScaledPixels);
252        Ok(Some(Some(Bounds {
253            origin: point(x, y),
254            size: size(w, h),
255        })))
256    }
257
258    fn ts(_: &mut TsTypes) -> String {
259        "number[]".into()
260    }
261}
262
263/// Values parsed from a string that drop the operation when invalid.
264macro_rules! parsed {
265    ($($ty:ty => $parse:path),* $(,)?) => {$(
266        impl<Cx> OpArg<Cx> for $ty {
267            fn read<L: HostList<Item: HostInput>>(
268        r: &mut OpReader<'_, L>, _: &mut Cx) -> Result<Option<Self>, OpsError> {
269                Ok(r.arg()?.as_string().and_then(|s| $parse(&s)))
270            }
271
272            fn ts(_: &mut TsTypes) -> String {
273                "string".into()
274            }
275        }
276    )*};
277}
278
279parsed! {
280    Color => Color::parse,
281    Composite => Composite::parse,
282    CanvasFont => CanvasFont::parse,
283}
284
285/// `fontVariantNumeric`: number forms only (space-separated, as in CSS);
286/// anything else drops the operation.
287impl<Cx> OpArg<Cx> for FontVariant {
288    fn read<L: HostList<Item: HostInput>>(
289        r: &mut OpReader<'_, L>,
290        _: &mut Cx,
291    ) -> Result<Option<Self>, OpsError> {
292        Ok(r.arg()?
293            .as_string()
294            .and_then(|s| FontVariant::parse(&s))
295            .filter(|v| !v.has(FontVariant::SMALL_CAPS)))
296    }
297
298    fn ts(_: &mut TsTypes) -> String {
299        "\"normal\" | \"tabular-nums\" | \"proportional-nums\" | \"lining-nums\" | \"oldstyle-nums\" | (string & {})".into()
300    }
301}
302
303/// String unions: names they do not have are the default.
304macro_rules! named {
305    ($($ty:ty),* $(,)?) => {$(
306        impl<Cx> OpArg<Cx> for $ty {
307            fn read<L: HostList<Item: HostInput>>(
308        r: &mut OpReader<'_, L>, _: &mut Cx) -> Result<Option<Self>, OpsError> {
309                Ok(Some(host_value(r)?.unwrap_or_default()))
310            }
311
312            fn ts(types: &mut TsTypes) -> String {
313                <$ty as HostValue>::ts_type(types)
314            }
315        }
316    )*};
317}
318
319named!(
320    FillRule,
321    LineCap,
322    LineJoin,
323    CanvasTextAlign,
324    CanvasTextBaseline
325);
326
327/// `setLineDash(segments)`: lists with negative or non-finite entries are
328/// ignored, as in canvas; an odd count is repeated.
329pub(crate) fn line_dash<L: HostList<Item: HostInput>>(
330    r: &mut OpReader<'_, L>,
331    _: &mut Drawing,
332) -> Result<Option<CanvasOp>, OpsError> {
333    let mut dash: Vec<f32> = match r.arg()?.as_list() {
334        Some(v) => (0..v.len())
335            .filter_map(|i| v.item(i)?.as_number())
336            .map(|d| d as f32)
337            .collect(),
338        None => Vec::new(),
339    };
340    if dash.iter().any(|d| !d.is_finite() || *d < 0.0) {
341        return Ok(None);
342    }
343    if dash.len() % 2 == 1 {
344        dash.extend_from_within(..);
345    }
346    Ok(Some(CanvasOp::LineDash(
347        dash.into_iter().map(Points).collect(),
348    )))
349}
350
351/// The declarations of the recording methods and properties (`nsh`
352/// declares the canvas's classes; `nsh-js` records natively from the same
353/// specs).
354pub fn declarations() -> String {
355    use std::fmt::Write as _;
356    let mut types = TsTypes::default();
357    let (mut path, mut context, mut properties) = (Vec::new(), Vec::new(), Vec::new());
358    PathOp::methods(&mut types, &mut path);
359    CanvasOp::methods(&mut types, &mut context);
360    CanvasOp::properties(&mut types, &mut properties);
361    let mut out = String::from(
362        "/** A number in a drawing: a constant, or an animated value the canvas reads\n \
363         * while it draws (its animations redraw natively, without JS). */\n\
364         export type CanvasNumber = number | AnimatedNode;\n",
365    );
366    for declaration in types.declarations() {
367        let _ = write!(out, "\n{declaration}\n");
368    }
369    let methods = |out: &mut String, iface: &str, doc: &str, list: &[OpMethod]| {
370        let _ = write!(out, "\n/** {doc} */\nexport interface {iface} {{\n");
371        for m in list {
372            let params = m
373                .params
374                .iter()
375                .map(|p| {
376                    format!(
377                        "{}{}: {}",
378                        p.name,
379                        if p.default.is_some() { "?" } else { "" },
380                        p.ts
381                    )
382                })
383                .collect::<Vec<_>>()
384                .join(", ");
385            let _ = writeln!(out, "  /** {} */\n  {}({params}): void;", m.doc, m.name);
386        }
387        out.push_str("}\n");
388    };
389    methods(
390        &mut out,
391        "CanvasPathMethods",
392        "Path building, shared by the context (its current path) and `Path2D`.",
393        &path,
394    );
395    methods(
396        &mut out,
397        "CanvasContextMethods",
398        "The context's transforms and rectangles.",
399        &context,
400    );
401    out.push_str("\n/** The drawing state kept as set. */\nexport interface CanvasProperties {\n");
402    for p in &properties {
403        let _ = writeln!(out, "  /** {} */\n  {}: {};", p.doc, p.name, p.ts);
404    }
405    out.push_str("}\n");
406    out
407}