1mod damage;
9mod hit;
10
11use std::sync::Arc;
12
13pub use self::{
14 damage::{Damage, DamageScan},
15 hit::{point_in_path, point_in_stroke},
16};
17use crate::{
18 geometry::{Bounds, Corners, Percentage, Point, Points, Radians, ScaledPixels, Size, px},
19 js::{
20 canvas::*,
21 host::{HostInput, HostList},
22 ops::{JsOps, OpArg, OpReader, OpsError},
23 },
24 style::{Color, FontVariant},
25 ui::{PropEnum, TsTypes},
26};
27
28#[derive(Debug, Clone, Copy, PartialEq)]
31pub enum Num {
32 Const(f32),
34 Slot(u16),
36}
37
38impl Num {
39 #[inline]
41 pub fn get(self, slot: impl Fn(u16) -> f32) -> f32 {
42 match self {
43 Num::Const(v) => v,
44 Num::Slot(s) => slot(s),
45 }
46 }
47}
48
49impl Default for Num {
50 fn default() -> Self {
51 Num::Const(0.0)
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, JsOps)]
57#[ops(cx = Drawing)]
58pub enum PathOp {
59 #[op(code = CV_MOVE_TO, method = "moveTo", params = "x, y")]
61 MoveTo(Num, Num),
62 #[op(code = CV_LINE_TO, method = "lineTo", params = "x, y")]
64 LineTo(Num, Num),
65 #[op(code = CV_QUAD_TO, method = "quadraticCurveTo", params = "cpx, cpy, x, y")]
68 QuadTo([Num; 4]),
69 #[op(
72 code = CV_CUBIC_TO,
73 method = "bezierCurveTo",
74 params = "cp1x, cp1y, cp2x, cp2y, x, y"
75 )]
76 CubicTo([Num; 6]),
77 #[op(
80 code = CV_ARC,
81 method = "arc",
82 params = "x, y, radius, startAngle, endAngle, counterclockwise = false"
83 )]
84 Arc {
85 x: Num,
87 y: Num,
89 radius: Num,
91 start: Num,
93 end: Num,
95 ccw: bool,
97 },
98 #[op(code = CV_ARC_TO, method = "arcTo", params = "x1, y1, x2, y2, radius")]
101 ArcTo([Num; 5]),
102 #[op(
105 code = CV_ELLIPSE,
106 method = "ellipse",
107 params = "x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise = false"
108 )]
109 Ellipse {
110 geometry: [Num; 5],
112 start: Num,
114 end: Num,
116 ccw: bool,
118 },
119 #[op(code = CV_RECT, method = "rect", params = "x, y, w, h")]
121 Rect([Num; 4]),
122 #[op(code = CV_ROUND_RECT)]
125 RoundRect([Num; 4], [Num; 4]),
126 #[op(code = CV_CLOSE, method = "closePath")]
128 Close,
129}
130
131pub type Path = Arc<[PathOp]>;
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
136pub enum FillRule {
137 #[default]
139 #[prop(rename = "nonzero")]
140 NonZero,
141 #[prop(rename = "evenodd")]
143 EvenOdd,
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
148pub enum LineCap {
149 #[default]
151 Butt,
152 Round,
154 Square,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
160pub enum LineJoin {
161 #[default]
163 Miter,
164 Round,
166 Bevel,
168}
169
170#[derive(Debug, Clone, Copy, PartialEq)]
172pub enum GradientShape {
173 Linear {
175 start: Point<Points>,
177 end: Point<Points>,
179 },
180 Radial {
182 start: Point<Points>,
184 start_radius: Points,
186 end: Point<Points>,
188 end_radius: Points,
190 },
191 Conic {
193 start_angle: Radians,
195 center: Point<Points>,
197 },
198}
199
200#[derive(Debug, Clone, PartialEq)]
202pub struct CanvasGradient {
203 pub shape: GradientShape,
205 pub stops: Vec<(Percentage, Color)>,
207}
208
209impl CanvasGradient {
210 fn new(shape: GradientShape) -> Self {
211 Self {
212 shape,
213 stops: Vec::new(),
214 }
215 }
216
217 pub fn linear(start: Point<Points>, end: Point<Points>) -> Self {
219 Self::new(GradientShape::Linear { start, end })
220 }
221
222 pub fn radial(
225 start: Point<Points>,
226 start_radius: Points,
227 end: Point<Points>,
228 end_radius: Points,
229 ) -> Self {
230 Self::new(GradientShape::Radial {
231 start,
232 start_radius,
233 end,
234 end_radius,
235 })
236 }
237
238 pub fn conic(start_angle: Radians, center: Point<Points>) -> Self {
241 Self::new(GradientShape::Conic {
242 start_angle,
243 center,
244 })
245 }
246
247 pub fn add_color_stop(mut self, offset: Percentage, color: impl Into<crate::Hsla>) -> Self {
250 let offset = offset.clamp(Percentage(0.0), Percentage(1.0));
251 let at = self.stops.partition_point(|(o, _)| *o <= offset);
252 self.stops.insert(at, (offset, Color::from(color.into())));
253 self
254 }
255}
256
257#[derive(Debug, Clone, PartialEq)]
259pub enum Paint {
260 Color(Color),
262 Slot(u16),
264 Gradient(Arc<CanvasGradient>),
266}
267
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
270#[allow(missing_docs)]
271pub enum Composite {
272 #[default]
273 SourceOver,
274 SourceIn,
275 SourceOut,
276 SourceAtop,
277 DestinationOver,
278 DestinationIn,
279 DestinationOut,
280 DestinationAtop,
281 Lighter,
282 Copy,
283 Xor,
284 Multiply,
285 Screen,
286 Overlay,
287 Darken,
288 Lighten,
289 ColorDodge,
290 ColorBurn,
291 HardLight,
292 SoftLight,
293 Difference,
294 Exclusion,
295 Hue,
296 Saturation,
297 Color,
298 Luminosity,
299}
300
301impl Composite {
302 pub fn parse(name: &str) -> Option<Composite> {
304 use Composite::*;
305 Some(match name {
306 "source-over" => SourceOver,
307 "source-in" => SourceIn,
308 "source-out" => SourceOut,
309 "source-atop" => SourceAtop,
310 "destination-over" => DestinationOver,
311 "destination-in" => DestinationIn,
312 "destination-out" => DestinationOut,
313 "destination-atop" => DestinationAtop,
314 "lighter" => Lighter,
315 "copy" => Copy,
316 "xor" => Xor,
317 "multiply" => Multiply,
318 "screen" => Screen,
319 "overlay" => Overlay,
320 "darken" => Darken,
321 "lighten" => Lighten,
322 "color-dodge" => ColorDodge,
323 "color-burn" => ColorBurn,
324 "hard-light" => HardLight,
325 "soft-light" => SoftLight,
326 "difference" => Difference,
327 "exclusion" => Exclusion,
328 "hue" => Hue,
329 "saturation" => Saturation,
330 "color" => Color,
331 "luminosity" => Luminosity,
332 _ => return None,
333 })
334 }
335}
336
337#[derive(Debug, Clone, PartialEq)]
339pub struct CanvasFont {
340 pub size: Points,
342 pub weight: u16,
344 pub italic: bool,
346 pub family: Option<Arc<str>>,
349 pub variant: FontVariant,
353}
354
355impl Default for CanvasFont {
356 fn default() -> Self {
358 Self {
359 size: px(10.0),
360 weight: 400,
361 italic: false,
362 family: None,
363 variant: FontVariant::default(),
364 }
365 }
366}
367
368impl CanvasFont {
369 pub fn parse(s: &str) -> Option<CanvasFont> {
373 let mut font = CanvasFont {
374 size: Points::ZERO,
375 ..CanvasFont::default()
376 };
377 let mut rest = s.trim();
378 loop {
380 let (word, tail) = match rest.split_once(char::is_whitespace) {
381 Some((w, t)) => (w, t.trim_start()),
382 None => (rest, ""),
383 };
384 if let Some(size) = font_size(word) {
385 font.size = size;
386 rest = tail;
387 break;
388 }
389 match word {
390 "italic" | "oblique" => font.italic = true,
391 "normal" | "condensed" | "expanded" => {}
392 w if let Some(v) = FontVariant::parse(w) => font.variant.0 |= v.0,
393 "bold" | "bolder" => font.weight = 700,
394 "lighter" => font.weight = 300,
395 w => match w.parse::<u16>() {
396 Ok(n) if (1..=1000).contains(&n) => font.weight = n,
397 _ => return None,
398 },
399 }
400 if tail.is_empty() {
401 return None;
402 }
403 rest = tail;
404 }
405 let family = rest
406 .split(',')
407 .next()
408 .map(|f| f.trim().trim_matches(['"', '\'']))
409 .filter(|f| !f.is_empty())?;
410 font.family = match family {
411 "system-ui" | "sans-serif" | "-apple-system" | "ui-sans-serif" => None,
412 f => Some(f.into()),
413 };
414 Some(font)
415 }
416}
417
418fn font_size(word: &str) -> Option<Points> {
420 let word = word.split('/').next()?;
421 let (num, scale) = if let Some(n) = word.strip_suffix("px") {
422 (n, 1.0)
423 } else if let Some(n) = word.strip_suffix("rem").or_else(|| word.strip_suffix("em")) {
424 (n, 16.0)
425 } else {
426 (word.strip_suffix("pt")?, 4.0 / 3.0)
427 };
428 num.parse::<f32>()
429 .ok()
430 .filter(|v| *v > 0.0)
431 .map(|v| Points(v * scale))
432}
433
434impl CanvasFont {
435 pub fn with_numeric(&self, numeric: FontVariant) -> CanvasFont {
438 let mut font = self.clone();
439 if numeric.0 != 0 {
440 font.variant = FontVariant(font.variant.0 & FontVariant::SMALL_CAPS | numeric.0);
441 }
442 font
443 }
444
445 pub fn text_style(&self) -> crate::text::ResolvedTextStyle {
447 crate::text::ResolvedTextStyle {
448 font_size: self.size,
449 font_weight: self.weight,
450 italic: self.italic,
451 font_variant: self.variant,
452 font_family: self.family.as_deref().map(crate::style::FontFamily::new),
453 ..Default::default()
454 }
455 }
456}
457
458pub fn measure_line(
460 engine: &impl crate::text::TextEngine,
461 font: &CanvasFont,
462 text: &str,
463) -> Points {
464 let mut attributed = crate::text::AttributedText {
465 no_wrap: true,
466 max_lines: 1,
467 ..Default::default()
468 };
469 attributed.push(text, font.text_style());
470 if attributed.text.is_empty() {
471 return Points::ZERO;
472 }
473 let prepared = engine.prepare(&attributed);
474 engine.measure(&prepared, None).width
475}
476
477#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
479pub enum CanvasTextAlign {
480 #[default]
482 Start,
483 End,
485 Left,
487 Right,
489 Center,
491}
492
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
495pub enum CanvasTextBaseline {
496 #[default]
498 Alphabetic,
499 Top,
501 Hanging,
503 Middle,
505 Ideographic,
507 Bottom,
509}
510
511#[derive(Debug, Clone, PartialEq)]
513pub struct CanvasImage {
514 pub uri: Arc<str>,
516}
517
518#[derive(Debug, Clone, PartialEq, JsOps)]
522#[ops(cx = Drawing)]
523pub enum CanvasOp {
524 #[op(code = CV_SAVE)]
526 Save,
527 #[op(code = CV_RESTORE)]
529 Restore,
530 #[op(code = CV_TRANSLATE, method = "translate", params = "x, y")]
532 Translate(Num, Num),
533 #[op(code = CV_SCALE, method = "scale", params = "x, y")]
535 Scale(Num, Num),
536 #[op(code = CV_ROTATE, method = "rotate", params = "angle")]
538 Rotate(Num),
539 #[op(code = CV_TRANSFORM, method = "transform", params = "a, b, c, d, e, f")]
542 Transform([Num; 6]),
543 #[op(code = CV_SET_TRANSFORM, method = "setTransform", params = "a, b, c, d, e, f")]
548 SetTransform([Num; 6]),
549 #[op(code = CV_BEGIN_PATH, method = "beginPath")]
551 BeginPath,
552 #[op(nested)]
554 Path(PathOp),
555 #[op(code = CV_FILL)]
557 Fill(Option<Path>, FillRule),
558 #[op(code = CV_STROKE)]
560 Stroke(Option<Path>),
561 #[op(code = CV_CLIP)]
563 Clip(Option<Path>, FillRule),
564 #[op(code = CV_FILL_RECT, method = "fillRect", params = "x, y, w, h")]
567 FillRect([Num; 4]),
568 #[op(code = CV_STROKE_RECT, method = "strokeRect", params = "x, y, w, h")]
570 StrokeRect([Num; 4]),
571 #[op(code = CV_CLEAR_RECT, method = "clearRect", params = "x, y, w, h")]
573 ClearRect([Num; 4]),
574 #[op(code = CV_FILL_STYLE)]
576 FillStyle(Paint),
577 #[op(code = CV_STROKE_STYLE)]
579 StrokeStyle(Paint),
580 #[op(code = CV_LINE_WIDTH, property = "lineWidth", initial = "1")]
582 LineWidth(Num),
583 #[op(code = CV_LINE_CAP, property = "lineCap", initial = "\"butt\"")]
585 LineCap(LineCap),
586 #[op(code = CV_LINE_JOIN, property = "lineJoin", initial = "\"miter\"")]
588 LineJoin(LineJoin),
589 #[op(code = CV_MITER_LIMIT, property = "miterLimit", initial = "10", min = 1.0)]
592 MiterLimit(f32),
593 #[op(code = CV_LINE_DASH, with = crate::js::canvas::line_dash)]
595 LineDash(Arc<[Points]>),
596 #[op(code = CV_LINE_DASH_OFFSET, property = "lineDashOffset", initial = "0")]
598 LineDashOffset(Num),
599 #[op(code = CV_GLOBAL_ALPHA, property = "globalAlpha", initial = "1")]
601 GlobalAlpha(Num),
602 #[op(
605 code = CV_COMPOSITE,
606 property = "globalCompositeOperation",
607 initial = "\"source-over\""
608 )]
609 Composite(Composite),
610 #[op(code = CV_SHADOW_COLOR, property = "shadowColor", initial = "\"rgba(0,0,0,0)\"")]
612 ShadowColor(Color),
613 #[op(code = CV_SHADOW_BLUR, property = "shadowBlur", initial = "0", min = 0.0)]
615 ShadowBlur(Points),
616 #[op(code = CV_SHADOW_OFFSET)]
618 ShadowOffset(Point<Points>),
619 #[op(code = CV_FONT, property = "font", initial = "\"10px sans-serif\"")]
622 Font(CanvasFont),
623 #[op(
628 code = CV_FONT_VARIANT_NUMERIC,
629 property = "fontVariantNumeric",
630 initial = "\"normal\""
631 )]
632 FontVariantNumeric(FontVariant),
633 #[op(code = CV_TEXT_ALIGN, property = "textAlign", initial = "\"start\"")]
635 TextAlign(CanvasTextAlign),
636 #[op(code = CV_TEXT_BASELINE, property = "textBaseline", initial = "\"alphabetic\"")]
638 TextBaseline(CanvasTextBaseline),
639 #[op(code = CV_FILL_TEXT)]
641 FillText {
642 text: Arc<str>,
644 x: Num,
646 y: Num,
648 max_width: Option<Points>,
650 },
651 #[op(code = CV_STROKE_TEXT)]
653 StrokeText {
654 text: Arc<str>,
656 x: Num,
658 y: Num,
660 max_width: Option<Points>,
662 },
663 #[op(code = CV_DRAW_IMAGE)]
665 DrawImage {
666 image: CanvasImage,
668 source: Option<Bounds<ScaledPixels>>,
670 dest: [Num; 4],
672 },
673}
674
675#[derive(Debug, Clone, PartialEq, Default)]
677pub struct Drawing {
678 pub ops: Vec<CanvasOp>,
680 pub slots: Vec<crate::animation::NodeId>,
682}
683
684impl Drawing {
685 pub fn slot(&mut self, node: crate::animation::NodeId) -> u16 {
687 match self.slots.iter().position(|&n| n == node) {
688 Some(i) => i as u16,
689 None => {
690 self.slots.push(node);
691 (self.slots.len() - 1) as u16
692 }
693 }
694 }
695
696 pub fn images(&self) -> impl Iterator<Item = &CanvasImage> {
698 self.ops.iter().filter_map(|op| match op {
699 CanvasOp::DrawImage { image, .. } => Some(image),
700 _ => None,
701 })
702 }
703}
704
705impl<Cx> OpArg<Cx> for Points {
707 fn read<L: HostList<Item: HostInput>>(
708 r: &mut OpReader<'_, L>,
709 cx: &mut Cx,
710 ) -> Result<Option<Self>, OpsError> {
711 Ok(<f32 as OpArg<Cx>>::read(r, cx)?.map(Points))
712 }
713
714 fn ts(types: &mut TsTypes) -> String {
715 <f32 as OpArg<Cx>>::ts(types)
716 }
717}
718
719impl<Cx> OpArg<Cx> for Option<Points> {
721 fn read<L: HostList<Item: HostInput>>(
722 r: &mut OpReader<'_, L>,
723 cx: &mut Cx,
724 ) -> Result<Option<Self>, OpsError> {
725 Ok(<Option<f32> as OpArg<Cx>>::read(r, cx)?.map(|v| v.map(Points)))
726 }
727
728 fn ts(types: &mut TsTypes) -> String {
729 <Option<f32> as OpArg<Cx>>::ts(types)
730 }
731}
732
733impl<Cx> OpArg<Cx> for Point<Points> {
735 const ARITY: usize = 2;
736
737 fn read<L: HostList<Item: HostInput>>(
738 r: &mut OpReader<'_, L>,
739 cx: &mut Cx,
740 ) -> Result<Option<Self>, OpsError> {
741 let x = <Points as OpArg<Cx>>::read(r, cx)?;
742 let y = <Points as OpArg<Cx>>::read(r, cx)?;
743 Ok(x.zip(y).map(|(x, y)| Point { x, y }))
744 }
745
746 fn ts(types: &mut TsTypes) -> String {
747 <Points as OpArg<Cx>>::ts(types)
748 }
749}
750
751pub fn arc_sweep(start: Radians, end: Radians, ccw: bool) -> Radians {
756 Radians(sweep(start.0, end.0, ccw))
757}
758
759pub(crate) fn sweep(start: f32, end: f32, ccw: bool) -> f32 {
760 use std::f32::consts::TAU;
761 if !ccw {
762 if end - start >= TAU {
763 TAU
764 } else {
765 (end - start).rem_euclid(TAU)
766 }
767 } else if start - end >= TAU {
768 -TAU
769 } else {
770 -(start - end).rem_euclid(TAU)
771 }
772}
773
774pub fn fit_radii(size: Size<Points>, radii: Corners<Points>) -> Corners<Points> {
778 let [tl, tr, br, bl] = fit(
779 size.width.0,
780 size.height.0,
781 [
782 radii.top_left.0,
783 radii.top_right.0,
784 radii.bottom_right.0,
785 radii.bottom_left.0,
786 ],
787 );
788 Corners {
789 top_left: Points(tl),
790 top_right: Points(tr),
791 bottom_right: Points(br),
792 bottom_left: Points(bl),
793 }
794}
795
796pub(crate) fn fit(w: f32, h: f32, radii: [f32; 4]) -> [f32; 4] {
799 let r = radii.map(|r| r.max(0.0));
800 let (w, h) = (w.abs(), h.abs());
801 let sides = [r[0] + r[1], r[2] + r[3], r[0] + r[3], r[1] + r[2]];
802 let limits = [w, w, h, h];
803 let scale = sides
804 .iter()
805 .zip(limits)
806 .filter(|(s, _)| **s > 0.0)
807 .map(|(s, l)| l / s)
808 .fold(1.0f32, f32::min);
809 r.map(|r| r * scale)
810}
811
812pub fn svg_path(d: &str) -> Path {
817 parse_svg_path(d).into()
818}
819
820pub fn parse_svg_path(d: &str) -> Vec<PathOp> {
824 let mut out = Vec::new();
825 let mut p = PathParser {
826 s: d.as_bytes(),
827 pos: 0,
828 };
829 let (mut x, mut y) = (0f32, 0f32);
830 let (mut sx, mut sy) = (0f32, 0f32);
831 let mut last_cubic: Option<(f32, f32)> = None;
833 let mut last_quad: Option<(f32, f32)> = None;
834 let mut command = 0u8;
835 let c = |v: f32| Num::Const(v);
836 loop {
837 p.skip_separators();
838 if p.pos >= p.s.len() {
839 break;
840 }
841 let b = p.s[p.pos];
842 if b.is_ascii_alphabetic() {
843 command = b;
844 p.pos += 1;
845 } else if command == 0 {
846 break;
847 } else if command == b'M' {
848 command = b'L';
850 } else if command == b'm' {
851 command = b'l';
852 }
853 let rel = command.is_ascii_lowercase();
854 let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) };
855 let upper = command.to_ascii_uppercase();
856 let ok = (|| -> Option<()> {
857 match upper {
858 b'M' => {
859 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
860 out.push(PathOp::MoveTo(c(nx), c(ny)));
861 (x, y, sx, sy) = (nx, ny, nx, ny);
862 last_cubic = None;
863 last_quad = None;
864 }
865 b'L' => {
866 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
867 out.push(PathOp::LineTo(c(nx), c(ny)));
868 (x, y) = (nx, ny);
869 last_cubic = None;
870 last_quad = None;
871 }
872 b'H' => {
873 x = p.number()? + ox;
874 out.push(PathOp::LineTo(c(x), c(y)));
875 last_cubic = None;
876 last_quad = None;
877 }
878 b'V' => {
879 y = p.number()? + oy;
880 out.push(PathOp::LineTo(c(x), c(y)));
881 last_cubic = None;
882 last_quad = None;
883 }
884 b'C' | b'S' => {
885 let (x1, y1) = if upper == b'C' {
886 (p.number()? + ox, p.number()? + oy)
887 } else {
888 last_cubic.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
890 };
891 let (x2, y2) = (p.number()? + ox, p.number()? + oy);
892 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
893 out.push(PathOp::CubicTo([x1, y1, x2, y2, nx, ny].map(c)));
894 last_cubic = Some((x2, y2));
895 last_quad = None;
896 (x, y) = (nx, ny);
897 }
898 b'Q' | b'T' => {
899 let (x1, y1) = if upper == b'Q' {
900 (p.number()? + ox, p.number()? + oy)
901 } else {
902 last_quad.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
903 };
904 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
905 out.push(PathOp::QuadTo([x1, y1, nx, ny].map(c)));
906 last_quad = Some((x1, y1));
907 last_cubic = None;
908 (x, y) = (nx, ny);
909 }
910 b'A' => {
911 let rx = p.number()?.abs();
912 let ry = p.number()?.abs();
913 let rotation = p.number()?;
914 let large = p.flag()?;
915 let sweep = p.flag()?;
916 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
917 arc_to_cubics(&mut out, (x, y), (rx, ry), rotation, large, sweep, (nx, ny));
918 (x, y) = (nx, ny);
919 last_cubic = None;
920 last_quad = None;
921 }
922 b'Z' => {
923 out.push(PathOp::Close);
924 (x, y) = (sx, sy);
925 last_cubic = None;
926 last_quad = None;
927 command = 0;
929 }
930 _ => return None,
931 }
932 Some(())
933 })();
934 if ok.is_none() {
935 break;
936 }
937 }
938 out
939}
940
941struct PathParser<'a> {
942 s: &'a [u8],
943 pos: usize,
944}
945
946impl PathParser<'_> {
947 fn skip_separators(&mut self) {
948 while self.pos < self.s.len()
949 && (self.s[self.pos].is_ascii_whitespace() || self.s[self.pos] == b',')
950 {
951 self.pos += 1;
952 }
953 }
954
955 fn number(&mut self) -> Option<f32> {
956 self.skip_separators();
957 let start = self.pos;
958 let s = self.s;
959 let mut i = self.pos;
960 if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
961 i += 1;
962 }
963 let mut digits = false;
964 while i < s.len() && s[i].is_ascii_digit() {
965 i += 1;
966 digits = true;
967 }
968 if i < s.len() && s[i] == b'.' {
969 i += 1;
970 while i < s.len() && s[i].is_ascii_digit() {
971 i += 1;
972 digits = true;
973 }
974 }
975 if !digits {
976 return None;
977 }
978 if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
979 let mut j = i + 1;
980 if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
981 j += 1;
982 }
983 if j < s.len() && s[j].is_ascii_digit() {
984 while j < s.len() && s[j].is_ascii_digit() {
985 j += 1;
986 }
987 i = j;
988 }
989 }
990 self.pos = i;
991 std::str::from_utf8(&s[start..i]).ok()?.parse().ok()
992 }
993
994 fn flag(&mut self) -> Option<bool> {
996 self.skip_separators();
997 let b = *self.s.get(self.pos)?;
998 self.pos += 1;
999 match b {
1000 b'0' => Some(false),
1001 b'1' => Some(true),
1002 _ => None,
1003 }
1004 }
1005}
1006
1007fn arc_to_cubics(
1010 out: &mut Vec<PathOp>,
1011 from: (f32, f32),
1012 radii: (f32, f32),
1013 rotation_deg: f32,
1014 large: bool,
1015 sweep: bool,
1016 to: (f32, f32),
1017) {
1018 let c = |v: f64| Num::Const(v as f32);
1019 let (x1, y1) = (from.0 as f64, from.1 as f64);
1020 let (x2, y2) = (to.0 as f64, to.1 as f64);
1021 let (mut rx, mut ry) = (radii.0 as f64, radii.1 as f64);
1022 if (x1 == x2 && y1 == y2) || rx == 0.0 || ry == 0.0 {
1023 if x1 != x2 || y1 != y2 {
1024 out.push(PathOp::LineTo(c(x2), c(y2)));
1025 }
1026 return;
1027 }
1028 let phi = (rotation_deg as f64).to_radians();
1029 let (sin, cos) = phi.sin_cos();
1030 let dx = (x1 - x2) / 2.0;
1031 let dy = (y1 - y2) / 2.0;
1032 let x1p = cos * dx + sin * dy;
1033 let y1p = -sin * dx + cos * dy;
1034 let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
1036 if lambda > 1.0 {
1037 let s = lambda.sqrt();
1038 rx *= s;
1039 ry *= s;
1040 }
1041 let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
1042 let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
1043 let mut coef = (num / den).max(0.0).sqrt();
1044 if large == sweep {
1045 coef = -coef;
1046 }
1047 let cxp = coef * rx * y1p / ry;
1048 let cyp = -coef * ry * x1p / rx;
1049 let cx = cos * cxp - sin * cyp + (x1 + x2) / 2.0;
1050 let cy = sin * cxp + cos * cyp + (y1 + y2) / 2.0;
1051 let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
1052 let theta1 = angle(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
1053 let mut delta = angle(
1054 (x1p - cxp) / rx,
1055 (y1p - cyp) / ry,
1056 (-x1p - cxp) / rx,
1057 (-y1p - cyp) / ry,
1058 );
1059 if !sweep && delta > 0.0 {
1060 delta -= std::f64::consts::TAU;
1061 } else if sweep && delta < 0.0 {
1062 delta += std::f64::consts::TAU;
1063 }
1064 let segments = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
1066 let step = delta / segments as f64;
1067 let k = 4.0 / 3.0 * (step / 4.0).tan();
1068 let point = |t: f64| {
1069 let (s, co) = t.sin_cos();
1070 (
1071 cx + rx * co * cos - ry * s * sin,
1072 cy + rx * co * sin + ry * s * cos,
1073 )
1074 };
1075 let derivative = |t: f64| {
1076 let (s, co) = t.sin_cos();
1077 (-rx * s * cos - ry * co * sin, -rx * s * sin + ry * co * cos)
1078 };
1079 let mut t = theta1;
1080 for i in 0..segments {
1081 let t2 = t + step;
1082 let (p1x, p1y) = point(t);
1083 let (d1x, d1y) = derivative(t);
1084 let (p2x, p2y) = if i + 1 == segments {
1085 (x2, y2)
1086 } else {
1087 point(t2)
1088 };
1089 let (d2x, d2y) = derivative(t2);
1090 out.push(PathOp::CubicTo([
1091 c(p1x + k * d1x),
1092 c(p1y + k * d1y),
1093 c(p2x - k * d2x),
1094 c(p2y - k * d2y),
1095 c(p2x),
1096 c(p2y),
1097 ]));
1098 t = t2;
1099 }
1100}
1101
1102#[cfg(test)]
1103mod tests {
1104 use super::*;
1105
1106 fn consts(op: &PathOp) -> Vec<f32> {
1107 let v = |n: &Num| match n {
1108 Num::Const(v) => *v,
1109 Num::Slot(_) => f32::NAN,
1110 };
1111 match op {
1112 PathOp::MoveTo(a, b) | PathOp::LineTo(a, b) => vec![v(a), v(b)],
1113 PathOp::QuadTo(n) => n.iter().map(v).collect(),
1114 PathOp::CubicTo(n) => n.iter().map(v).collect(),
1115 _ => vec![],
1116 }
1117 }
1118
1119 #[test]
1120 fn svg_paths_parse_to_absolute_ops() {
1121 let ops = parse_svg_path("M10 20 l5-5 H30 v10 z m1 1 2 2");
1122 assert_eq!(ops.len(), 7);
1123 assert_eq!(consts(&ops[1]), vec![15.0, 15.0]);
1124 assert_eq!(consts(&ops[2]), vec![30.0, 15.0]);
1125 assert_eq!(consts(&ops[3]), vec![30.0, 25.0]);
1126 assert_eq!(ops[4], PathOp::Close);
1127 assert_eq!(consts(&ops[5]), vec![11.0, 21.0]);
1129 assert_eq!(consts(&ops[6]), vec![13.0, 23.0]);
1131 let ops = parse_svg_path("M.5.5L1e1-2");
1133 assert_eq!(consts(&ops[0]), vec![0.5, 0.5]);
1134 assert_eq!(consts(&ops[1]), vec![10.0, -2.0]);
1135 }
1136
1137 #[test]
1138 fn smooth_curves_reflect_control_points() {
1139 let ops = parse_svg_path("M0 0 C0 10 10 10 10 0 S20 -10 20 0");
1140 assert_eq!(consts(&ops[2]), vec![10.0, -10.0, 20.0, -10.0, 20.0, 0.0]);
1141 }
1142
1143 #[test]
1144 fn arcs_become_cubics_ending_on_the_point() {
1145 let ops = parse_svg_path("M0 0 A10 10 0 0120 0");
1147 assert_eq!(ops.len(), 3);
1148 let last = consts(&ops[2]);
1149 assert!((last[4] - 20.0).abs() < 1e-4 && last[5].abs() < 1e-4);
1150 let mid = consts(&ops[1]);
1152 assert!((mid[4] - 10.0).abs() < 1e-3 && (mid[5] + 10.0).abs() < 1e-3);
1153 }
1154
1155 #[test]
1156 fn bad_path_data_keeps_what_parsed() {
1157 let ops = parse_svg_path("M0 0 L10 10 L oops");
1158 assert_eq!(ops.len(), 2);
1159 }
1160
1161 #[test]
1162 fn arc_sweeps_follow_the_canvas_spec() {
1163 use std::f32::consts::{PI, TAU};
1164
1165 use crate::geometry::{radians, size};
1166 let sweep = |a, b, ccw| arc_sweep(radians(a), radians(b), ccw).0;
1167 assert_eq!(sweep(0.0, PI, false), PI);
1168 assert!((sweep(PI, 0.0, false) - PI).abs() < 1e-6);
1170 assert!((sweep(0.0, -PI / 2.0, false) - 1.5 * PI).abs() < 1e-5);
1171 assert_eq!(sweep(0.0, 3.0 * TAU, false), TAU);
1172 assert!((sweep(0.0, PI / 2.0, true) + 1.5 * PI).abs() < 1e-5);
1173 assert_eq!(sweep(TAU, 0.0, true), -TAU);
1174 let corners = |[top_left, top_right, bottom_right, bottom_left]: [f32; 4]| Corners {
1175 top_left: px(top_left),
1176 top_right: px(top_right),
1177 bottom_right: px(bottom_right),
1178 bottom_left: px(bottom_left),
1179 };
1180 assert_eq!(
1181 fit_radii(size(px(10.0), px(100.0)), corners([8.0, 8.0, 0.0, 0.0])),
1182 corners([5.0, 5.0, 0.0, 0.0])
1183 );
1184 }
1185
1186 #[test]
1187 fn fonts_parse_the_css_shorthand() {
1188 let f = CanvasFont::parse("italic bold 14px \"Inter\", sans-serif").unwrap();
1189 assert_eq!((f.size, f.weight, f.italic), (px(14.0), 700, true));
1190 assert_eq!(f.family.as_deref(), Some("Inter"));
1191 let f = CanvasFont::parse("600 12px/1.5 system-ui").unwrap();
1192 assert_eq!((f.size, f.weight, f.family), (px(12.0), 600, None));
1193 let f = CanvasFont::parse("small-caps tabular-nums 13px system-ui").unwrap();
1194 assert_eq!(
1195 f.variant.0,
1196 FontVariant::SMALL_CAPS | FontVariant::TABULAR_NUMS
1197 );
1198 let numeric = f.with_numeric(FontVariant(FontVariant::OLDSTYLE_NUMS));
1199 assert_eq!(
1200 numeric.variant.0,
1201 FontVariant::SMALL_CAPS | FontVariant::OLDSTYLE_NUMS
1202 );
1203 assert_eq!(f.with_numeric(FontVariant::default()), f);
1204 assert!(CanvasFont::parse("wide 13px system-ui").is_none());
1205 assert!(CanvasFont::parse("bold").is_none());
1206 assert!(CanvasFont::parse("14px").is_none());
1207 }
1208}