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 stops = gradient
315 .resolved_stops(size)
316 .into_iter()
317 .map(|(color, at)| (at.0, color))
318 .collect();
319 let mut out = Self::new(shape);
320 for (offset, color) in line_stops(stops, gradient.repeating) {
321 out.stops.push((Percentage(offset), color));
322 }
323 Some(out)
324 }
325}
326
327fn line_stops(stops: Vec<(f32, Color)>, repeating: bool) -> Vec<(f32, Color)> {
333 let (Some(&(first, _)), Some(&(last, _))) = (stops.first(), stops.last()) else {
334 return stops;
335 };
336 let period = last - first;
337 let (start, end) = if period > 0.0 {
340 (
341 ((0.0 - last) / period).floor(),
342 ((1.0 - first) / period).ceil(),
343 )
344 } else {
345 (0.0, 0.0)
346 };
347 let all = if repeating && period > 1e-4 && end - start < 256.0 {
349 (start as i32..=end as i32)
350 .flat_map(|k| {
351 let shift = k as f32 * period;
352 stops.iter().map(move |&(o, c)| (o + shift, c))
353 })
354 .collect()
355 } else {
356 stops
357 };
358 if all.iter().all(|&(o, _)| (0.0..=1.0).contains(&o)) {
359 return all;
360 }
361 let color_at = |t: f32| {
364 let Some(i) = all.iter().rposition(|&(o, _)| o <= t) else {
365 return all[0].1;
366 };
367 match all.get(i + 1) {
368 Some(&(o, c)) if o > all[i].0 => mix(all[i].1, c, (t - all[i].0) / (o - all[i].0)),
369 _ => all[i].1,
370 }
371 };
372 let mut out = vec![(0.0, color_at(0.0))];
373 out.extend(all.iter().copied().filter(|&(o, _)| o > 0.0 && o < 1.0));
374 out.push((1.0, color_at(1.0)));
375 out
376}
377
378fn mix(a: Color, b: Color, t: f32) -> Color {
380 let channel = |shift: u32| {
381 let (x, y) = ((a.0 >> shift) & 0xff, (b.0 >> shift) & 0xff);
382 ((x as f32 + (y as f32 - x as f32) * t)
383 .round()
384 .clamp(0.0, 255.0) as u32)
385 << shift
386 };
387 Color(channel(24) | channel(16) | channel(8) | channel(0))
388}
389
390#[derive(Debug, Clone, PartialEq)]
392pub enum Paint {
393 Color(Color),
395 Slot(u16),
397 Gradient(Arc<CanvasGradient>),
399}
400
401#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
403#[allow(missing_docs)]
404pub enum Composite {
405 #[default]
406 SourceOver,
407 SourceIn,
408 SourceOut,
409 SourceAtop,
410 DestinationOver,
411 DestinationIn,
412 DestinationOut,
413 DestinationAtop,
414 Lighter,
415 Copy,
416 Xor,
417 Multiply,
418 Screen,
419 Overlay,
420 Darken,
421 Lighten,
422 ColorDodge,
423 ColorBurn,
424 HardLight,
425 SoftLight,
426 Difference,
427 Exclusion,
428 Hue,
429 Saturation,
430 Color,
431 Luminosity,
432}
433
434impl Composite {
435 pub fn parse(name: &str) -> Option<Composite> {
437 use Composite::*;
438 Some(match name {
439 "source-over" => SourceOver,
440 "source-in" => SourceIn,
441 "source-out" => SourceOut,
442 "source-atop" => SourceAtop,
443 "destination-over" => DestinationOver,
444 "destination-in" => DestinationIn,
445 "destination-out" => DestinationOut,
446 "destination-atop" => DestinationAtop,
447 "lighter" => Lighter,
448 "copy" => Copy,
449 "xor" => Xor,
450 "multiply" => Multiply,
451 "screen" => Screen,
452 "overlay" => Overlay,
453 "darken" => Darken,
454 "lighten" => Lighten,
455 "color-dodge" => ColorDodge,
456 "color-burn" => ColorBurn,
457 "hard-light" => HardLight,
458 "soft-light" => SoftLight,
459 "difference" => Difference,
460 "exclusion" => Exclusion,
461 "hue" => Hue,
462 "saturation" => Saturation,
463 "color" => Color,
464 "luminosity" => Luminosity,
465 _ => return None,
466 })
467 }
468}
469
470#[derive(Debug, Clone, PartialEq)]
472pub struct CanvasFont {
473 pub size: Points,
475 pub weight: u16,
477 pub italic: bool,
479 pub family: Option<Arc<str>>,
482 pub variant: FontVariant,
486}
487
488impl Default for CanvasFont {
489 fn default() -> Self {
491 Self {
492 size: px(10.0),
493 weight: 400,
494 italic: false,
495 family: None,
496 variant: FontVariant::default(),
497 }
498 }
499}
500
501impl CanvasFont {
502 pub fn parse(s: &str) -> Option<CanvasFont> {
506 let mut font = CanvasFont {
507 size: Points::ZERO,
508 ..CanvasFont::default()
509 };
510 let mut rest = s.trim();
511 loop {
513 let (word, tail) = match rest.split_once(char::is_whitespace) {
514 Some((w, t)) => (w, t.trim_start()),
515 None => (rest, ""),
516 };
517 if let Some(size) = font_size(word) {
518 font.size = size;
519 rest = tail;
520 break;
521 }
522 match word {
523 "italic" | "oblique" => font.italic = true,
524 "normal" | "condensed" | "expanded" => {}
525 w if let Some(v) = FontVariant::parse(w) => font.variant.0 |= v.0,
526 "bold" | "bolder" => font.weight = 700,
527 "lighter" => font.weight = 300,
528 w => match w.parse::<u16>() {
529 Ok(n) if (1..=1000).contains(&n) => font.weight = n,
530 _ => return None,
531 },
532 }
533 if tail.is_empty() {
534 return None;
535 }
536 rest = tail;
537 }
538 let family = rest
539 .split(',')
540 .next()
541 .map(|f| f.trim().trim_matches(['"', '\'']))
542 .filter(|f| !f.is_empty())?;
543 font.family = match family {
544 "system-ui" | "sans-serif" | "-apple-system" | "ui-sans-serif" => None,
545 f => Some(f.into()),
546 };
547 Some(font)
548 }
549}
550
551fn font_size(word: &str) -> Option<Points> {
553 let word = word.split('/').next()?;
554 let (num, scale) = if let Some(n) = word.strip_suffix("px") {
555 (n, 1.0)
556 } else if let Some(n) = word.strip_suffix("rem").or_else(|| word.strip_suffix("em")) {
557 (n, 16.0)
558 } else {
559 (word.strip_suffix("pt")?, 4.0 / 3.0)
560 };
561 num.parse::<f32>()
562 .ok()
563 .filter(|v| *v > 0.0)
564 .map(|v| Points(v * scale))
565}
566
567impl CanvasFont {
568 pub fn with_numeric(&self, numeric: FontVariant) -> CanvasFont {
571 let mut font = self.clone();
572 if numeric.0 != 0 {
573 font.variant = FontVariant(font.variant.0 & FontVariant::SMALL_CAPS | numeric.0);
574 }
575 font
576 }
577
578 pub fn text_style(&self) -> crate::text::ResolvedTextStyle {
580 crate::text::ResolvedTextStyle {
581 font_size: self.size,
582 font_weight: self.weight,
583 italic: self.italic,
584 font_variant: self.variant,
585 font_family: self.family.as_deref().map(crate::style::FontFamily::new),
586 ..Default::default()
587 }
588 }
589}
590
591pub fn measure_line(
593 engine: &impl crate::text::TextEngine,
594 font: &CanvasFont,
595 text: &str,
596) -> Points {
597 if text.is_empty() {
598 return Points::ZERO;
599 }
600 advance(engine, font, text)
601}
602
603const MARK: &str = "x";
605
606fn advance(engine: &impl crate::text::TextEngine, font: &CanvasFont, text: &str) -> Points {
612 let width = |text: &str| {
613 let mut attributed = crate::text::AttributedText {
614 no_wrap: true,
615 max_lines: 1,
616 ..Default::default()
617 };
618 attributed.push(text, font.text_style());
619 let prepared = engine.prepare(&attributed);
620 engine.measure(&prepared, None).width
621 };
622 let hangs = text.ends_with(|c: char| c.is_whitespace() && !is_line_break(c));
624 if !hangs {
625 return width(text);
626 }
627 let mut marked = String::with_capacity(text.len() + MARK.len());
628 marked.push_str(text);
629 marked.push_str(MARK);
630 (width(&marked) - width(MARK)).max(Points::ZERO)
631}
632
633fn is_line_break(c: char) -> bool {
635 matches!(
636 c,
637 '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}'
638 )
639}
640
641#[derive(Debug, Clone, Copy, PartialEq, Default)]
645#[non_exhaustive]
646pub struct TextMetrics {
647 pub width: Points,
649 pub ascent: Points,
651 pub descent: Points,
653 pub height: Points,
655}
656
657pub fn line_metrics(
661 engine: &impl crate::text::TextEngine,
662 font: &CanvasFont,
663 text: &str,
664) -> TextMetrics {
665 let mut attributed = crate::text::AttributedText {
666 no_wrap: true,
667 max_lines: 1,
668 ..Default::default()
669 };
670 attributed.push(if text.is_empty() { " " } else { text }, font.text_style());
672 let prepared = engine.prepare(&attributed);
673 let size = engine.measure(&prepared, None);
674 let width = if text.is_empty() {
675 Points::ZERO
676 } else {
677 advance(engine, font, text)
678 };
679 let layout = engine.layout(&prepared, size);
680 match engine.lines(&layout).first() {
681 Some(line) => TextMetrics {
682 width,
683 ascent: line.ascender,
684 descent: line.descender,
685 height: line.height,
686 },
687 None => TextMetrics {
688 width,
689 ascent: Points(font.size.0 * 0.8),
690 descent: Points(font.size.0 * 0.2),
691 height: size.height,
692 },
693 }
694}
695
696#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
698pub enum CanvasTextAlign {
699 #[default]
701 Start,
702 End,
704 Left,
706 Right,
708 Center,
710}
711
712#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
714pub enum CanvasTextBaseline {
715 #[default]
717 Alphabetic,
718 Top,
720 Hanging,
722 Middle,
724 Ideographic,
726 Bottom,
728}
729
730#[derive(Debug, Clone, PartialEq)]
732pub struct CanvasImage {
733 pub uri: Arc<str>,
735}
736
737#[derive(Debug, Clone, PartialEq, JsOps)]
741#[ops(cx = Drawing)]
742pub enum CanvasOp {
743 #[op(code = CV_SAVE)]
745 Save,
746 #[op(code = CV_RESTORE)]
748 Restore,
749 #[op(code = CV_TRANSLATE, method = "translate", params = "x, y")]
751 Translate(Num, Num),
752 #[op(code = CV_SCALE, method = "scale", params = "x, y")]
754 Scale(Num, Num),
755 #[op(code = CV_ROTATE, method = "rotate", params = "angle")]
757 Rotate(Num),
758 #[op(code = CV_TRANSFORM, method = "transform", params = "a, b, c, d, e, f")]
761 Transform([Num; 6]),
762 #[op(code = CV_SET_TRANSFORM, method = "setTransform", params = "a, b, c, d, e, f")]
767 SetTransform([Num; 6]),
768 #[op(code = CV_BEGIN_PATH, method = "beginPath")]
770 BeginPath,
771 #[op(nested)]
773 Path(PathOp),
774 #[op(code = CV_FILL)]
776 Fill(Option<Path>, FillRule),
777 #[op(code = CV_STROKE)]
779 Stroke(Option<Path>),
780 #[op(code = CV_CLIP)]
782 Clip(Option<Path>, FillRule),
783 #[op(code = CV_FILL_RECT, method = "fillRect", params = "x, y, w, h")]
786 FillRect([Num; 4]),
787 #[op(code = CV_STROKE_RECT, method = "strokeRect", params = "x, y, w, h")]
789 StrokeRect([Num; 4]),
790 #[op(code = CV_CLEAR_RECT, method = "clearRect", params = "x, y, w, h")]
792 ClearRect([Num; 4]),
793 #[op(code = CV_FILL_STYLE)]
795 FillStyle(Paint),
796 #[op(code = CV_STROKE_STYLE)]
798 StrokeStyle(Paint),
799 #[op(code = CV_LINE_WIDTH, property = "lineWidth", initial = "1")]
801 LineWidth(Num),
802 #[op(code = CV_LINE_CAP, property = "lineCap", initial = "\"butt\"")]
804 LineCap(LineCap),
805 #[op(code = CV_LINE_JOIN, property = "lineJoin", initial = "\"miter\"")]
807 LineJoin(LineJoin),
808 #[op(code = CV_MITER_LIMIT, property = "miterLimit", initial = "10", min = 1.0)]
811 MiterLimit(f32),
812 #[op(code = CV_LINE_DASH, with = crate::js::canvas::line_dash)]
814 LineDash(Arc<[Points]>),
815 #[op(code = CV_LINE_DASH_OFFSET, property = "lineDashOffset", initial = "0")]
817 LineDashOffset(Num),
818 #[op(code = CV_GLOBAL_ALPHA, property = "globalAlpha", initial = "1")]
820 GlobalAlpha(Num),
821 #[op(
824 code = CV_COMPOSITE,
825 property = "globalCompositeOperation",
826 initial = "\"source-over\""
827 )]
828 Composite(Composite),
829 #[op(code = CV_SHADOW_COLOR, property = "shadowColor", initial = "\"rgba(0,0,0,0)\"")]
831 ShadowColor(Color),
832 #[op(code = CV_SHADOW_BLUR, property = "shadowBlur", initial = "0", min = 0.0)]
834 ShadowBlur(Points),
835 #[op(code = CV_SHADOW_OFFSET)]
837 ShadowOffset(Point<Points>),
838 #[op(code = CV_FONT, property = "font", initial = "\"10px sans-serif\"")]
841 Font(CanvasFont),
842 #[op(
847 code = CV_FONT_VARIANT_NUMERIC,
848 property = "fontVariantNumeric",
849 initial = "\"normal\""
850 )]
851 FontVariantNumeric(FontVariant),
852 #[op(code = CV_TEXT_ALIGN, property = "textAlign", initial = "\"start\"")]
854 TextAlign(CanvasTextAlign),
855 #[op(code = CV_TEXT_BASELINE, property = "textBaseline", initial = "\"alphabetic\"")]
857 TextBaseline(CanvasTextBaseline),
858 #[op(code = CV_FILL_TEXT)]
860 FillText {
861 text: Arc<str>,
863 x: Num,
865 y: Num,
867 max_width: Option<Points>,
869 },
870 #[op(code = CV_STROKE_TEXT)]
872 StrokeText {
873 text: Arc<str>,
875 x: Num,
877 y: Num,
879 max_width: Option<Points>,
881 },
882 #[op(code = CV_DRAW_IMAGE)]
884 DrawImage {
885 image: CanvasImage,
887 source: Option<Bounds<ScaledPixels>>,
889 dest: [Num; 4],
891 },
892}
893
894impl CanvasOp {
895 pub fn paints(&self) -> bool {
898 matches!(
899 self,
900 CanvasOp::Fill(..)
901 | CanvasOp::Stroke(_)
902 | CanvasOp::FillRect(_)
903 | CanvasOp::StrokeRect(_)
904 | CanvasOp::ClearRect(_)
905 | CanvasOp::FillText { .. }
906 | CanvasOp::StrokeText { .. }
907 | CanvasOp::DrawImage { .. }
908 )
909 }
910}
911
912#[derive(Debug, Clone, PartialEq, Default)]
914pub struct Drawing {
915 pub ops: Vec<CanvasOp>,
917 pub slots: Vec<crate::animation::NodeId>,
919 pub nodes: Vec<CanvasNode>,
923 pub view_paints: Vec<(u32, ViewPaint)>,
931}
932
933#[derive(Debug, Clone, Copy, PartialEq)]
936pub enum ViewPaint {
937 Fill(crate::style::SvgPaint),
939 Stroke(crate::style::SvgPaint),
941 StrokeWidth,
944 StrokeDasharray,
947 Background {
956 area: Bounds<Points>,
958 rule: FillRule,
960 },
961}
962
963#[derive(Debug, Clone, PartialEq, Default)]
971#[non_exhaustive]
972pub struct CanvasNode {
973 pub bounds: Bounds<Points>,
975 pub role: crate::AccessibilityRole,
977 pub label: Arc<str>,
979 pub test_id: Option<Arc<str>>,
981 pub selected: bool,
983}
984
985impl CanvasNode {
986 pub fn new(
988 bounds: Bounds<Points>,
989 role: crate::AccessibilityRole,
990 label: impl Into<Arc<str>>,
991 ) -> Self {
992 Self {
993 bounds,
994 role,
995 label: label.into(),
996 ..Self::default()
997 }
998 }
999
1000 pub fn test_id(mut self, id: impl Into<Arc<str>>) -> Self {
1002 self.test_id = Some(id.into());
1003 self
1004 }
1005
1006 pub fn selected(mut self, selected: bool) -> Self {
1008 self.selected = selected;
1009 self
1010 }
1011}
1012
1013impl Drawing {
1014 pub fn paints_background(&self) -> bool {
1017 self.view_paints
1018 .iter()
1019 .any(|(_, v)| matches!(v, ViewPaint::Background { .. }))
1020 }
1021
1022 pub fn painted(
1029 &self,
1030 paint: &crate::style::PaintStyle,
1031 current: Color,
1032 background: Color,
1033 images: &[crate::effects::Gradient],
1034 ) -> Drawing {
1035 use crate::style::SvgPaint;
1036 let color = |p: SvgPaint| {
1037 Paint::Color(match p {
1038 SvgPaint::None => Color::TRANSPARENT,
1039 SvgPaint::CurrentColor => current,
1040 SvgPaint::Color(c) => c,
1041 })
1042 };
1043 let mut out = self.clone();
1044 for &(at, view) in &self.view_paints {
1045 let Some(op) = out.ops.get_mut(at as usize) else {
1046 continue;
1047 };
1048 *op = match view {
1049 ViewPaint::Fill(initial) => {
1050 CanvasOp::FillStyle(color(paint.fill.unwrap_or(initial)))
1051 }
1052 ViewPaint::Stroke(initial) => {
1053 CanvasOp::StrokeStyle(color(paint.stroke.unwrap_or(initial)))
1054 }
1055 ViewPaint::StrokeWidth => {
1056 CanvasOp::LineWidth(Num::Const(paint.stroke_width.map_or(1.0, |w| w.0)))
1057 }
1058 ViewPaint::StrokeDasharray => CanvasOp::LineDash(
1059 paint
1060 .stroke_dasharray
1061 .clone()
1062 .unwrap_or_else(|| Arc::from([])),
1063 ),
1064 ViewPaint::Background { .. } => continue,
1066 };
1067 }
1068 out.view_paints = Vec::new();
1069 if !self.paints_background() {
1070 return out;
1071 }
1072 let ops = std::mem::take(&mut out.ops);
1073 let mut backgrounds = self.view_paints.iter().filter_map(|&(at, v)| match v {
1074 ViewPaint::Background { area, rule } => Some((at as usize, area, rule)),
1075 _ => None,
1076 });
1077 let mut next = backgrounds.next();
1078 for (i, op) in ops.into_iter().enumerate() {
1079 let Some((_, area, rule)) = next.filter(|&(at, ..)| at == i) else {
1080 out.ops.push(op);
1081 continue;
1082 };
1083 next = backgrounds.next();
1084 out.ops.push(CanvasOp::Save);
1085 if !background.is_transparent() {
1086 out.ops.push(CanvasOp::FillStyle(Paint::Color(background)));
1087 out.ops.push(CanvasOp::Fill(None, rule));
1088 }
1089 for image in images.iter().rev() {
1090 let Some(gradient) = CanvasGradient::from_css(image, area) else {
1091 log::warn!("an elliptical `radial-gradient()` fills no canvas shape");
1092 continue;
1093 };
1094 out.ops
1095 .push(CanvasOp::FillStyle(Paint::Gradient(Arc::new(gradient))));
1096 out.ops.push(CanvasOp::Fill(None, rule));
1097 }
1098 out.ops.push(CanvasOp::Restore);
1099 }
1100 out
1101 }
1102
1103 pub fn slot(&mut self, node: crate::animation::NodeId) -> u16 {
1105 match self.slots.iter().position(|&n| n == node) {
1106 Some(i) => i as u16,
1107 None => {
1108 self.slots.push(node);
1109 (self.slots.len() - 1) as u16
1110 }
1111 }
1112 }
1113
1114 pub fn images(&self) -> impl Iterator<Item = &CanvasImage> {
1116 self.ops.iter().filter_map(|op| match op {
1117 CanvasOp::DrawImage { image, .. } => Some(image),
1118 _ => None,
1119 })
1120 }
1121}
1122
1123impl<Cx> OpArg<Cx> for Points {
1125 fn read<L: HostList<Item: HostInput>>(
1126 r: &mut OpReader<'_, L>,
1127 cx: &mut Cx,
1128 ) -> Result<Option<Self>, OpsError> {
1129 Ok(<f32 as OpArg<Cx>>::read(r, cx)?.map(Points))
1130 }
1131
1132 fn ts(types: &mut TsTypes) -> String {
1133 <f32 as OpArg<Cx>>::ts(types)
1134 }
1135}
1136
1137impl<Cx> OpArg<Cx> for Option<Points> {
1139 fn read<L: HostList<Item: HostInput>>(
1140 r: &mut OpReader<'_, L>,
1141 cx: &mut Cx,
1142 ) -> Result<Option<Self>, OpsError> {
1143 Ok(<Option<f32> as OpArg<Cx>>::read(r, cx)?.map(|v| v.map(Points)))
1144 }
1145
1146 fn ts(types: &mut TsTypes) -> String {
1147 <Option<f32> as OpArg<Cx>>::ts(types)
1148 }
1149}
1150
1151impl<Cx> OpArg<Cx> for Point<Points> {
1153 const ARITY: usize = 2;
1154
1155 fn read<L: HostList<Item: HostInput>>(
1156 r: &mut OpReader<'_, L>,
1157 cx: &mut Cx,
1158 ) -> Result<Option<Self>, OpsError> {
1159 let x = <Points as OpArg<Cx>>::read(r, cx)?;
1160 let y = <Points as OpArg<Cx>>::read(r, cx)?;
1161 Ok(x.zip(y).map(|(x, y)| Point { x, y }))
1162 }
1163
1164 fn ts(types: &mut TsTypes) -> String {
1165 <Points as OpArg<Cx>>::ts(types)
1166 }
1167}
1168
1169pub fn arc_sweep(start: Radians, end: Radians, ccw: bool) -> Radians {
1174 Radians(sweep(start.0, end.0, ccw))
1175}
1176
1177pub(crate) fn sweep(start: f32, end: f32, ccw: bool) -> f32 {
1178 use std::f32::consts::TAU;
1179 if !ccw {
1180 if end - start >= TAU {
1181 TAU
1182 } else {
1183 (end - start).rem_euclid(TAU)
1184 }
1185 } else if start - end >= TAU {
1186 -TAU
1187 } else {
1188 -(start - end).rem_euclid(TAU)
1189 }
1190}
1191
1192pub fn fit_radii(size: Size<Points>, radii: Corners<Points>) -> Corners<Points> {
1196 let [tl, tr, br, bl] = fit(
1197 size.width.0,
1198 size.height.0,
1199 [
1200 radii.top_left.0,
1201 radii.top_right.0,
1202 radii.bottom_right.0,
1203 radii.bottom_left.0,
1204 ],
1205 );
1206 Corners {
1207 top_left: Points(tl),
1208 top_right: Points(tr),
1209 bottom_right: Points(br),
1210 bottom_left: Points(bl),
1211 }
1212}
1213
1214pub(crate) fn fit(w: f32, h: f32, radii: [f32; 4]) -> [f32; 4] {
1217 let r = radii.map(|r| r.max(0.0));
1218 let (w, h) = (w.abs(), h.abs());
1219 let sides = [r[0] + r[1], r[2] + r[3], r[0] + r[3], r[1] + r[2]];
1220 let limits = [w, w, h, h];
1221 let scale = sides
1222 .iter()
1223 .zip(limits)
1224 .filter(|(s, _)| **s > 0.0)
1225 .map(|(s, l)| l / s)
1226 .fold(1.0f32, f32::min);
1227 r.map(|r| r * scale)
1228}
1229
1230pub fn svg_path(d: &str) -> Path {
1235 parse_svg_path(d).into()
1236}
1237
1238pub fn parse_svg_path(d: &str) -> Vec<PathOp> {
1242 let mut out = Vec::new();
1243 let mut p = PathParser {
1244 s: d.as_bytes(),
1245 pos: 0,
1246 };
1247 let (mut x, mut y) = (0f32, 0f32);
1248 let (mut sx, mut sy) = (0f32, 0f32);
1249 let mut last_cubic: Option<(f32, f32)> = None;
1251 let mut last_quad: Option<(f32, f32)> = None;
1252 let mut command = 0u8;
1253 let c = |v: f32| Num::Const(v);
1254 loop {
1255 p.skip_separators();
1256 if p.pos >= p.s.len() {
1257 break;
1258 }
1259 let b = p.s[p.pos];
1260 if b.is_ascii_alphabetic() {
1261 command = b;
1262 p.pos += 1;
1263 } else if command == 0 {
1264 break;
1265 } else if command == b'M' {
1266 command = b'L';
1268 } else if command == b'm' {
1269 command = b'l';
1270 }
1271 let rel = command.is_ascii_lowercase();
1272 let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) };
1273 let upper = command.to_ascii_uppercase();
1274 let ok = (|| -> Option<()> {
1275 match upper {
1276 b'M' => {
1277 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1278 out.push(PathOp::MoveTo(c(nx), c(ny)));
1279 (x, y, sx, sy) = (nx, ny, nx, ny);
1280 last_cubic = None;
1281 last_quad = None;
1282 }
1283 b'L' => {
1284 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1285 out.push(PathOp::LineTo(c(nx), c(ny)));
1286 (x, y) = (nx, ny);
1287 last_cubic = None;
1288 last_quad = None;
1289 }
1290 b'H' => {
1291 x = p.number()? + ox;
1292 out.push(PathOp::LineTo(c(x), c(y)));
1293 last_cubic = None;
1294 last_quad = None;
1295 }
1296 b'V' => {
1297 y = p.number()? + oy;
1298 out.push(PathOp::LineTo(c(x), c(y)));
1299 last_cubic = None;
1300 last_quad = None;
1301 }
1302 b'C' | b'S' => {
1303 let (x1, y1) = if upper == b'C' {
1304 (p.number()? + ox, p.number()? + oy)
1305 } else {
1306 last_cubic.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1308 };
1309 let (x2, y2) = (p.number()? + ox, p.number()? + oy);
1310 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1311 out.push(PathOp::CubicTo([x1, y1, x2, y2, nx, ny].map(c)));
1312 last_cubic = Some((x2, y2));
1313 last_quad = None;
1314 (x, y) = (nx, ny);
1315 }
1316 b'Q' | b'T' => {
1317 let (x1, y1) = if upper == b'Q' {
1318 (p.number()? + ox, p.number()? + oy)
1319 } else {
1320 last_quad.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1321 };
1322 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1323 out.push(PathOp::QuadTo([x1, y1, nx, ny].map(c)));
1324 last_quad = Some((x1, y1));
1325 last_cubic = None;
1326 (x, y) = (nx, ny);
1327 }
1328 b'A' => {
1329 let rx = p.number()?.abs();
1330 let ry = p.number()?.abs();
1331 let rotation = p.number()?;
1332 let large = p.flag()?;
1333 let sweep = p.flag()?;
1334 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1335 arc_to_cubics(&mut out, (x, y), (rx, ry), rotation, large, sweep, (nx, ny));
1336 (x, y) = (nx, ny);
1337 last_cubic = None;
1338 last_quad = None;
1339 }
1340 b'Z' => {
1341 out.push(PathOp::Close);
1342 (x, y) = (sx, sy);
1343 last_cubic = None;
1344 last_quad = None;
1345 command = 0;
1347 }
1348 _ => return None,
1349 }
1350 Some(())
1351 })();
1352 if ok.is_none() {
1353 break;
1354 }
1355 }
1356 out
1357}
1358
1359struct PathParser<'a> {
1360 s: &'a [u8],
1361 pos: usize,
1362}
1363
1364impl PathParser<'_> {
1365 fn skip_separators(&mut self) {
1366 while self.pos < self.s.len()
1367 && (self.s[self.pos].is_ascii_whitespace() || self.s[self.pos] == b',')
1368 {
1369 self.pos += 1;
1370 }
1371 }
1372
1373 fn number(&mut self) -> Option<f32> {
1374 self.skip_separators();
1375 let start = self.pos;
1376 let s = self.s;
1377 let mut i = self.pos;
1378 if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
1379 i += 1;
1380 }
1381 let mut digits = false;
1382 while i < s.len() && s[i].is_ascii_digit() {
1383 i += 1;
1384 digits = true;
1385 }
1386 if i < s.len() && s[i] == b'.' {
1387 i += 1;
1388 while i < s.len() && s[i].is_ascii_digit() {
1389 i += 1;
1390 digits = true;
1391 }
1392 }
1393 if !digits {
1394 return None;
1395 }
1396 if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
1397 let mut j = i + 1;
1398 if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
1399 j += 1;
1400 }
1401 if j < s.len() && s[j].is_ascii_digit() {
1402 while j < s.len() && s[j].is_ascii_digit() {
1403 j += 1;
1404 }
1405 i = j;
1406 }
1407 }
1408 self.pos = i;
1409 std::str::from_utf8(&s[start..i]).ok()?.parse().ok()
1410 }
1411
1412 fn flag(&mut self) -> Option<bool> {
1414 self.skip_separators();
1415 let b = *self.s.get(self.pos)?;
1416 self.pos += 1;
1417 match b {
1418 b'0' => Some(false),
1419 b'1' => Some(true),
1420 _ => None,
1421 }
1422 }
1423}
1424
1425fn arc_to_cubics(
1428 out: &mut Vec<PathOp>,
1429 from: (f32, f32),
1430 radii: (f32, f32),
1431 rotation_deg: f32,
1432 large: bool,
1433 sweep: bool,
1434 to: (f32, f32),
1435) {
1436 let c = |v: f64| Num::Const(v as f32);
1437 let (x1, y1) = (from.0 as f64, from.1 as f64);
1438 let (x2, y2) = (to.0 as f64, to.1 as f64);
1439 let (mut rx, mut ry) = (radii.0 as f64, radii.1 as f64);
1440 if (x1 == x2 && y1 == y2) || rx == 0.0 || ry == 0.0 {
1441 if x1 != x2 || y1 != y2 {
1442 out.push(PathOp::LineTo(c(x2), c(y2)));
1443 }
1444 return;
1445 }
1446 let phi = (rotation_deg as f64).to_radians();
1447 let (sin, cos) = phi.sin_cos();
1448 let dx = (x1 - x2) / 2.0;
1449 let dy = (y1 - y2) / 2.0;
1450 let x1p = cos * dx + sin * dy;
1451 let y1p = -sin * dx + cos * dy;
1452 let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
1454 if lambda > 1.0 {
1455 let s = lambda.sqrt();
1456 rx *= s;
1457 ry *= s;
1458 }
1459 let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
1460 let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
1461 let mut coef = (num / den).max(0.0).sqrt();
1462 if large == sweep {
1463 coef = -coef;
1464 }
1465 let cxp = coef * rx * y1p / ry;
1466 let cyp = -coef * ry * x1p / rx;
1467 let cx = cos * cxp - sin * cyp + (x1 + x2) / 2.0;
1468 let cy = sin * cxp + cos * cyp + (y1 + y2) / 2.0;
1469 let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
1470 let theta1 = angle(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
1471 let mut delta = angle(
1472 (x1p - cxp) / rx,
1473 (y1p - cyp) / ry,
1474 (-x1p - cxp) / rx,
1475 (-y1p - cyp) / ry,
1476 );
1477 if !sweep && delta > 0.0 {
1478 delta -= std::f64::consts::TAU;
1479 } else if sweep && delta < 0.0 {
1480 delta += std::f64::consts::TAU;
1481 }
1482 let segments = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
1484 let step = delta / segments as f64;
1485 let k = 4.0 / 3.0 * (step / 4.0).tan();
1486 let point = |t: f64| {
1487 let (s, co) = t.sin_cos();
1488 (
1489 cx + rx * co * cos - ry * s * sin,
1490 cy + rx * co * sin + ry * s * cos,
1491 )
1492 };
1493 let derivative = |t: f64| {
1494 let (s, co) = t.sin_cos();
1495 (-rx * s * cos - ry * co * sin, -rx * s * sin + ry * co * cos)
1496 };
1497 let mut t = theta1;
1498 for i in 0..segments {
1499 let t2 = t + step;
1500 let (p1x, p1y) = point(t);
1501 let (d1x, d1y) = derivative(t);
1502 let (p2x, p2y) = if i + 1 == segments {
1503 (x2, y2)
1504 } else {
1505 point(t2)
1506 };
1507 let (d2x, d2y) = derivative(t2);
1508 out.push(PathOp::CubicTo([
1509 c(p1x + k * d1x),
1510 c(p1y + k * d1y),
1511 c(p2x - k * d2x),
1512 c(p2y - k * d2y),
1513 c(p2x),
1514 c(p2y),
1515 ]));
1516 t = t2;
1517 }
1518}
1519
1520#[cfg(test)]
1521mod tests {
1522 use super::*;
1523 use crate::text::{AttributedText, TextEngine, TextLayout};
1524
1525 #[test]
1530 fn css_gradients_become_canvas_gradients_over_a_box() {
1531 use crate::geometry::{bounds, point, size};
1532 let area = bounds(point(px(10.0), px(20.0)), size(px(100.0), px(50.0)));
1533 let one = |css: &str| crate::css::gradients(css).unwrap().remove(0);
1534 let gradient = |css: &str| CanvasGradient::from_css(&one(css), area);
1535 let down = gradient("linear-gradient(to bottom, #ff0000, #0000ff)").unwrap();
1536 assert_eq!(
1537 down.shape,
1538 GradientShape::Linear {
1539 start: point(px(60.0), px(20.0)),
1540 end: point(px(60.0), px(70.0)),
1541 }
1542 );
1543 assert_eq!(down.stops[0], (Percentage(0.0), Color(0xff00_00ff)));
1544 assert_eq!(
1545 down.stops[down.stops.len() - 1],
1546 (Percentage(1.0), Color(0x0000_ffff))
1547 );
1548 let right = gradient("linear-gradient(90deg, #ff0000, #0000ff)").unwrap();
1549 let GradientShape::Linear { start, end } = right.shape else {
1550 panic!("{right:?}")
1551 };
1552 assert!((start.x.0 - 10.0).abs() < 1e-3 && (start.y.0 - 45.0).abs() < 1e-3);
1553 assert!((end.x.0 - 110.0).abs() < 1e-3 && (end.y.0 - 45.0).abs() < 1e-3);
1554 let stripes =
1557 gradient("repeating-linear-gradient(to bottom, #ff0000 0%, #0000ff 25%)").unwrap();
1558 let at = |o: f32| {
1559 stripes
1560 .stops
1561 .iter()
1562 .filter(|(p, _)| (p.0 - o).abs() < 1e-4)
1563 .count()
1564 };
1565 assert!(
1566 at(0.25) >= 2 && at(0.5) >= 2 && at(0.75) >= 2,
1567 "{stripes:?}"
1568 );
1569 assert!(
1570 stripes
1571 .stops
1572 .iter()
1573 .all(|(p, _)| (0.0..=1.0).contains(&p.0))
1574 );
1575 let cut = line_stops(
1577 vec![(0.0, Color(0x0000_00ff)), (2.0, Color(0xffff_ffff))],
1578 false,
1579 );
1580 assert_eq!(cut[cut.len() - 1], (1.0, Color(0x8080_80ff)));
1581 assert!(gradient("radial-gradient(#ff0000, #0000ff)").is_none());
1582 let circle = gradient("radial-gradient(circle, #ff0000, #0000ff)").unwrap();
1583 assert!(matches!(circle.shape, GradientShape::Radial { .. }));
1584 }
1585
1586 #[test]
1590 fn a_drawing_fills_with_its_views_background() {
1591 use crate::geometry::{bounds, point, size};
1592 let area = bounds(point(px(0.0), px(0.0)), size(px(10.0), px(10.0)));
1593 let drawing = crate::element::Painter::new()
1594 .begin_path()
1595 .fill_background_from_view(area)
1596 .finish();
1597 assert!(drawing.paints_background());
1598 let images = crate::css::gradients("linear-gradient(#ff0000, #0000ff)").unwrap();
1599 let none = crate::style::PaintStyle::default();
1600 let painted = drawing.painted(&none, Color::TRANSPARENT, Color(0x00ff_00ff), &images);
1601 assert!(painted.view_paints.is_empty());
1602 let ops = &painted.ops[1..];
1603 assert_eq!(ops[0], CanvasOp::Save);
1604 assert_eq!(
1605 ops[1],
1606 CanvasOp::FillStyle(Paint::Color(Color(0x00ff_00ff)))
1607 );
1608 assert_eq!(ops[2], CanvasOp::Fill(None, FillRule::NonZero));
1609 assert!(matches!(ops[3], CanvasOp::FillStyle(Paint::Gradient(_))));
1610 assert_eq!(ops[4], CanvasOp::Fill(None, FillRule::NonZero));
1611 assert_eq!(ops[5], CanvasOp::Restore);
1612 let bare = drawing.painted(&none, Color::TRANSPARENT, Color::TRANSPARENT, &[]);
1614 assert_eq!(&bare.ops[1..], [CanvasOp::Save, CanvasOp::Restore]);
1615 }
1616
1617 struct Hanging;
1620
1621 impl TextEngine for Hanging {
1622 type Prepared = String;
1623
1624 fn prepare(&self, text: &AttributedText) -> String {
1625 text.text.to_string()
1626 }
1627
1628 fn prepare_aligned(
1629 &self,
1630 text: &AttributedText,
1631 _: &crate::text::AttachmentAlignments,
1632 ) -> String {
1633 self.prepare(text)
1634 }
1635
1636 fn measure(&self, text: &String, _: Option<Points>) -> Size<Points> {
1637 let shown = text.trim_end_matches(|c: char| c.is_whitespace());
1638 Size::new(Points(10.0 * shown.chars().count() as f32), Points(12.0))
1639 }
1640
1641 fn layout(&self, _: &String, _: Size<Points>) -> TextLayout {
1642 TextLayout(std::sync::Arc::new(()))
1643 }
1644 }
1645
1646 #[test]
1647 fn trailing_white_space_advances_as_canvas_measures_it() {
1648 let font = CanvasFont::default();
1649 for (text, width) in [
1650 ("", 0.0),
1651 ("ab", 20.0),
1652 (" ", 10.0),
1653 (" ", 30.0),
1654 (" items: ", 90.0),
1655 ("a\t", 20.0),
1656 ("名字\u{3000}", 30.0),
1658 ("你好 ", 30.0),
1659 ("ab\n", 20.0),
1661 ] {
1662 assert_eq!(
1663 measure_line(&Hanging, &font, text),
1664 Points(width),
1665 "{text:?}"
1666 );
1667 assert_eq!(
1668 line_metrics(&Hanging, &font, text).width,
1669 Points(width),
1670 "{text:?}"
1671 );
1672 }
1673 }
1674
1675 fn consts(op: &PathOp) -> Vec<f32> {
1676 let v = |n: &Num| match n {
1677 Num::Const(v) => *v,
1678 Num::Slot(_) => f32::NAN,
1679 };
1680 match op {
1681 PathOp::MoveTo(a, b) | PathOp::LineTo(a, b) => vec![v(a), v(b)],
1682 PathOp::QuadTo(n) => n.iter().map(v).collect(),
1683 PathOp::CubicTo(n) => n.iter().map(v).collect(),
1684 _ => vec![],
1685 }
1686 }
1687
1688 #[test]
1689 fn svg_paths_parse_to_absolute_ops() {
1690 let ops = parse_svg_path("M10 20 l5-5 H30 v10 z m1 1 2 2");
1691 assert_eq!(ops.len(), 7);
1692 assert_eq!(consts(&ops[1]), vec![15.0, 15.0]);
1693 assert_eq!(consts(&ops[2]), vec![30.0, 15.0]);
1694 assert_eq!(consts(&ops[3]), vec![30.0, 25.0]);
1695 assert_eq!(ops[4], PathOp::Close);
1696 assert_eq!(consts(&ops[5]), vec![11.0, 21.0]);
1698 assert_eq!(consts(&ops[6]), vec![13.0, 23.0]);
1700 let ops = parse_svg_path("M.5.5L1e1-2");
1702 assert_eq!(consts(&ops[0]), vec![0.5, 0.5]);
1703 assert_eq!(consts(&ops[1]), vec![10.0, -2.0]);
1704 }
1705
1706 #[test]
1707 fn smooth_curves_reflect_control_points() {
1708 let ops = parse_svg_path("M0 0 C0 10 10 10 10 0 S20 -10 20 0");
1709 assert_eq!(consts(&ops[2]), vec![10.0, -10.0, 20.0, -10.0, 20.0, 0.0]);
1710 }
1711
1712 #[test]
1713 fn arcs_become_cubics_ending_on_the_point() {
1714 let ops = parse_svg_path("M0 0 A10 10 0 0120 0");
1716 assert_eq!(ops.len(), 3);
1717 let last = consts(&ops[2]);
1718 assert!((last[4] - 20.0).abs() < 1e-4 && last[5].abs() < 1e-4);
1719 let mid = consts(&ops[1]);
1721 assert!((mid[4] - 10.0).abs() < 1e-3 && (mid[5] + 10.0).abs() < 1e-3);
1722 }
1723
1724 #[test]
1725 fn bad_path_data_keeps_what_parsed() {
1726 let ops = parse_svg_path("M0 0 L10 10 L oops");
1727 assert_eq!(ops.len(), 2);
1728 }
1729
1730 #[test]
1731 fn arc_sweeps_follow_the_canvas_spec() {
1732 use std::f32::consts::{PI, TAU};
1733
1734 use crate::geometry::{radians, size};
1735 let sweep = |a, b, ccw| arc_sweep(radians(a), radians(b), ccw).0;
1736 assert_eq!(sweep(0.0, PI, false), PI);
1737 assert!((sweep(PI, 0.0, false) - PI).abs() < 1e-6);
1739 assert!((sweep(0.0, -PI / 2.0, false) - 1.5 * PI).abs() < 1e-5);
1740 assert_eq!(sweep(0.0, 3.0 * TAU, false), TAU);
1741 assert!((sweep(0.0, PI / 2.0, true) + 1.5 * PI).abs() < 1e-5);
1742 assert_eq!(sweep(TAU, 0.0, true), -TAU);
1743 let corners = |[top_left, top_right, bottom_right, bottom_left]: [f32; 4]| Corners {
1744 top_left: px(top_left),
1745 top_right: px(top_right),
1746 bottom_right: px(bottom_right),
1747 bottom_left: px(bottom_left),
1748 };
1749 assert_eq!(
1750 fit_radii(size(px(10.0), px(100.0)), corners([8.0, 8.0, 0.0, 0.0])),
1751 corners([5.0, 5.0, 0.0, 0.0])
1752 );
1753 }
1754
1755 #[test]
1756 fn fonts_parse_the_css_shorthand() {
1757 let f = CanvasFont::parse("italic bold 14px \"Inter\", sans-serif").unwrap();
1758 assert_eq!((f.size, f.weight, f.italic), (px(14.0), 700, true));
1759 assert_eq!(f.family.as_deref(), Some("Inter"));
1760 let f = CanvasFont::parse("600 12px/1.5 system-ui").unwrap();
1761 assert_eq!((f.size, f.weight, f.family), (px(12.0), 600, None));
1762 let f = CanvasFont::parse("small-caps tabular-nums 13px system-ui").unwrap();
1763 assert_eq!(
1764 f.variant.0,
1765 FontVariant::SMALL_CAPS | FontVariant::TABULAR_NUMS
1766 );
1767 let numeric = f.with_numeric(FontVariant(FontVariant::OLDSTYLE_NUMS));
1768 assert_eq!(
1769 numeric.variant.0,
1770 FontVariant::SMALL_CAPS | FontVariant::OLDSTYLE_NUMS
1771 );
1772 assert_eq!(f.with_numeric(FontVariant::default()), f);
1773 assert!(CanvasFont::parse("wide 13px system-ui").is_none());
1774 assert!(CanvasFont::parse("bold").is_none());
1775 assert!(CanvasFont::parse("14px").is_none());
1776 }
1777}