1mod damage;
9mod hit;
10pub mod render;
11
12use std::sync::Arc;
13
14pub use self::{
15 damage::{Damage, DamageScan, first_animated, prefix_path_needed},
16 hit::{point_in_path, point_in_stroke},
17};
18use crate::{
19 element::{PropEnum, TsTypes},
20 geometry::{Bounds, Corners, Percentage, Point, Points, Radians, ScaledPixels, Size, px},
21 js::{
22 canvas::*,
23 host::{HostInput, HostList},
24 ops::{JsOps, OpArg, OpReader, OpsError},
25 },
26 style::{Color, FontVariant},
27};
28
29#[derive(Debug, Clone, Copy, PartialEq)]
32pub enum Num {
33 Const(f32),
35 Slot(u16),
37}
38
39impl Num {
40 #[inline]
42 pub fn get(self, slot: impl Fn(u16) -> f32) -> f32 {
43 match self {
44 Num::Const(v) => v,
45 Num::Slot(s) => slot(s),
46 }
47 }
48}
49
50impl Default for Num {
51 fn default() -> Self {
52 Num::Const(0.0)
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, JsOps)]
58#[ops(cx = Drawing)]
59pub enum PathOp {
60 #[op(code = CV_MOVE_TO, method = "moveTo", params = "x, y")]
62 MoveTo(Num, Num),
63 #[op(code = CV_LINE_TO, method = "lineTo", params = "x, y")]
65 LineTo(Num, Num),
66 #[op(code = CV_QUAD_TO, method = "quadraticCurveTo", params = "cpx, cpy, x, y")]
69 QuadTo([Num; 4]),
70 #[op(
73 code = CV_CUBIC_TO,
74 method = "bezierCurveTo",
75 params = "cp1x, cp1y, cp2x, cp2y, x, y"
76 )]
77 CubicTo([Num; 6]),
78 #[op(
81 code = CV_ARC,
82 method = "arc",
83 params = "x, y, radius, startAngle, endAngle, counterclockwise = false"
84 )]
85 Arc {
86 x: Num,
88 y: Num,
90 radius: Num,
92 start: Num,
94 end: Num,
96 ccw: bool,
98 },
99 #[op(code = CV_ARC_TO, method = "arcTo", params = "x1, y1, x2, y2, radius")]
102 ArcTo([Num; 5]),
103 #[op(
106 code = CV_ELLIPSE,
107 method = "ellipse",
108 params = "x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise = false"
109 )]
110 Ellipse {
111 geometry: [Num; 5],
113 start: Num,
115 end: Num,
117 ccw: bool,
119 },
120 #[op(code = CV_RECT, method = "rect", params = "x, y, w, h")]
122 Rect([Num; 4]),
123 #[op(code = CV_ROUND_RECT)]
126 RoundRect([Num; 4], [Num; 4]),
127 #[op(code = CV_CLOSE, method = "closePath")]
129 Close,
130}
131
132pub type Path = Arc<[PathOp]>;
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
137pub enum FillRule {
138 #[default]
140 #[prop(rename = "nonzero")]
141 NonZero,
142 #[prop(rename = "evenodd")]
144 EvenOdd,
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
149pub enum LineCap {
150 #[default]
152 Butt,
153 Round,
155 Square,
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
161pub enum LineJoin {
162 #[default]
164 Miter,
165 Round,
167 Bevel,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq)]
173pub enum GradientShape {
174 Linear {
176 start: Point<Points>,
178 end: Point<Points>,
180 },
181 Radial {
183 start: Point<Points>,
185 start_radius: Points,
187 end: Point<Points>,
189 end_radius: Points,
191 },
192 Conic {
194 start_angle: Radians,
196 center: Point<Points>,
198 },
199}
200
201#[derive(Debug, Clone, PartialEq)]
203pub struct CanvasGradient {
204 pub shape: GradientShape,
206 pub stops: Vec<(Percentage, Color)>,
208}
209
210impl CanvasGradient {
211 fn new(shape: GradientShape) -> Self {
212 Self {
213 shape,
214 stops: Vec::new(),
215 }
216 }
217
218 pub fn linear(start: Point<Points>, end: Point<Points>) -> Self {
220 Self::new(GradientShape::Linear { start, end })
221 }
222
223 pub fn radial(
226 start: Point<Points>,
227 start_radius: Points,
228 end: Point<Points>,
229 end_radius: Points,
230 ) -> Self {
231 Self::new(GradientShape::Radial {
232 start,
233 start_radius,
234 end,
235 end_radius,
236 })
237 }
238
239 pub fn conic(start_angle: Radians, center: Point<Points>) -> Self {
242 Self::new(GradientShape::Conic {
243 start_angle,
244 center,
245 })
246 }
247
248 pub fn add_color_stop(mut self, offset: Percentage, color: impl Into<crate::Hsla>) -> Self {
251 let offset = offset.clamp(Percentage(0.0), Percentage(1.0));
252 let at = self.stops.partition_point(|(o, _)| *o <= offset);
253 self.stops.insert(at, (offset, Color::from(color.into())));
254 self
255 }
256
257 pub fn from_css(gradient: &crate::effects::Gradient, area: Bounds<Points>) -> Option<Self> {
264 use crate::{effects::GradientKind, geometry::point};
265 let size = area.size;
266 let (w, h) = (size.width.0, size.height.0);
267 let (left, top) = (area.origin.x.0, area.origin.y.0);
268 let at = |x: f32, y: f32| point(px(x), px(y));
269 let shape = match gradient.kind {
270 GradientKind::Radial { circle: false, .. } => return None,
271 GradientKind::Radial { x, y, .. } => {
272 let center = at(left + x.0 * w, top + y.0 * h);
273 GradientShape::Radial {
274 start: center,
275 start_radius: Points::ZERO,
276 end: center,
277 end_radius: gradient.line_length(size),
278 }
279 }
280 GradientKind::Conic { from, x, y } => GradientShape::Conic {
283 start_angle: Radians(from.0 - std::f32::consts::FRAC_PI_2),
284 center: at(left + x.0 * w, top + y.0 * h),
285 },
286 kind => {
287 let angle = kind
290 .linear_angle(size)
291 .unwrap_or(Radians(std::f32::consts::PI));
292 let exact = |v: f32| {
296 if v.abs() < 1e-6 {
297 0.0
298 } else if (v.abs() - 1.0).abs() < 1e-6 {
299 v.signum()
300 } else {
301 v
302 }
303 };
304 let (sin, cos) = angle.sin_cos();
305 let (sin, cos) = (exact(sin), exact(cos));
306 let half = ((w * sin).abs() + (h * cos).abs()) / 2.0;
308 let (cx, cy) = (left + w / 2.0, top + h / 2.0);
309 GradientShape::Linear {
310 start: at(cx - sin * half, cy + cos * half),
311 end: at(cx + sin * half, cy - cos * half),
312 }
313 }
314 };
315 let mut stops = gradient.unrolled_stops(size, Percentage(1.0));
316 if !stops.iter().all(|s| (0.0..=1.0).contains(&s.1.0)) {
319 stops = crate::effects::cut_stops(&stops, Percentage(1.0));
320 }
321 let mut out = Self::new(shape);
322 out.stops = stops.into_iter().map(|(color, at)| (at, color)).collect();
323 Some(out)
324 }
325}
326
327#[derive(Debug, Clone, PartialEq)]
329pub enum Paint {
330 Color(Color),
332 Slot(u16),
334 Gradient(Arc<CanvasGradient>),
336}
337
338#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
340#[allow(missing_docs)]
341pub enum Composite {
342 #[default]
343 SourceOver,
344 SourceIn,
345 SourceOut,
346 SourceAtop,
347 DestinationOver,
348 DestinationIn,
349 DestinationOut,
350 DestinationAtop,
351 Lighter,
352 Copy,
353 Xor,
354 Multiply,
355 Screen,
356 Overlay,
357 Darken,
358 Lighten,
359 ColorDodge,
360 ColorBurn,
361 HardLight,
362 SoftLight,
363 Difference,
364 Exclusion,
365 Hue,
366 Saturation,
367 Color,
368 Luminosity,
369}
370
371impl Composite {
372 pub fn parse(name: &str) -> Option<Composite> {
374 use Composite::*;
375 Some(match name {
376 "source-over" => SourceOver,
377 "source-in" => SourceIn,
378 "source-out" => SourceOut,
379 "source-atop" => SourceAtop,
380 "destination-over" => DestinationOver,
381 "destination-in" => DestinationIn,
382 "destination-out" => DestinationOut,
383 "destination-atop" => DestinationAtop,
384 "lighter" => Lighter,
385 "copy" => Copy,
386 "xor" => Xor,
387 "multiply" => Multiply,
388 "screen" => Screen,
389 "overlay" => Overlay,
390 "darken" => Darken,
391 "lighten" => Lighten,
392 "color-dodge" => ColorDodge,
393 "color-burn" => ColorBurn,
394 "hard-light" => HardLight,
395 "soft-light" => SoftLight,
396 "difference" => Difference,
397 "exclusion" => Exclusion,
398 "hue" => Hue,
399 "saturation" => Saturation,
400 "color" => Color,
401 "luminosity" => Luminosity,
402 _ => return None,
403 })
404 }
405}
406
407#[derive(Debug, Clone, PartialEq)]
409pub struct CanvasFont {
410 pub size: Points,
412 pub weight: u16,
414 pub italic: bool,
416 pub family: Option<Arc<str>>,
419 pub variant: FontVariant,
423}
424
425impl Default for CanvasFont {
426 fn default() -> Self {
428 Self {
429 size: px(10.0),
430 weight: 400,
431 italic: false,
432 family: None,
433 variant: FontVariant::default(),
434 }
435 }
436}
437
438impl CanvasFont {
439 pub fn parse(s: &str) -> Option<CanvasFont> {
443 let mut font = CanvasFont {
444 size: Points::ZERO,
445 ..CanvasFont::default()
446 };
447 let mut rest = s.trim();
448 loop {
450 let (word, tail) = match rest.split_once(char::is_whitespace) {
451 Some((w, t)) => (w, t.trim_start()),
452 None => (rest, ""),
453 };
454 if let Some(size) = font_size(word) {
455 font.size = size;
456 rest = tail;
457 break;
458 }
459 match word {
460 "italic" | "oblique" => font.italic = true,
461 "normal" | "condensed" | "expanded" => {}
462 w if let Some(v) = FontVariant::parse(w) => font.variant.0 |= v.0,
463 "bold" | "bolder" => font.weight = 700,
464 "lighter" => font.weight = 300,
465 w => match w.parse::<u16>() {
466 Ok(n) if (1..=1000).contains(&n) => font.weight = n,
467 _ => return None,
468 },
469 }
470 if tail.is_empty() {
471 return None;
472 }
473 rest = tail;
474 }
475 let mut families = crate::style::font_families(rest);
476 let first = families.next()?;
477 font.family = match (first, families.next()) {
478 (crate::style::FamilyName::System, None) => None,
479 (crate::style::FamilyName::Named(name), None)
480 if !name.contains([',', '"', '\'', '\\'])
481 && !crate::style::is_css_generic_keyword(name) =>
482 {
483 Some(name.into())
484 }
485 _ => Some(rest.into()),
486 };
487 Some(font)
488 }
489}
490
491fn font_size(word: &str) -> Option<Points> {
493 let word = word.split('/').next()?;
494 let (num, scale) = if let Some(n) = word.strip_suffix("px") {
495 (n, 1.0)
496 } else if let Some(n) = word.strip_suffix("rem").or_else(|| word.strip_suffix("em")) {
497 (n, 16.0)
498 } else {
499 (word.strip_suffix("pt")?, 4.0 / 3.0)
500 };
501 num.parse::<f32>()
502 .ok()
503 .filter(|v| *v > 0.0)
504 .map(|v| Points(v * scale))
505}
506
507impl CanvasFont {
508 pub fn with_numeric(&self, numeric: FontVariant) -> CanvasFont {
511 let mut font = self.clone();
512 if numeric.0 != 0 {
513 font.variant = FontVariant(font.variant.0 & FontVariant::SMALL_CAPS | numeric.0);
514 }
515 font
516 }
517
518 pub fn text_style(&self) -> crate::text::ResolvedTextStyle {
520 crate::text::ResolvedTextStyle {
521 font_size: self.size,
522 font_weight: self.weight,
523 italic: self.italic,
524 font_variant: self.variant,
525 font_family: self.family.as_deref().map(crate::style::FontFamily::new),
526 ..Default::default()
527 }
528 }
529}
530
531pub fn measure_line(
533 engine: &impl crate::text::TextEngine,
534 font: &CanvasFont,
535 text: &str,
536) -> Points {
537 if text.is_empty() {
538 return Points::ZERO;
539 }
540 advance(engine, font, text)
541}
542
543const MARK: &str = "x";
545
546fn advance(engine: &impl crate::text::TextEngine, font: &CanvasFont, text: &str) -> Points {
552 let width = |text: &str| {
553 let mut attributed = crate::text::AttributedText {
554 no_wrap: true,
555 max_lines: 1,
556 ..Default::default()
557 };
558 attributed.push(text, font.text_style());
559 let prepared = engine.prepare(&attributed);
560 engine.measure(&prepared, None).width
561 };
562 let hangs = text.ends_with(|c: char| c.is_whitespace() && !is_line_break(c));
564 if !hangs {
565 return width(text);
566 }
567 let mut marked = String::with_capacity(text.len() + MARK.len());
568 marked.push_str(text);
569 marked.push_str(MARK);
570 (width(&marked) - width(MARK)).max(Points::ZERO)
571}
572
573fn is_line_break(c: char) -> bool {
575 matches!(
576 c,
577 '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}'
578 )
579}
580
581#[derive(Debug, Clone, Copy, PartialEq, Default)]
585#[non_exhaustive]
586pub struct TextMetrics {
587 pub width: Points,
589 pub ascent: Points,
591 pub descent: Points,
593 pub height: Points,
595}
596
597pub fn line_metrics(
601 engine: &impl crate::text::TextEngine,
602 font: &CanvasFont,
603 text: &str,
604) -> TextMetrics {
605 let mut attributed = crate::text::AttributedText {
606 no_wrap: true,
607 max_lines: 1,
608 ..Default::default()
609 };
610 attributed.push(if text.is_empty() { " " } else { text }, font.text_style());
612 let prepared = engine.prepare(&attributed);
613 let size = engine.measure(&prepared, None);
614 let width = if text.is_empty() {
615 Points::ZERO
616 } else {
617 advance(engine, font, text)
618 };
619 let layout = engine.layout(&prepared, size);
620 match engine.lines(&layout).first() {
621 Some(line) => TextMetrics {
622 width,
623 ascent: line.ascender,
624 descent: line.descender,
625 height: line.height,
626 },
627 None => TextMetrics {
628 width,
629 ascent: Points(font.size.0 * 0.8),
630 descent: Points(font.size.0 * 0.2),
631 height: size.height,
632 },
633 }
634}
635
636#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
638pub enum CanvasTextAlign {
639 #[default]
641 Start,
642 End,
644 Left,
646 Right,
648 Center,
650}
651
652#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
654pub enum CanvasTextBaseline {
655 #[default]
657 Alphabetic,
658 Top,
660 Hanging,
662 Middle,
664 Ideographic,
666 Bottom,
668}
669
670#[derive(Debug, Clone, PartialEq)]
672pub struct CanvasImage {
673 pub uri: Arc<str>,
675}
676
677impl CanvasImage {
678 pub fn density(&self) -> f32 {
682 crate::image::density(&self.uri)
683 }
684}
685
686#[derive(Debug, Clone, PartialEq, JsOps)]
690#[ops(cx = Drawing)]
691pub enum CanvasOp {
692 #[op(code = CV_SAVE)]
694 Save,
695 #[op(code = CV_RESTORE)]
697 Restore,
698 #[op(code = CV_TRANSLATE, method = "translate", params = "x, y")]
700 Translate(Num, Num),
701 #[op(code = CV_SCALE, method = "scale", params = "x, y")]
703 Scale(Num, Num),
704 #[op(code = CV_ROTATE, method = "rotate", params = "angle")]
706 Rotate(Num),
707 #[op(code = CV_TRANSFORM, method = "transform", params = "a, b, c, d, e, f")]
710 Transform([Num; 6]),
711 #[op(code = CV_SET_TRANSFORM, method = "setTransform", params = "a, b, c, d, e, f")]
716 SetTransform([Num; 6]),
717 #[op(code = CV_BEGIN_PATH, method = "beginPath")]
719 BeginPath,
720 #[op(nested)]
722 Path(PathOp),
723 #[op(code = CV_FILL)]
725 Fill(Option<Path>, FillRule),
726 #[op(code = CV_STROKE)]
728 Stroke(Option<Path>),
729 #[op(code = CV_CLIP)]
731 Clip(Option<Path>, FillRule),
732 #[op(code = CV_FILL_RECT, method = "fillRect", params = "x, y, w, h")]
735 FillRect([Num; 4]),
736 #[op(code = CV_STROKE_RECT, method = "strokeRect", params = "x, y, w, h")]
738 StrokeRect([Num; 4]),
739 #[op(code = CV_CLEAR_RECT, method = "clearRect", params = "x, y, w, h")]
741 ClearRect([Num; 4]),
742 #[op(code = CV_FILL_STYLE)]
744 FillStyle(Paint),
745 #[op(code = CV_STROKE_STYLE)]
747 StrokeStyle(Paint),
748 #[op(code = CV_LINE_WIDTH, property = "lineWidth", initial = "1")]
750 LineWidth(Num),
751 #[op(code = CV_LINE_CAP, property = "lineCap", initial = "\"butt\"")]
753 LineCap(LineCap),
754 #[op(code = CV_LINE_JOIN, property = "lineJoin", initial = "\"miter\"")]
756 LineJoin(LineJoin),
757 #[op(code = CV_MITER_LIMIT, property = "miterLimit", initial = "10", min = 1.0)]
760 MiterLimit(f32),
761 #[op(code = CV_LINE_DASH, with = crate::js::canvas::line_dash)]
763 LineDash(Arc<[Points]>),
764 #[op(code = CV_LINE_DASH_OFFSET, property = "lineDashOffset", initial = "0")]
766 LineDashOffset(Num),
767 #[op(code = CV_GLOBAL_ALPHA, property = "globalAlpha", initial = "1")]
769 GlobalAlpha(Num),
770 #[op(
773 code = CV_COMPOSITE,
774 property = "globalCompositeOperation",
775 initial = "\"source-over\""
776 )]
777 Composite(Composite),
778 #[op(code = CV_SHADOW_COLOR, property = "shadowColor", initial = "\"rgba(0,0,0,0)\"")]
780 ShadowColor(Color),
781 #[op(code = CV_SHADOW_BLUR, property = "shadowBlur", initial = "0", min = 0.0)]
783 ShadowBlur(Points),
784 #[op(code = CV_SHADOW_OFFSET)]
786 ShadowOffset(Point<Points>),
787 #[op(code = CV_FONT, property = "font", initial = "\"10px sans-serif\"")]
790 Font(CanvasFont),
791 #[op(
796 code = CV_FONT_VARIANT_NUMERIC,
797 property = "fontVariantNumeric",
798 initial = "\"normal\""
799 )]
800 FontVariantNumeric(FontVariant),
801 #[op(code = CV_TEXT_ALIGN, property = "textAlign", initial = "\"start\"")]
803 TextAlign(CanvasTextAlign),
804 #[op(code = CV_TEXT_BASELINE, property = "textBaseline", initial = "\"alphabetic\"")]
806 TextBaseline(CanvasTextBaseline),
807 #[op(code = CV_FILL_TEXT)]
809 FillText {
810 text: Arc<str>,
812 x: Num,
814 y: Num,
816 max_width: Option<Points>,
818 },
819 #[op(code = CV_STROKE_TEXT)]
821 StrokeText {
822 text: Arc<str>,
824 x: Num,
826 y: Num,
828 max_width: Option<Points>,
830 },
831 #[op(code = CV_DRAW_IMAGE)]
833 DrawImage {
834 image: CanvasImage,
836 source: Option<Bounds<ScaledPixels>>,
838 dest: [Num; 4],
840 },
841}
842
843impl CanvasOp {
844 pub fn paints(&self) -> bool {
847 matches!(
848 self,
849 CanvasOp::Fill(..)
850 | CanvasOp::Stroke(_)
851 | CanvasOp::FillRect(_)
852 | CanvasOp::StrokeRect(_)
853 | CanvasOp::ClearRect(_)
854 | CanvasOp::FillText { .. }
855 | CanvasOp::StrokeText { .. }
856 | CanvasOp::DrawImage { .. }
857 )
858 }
859}
860
861#[derive(Debug, Clone, PartialEq, Default)]
863pub struct Drawing {
864 pub ops: Vec<CanvasOp>,
866 pub slots: Vec<crate::animation::NodeId>,
868 pub nodes: Vec<CanvasNode>,
872 pub view_paints: Vec<(u32, ViewPaint)>,
880}
881
882#[derive(Debug, Clone, Copy, PartialEq)]
885pub enum ViewPaint {
886 Fill(crate::style::SvgPaint),
888 Stroke(crate::style::SvgPaint),
890 StrokeWidth,
893 StrokeDasharray,
896 FillCurrentColor,
900 StrokeCurrentColor,
903 Fit(ViewBoxFit),
907 Background {
916 area: Bounds<Points>,
918 rule: FillRule,
920 },
921}
922
923#[derive(Debug, Clone, Copy, PartialEq)]
930pub struct ViewBoxFit {
931 pub view_box: Bounds<Points>,
933 pub align: Option<(Percentage, Percentage)>,
938 pub slice: bool,
940 pub size: Size<Points>,
942}
943
944impl ViewBoxFit {
945 pub fn transform(&self, size: Size<Points>) -> [f32; 6] {
948 let Size { width, height } = self.view_box.size;
949 let (vw, vh) = (width.0, height.0);
950 let (w, h) = (size.width.0.max(0.0), size.height.0.max(0.0));
951 if !(vw > 0.0 && vh > 0.0) {
952 return [0.0; 6];
953 }
954 let (mut sx, mut sy) = (w / vw, h / vh);
955 let (ax, ay) = match self.align {
956 None => (0.0, 0.0),
957 Some((x, y)) => {
958 let s = if self.slice { sx.max(sy) } else { sx.min(sy) };
959 (sx, sy) = (s, s);
960 (x.0, y.0)
961 }
962 };
963 let origin = self.view_box.origin;
964 [
965 sx,
966 0.0,
967 0.0,
968 sy,
969 (w - vw * sx) * ax - origin.x.0 * sx,
970 (h - vh * sy) * ay - origin.y.0 * sy,
971 ]
972 }
973}
974
975#[derive(Debug, Clone, PartialEq, Default)]
983#[non_exhaustive]
984pub struct CanvasNode {
985 pub bounds: Bounds<Points>,
987 pub role: crate::AccessibilityRole,
989 pub label: Arc<str>,
991 pub test_id: Option<Arc<str>>,
993 pub selected: bool,
995}
996
997impl CanvasNode {
998 pub fn new(
1000 bounds: Bounds<Points>,
1001 role: crate::AccessibilityRole,
1002 label: impl Into<Arc<str>>,
1003 ) -> Self {
1004 Self {
1005 bounds,
1006 role,
1007 label: label.into(),
1008 ..Self::default()
1009 }
1010 }
1011
1012 pub fn test_id(mut self, id: impl Into<Arc<str>>) -> Self {
1014 self.test_id = Some(id.into());
1015 self
1016 }
1017
1018 pub fn selected(mut self, selected: bool) -> Self {
1020 self.selected = selected;
1021 self
1022 }
1023}
1024
1025impl Drawing {
1026 pub fn paints_background(&self) -> bool {
1029 self.view_paints
1030 .iter()
1031 .any(|(_, v)| matches!(v, ViewPaint::Background { .. }))
1032 }
1033
1034 pub fn fit(&self) -> Option<ViewBoxFit> {
1036 self.view_paints.iter().find_map(|&(_, v)| match v {
1037 ViewPaint::Fit(fit) => Some(fit),
1038 _ => None,
1039 })
1040 }
1041
1042 pub fn painted(
1050 &self,
1051 paint: &crate::style::PaintStyle,
1052 current: Color,
1053 background: Color,
1054 images: &[crate::effects::Gradient],
1055 size: Size<Points>,
1056 ) -> Drawing {
1057 use crate::style::SvgPaint;
1058 let color = |p: SvgPaint| {
1059 Paint::Color(match p {
1060 SvgPaint::None => Color::TRANSPARENT,
1061 SvgPaint::CurrentColor => current,
1062 SvgPaint::Color(c) => c,
1063 })
1064 };
1065 let mut out = self.clone();
1066 for &(at, view) in &self.view_paints {
1067 let Some(op) = out.ops.get_mut(at as usize) else {
1068 continue;
1069 };
1070 *op = match view {
1071 ViewPaint::Fill(initial) => {
1072 CanvasOp::FillStyle(color(paint.fill.unwrap_or(initial)))
1073 }
1074 ViewPaint::Stroke(initial) => {
1075 CanvasOp::StrokeStyle(color(paint.stroke.unwrap_or(initial)))
1076 }
1077 ViewPaint::StrokeWidth => {
1078 CanvasOp::LineWidth(Num::Const(paint.stroke_width.map_or(1.0, |w| w.0)))
1079 }
1080 ViewPaint::StrokeDasharray => CanvasOp::LineDash(
1081 paint
1082 .stroke_dasharray
1083 .clone()
1084 .unwrap_or_else(|| Arc::from([])),
1085 ),
1086 ViewPaint::FillCurrentColor => CanvasOp::FillStyle(Paint::Color(current)),
1087 ViewPaint::StrokeCurrentColor => CanvasOp::StrokeStyle(Paint::Color(current)),
1088 ViewPaint::Fit(fit) => CanvasOp::Transform(fit.transform(size).map(Num::Const)),
1089 ViewPaint::Background { .. } => continue,
1091 };
1092 }
1093 out.view_paints = Vec::new();
1094 if !self.paints_background() {
1095 return out;
1096 }
1097 let ops = std::mem::take(&mut out.ops);
1098 let mut backgrounds = self.view_paints.iter().filter_map(|&(at, v)| match v {
1099 ViewPaint::Background { area, rule } => Some((at as usize, area, rule)),
1100 _ => None,
1101 });
1102 let mut next = backgrounds.next();
1103 for (i, op) in ops.into_iter().enumerate() {
1104 let Some((_, area, rule)) = next.filter(|&(at, ..)| at == i) else {
1105 out.ops.push(op);
1106 continue;
1107 };
1108 next = backgrounds.next();
1109 out.ops.push(CanvasOp::Save);
1110 if !background.is_transparent() {
1111 out.ops.push(CanvasOp::FillStyle(Paint::Color(background)));
1112 out.ops.push(CanvasOp::Fill(None, rule));
1113 }
1114 for image in images.iter().rev() {
1115 let Some(gradient) = CanvasGradient::from_css(image, area) else {
1116 log::warn!("an elliptical `radial-gradient()` fills no canvas shape");
1117 continue;
1118 };
1119 out.ops
1120 .push(CanvasOp::FillStyle(Paint::Gradient(Arc::new(gradient))));
1121 out.ops.push(CanvasOp::Fill(None, rule));
1122 }
1123 out.ops.push(CanvasOp::Restore);
1124 }
1125 out
1126 }
1127
1128 pub fn slot(&mut self, node: crate::animation::NodeId) -> u16 {
1130 match self.slots.iter().position(|&n| n == node) {
1131 Some(i) => i as u16,
1132 None => {
1133 self.slots.push(node);
1134 (self.slots.len() - 1) as u16
1135 }
1136 }
1137 }
1138
1139 pub fn images(&self) -> impl Iterator<Item = &CanvasImage> {
1141 self.ops.iter().filter_map(|op| match op {
1142 CanvasOp::DrawImage { image, .. } => Some(image),
1143 _ => None,
1144 })
1145 }
1146}
1147
1148impl<Cx> OpArg<Cx> for Points {
1150 fn read<L: HostList<Item: HostInput>>(
1151 r: &mut OpReader<'_, L>,
1152 cx: &mut Cx,
1153 ) -> Result<Option<Self>, OpsError> {
1154 Ok(<f32 as OpArg<Cx>>::read(r, cx)?.map(Points))
1155 }
1156
1157 fn ts(types: &mut TsTypes) -> String {
1158 <f32 as OpArg<Cx>>::ts(types)
1159 }
1160}
1161
1162impl<Cx> OpArg<Cx> for Option<Points> {
1164 fn read<L: HostList<Item: HostInput>>(
1165 r: &mut OpReader<'_, L>,
1166 cx: &mut Cx,
1167 ) -> Result<Option<Self>, OpsError> {
1168 Ok(<Option<f32> as OpArg<Cx>>::read(r, cx)?.map(|v| v.map(Points)))
1169 }
1170
1171 fn ts(types: &mut TsTypes) -> String {
1172 <Option<f32> as OpArg<Cx>>::ts(types)
1173 }
1174}
1175
1176impl<Cx> OpArg<Cx> for Point<Points> {
1178 const ARITY: usize = 2;
1179
1180 fn read<L: HostList<Item: HostInput>>(
1181 r: &mut OpReader<'_, L>,
1182 cx: &mut Cx,
1183 ) -> Result<Option<Self>, OpsError> {
1184 let x = <Points as OpArg<Cx>>::read(r, cx)?;
1185 let y = <Points as OpArg<Cx>>::read(r, cx)?;
1186 Ok(x.zip(y).map(|(x, y)| Point { x, y }))
1187 }
1188
1189 fn ts(types: &mut TsTypes) -> String {
1190 <Points as OpArg<Cx>>::ts(types)
1191 }
1192}
1193
1194pub fn arc_sweep(start: Radians, end: Radians, ccw: bool) -> Radians {
1199 Radians(sweep(start.0, end.0, ccw))
1200}
1201
1202pub(crate) fn sweep(start: f32, end: f32, ccw: bool) -> f32 {
1203 use std::f32::consts::TAU;
1204 if !ccw {
1205 if end - start >= TAU {
1206 TAU
1207 } else {
1208 (end - start).rem_euclid(TAU)
1209 }
1210 } else if start - end >= TAU {
1211 -TAU
1212 } else {
1213 -(start - end).rem_euclid(TAU)
1214 }
1215}
1216
1217pub fn fit_radii(size: Size<Points>, radii: Corners<Points>) -> Corners<Points> {
1221 let [tl, tr, br, bl] = fit(
1222 size.width.0,
1223 size.height.0,
1224 [
1225 radii.top_left.0,
1226 radii.top_right.0,
1227 radii.bottom_right.0,
1228 radii.bottom_left.0,
1229 ],
1230 );
1231 Corners {
1232 top_left: Points(tl),
1233 top_right: Points(tr),
1234 bottom_right: Points(br),
1235 bottom_left: Points(bl),
1236 }
1237}
1238
1239pub(crate) fn fit(w: f32, h: f32, radii: [f32; 4]) -> [f32; 4] {
1242 let r = radii.map(|r| r.max(0.0));
1243 let (w, h) = (w.abs(), h.abs());
1244 let sides = [r[0] + r[1], r[2] + r[3], r[0] + r[3], r[1] + r[2]];
1245 let limits = [w, w, h, h];
1246 let scale = sides
1247 .iter()
1248 .zip(limits)
1249 .filter(|(s, _)| **s > 0.0)
1250 .map(|(s, l)| l / s)
1251 .fold(1.0f32, f32::min);
1252 r.map(|r| r * scale)
1253}
1254
1255pub fn svg_path(d: &str) -> Path {
1260 parse_svg_path(d).into()
1261}
1262
1263pub fn parse_svg_path(d: &str) -> Vec<PathOp> {
1267 let mut out = Vec::new();
1268 let mut p = PathParser {
1269 s: d.as_bytes(),
1270 pos: 0,
1271 };
1272 let (mut x, mut y) = (0f32, 0f32);
1273 let (mut sx, mut sy) = (0f32, 0f32);
1274 let mut last_cubic: Option<(f32, f32)> = None;
1276 let mut last_quad: Option<(f32, f32)> = None;
1277 let mut command = 0u8;
1278 let c = |v: f32| Num::Const(v);
1279 loop {
1280 p.skip_separators();
1281 if p.pos >= p.s.len() {
1282 break;
1283 }
1284 let b = p.s[p.pos];
1285 if b.is_ascii_alphabetic() {
1286 command = b;
1287 p.pos += 1;
1288 } else if command == 0 {
1289 break;
1290 } else if command == b'M' {
1291 command = b'L';
1293 } else if command == b'm' {
1294 command = b'l';
1295 }
1296 let rel = command.is_ascii_lowercase();
1297 let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) };
1298 let upper = command.to_ascii_uppercase();
1299 let ok = (|| -> Option<()> {
1300 match upper {
1301 b'M' => {
1302 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1303 out.push(PathOp::MoveTo(c(nx), c(ny)));
1304 (x, y, sx, sy) = (nx, ny, nx, ny);
1305 last_cubic = None;
1306 last_quad = None;
1307 }
1308 b'L' => {
1309 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1310 out.push(PathOp::LineTo(c(nx), c(ny)));
1311 (x, y) = (nx, ny);
1312 last_cubic = None;
1313 last_quad = None;
1314 }
1315 b'H' => {
1316 x = p.number()? + ox;
1317 out.push(PathOp::LineTo(c(x), c(y)));
1318 last_cubic = None;
1319 last_quad = None;
1320 }
1321 b'V' => {
1322 y = p.number()? + oy;
1323 out.push(PathOp::LineTo(c(x), c(y)));
1324 last_cubic = None;
1325 last_quad = None;
1326 }
1327 b'C' | b'S' => {
1328 let (x1, y1) = if upper == b'C' {
1329 (p.number()? + ox, p.number()? + oy)
1330 } else {
1331 last_cubic.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1333 };
1334 let (x2, y2) = (p.number()? + ox, p.number()? + oy);
1335 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1336 out.push(PathOp::CubicTo([x1, y1, x2, y2, nx, ny].map(c)));
1337 last_cubic = Some((x2, y2));
1338 last_quad = None;
1339 (x, y) = (nx, ny);
1340 }
1341 b'Q' | b'T' => {
1342 let (x1, y1) = if upper == b'Q' {
1343 (p.number()? + ox, p.number()? + oy)
1344 } else {
1345 last_quad.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1346 };
1347 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1348 out.push(PathOp::QuadTo([x1, y1, nx, ny].map(c)));
1349 last_quad = Some((x1, y1));
1350 last_cubic = None;
1351 (x, y) = (nx, ny);
1352 }
1353 b'A' => {
1354 let rx = p.number()?.abs();
1355 let ry = p.number()?.abs();
1356 let rotation = p.number()?;
1357 let large = p.flag()?;
1358 let sweep = p.flag()?;
1359 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1360 arc_to_cubics(&mut out, (x, y), (rx, ry), rotation, large, sweep, (nx, ny));
1361 (x, y) = (nx, ny);
1362 last_cubic = None;
1363 last_quad = None;
1364 }
1365 b'Z' => {
1366 out.push(PathOp::Close);
1367 (x, y) = (sx, sy);
1368 last_cubic = None;
1369 last_quad = None;
1370 command = 0;
1372 }
1373 _ => return None,
1374 }
1375 Some(())
1376 })();
1377 if ok.is_none() {
1378 break;
1379 }
1380 }
1381 out
1382}
1383
1384struct PathParser<'a> {
1385 s: &'a [u8],
1386 pos: usize,
1387}
1388
1389impl PathParser<'_> {
1390 fn skip_separators(&mut self) {
1391 while self.pos < self.s.len()
1392 && (self.s[self.pos].is_ascii_whitespace() || self.s[self.pos] == b',')
1393 {
1394 self.pos += 1;
1395 }
1396 }
1397
1398 fn number(&mut self) -> Option<f32> {
1399 self.skip_separators();
1400 let start = self.pos;
1401 let s = self.s;
1402 let mut i = self.pos;
1403 if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
1404 i += 1;
1405 }
1406 let mut digits = false;
1407 while i < s.len() && s[i].is_ascii_digit() {
1408 i += 1;
1409 digits = true;
1410 }
1411 if i < s.len() && s[i] == b'.' {
1412 i += 1;
1413 while i < s.len() && s[i].is_ascii_digit() {
1414 i += 1;
1415 digits = true;
1416 }
1417 }
1418 if !digits {
1419 return None;
1420 }
1421 if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
1422 let mut j = i + 1;
1423 if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
1424 j += 1;
1425 }
1426 if j < s.len() && s[j].is_ascii_digit() {
1427 while j < s.len() && s[j].is_ascii_digit() {
1428 j += 1;
1429 }
1430 i = j;
1431 }
1432 }
1433 self.pos = i;
1434 std::str::from_utf8(&s[start..i]).ok()?.parse().ok()
1435 }
1436
1437 fn flag(&mut self) -> Option<bool> {
1439 self.skip_separators();
1440 let b = *self.s.get(self.pos)?;
1441 self.pos += 1;
1442 match b {
1443 b'0' => Some(false),
1444 b'1' => Some(true),
1445 _ => None,
1446 }
1447 }
1448}
1449
1450fn arc_to_cubics(
1453 out: &mut Vec<PathOp>,
1454 from: (f32, f32),
1455 radii: (f32, f32),
1456 rotation_deg: f32,
1457 large: bool,
1458 sweep: bool,
1459 to: (f32, f32),
1460) {
1461 let c = |v: f64| Num::Const(v as f32);
1462 let (x1, y1) = (from.0 as f64, from.1 as f64);
1463 let (x2, y2) = (to.0 as f64, to.1 as f64);
1464 let (mut rx, mut ry) = (radii.0 as f64, radii.1 as f64);
1465 if (x1 == x2 && y1 == y2) || rx == 0.0 || ry == 0.0 {
1466 if x1 != x2 || y1 != y2 {
1467 out.push(PathOp::LineTo(c(x2), c(y2)));
1468 }
1469 return;
1470 }
1471 let phi = (rotation_deg as f64).to_radians();
1472 let (sin, cos) = phi.sin_cos();
1473 let dx = (x1 - x2) / 2.0;
1474 let dy = (y1 - y2) / 2.0;
1475 let x1p = cos * dx + sin * dy;
1476 let y1p = -sin * dx + cos * dy;
1477 let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
1479 if lambda > 1.0 {
1480 let s = lambda.sqrt();
1481 rx *= s;
1482 ry *= s;
1483 }
1484 let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
1485 let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
1486 let mut coef = (num / den).max(0.0).sqrt();
1487 if large == sweep {
1488 coef = -coef;
1489 }
1490 let cxp = coef * rx * y1p / ry;
1491 let cyp = -coef * ry * x1p / rx;
1492 let cx = cos * cxp - sin * cyp + (x1 + x2) / 2.0;
1493 let cy = sin * cxp + cos * cyp + (y1 + y2) / 2.0;
1494 let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
1495 let theta1 = angle(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
1496 let mut delta = angle(
1497 (x1p - cxp) / rx,
1498 (y1p - cyp) / ry,
1499 (-x1p - cxp) / rx,
1500 (-y1p - cyp) / ry,
1501 );
1502 if !sweep && delta > 0.0 {
1503 delta -= std::f64::consts::TAU;
1504 } else if sweep && delta < 0.0 {
1505 delta += std::f64::consts::TAU;
1506 }
1507 let segments = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
1509 let step = delta / segments as f64;
1510 let k = 4.0 / 3.0 * (step / 4.0).tan();
1511 let point = |t: f64| {
1512 let (s, co) = t.sin_cos();
1513 (
1514 cx + rx * co * cos - ry * s * sin,
1515 cy + rx * co * sin + ry * s * cos,
1516 )
1517 };
1518 let derivative = |t: f64| {
1519 let (s, co) = t.sin_cos();
1520 (-rx * s * cos - ry * co * sin, -rx * s * sin + ry * co * cos)
1521 };
1522 let mut t = theta1;
1523 for i in 0..segments {
1524 let t2 = t + step;
1525 let (p1x, p1y) = point(t);
1526 let (d1x, d1y) = derivative(t);
1527 let (p2x, p2y) = if i + 1 == segments {
1528 (x2, y2)
1529 } else {
1530 point(t2)
1531 };
1532 let (d2x, d2y) = derivative(t2);
1533 out.push(PathOp::CubicTo([
1534 c(p1x + k * d1x),
1535 c(p1y + k * d1y),
1536 c(p2x - k * d2x),
1537 c(p2y - k * d2y),
1538 c(p2x),
1539 c(p2y),
1540 ]));
1541 t = t2;
1542 }
1543}
1544
1545#[cfg(test)]
1546mod tests {
1547 use super::*;
1548 use crate::text::{AttributedText, TextEngine, TextLayout};
1549
1550 #[test]
1551 fn an_image_density_is_its_file_name_s() {
1552 let density = |uri: &str| CanvasImage { uri: uri.into() }.density();
1553 assert_eq!(density("asset:/logo@3x.png"), 3.0);
1554 assert_eq!(density("https://example.com/a/b@2x.jpg"), 2.0);
1555 assert_eq!(density("asset:/logo.png"), 1.0);
1556 }
1557
1558 #[test]
1563 fn css_gradients_become_canvas_gradients_over_a_box() {
1564 use crate::geometry::{bounds, point, size};
1565 let area = bounds(point(px(10.0), px(20.0)), size(px(100.0), px(50.0)));
1566 let one = |css: &str| crate::css::gradients(css).unwrap().remove(0);
1567 let gradient = |css: &str| CanvasGradient::from_css(&one(css), area);
1568 let down = gradient("linear-gradient(to bottom, #ff0000, #0000ff)").unwrap();
1569 assert_eq!(
1570 down.shape,
1571 GradientShape::Linear {
1572 start: point(px(60.0), px(20.0)),
1573 end: point(px(60.0), px(70.0)),
1574 }
1575 );
1576 assert_eq!(down.stops[0], (Percentage(0.0), Color(0xff00_00ff)));
1577 assert_eq!(
1578 down.stops[down.stops.len() - 1],
1579 (Percentage(1.0), Color(0x0000_ffff))
1580 );
1581 let right = gradient("linear-gradient(90deg, #ff0000, #0000ff)").unwrap();
1582 let GradientShape::Linear { start, end } = right.shape else {
1583 panic!("{right:?}")
1584 };
1585 assert!((start.x.0 - 10.0).abs() < 1e-3 && (start.y.0 - 45.0).abs() < 1e-3);
1586 assert!((end.x.0 - 110.0).abs() < 1e-3 && (end.y.0 - 45.0).abs() < 1e-3);
1587 let stripes =
1590 gradient("repeating-linear-gradient(to bottom, #ff0000 0%, #0000ff 25%)").unwrap();
1591 let at = |o: f32| {
1592 stripes
1593 .stops
1594 .iter()
1595 .filter(|(p, _)| (p.0 - o).abs() < 1e-4)
1596 .count()
1597 };
1598 assert!(
1599 at(0.25) >= 2 && at(0.5) >= 2 && at(0.75) >= 2,
1600 "{stripes:?}"
1601 );
1602 assert!(
1603 stripes
1604 .stops
1605 .iter()
1606 .all(|(p, _)| (0.0..=1.0).contains(&p.0))
1607 );
1608 let cut = gradient("linear-gradient(to bottom, #000000 0%, #ffffff 200%)").unwrap();
1610 assert_eq!(
1611 cut.stops[cut.stops.len() - 1],
1612 (Percentage(1.0), Color(0x8080_80ff))
1613 );
1614 assert!(gradient("radial-gradient(#ff0000, #0000ff)").is_none());
1615 let circle = gradient("radial-gradient(circle, #ff0000, #0000ff)").unwrap();
1616 assert!(matches!(circle.shape, GradientShape::Radial { .. }));
1617 }
1618
1619 #[test]
1623 fn a_drawing_fills_with_its_views_background() {
1624 use crate::geometry::{bounds, point, size};
1625 let area = bounds(point(px(0.0), px(0.0)), size(px(10.0), px(10.0)));
1626 let drawing = crate::element::Painter::new()
1627 .begin_path()
1628 .fill_background_from_view(area)
1629 .finish();
1630 assert!(drawing.paints_background());
1631 let images = crate::css::gradients("linear-gradient(#ff0000, #0000ff)").unwrap();
1632 let none = crate::style::PaintStyle::default();
1633 let painted = drawing.painted(
1634 &none,
1635 Color::TRANSPARENT,
1636 Color(0x00ff_00ff),
1637 &images,
1638 Size::default(),
1639 );
1640 assert!(painted.view_paints.is_empty());
1641 let ops = &painted.ops[1..];
1642 assert_eq!(ops[0], CanvasOp::Save);
1643 assert_eq!(
1644 ops[1],
1645 CanvasOp::FillStyle(Paint::Color(Color(0x00ff_00ff)))
1646 );
1647 assert_eq!(ops[2], CanvasOp::Fill(None, FillRule::NonZero));
1648 assert!(matches!(ops[3], CanvasOp::FillStyle(Paint::Gradient(_))));
1649 assert_eq!(ops[4], CanvasOp::Fill(None, FillRule::NonZero));
1650 assert_eq!(ops[5], CanvasOp::Restore);
1651 let bare = drawing.painted(
1653 &none,
1654 Color::TRANSPARENT,
1655 Color::TRANSPARENT,
1656 &[],
1657 Size::default(),
1658 );
1659 assert_eq!(&bare.ops[1..], [CanvasOp::Save, CanvasOp::Restore]);
1660 }
1661
1662 struct Hanging;
1665
1666 impl TextEngine for Hanging {
1667 type Prepared = String;
1668
1669 fn prepare(&self, text: &AttributedText) -> String {
1670 text.text.to_string()
1671 }
1672
1673 fn prepare_aligned(
1674 &self,
1675 text: &AttributedText,
1676 _: &crate::text::AttachmentAlignments,
1677 ) -> String {
1678 self.prepare(text)
1679 }
1680
1681 fn measure(&self, text: &String, _: Option<Points>) -> Size<Points> {
1682 let shown = text.trim_end_matches(|c: char| c.is_whitespace());
1683 Size::new(Points(10.0 * shown.chars().count() as f32), Points(12.0))
1684 }
1685
1686 fn layout(&self, _: &String, _: Size<Points>) -> TextLayout {
1687 TextLayout(std::sync::Arc::new(()))
1688 }
1689 }
1690
1691 #[test]
1692 fn trailing_white_space_advances_as_canvas_measures_it() {
1693 let font = CanvasFont::default();
1694 for (text, width) in [
1695 ("", 0.0),
1696 ("ab", 20.0),
1697 (" ", 10.0),
1698 (" ", 30.0),
1699 (" items: ", 90.0),
1700 ("a\t", 20.0),
1701 ("名字\u{3000}", 30.0),
1703 ("你好 ", 30.0),
1704 ("ab\n", 20.0),
1706 ] {
1707 assert_eq!(
1708 measure_line(&Hanging, &font, text),
1709 Points(width),
1710 "{text:?}"
1711 );
1712 assert_eq!(
1713 line_metrics(&Hanging, &font, text).width,
1714 Points(width),
1715 "{text:?}"
1716 );
1717 }
1718 }
1719
1720 fn consts(op: &PathOp) -> Vec<f32> {
1721 let v = |n: &Num| match n {
1722 Num::Const(v) => *v,
1723 Num::Slot(_) => f32::NAN,
1724 };
1725 match op {
1726 PathOp::MoveTo(a, b) | PathOp::LineTo(a, b) => vec![v(a), v(b)],
1727 PathOp::QuadTo(n) => n.iter().map(v).collect(),
1728 PathOp::CubicTo(n) => n.iter().map(v).collect(),
1729 _ => vec![],
1730 }
1731 }
1732
1733 #[test]
1734 fn svg_paths_parse_to_absolute_ops() {
1735 let ops = parse_svg_path("M10 20 l5-5 H30 v10 z m1 1 2 2");
1736 assert_eq!(ops.len(), 7);
1737 assert_eq!(consts(&ops[1]), vec![15.0, 15.0]);
1738 assert_eq!(consts(&ops[2]), vec![30.0, 15.0]);
1739 assert_eq!(consts(&ops[3]), vec![30.0, 25.0]);
1740 assert_eq!(ops[4], PathOp::Close);
1741 assert_eq!(consts(&ops[5]), vec![11.0, 21.0]);
1743 assert_eq!(consts(&ops[6]), vec![13.0, 23.0]);
1745 let ops = parse_svg_path("M.5.5L1e1-2");
1747 assert_eq!(consts(&ops[0]), vec![0.5, 0.5]);
1748 assert_eq!(consts(&ops[1]), vec![10.0, -2.0]);
1749 }
1750
1751 #[test]
1752 fn smooth_curves_reflect_control_points() {
1753 let ops = parse_svg_path("M0 0 C0 10 10 10 10 0 S20 -10 20 0");
1754 assert_eq!(consts(&ops[2]), vec![10.0, -10.0, 20.0, -10.0, 20.0, 0.0]);
1755 }
1756
1757 #[test]
1758 fn arcs_become_cubics_ending_on_the_point() {
1759 let ops = parse_svg_path("M0 0 A10 10 0 0120 0");
1761 assert_eq!(ops.len(), 3);
1762 let last = consts(&ops[2]);
1763 assert!((last[4] - 20.0).abs() < 1e-4 && last[5].abs() < 1e-4);
1764 let mid = consts(&ops[1]);
1766 assert!((mid[4] - 10.0).abs() < 1e-3 && (mid[5] + 10.0).abs() < 1e-3);
1767 }
1768
1769 #[test]
1770 fn bad_path_data_keeps_what_parsed() {
1771 let ops = parse_svg_path("M0 0 L10 10 L oops");
1772 assert_eq!(ops.len(), 2);
1773 }
1774
1775 #[test]
1776 fn arc_sweeps_follow_the_canvas_spec() {
1777 use std::f32::consts::{PI, TAU};
1778
1779 use crate::geometry::{radians, size};
1780 let sweep = |a, b, ccw| arc_sweep(radians(a), radians(b), ccw).0;
1781 assert_eq!(sweep(0.0, PI, false), PI);
1782 assert!((sweep(PI, 0.0, false) - PI).abs() < 1e-6);
1784 assert!((sweep(0.0, -PI / 2.0, false) - 1.5 * PI).abs() < 1e-5);
1785 assert_eq!(sweep(0.0, 3.0 * TAU, false), TAU);
1786 assert!((sweep(0.0, PI / 2.0, true) + 1.5 * PI).abs() < 1e-5);
1787 assert_eq!(sweep(TAU, 0.0, true), -TAU);
1788 let corners = |[top_left, top_right, bottom_right, bottom_left]: [f32; 4]| Corners {
1789 top_left: px(top_left),
1790 top_right: px(top_right),
1791 bottom_right: px(bottom_right),
1792 bottom_left: px(bottom_left),
1793 };
1794 assert_eq!(
1795 fit_radii(size(px(10.0), px(100.0)), corners([8.0, 8.0, 0.0, 0.0])),
1796 corners([5.0, 5.0, 0.0, 0.0])
1797 );
1798 }
1799
1800 #[test]
1801 fn fonts_parse_the_css_shorthand() {
1802 let f = CanvasFont::parse("italic bold 14px \"Inter\", sans-serif").unwrap();
1803 assert_eq!((f.size, f.weight, f.italic), (px(14.0), 700, true));
1804 assert_eq!(f.family.as_deref(), Some("\"Inter\", sans-serif"));
1805 assert_eq!(
1806 crate::style::font_families(f.family.as_deref().unwrap()).collect::<Vec<_>>(),
1807 vec![
1808 crate::style::FamilyName::Named("Inter"),
1809 crate::style::FamilyName::System,
1810 ]
1811 );
1812 let single = CanvasFont::parse("14px \"Inter\"").unwrap();
1813 assert_eq!(single.family.as_deref(), Some("Inter"));
1814 let quoted_generic = CanvasFont::parse("14px \"serif\"").unwrap();
1815 assert_eq!(
1816 crate::style::font_families(quoted_generic.family.as_deref().unwrap())
1817 .collect::<Vec<_>>(),
1818 vec![crate::style::FamilyName::Named("serif")]
1819 );
1820 let f = CanvasFont::parse("600 12px/1.5 system-ui").unwrap();
1821 assert_eq!((f.size, f.weight, f.family), (px(12.0), 600, None));
1822 let f = CanvasFont::parse("small-caps tabular-nums 13px system-ui").unwrap();
1823 assert_eq!(
1824 f.variant.0,
1825 FontVariant::SMALL_CAPS | FontVariant::TABULAR_NUMS
1826 );
1827 let numeric = f.with_numeric(FontVariant(FontVariant::OLDSTYLE_NUMS));
1828 assert_eq!(
1829 numeric.variant.0,
1830 FontVariant::SMALL_CAPS | FontVariant::OLDSTYLE_NUMS
1831 );
1832 assert_eq!(f.with_numeric(FontVariant::default()), f);
1833 assert!(CanvasFont::parse("wide 13px system-ui").is_none());
1834 assert!(CanvasFont::parse("bold").is_none());
1835 assert!(CanvasFont::parse("14px").is_none());
1836 assert!(CanvasFont::parse("14px , ").is_none());
1837 }
1838}