1mod damage;
9mod hit;
10
11use std::sync::Arc;
12
13pub use self::{
14 damage::{Damage, DamageScan, first_animated, prefix_path_needed},
15 hit::{point_in_path, point_in_stroke},
16};
17use crate::{
18 element::{PropEnum, TsTypes},
19 geometry::{Bounds, Corners, Percentage, Point, Points, Radians, ScaledPixels, Size, px},
20 js::{
21 canvas::*,
22 host::{HostInput, HostList},
23 ops::{JsOps, OpArg, OpReader, OpsError},
24 },
25 style::{Color, FontVariant},
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 pub fn from_css(gradient: &crate::effects::Gradient, area: Bounds<Points>) -> Option<Self> {
263 use crate::{effects::GradientKind, geometry::point};
264 let size = area.size;
265 let (w, h) = (size.width.0, size.height.0);
266 let (left, top) = (area.origin.x.0, area.origin.y.0);
267 let at = |x: f32, y: f32| point(px(x), px(y));
268 let shape = match gradient.kind {
269 GradientKind::Radial { circle: false, .. } => return None,
270 GradientKind::Radial { x, y, .. } => {
271 let center = at(left + x.0 * w, top + y.0 * h);
272 GradientShape::Radial {
273 start: center,
274 start_radius: Points::ZERO,
275 end: center,
276 end_radius: gradient.line_length(size),
277 }
278 }
279 GradientKind::Conic { from, x, y } => GradientShape::Conic {
282 start_angle: Radians(from.0 - std::f32::consts::FRAC_PI_2),
283 center: at(left + x.0 * w, top + y.0 * h),
284 },
285 kind => {
286 let angle = kind
289 .linear_angle(size)
290 .unwrap_or(Radians(std::f32::consts::PI));
291 let exact = |v: f32| {
295 if v.abs() < 1e-6 {
296 0.0
297 } else if (v.abs() - 1.0).abs() < 1e-6 {
298 v.signum()
299 } else {
300 v
301 }
302 };
303 let (sin, cos) = angle.sin_cos();
304 let (sin, cos) = (exact(sin), exact(cos));
305 let half = ((w * sin).abs() + (h * cos).abs()) / 2.0;
307 let (cx, cy) = (left + w / 2.0, top + h / 2.0);
308 GradientShape::Linear {
309 start: at(cx - sin * half, cy + cos * half),
310 end: at(cx + sin * half, cy - cos * half),
311 }
312 }
313 };
314 let mut stops = gradient.unrolled_stops(size, Percentage(1.0));
315 if !stops.iter().all(|s| (0.0..=1.0).contains(&s.1.0)) {
318 stops = crate::effects::cut_stops(&stops, Percentage(1.0));
319 }
320 let mut out = Self::new(shape);
321 out.stops = stops.into_iter().map(|(color, at)| (at, color)).collect();
322 Some(out)
323 }
324}
325
326#[derive(Debug, Clone, PartialEq)]
328pub enum Paint {
329 Color(Color),
331 Slot(u16),
333 Gradient(Arc<CanvasGradient>),
335}
336
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
339#[allow(missing_docs)]
340pub enum Composite {
341 #[default]
342 SourceOver,
343 SourceIn,
344 SourceOut,
345 SourceAtop,
346 DestinationOver,
347 DestinationIn,
348 DestinationOut,
349 DestinationAtop,
350 Lighter,
351 Copy,
352 Xor,
353 Multiply,
354 Screen,
355 Overlay,
356 Darken,
357 Lighten,
358 ColorDodge,
359 ColorBurn,
360 HardLight,
361 SoftLight,
362 Difference,
363 Exclusion,
364 Hue,
365 Saturation,
366 Color,
367 Luminosity,
368}
369
370impl Composite {
371 pub fn parse(name: &str) -> Option<Composite> {
373 use Composite::*;
374 Some(match name {
375 "source-over" => SourceOver,
376 "source-in" => SourceIn,
377 "source-out" => SourceOut,
378 "source-atop" => SourceAtop,
379 "destination-over" => DestinationOver,
380 "destination-in" => DestinationIn,
381 "destination-out" => DestinationOut,
382 "destination-atop" => DestinationAtop,
383 "lighter" => Lighter,
384 "copy" => Copy,
385 "xor" => Xor,
386 "multiply" => Multiply,
387 "screen" => Screen,
388 "overlay" => Overlay,
389 "darken" => Darken,
390 "lighten" => Lighten,
391 "color-dodge" => ColorDodge,
392 "color-burn" => ColorBurn,
393 "hard-light" => HardLight,
394 "soft-light" => SoftLight,
395 "difference" => Difference,
396 "exclusion" => Exclusion,
397 "hue" => Hue,
398 "saturation" => Saturation,
399 "color" => Color,
400 "luminosity" => Luminosity,
401 _ => return None,
402 })
403 }
404}
405
406#[derive(Debug, Clone, PartialEq)]
408pub struct CanvasFont {
409 pub size: Points,
411 pub weight: u16,
413 pub italic: bool,
415 pub family: Option<Arc<str>>,
418 pub variant: FontVariant,
422}
423
424impl Default for CanvasFont {
425 fn default() -> Self {
427 Self {
428 size: px(10.0),
429 weight: 400,
430 italic: false,
431 family: None,
432 variant: FontVariant::default(),
433 }
434 }
435}
436
437impl CanvasFont {
438 pub fn parse(s: &str) -> Option<CanvasFont> {
442 let mut font = CanvasFont {
443 size: Points::ZERO,
444 ..CanvasFont::default()
445 };
446 let mut rest = s.trim();
447 loop {
449 let (word, tail) = match rest.split_once(char::is_whitespace) {
450 Some((w, t)) => (w, t.trim_start()),
451 None => (rest, ""),
452 };
453 if let Some(size) = font_size(word) {
454 font.size = size;
455 rest = tail;
456 break;
457 }
458 match word {
459 "italic" | "oblique" => font.italic = true,
460 "normal" | "condensed" | "expanded" => {}
461 w if let Some(v) = FontVariant::parse(w) => font.variant.0 |= v.0,
462 "bold" | "bolder" => font.weight = 700,
463 "lighter" => font.weight = 300,
464 w => match w.parse::<u16>() {
465 Ok(n) if (1..=1000).contains(&n) => font.weight = n,
466 _ => return None,
467 },
468 }
469 if tail.is_empty() {
470 return None;
471 }
472 rest = tail;
473 }
474 let family = rest
475 .split(',')
476 .next()
477 .map(|f| f.trim().trim_matches(['"', '\'']))
478 .filter(|f| !f.is_empty())?;
479 font.family = match family {
480 "system-ui" | "sans-serif" | "-apple-system" | "ui-sans-serif" => None,
481 f => Some(f.into()),
482 };
483 Some(font)
484 }
485}
486
487fn font_size(word: &str) -> Option<Points> {
489 let word = word.split('/').next()?;
490 let (num, scale) = if let Some(n) = word.strip_suffix("px") {
491 (n, 1.0)
492 } else if let Some(n) = word.strip_suffix("rem").or_else(|| word.strip_suffix("em")) {
493 (n, 16.0)
494 } else {
495 (word.strip_suffix("pt")?, 4.0 / 3.0)
496 };
497 num.parse::<f32>()
498 .ok()
499 .filter(|v| *v > 0.0)
500 .map(|v| Points(v * scale))
501}
502
503impl CanvasFont {
504 pub fn with_numeric(&self, numeric: FontVariant) -> CanvasFont {
507 let mut font = self.clone();
508 if numeric.0 != 0 {
509 font.variant = FontVariant(font.variant.0 & FontVariant::SMALL_CAPS | numeric.0);
510 }
511 font
512 }
513
514 pub fn text_style(&self) -> crate::text::ResolvedTextStyle {
516 crate::text::ResolvedTextStyle {
517 font_size: self.size,
518 font_weight: self.weight,
519 italic: self.italic,
520 font_variant: self.variant,
521 font_family: self.family.as_deref().map(crate::style::FontFamily::new),
522 ..Default::default()
523 }
524 }
525}
526
527pub fn measure_line(
529 engine: &impl crate::text::TextEngine,
530 font: &CanvasFont,
531 text: &str,
532) -> Points {
533 if text.is_empty() {
534 return Points::ZERO;
535 }
536 advance(engine, font, text)
537}
538
539const MARK: &str = "x";
541
542fn advance(engine: &impl crate::text::TextEngine, font: &CanvasFont, text: &str) -> Points {
548 let width = |text: &str| {
549 let mut attributed = crate::text::AttributedText {
550 no_wrap: true,
551 max_lines: 1,
552 ..Default::default()
553 };
554 attributed.push(text, font.text_style());
555 let prepared = engine.prepare(&attributed);
556 engine.measure(&prepared, None).width
557 };
558 let hangs = text.ends_with(|c: char| c.is_whitespace() && !is_line_break(c));
560 if !hangs {
561 return width(text);
562 }
563 let mut marked = String::with_capacity(text.len() + MARK.len());
564 marked.push_str(text);
565 marked.push_str(MARK);
566 (width(&marked) - width(MARK)).max(Points::ZERO)
567}
568
569fn is_line_break(c: char) -> bool {
571 matches!(
572 c,
573 '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}'
574 )
575}
576
577#[derive(Debug, Clone, Copy, PartialEq, Default)]
581#[non_exhaustive]
582pub struct TextMetrics {
583 pub width: Points,
585 pub ascent: Points,
587 pub descent: Points,
589 pub height: Points,
591}
592
593pub fn line_metrics(
597 engine: &impl crate::text::TextEngine,
598 font: &CanvasFont,
599 text: &str,
600) -> TextMetrics {
601 let mut attributed = crate::text::AttributedText {
602 no_wrap: true,
603 max_lines: 1,
604 ..Default::default()
605 };
606 attributed.push(if text.is_empty() { " " } else { text }, font.text_style());
608 let prepared = engine.prepare(&attributed);
609 let size = engine.measure(&prepared, None);
610 let width = if text.is_empty() {
611 Points::ZERO
612 } else {
613 advance(engine, font, text)
614 };
615 let layout = engine.layout(&prepared, size);
616 match engine.lines(&layout).first() {
617 Some(line) => TextMetrics {
618 width,
619 ascent: line.ascender,
620 descent: line.descender,
621 height: line.height,
622 },
623 None => TextMetrics {
624 width,
625 ascent: Points(font.size.0 * 0.8),
626 descent: Points(font.size.0 * 0.2),
627 height: size.height,
628 },
629 }
630}
631
632#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
634pub enum CanvasTextAlign {
635 #[default]
637 Start,
638 End,
640 Left,
642 Right,
644 Center,
646}
647
648#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
650pub enum CanvasTextBaseline {
651 #[default]
653 Alphabetic,
654 Top,
656 Hanging,
658 Middle,
660 Ideographic,
662 Bottom,
664}
665
666#[derive(Debug, Clone, PartialEq)]
668pub struct CanvasImage {
669 pub uri: Arc<str>,
671}
672
673#[derive(Debug, Clone, PartialEq, JsOps)]
677#[ops(cx = Drawing)]
678pub enum CanvasOp {
679 #[op(code = CV_SAVE)]
681 Save,
682 #[op(code = CV_RESTORE)]
684 Restore,
685 #[op(code = CV_TRANSLATE, method = "translate", params = "x, y")]
687 Translate(Num, Num),
688 #[op(code = CV_SCALE, method = "scale", params = "x, y")]
690 Scale(Num, Num),
691 #[op(code = CV_ROTATE, method = "rotate", params = "angle")]
693 Rotate(Num),
694 #[op(code = CV_TRANSFORM, method = "transform", params = "a, b, c, d, e, f")]
697 Transform([Num; 6]),
698 #[op(code = CV_SET_TRANSFORM, method = "setTransform", params = "a, b, c, d, e, f")]
703 SetTransform([Num; 6]),
704 #[op(code = CV_BEGIN_PATH, method = "beginPath")]
706 BeginPath,
707 #[op(nested)]
709 Path(PathOp),
710 #[op(code = CV_FILL)]
712 Fill(Option<Path>, FillRule),
713 #[op(code = CV_STROKE)]
715 Stroke(Option<Path>),
716 #[op(code = CV_CLIP)]
718 Clip(Option<Path>, FillRule),
719 #[op(code = CV_FILL_RECT, method = "fillRect", params = "x, y, w, h")]
722 FillRect([Num; 4]),
723 #[op(code = CV_STROKE_RECT, method = "strokeRect", params = "x, y, w, h")]
725 StrokeRect([Num; 4]),
726 #[op(code = CV_CLEAR_RECT, method = "clearRect", params = "x, y, w, h")]
728 ClearRect([Num; 4]),
729 #[op(code = CV_FILL_STYLE)]
731 FillStyle(Paint),
732 #[op(code = CV_STROKE_STYLE)]
734 StrokeStyle(Paint),
735 #[op(code = CV_LINE_WIDTH, property = "lineWidth", initial = "1")]
737 LineWidth(Num),
738 #[op(code = CV_LINE_CAP, property = "lineCap", initial = "\"butt\"")]
740 LineCap(LineCap),
741 #[op(code = CV_LINE_JOIN, property = "lineJoin", initial = "\"miter\"")]
743 LineJoin(LineJoin),
744 #[op(code = CV_MITER_LIMIT, property = "miterLimit", initial = "10", min = 1.0)]
747 MiterLimit(f32),
748 #[op(code = CV_LINE_DASH, with = crate::js::canvas::line_dash)]
750 LineDash(Arc<[Points]>),
751 #[op(code = CV_LINE_DASH_OFFSET, property = "lineDashOffset", initial = "0")]
753 LineDashOffset(Num),
754 #[op(code = CV_GLOBAL_ALPHA, property = "globalAlpha", initial = "1")]
756 GlobalAlpha(Num),
757 #[op(
760 code = CV_COMPOSITE,
761 property = "globalCompositeOperation",
762 initial = "\"source-over\""
763 )]
764 Composite(Composite),
765 #[op(code = CV_SHADOW_COLOR, property = "shadowColor", initial = "\"rgba(0,0,0,0)\"")]
767 ShadowColor(Color),
768 #[op(code = CV_SHADOW_BLUR, property = "shadowBlur", initial = "0", min = 0.0)]
770 ShadowBlur(Points),
771 #[op(code = CV_SHADOW_OFFSET)]
773 ShadowOffset(Point<Points>),
774 #[op(code = CV_FONT, property = "font", initial = "\"10px sans-serif\"")]
777 Font(CanvasFont),
778 #[op(
783 code = CV_FONT_VARIANT_NUMERIC,
784 property = "fontVariantNumeric",
785 initial = "\"normal\""
786 )]
787 FontVariantNumeric(FontVariant),
788 #[op(code = CV_TEXT_ALIGN, property = "textAlign", initial = "\"start\"")]
790 TextAlign(CanvasTextAlign),
791 #[op(code = CV_TEXT_BASELINE, property = "textBaseline", initial = "\"alphabetic\"")]
793 TextBaseline(CanvasTextBaseline),
794 #[op(code = CV_FILL_TEXT)]
796 FillText {
797 text: Arc<str>,
799 x: Num,
801 y: Num,
803 max_width: Option<Points>,
805 },
806 #[op(code = CV_STROKE_TEXT)]
808 StrokeText {
809 text: Arc<str>,
811 x: Num,
813 y: Num,
815 max_width: Option<Points>,
817 },
818 #[op(code = CV_DRAW_IMAGE)]
820 DrawImage {
821 image: CanvasImage,
823 source: Option<Bounds<ScaledPixels>>,
825 dest: [Num; 4],
827 },
828}
829
830impl CanvasOp {
831 pub fn paints(&self) -> bool {
834 matches!(
835 self,
836 CanvasOp::Fill(..)
837 | CanvasOp::Stroke(_)
838 | CanvasOp::FillRect(_)
839 | CanvasOp::StrokeRect(_)
840 | CanvasOp::ClearRect(_)
841 | CanvasOp::FillText { .. }
842 | CanvasOp::StrokeText { .. }
843 | CanvasOp::DrawImage { .. }
844 )
845 }
846}
847
848#[derive(Debug, Clone, PartialEq, Default)]
850pub struct Drawing {
851 pub ops: Vec<CanvasOp>,
853 pub slots: Vec<crate::animation::NodeId>,
855 pub nodes: Vec<CanvasNode>,
859 pub view_paints: Vec<(u32, ViewPaint)>,
867}
868
869#[derive(Debug, Clone, Copy, PartialEq)]
872pub enum ViewPaint {
873 Fill(crate::style::SvgPaint),
875 Stroke(crate::style::SvgPaint),
877 StrokeWidth,
880 StrokeDasharray,
883 FillCurrentColor,
887 StrokeCurrentColor,
890 Fit(ViewBoxFit),
894 Background {
903 area: Bounds<Points>,
905 rule: FillRule,
907 },
908}
909
910#[derive(Debug, Clone, Copy, PartialEq)]
917pub struct ViewBoxFit {
918 pub view_box: Bounds<Points>,
920 pub align: Option<(Percentage, Percentage)>,
925 pub slice: bool,
927 pub size: Size<Points>,
929}
930
931impl ViewBoxFit {
932 pub fn transform(&self, size: Size<Points>) -> [f32; 6] {
935 let Size { width, height } = self.view_box.size;
936 let (vw, vh) = (width.0, height.0);
937 let (w, h) = (size.width.0.max(0.0), size.height.0.max(0.0));
938 if !(vw > 0.0 && vh > 0.0) {
939 return [0.0; 6];
940 }
941 let (mut sx, mut sy) = (w / vw, h / vh);
942 let (ax, ay) = match self.align {
943 None => (0.0, 0.0),
944 Some((x, y)) => {
945 let s = if self.slice { sx.max(sy) } else { sx.min(sy) };
946 (sx, sy) = (s, s);
947 (x.0, y.0)
948 }
949 };
950 let origin = self.view_box.origin;
951 [
952 sx,
953 0.0,
954 0.0,
955 sy,
956 (w - vw * sx) * ax - origin.x.0 * sx,
957 (h - vh * sy) * ay - origin.y.0 * sy,
958 ]
959 }
960}
961
962#[derive(Debug, Clone, PartialEq, Default)]
970#[non_exhaustive]
971pub struct CanvasNode {
972 pub bounds: Bounds<Points>,
974 pub role: crate::AccessibilityRole,
976 pub label: Arc<str>,
978 pub test_id: Option<Arc<str>>,
980 pub selected: bool,
982}
983
984impl CanvasNode {
985 pub fn new(
987 bounds: Bounds<Points>,
988 role: crate::AccessibilityRole,
989 label: impl Into<Arc<str>>,
990 ) -> Self {
991 Self {
992 bounds,
993 role,
994 label: label.into(),
995 ..Self::default()
996 }
997 }
998
999 pub fn test_id(mut self, id: impl Into<Arc<str>>) -> Self {
1001 self.test_id = Some(id.into());
1002 self
1003 }
1004
1005 pub fn selected(mut self, selected: bool) -> Self {
1007 self.selected = selected;
1008 self
1009 }
1010}
1011
1012impl Drawing {
1013 pub fn paints_background(&self) -> bool {
1016 self.view_paints
1017 .iter()
1018 .any(|(_, v)| matches!(v, ViewPaint::Background { .. }))
1019 }
1020
1021 pub fn fit(&self) -> Option<ViewBoxFit> {
1023 self.view_paints.iter().find_map(|&(_, v)| match v {
1024 ViewPaint::Fit(fit) => Some(fit),
1025 _ => None,
1026 })
1027 }
1028
1029 pub fn painted(
1037 &self,
1038 paint: &crate::style::PaintStyle,
1039 current: Color,
1040 background: Color,
1041 images: &[crate::effects::Gradient],
1042 size: Size<Points>,
1043 ) -> Drawing {
1044 use crate::style::SvgPaint;
1045 let color = |p: SvgPaint| {
1046 Paint::Color(match p {
1047 SvgPaint::None => Color::TRANSPARENT,
1048 SvgPaint::CurrentColor => current,
1049 SvgPaint::Color(c) => c,
1050 })
1051 };
1052 let mut out = self.clone();
1053 for &(at, view) in &self.view_paints {
1054 let Some(op) = out.ops.get_mut(at as usize) else {
1055 continue;
1056 };
1057 *op = match view {
1058 ViewPaint::Fill(initial) => {
1059 CanvasOp::FillStyle(color(paint.fill.unwrap_or(initial)))
1060 }
1061 ViewPaint::Stroke(initial) => {
1062 CanvasOp::StrokeStyle(color(paint.stroke.unwrap_or(initial)))
1063 }
1064 ViewPaint::StrokeWidth => {
1065 CanvasOp::LineWidth(Num::Const(paint.stroke_width.map_or(1.0, |w| w.0)))
1066 }
1067 ViewPaint::StrokeDasharray => CanvasOp::LineDash(
1068 paint
1069 .stroke_dasharray
1070 .clone()
1071 .unwrap_or_else(|| Arc::from([])),
1072 ),
1073 ViewPaint::FillCurrentColor => CanvasOp::FillStyle(Paint::Color(current)),
1074 ViewPaint::StrokeCurrentColor => CanvasOp::StrokeStyle(Paint::Color(current)),
1075 ViewPaint::Fit(fit) => CanvasOp::Transform(fit.transform(size).map(Num::Const)),
1076 ViewPaint::Background { .. } => continue,
1078 };
1079 }
1080 out.view_paints = Vec::new();
1081 if !self.paints_background() {
1082 return out;
1083 }
1084 let ops = std::mem::take(&mut out.ops);
1085 let mut backgrounds = self.view_paints.iter().filter_map(|&(at, v)| match v {
1086 ViewPaint::Background { area, rule } => Some((at as usize, area, rule)),
1087 _ => None,
1088 });
1089 let mut next = backgrounds.next();
1090 for (i, op) in ops.into_iter().enumerate() {
1091 let Some((_, area, rule)) = next.filter(|&(at, ..)| at == i) else {
1092 out.ops.push(op);
1093 continue;
1094 };
1095 next = backgrounds.next();
1096 out.ops.push(CanvasOp::Save);
1097 if !background.is_transparent() {
1098 out.ops.push(CanvasOp::FillStyle(Paint::Color(background)));
1099 out.ops.push(CanvasOp::Fill(None, rule));
1100 }
1101 for image in images.iter().rev() {
1102 let Some(gradient) = CanvasGradient::from_css(image, area) else {
1103 log::warn!("an elliptical `radial-gradient()` fills no canvas shape");
1104 continue;
1105 };
1106 out.ops
1107 .push(CanvasOp::FillStyle(Paint::Gradient(Arc::new(gradient))));
1108 out.ops.push(CanvasOp::Fill(None, rule));
1109 }
1110 out.ops.push(CanvasOp::Restore);
1111 }
1112 out
1113 }
1114
1115 pub fn slot(&mut self, node: crate::animation::NodeId) -> u16 {
1117 match self.slots.iter().position(|&n| n == node) {
1118 Some(i) => i as u16,
1119 None => {
1120 self.slots.push(node);
1121 (self.slots.len() - 1) as u16
1122 }
1123 }
1124 }
1125
1126 pub fn images(&self) -> impl Iterator<Item = &CanvasImage> {
1128 self.ops.iter().filter_map(|op| match op {
1129 CanvasOp::DrawImage { image, .. } => Some(image),
1130 _ => None,
1131 })
1132 }
1133}
1134
1135impl<Cx> OpArg<Cx> for Points {
1137 fn read<L: HostList<Item: HostInput>>(
1138 r: &mut OpReader<'_, L>,
1139 cx: &mut Cx,
1140 ) -> Result<Option<Self>, OpsError> {
1141 Ok(<f32 as OpArg<Cx>>::read(r, cx)?.map(Points))
1142 }
1143
1144 fn ts(types: &mut TsTypes) -> String {
1145 <f32 as OpArg<Cx>>::ts(types)
1146 }
1147}
1148
1149impl<Cx> OpArg<Cx> for Option<Points> {
1151 fn read<L: HostList<Item: HostInput>>(
1152 r: &mut OpReader<'_, L>,
1153 cx: &mut Cx,
1154 ) -> Result<Option<Self>, OpsError> {
1155 Ok(<Option<f32> as OpArg<Cx>>::read(r, cx)?.map(|v| v.map(Points)))
1156 }
1157
1158 fn ts(types: &mut TsTypes) -> String {
1159 <Option<f32> as OpArg<Cx>>::ts(types)
1160 }
1161}
1162
1163impl<Cx> OpArg<Cx> for Point<Points> {
1165 const ARITY: usize = 2;
1166
1167 fn read<L: HostList<Item: HostInput>>(
1168 r: &mut OpReader<'_, L>,
1169 cx: &mut Cx,
1170 ) -> Result<Option<Self>, OpsError> {
1171 let x = <Points as OpArg<Cx>>::read(r, cx)?;
1172 let y = <Points as OpArg<Cx>>::read(r, cx)?;
1173 Ok(x.zip(y).map(|(x, y)| Point { x, y }))
1174 }
1175
1176 fn ts(types: &mut TsTypes) -> String {
1177 <Points as OpArg<Cx>>::ts(types)
1178 }
1179}
1180
1181pub fn arc_sweep(start: Radians, end: Radians, ccw: bool) -> Radians {
1186 Radians(sweep(start.0, end.0, ccw))
1187}
1188
1189pub(crate) fn sweep(start: f32, end: f32, ccw: bool) -> f32 {
1190 use std::f32::consts::TAU;
1191 if !ccw {
1192 if end - start >= TAU {
1193 TAU
1194 } else {
1195 (end - start).rem_euclid(TAU)
1196 }
1197 } else if start - end >= TAU {
1198 -TAU
1199 } else {
1200 -(start - end).rem_euclid(TAU)
1201 }
1202}
1203
1204pub fn fit_radii(size: Size<Points>, radii: Corners<Points>) -> Corners<Points> {
1208 let [tl, tr, br, bl] = fit(
1209 size.width.0,
1210 size.height.0,
1211 [
1212 radii.top_left.0,
1213 radii.top_right.0,
1214 radii.bottom_right.0,
1215 radii.bottom_left.0,
1216 ],
1217 );
1218 Corners {
1219 top_left: Points(tl),
1220 top_right: Points(tr),
1221 bottom_right: Points(br),
1222 bottom_left: Points(bl),
1223 }
1224}
1225
1226pub(crate) fn fit(w: f32, h: f32, radii: [f32; 4]) -> [f32; 4] {
1229 let r = radii.map(|r| r.max(0.0));
1230 let (w, h) = (w.abs(), h.abs());
1231 let sides = [r[0] + r[1], r[2] + r[3], r[0] + r[3], r[1] + r[2]];
1232 let limits = [w, w, h, h];
1233 let scale = sides
1234 .iter()
1235 .zip(limits)
1236 .filter(|(s, _)| **s > 0.0)
1237 .map(|(s, l)| l / s)
1238 .fold(1.0f32, f32::min);
1239 r.map(|r| r * scale)
1240}
1241
1242pub fn svg_path(d: &str) -> Path {
1247 parse_svg_path(d).into()
1248}
1249
1250pub fn parse_svg_path(d: &str) -> Vec<PathOp> {
1254 let mut out = Vec::new();
1255 let mut p = PathParser {
1256 s: d.as_bytes(),
1257 pos: 0,
1258 };
1259 let (mut x, mut y) = (0f32, 0f32);
1260 let (mut sx, mut sy) = (0f32, 0f32);
1261 let mut last_cubic: Option<(f32, f32)> = None;
1263 let mut last_quad: Option<(f32, f32)> = None;
1264 let mut command = 0u8;
1265 let c = |v: f32| Num::Const(v);
1266 loop {
1267 p.skip_separators();
1268 if p.pos >= p.s.len() {
1269 break;
1270 }
1271 let b = p.s[p.pos];
1272 if b.is_ascii_alphabetic() {
1273 command = b;
1274 p.pos += 1;
1275 } else if command == 0 {
1276 break;
1277 } else if command == b'M' {
1278 command = b'L';
1280 } else if command == b'm' {
1281 command = b'l';
1282 }
1283 let rel = command.is_ascii_lowercase();
1284 let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) };
1285 let upper = command.to_ascii_uppercase();
1286 let ok = (|| -> Option<()> {
1287 match upper {
1288 b'M' => {
1289 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1290 out.push(PathOp::MoveTo(c(nx), c(ny)));
1291 (x, y, sx, sy) = (nx, ny, nx, ny);
1292 last_cubic = None;
1293 last_quad = None;
1294 }
1295 b'L' => {
1296 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1297 out.push(PathOp::LineTo(c(nx), c(ny)));
1298 (x, y) = (nx, ny);
1299 last_cubic = None;
1300 last_quad = None;
1301 }
1302 b'H' => {
1303 x = p.number()? + ox;
1304 out.push(PathOp::LineTo(c(x), c(y)));
1305 last_cubic = None;
1306 last_quad = None;
1307 }
1308 b'V' => {
1309 y = p.number()? + oy;
1310 out.push(PathOp::LineTo(c(x), c(y)));
1311 last_cubic = None;
1312 last_quad = None;
1313 }
1314 b'C' | b'S' => {
1315 let (x1, y1) = if upper == b'C' {
1316 (p.number()? + ox, p.number()? + oy)
1317 } else {
1318 last_cubic.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1320 };
1321 let (x2, y2) = (p.number()? + ox, p.number()? + oy);
1322 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1323 out.push(PathOp::CubicTo([x1, y1, x2, y2, nx, ny].map(c)));
1324 last_cubic = Some((x2, y2));
1325 last_quad = None;
1326 (x, y) = (nx, ny);
1327 }
1328 b'Q' | b'T' => {
1329 let (x1, y1) = if upper == b'Q' {
1330 (p.number()? + ox, p.number()? + oy)
1331 } else {
1332 last_quad.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1333 };
1334 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1335 out.push(PathOp::QuadTo([x1, y1, nx, ny].map(c)));
1336 last_quad = Some((x1, y1));
1337 last_cubic = None;
1338 (x, y) = (nx, ny);
1339 }
1340 b'A' => {
1341 let rx = p.number()?.abs();
1342 let ry = p.number()?.abs();
1343 let rotation = p.number()?;
1344 let large = p.flag()?;
1345 let sweep = p.flag()?;
1346 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1347 arc_to_cubics(&mut out, (x, y), (rx, ry), rotation, large, sweep, (nx, ny));
1348 (x, y) = (nx, ny);
1349 last_cubic = None;
1350 last_quad = None;
1351 }
1352 b'Z' => {
1353 out.push(PathOp::Close);
1354 (x, y) = (sx, sy);
1355 last_cubic = None;
1356 last_quad = None;
1357 command = 0;
1359 }
1360 _ => return None,
1361 }
1362 Some(())
1363 })();
1364 if ok.is_none() {
1365 break;
1366 }
1367 }
1368 out
1369}
1370
1371struct PathParser<'a> {
1372 s: &'a [u8],
1373 pos: usize,
1374}
1375
1376impl PathParser<'_> {
1377 fn skip_separators(&mut self) {
1378 while self.pos < self.s.len()
1379 && (self.s[self.pos].is_ascii_whitespace() || self.s[self.pos] == b',')
1380 {
1381 self.pos += 1;
1382 }
1383 }
1384
1385 fn number(&mut self) -> Option<f32> {
1386 self.skip_separators();
1387 let start = self.pos;
1388 let s = self.s;
1389 let mut i = self.pos;
1390 if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
1391 i += 1;
1392 }
1393 let mut digits = false;
1394 while i < s.len() && s[i].is_ascii_digit() {
1395 i += 1;
1396 digits = true;
1397 }
1398 if i < s.len() && s[i] == b'.' {
1399 i += 1;
1400 while i < s.len() && s[i].is_ascii_digit() {
1401 i += 1;
1402 digits = true;
1403 }
1404 }
1405 if !digits {
1406 return None;
1407 }
1408 if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
1409 let mut j = i + 1;
1410 if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
1411 j += 1;
1412 }
1413 if j < s.len() && s[j].is_ascii_digit() {
1414 while j < s.len() && s[j].is_ascii_digit() {
1415 j += 1;
1416 }
1417 i = j;
1418 }
1419 }
1420 self.pos = i;
1421 std::str::from_utf8(&s[start..i]).ok()?.parse().ok()
1422 }
1423
1424 fn flag(&mut self) -> Option<bool> {
1426 self.skip_separators();
1427 let b = *self.s.get(self.pos)?;
1428 self.pos += 1;
1429 match b {
1430 b'0' => Some(false),
1431 b'1' => Some(true),
1432 _ => None,
1433 }
1434 }
1435}
1436
1437fn arc_to_cubics(
1440 out: &mut Vec<PathOp>,
1441 from: (f32, f32),
1442 radii: (f32, f32),
1443 rotation_deg: f32,
1444 large: bool,
1445 sweep: bool,
1446 to: (f32, f32),
1447) {
1448 let c = |v: f64| Num::Const(v as f32);
1449 let (x1, y1) = (from.0 as f64, from.1 as f64);
1450 let (x2, y2) = (to.0 as f64, to.1 as f64);
1451 let (mut rx, mut ry) = (radii.0 as f64, radii.1 as f64);
1452 if (x1 == x2 && y1 == y2) || rx == 0.0 || ry == 0.0 {
1453 if x1 != x2 || y1 != y2 {
1454 out.push(PathOp::LineTo(c(x2), c(y2)));
1455 }
1456 return;
1457 }
1458 let phi = (rotation_deg as f64).to_radians();
1459 let (sin, cos) = phi.sin_cos();
1460 let dx = (x1 - x2) / 2.0;
1461 let dy = (y1 - y2) / 2.0;
1462 let x1p = cos * dx + sin * dy;
1463 let y1p = -sin * dx + cos * dy;
1464 let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
1466 if lambda > 1.0 {
1467 let s = lambda.sqrt();
1468 rx *= s;
1469 ry *= s;
1470 }
1471 let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
1472 let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
1473 let mut coef = (num / den).max(0.0).sqrt();
1474 if large == sweep {
1475 coef = -coef;
1476 }
1477 let cxp = coef * rx * y1p / ry;
1478 let cyp = -coef * ry * x1p / rx;
1479 let cx = cos * cxp - sin * cyp + (x1 + x2) / 2.0;
1480 let cy = sin * cxp + cos * cyp + (y1 + y2) / 2.0;
1481 let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
1482 let theta1 = angle(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
1483 let mut delta = angle(
1484 (x1p - cxp) / rx,
1485 (y1p - cyp) / ry,
1486 (-x1p - cxp) / rx,
1487 (-y1p - cyp) / ry,
1488 );
1489 if !sweep && delta > 0.0 {
1490 delta -= std::f64::consts::TAU;
1491 } else if sweep && delta < 0.0 {
1492 delta += std::f64::consts::TAU;
1493 }
1494 let segments = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
1496 let step = delta / segments as f64;
1497 let k = 4.0 / 3.0 * (step / 4.0).tan();
1498 let point = |t: f64| {
1499 let (s, co) = t.sin_cos();
1500 (
1501 cx + rx * co * cos - ry * s * sin,
1502 cy + rx * co * sin + ry * s * cos,
1503 )
1504 };
1505 let derivative = |t: f64| {
1506 let (s, co) = t.sin_cos();
1507 (-rx * s * cos - ry * co * sin, -rx * s * sin + ry * co * cos)
1508 };
1509 let mut t = theta1;
1510 for i in 0..segments {
1511 let t2 = t + step;
1512 let (p1x, p1y) = point(t);
1513 let (d1x, d1y) = derivative(t);
1514 let (p2x, p2y) = if i + 1 == segments {
1515 (x2, y2)
1516 } else {
1517 point(t2)
1518 };
1519 let (d2x, d2y) = derivative(t2);
1520 out.push(PathOp::CubicTo([
1521 c(p1x + k * d1x),
1522 c(p1y + k * d1y),
1523 c(p2x - k * d2x),
1524 c(p2y - k * d2y),
1525 c(p2x),
1526 c(p2y),
1527 ]));
1528 t = t2;
1529 }
1530}
1531
1532#[cfg(test)]
1533mod tests {
1534 use super::*;
1535 use crate::text::{AttributedText, TextEngine, TextLayout};
1536
1537 #[test]
1542 fn css_gradients_become_canvas_gradients_over_a_box() {
1543 use crate::geometry::{bounds, point, size};
1544 let area = bounds(point(px(10.0), px(20.0)), size(px(100.0), px(50.0)));
1545 let one = |css: &str| crate::css::gradients(css).unwrap().remove(0);
1546 let gradient = |css: &str| CanvasGradient::from_css(&one(css), area);
1547 let down = gradient("linear-gradient(to bottom, #ff0000, #0000ff)").unwrap();
1548 assert_eq!(
1549 down.shape,
1550 GradientShape::Linear {
1551 start: point(px(60.0), px(20.0)),
1552 end: point(px(60.0), px(70.0)),
1553 }
1554 );
1555 assert_eq!(down.stops[0], (Percentage(0.0), Color(0xff00_00ff)));
1556 assert_eq!(
1557 down.stops[down.stops.len() - 1],
1558 (Percentage(1.0), Color(0x0000_ffff))
1559 );
1560 let right = gradient("linear-gradient(90deg, #ff0000, #0000ff)").unwrap();
1561 let GradientShape::Linear { start, end } = right.shape else {
1562 panic!("{right:?}")
1563 };
1564 assert!((start.x.0 - 10.0).abs() < 1e-3 && (start.y.0 - 45.0).abs() < 1e-3);
1565 assert!((end.x.0 - 110.0).abs() < 1e-3 && (end.y.0 - 45.0).abs() < 1e-3);
1566 let stripes =
1569 gradient("repeating-linear-gradient(to bottom, #ff0000 0%, #0000ff 25%)").unwrap();
1570 let at = |o: f32| {
1571 stripes
1572 .stops
1573 .iter()
1574 .filter(|(p, _)| (p.0 - o).abs() < 1e-4)
1575 .count()
1576 };
1577 assert!(
1578 at(0.25) >= 2 && at(0.5) >= 2 && at(0.75) >= 2,
1579 "{stripes:?}"
1580 );
1581 assert!(
1582 stripes
1583 .stops
1584 .iter()
1585 .all(|(p, _)| (0.0..=1.0).contains(&p.0))
1586 );
1587 let cut = gradient("linear-gradient(to bottom, #000000 0%, #ffffff 200%)").unwrap();
1589 assert_eq!(
1590 cut.stops[cut.stops.len() - 1],
1591 (Percentage(1.0), Color(0x8080_80ff))
1592 );
1593 assert!(gradient("radial-gradient(#ff0000, #0000ff)").is_none());
1594 let circle = gradient("radial-gradient(circle, #ff0000, #0000ff)").unwrap();
1595 assert!(matches!(circle.shape, GradientShape::Radial { .. }));
1596 }
1597
1598 #[test]
1602 fn a_drawing_fills_with_its_views_background() {
1603 use crate::geometry::{bounds, point, size};
1604 let area = bounds(point(px(0.0), px(0.0)), size(px(10.0), px(10.0)));
1605 let drawing = crate::element::Painter::new()
1606 .begin_path()
1607 .fill_background_from_view(area)
1608 .finish();
1609 assert!(drawing.paints_background());
1610 let images = crate::css::gradients("linear-gradient(#ff0000, #0000ff)").unwrap();
1611 let none = crate::style::PaintStyle::default();
1612 let painted = drawing.painted(
1613 &none,
1614 Color::TRANSPARENT,
1615 Color(0x00ff_00ff),
1616 &images,
1617 Size::default(),
1618 );
1619 assert!(painted.view_paints.is_empty());
1620 let ops = &painted.ops[1..];
1621 assert_eq!(ops[0], CanvasOp::Save);
1622 assert_eq!(
1623 ops[1],
1624 CanvasOp::FillStyle(Paint::Color(Color(0x00ff_00ff)))
1625 );
1626 assert_eq!(ops[2], CanvasOp::Fill(None, FillRule::NonZero));
1627 assert!(matches!(ops[3], CanvasOp::FillStyle(Paint::Gradient(_))));
1628 assert_eq!(ops[4], CanvasOp::Fill(None, FillRule::NonZero));
1629 assert_eq!(ops[5], CanvasOp::Restore);
1630 let bare = drawing.painted(
1632 &none,
1633 Color::TRANSPARENT,
1634 Color::TRANSPARENT,
1635 &[],
1636 Size::default(),
1637 );
1638 assert_eq!(&bare.ops[1..], [CanvasOp::Save, CanvasOp::Restore]);
1639 }
1640
1641 struct Hanging;
1644
1645 impl TextEngine for Hanging {
1646 type Prepared = String;
1647
1648 fn prepare(&self, text: &AttributedText) -> String {
1649 text.text.to_string()
1650 }
1651
1652 fn prepare_aligned(
1653 &self,
1654 text: &AttributedText,
1655 _: &crate::text::AttachmentAlignments,
1656 ) -> String {
1657 self.prepare(text)
1658 }
1659
1660 fn measure(&self, text: &String, _: Option<Points>) -> Size<Points> {
1661 let shown = text.trim_end_matches(|c: char| c.is_whitespace());
1662 Size::new(Points(10.0 * shown.chars().count() as f32), Points(12.0))
1663 }
1664
1665 fn layout(&self, _: &String, _: Size<Points>) -> TextLayout {
1666 TextLayout(std::sync::Arc::new(()))
1667 }
1668 }
1669
1670 #[test]
1671 fn trailing_white_space_advances_as_canvas_measures_it() {
1672 let font = CanvasFont::default();
1673 for (text, width) in [
1674 ("", 0.0),
1675 ("ab", 20.0),
1676 (" ", 10.0),
1677 (" ", 30.0),
1678 (" items: ", 90.0),
1679 ("a\t", 20.0),
1680 ("名字\u{3000}", 30.0),
1682 ("你好 ", 30.0),
1683 ("ab\n", 20.0),
1685 ] {
1686 assert_eq!(
1687 measure_line(&Hanging, &font, text),
1688 Points(width),
1689 "{text:?}"
1690 );
1691 assert_eq!(
1692 line_metrics(&Hanging, &font, text).width,
1693 Points(width),
1694 "{text:?}"
1695 );
1696 }
1697 }
1698
1699 fn consts(op: &PathOp) -> Vec<f32> {
1700 let v = |n: &Num| match n {
1701 Num::Const(v) => *v,
1702 Num::Slot(_) => f32::NAN,
1703 };
1704 match op {
1705 PathOp::MoveTo(a, b) | PathOp::LineTo(a, b) => vec![v(a), v(b)],
1706 PathOp::QuadTo(n) => n.iter().map(v).collect(),
1707 PathOp::CubicTo(n) => n.iter().map(v).collect(),
1708 _ => vec![],
1709 }
1710 }
1711
1712 #[test]
1713 fn svg_paths_parse_to_absolute_ops() {
1714 let ops = parse_svg_path("M10 20 l5-5 H30 v10 z m1 1 2 2");
1715 assert_eq!(ops.len(), 7);
1716 assert_eq!(consts(&ops[1]), vec![15.0, 15.0]);
1717 assert_eq!(consts(&ops[2]), vec![30.0, 15.0]);
1718 assert_eq!(consts(&ops[3]), vec![30.0, 25.0]);
1719 assert_eq!(ops[4], PathOp::Close);
1720 assert_eq!(consts(&ops[5]), vec![11.0, 21.0]);
1722 assert_eq!(consts(&ops[6]), vec![13.0, 23.0]);
1724 let ops = parse_svg_path("M.5.5L1e1-2");
1726 assert_eq!(consts(&ops[0]), vec![0.5, 0.5]);
1727 assert_eq!(consts(&ops[1]), vec![10.0, -2.0]);
1728 }
1729
1730 #[test]
1731 fn smooth_curves_reflect_control_points() {
1732 let ops = parse_svg_path("M0 0 C0 10 10 10 10 0 S20 -10 20 0");
1733 assert_eq!(consts(&ops[2]), vec![10.0, -10.0, 20.0, -10.0, 20.0, 0.0]);
1734 }
1735
1736 #[test]
1737 fn arcs_become_cubics_ending_on_the_point() {
1738 let ops = parse_svg_path("M0 0 A10 10 0 0120 0");
1740 assert_eq!(ops.len(), 3);
1741 let last = consts(&ops[2]);
1742 assert!((last[4] - 20.0).abs() < 1e-4 && last[5].abs() < 1e-4);
1743 let mid = consts(&ops[1]);
1745 assert!((mid[4] - 10.0).abs() < 1e-3 && (mid[5] + 10.0).abs() < 1e-3);
1746 }
1747
1748 #[test]
1749 fn bad_path_data_keeps_what_parsed() {
1750 let ops = parse_svg_path("M0 0 L10 10 L oops");
1751 assert_eq!(ops.len(), 2);
1752 }
1753
1754 #[test]
1755 fn arc_sweeps_follow_the_canvas_spec() {
1756 use std::f32::consts::{PI, TAU};
1757
1758 use crate::geometry::{radians, size};
1759 let sweep = |a, b, ccw| arc_sweep(radians(a), radians(b), ccw).0;
1760 assert_eq!(sweep(0.0, PI, false), PI);
1761 assert!((sweep(PI, 0.0, false) - PI).abs() < 1e-6);
1763 assert!((sweep(0.0, -PI / 2.0, false) - 1.5 * PI).abs() < 1e-5);
1764 assert_eq!(sweep(0.0, 3.0 * TAU, false), TAU);
1765 assert!((sweep(0.0, PI / 2.0, true) + 1.5 * PI).abs() < 1e-5);
1766 assert_eq!(sweep(TAU, 0.0, true), -TAU);
1767 let corners = |[top_left, top_right, bottom_right, bottom_left]: [f32; 4]| Corners {
1768 top_left: px(top_left),
1769 top_right: px(top_right),
1770 bottom_right: px(bottom_right),
1771 bottom_left: px(bottom_left),
1772 };
1773 assert_eq!(
1774 fit_radii(size(px(10.0), px(100.0)), corners([8.0, 8.0, 0.0, 0.0])),
1775 corners([5.0, 5.0, 0.0, 0.0])
1776 );
1777 }
1778
1779 #[test]
1780 fn fonts_parse_the_css_shorthand() {
1781 let f = CanvasFont::parse("italic bold 14px \"Inter\", sans-serif").unwrap();
1782 assert_eq!((f.size, f.weight, f.italic), (px(14.0), 700, true));
1783 assert_eq!(f.family.as_deref(), Some("Inter"));
1784 let f = CanvasFont::parse("600 12px/1.5 system-ui").unwrap();
1785 assert_eq!((f.size, f.weight, f.family), (px(12.0), 600, None));
1786 let f = CanvasFont::parse("small-caps tabular-nums 13px system-ui").unwrap();
1787 assert_eq!(
1788 f.variant.0,
1789 FontVariant::SMALL_CAPS | FontVariant::TABULAR_NUMS
1790 );
1791 let numeric = f.with_numeric(FontVariant(FontVariant::OLDSTYLE_NUMS));
1792 assert_eq!(
1793 numeric.variant.0,
1794 FontVariant::SMALL_CAPS | FontVariant::OLDSTYLE_NUMS
1795 );
1796 assert_eq!(f.with_numeric(FontVariant::default()), f);
1797 assert!(CanvasFont::parse("wide 13px system-ui").is_none());
1798 assert!(CanvasFont::parse("bold").is_none());
1799 assert!(CanvasFont::parse("14px").is_none());
1800 }
1801}