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 (ascent, descent, height) = laid_line(engine, font, text);
606 let width = if text.is_empty() {
607 Points::ZERO
608 } else {
609 advance(engine, font, text)
610 };
611 TextMetrics {
612 width,
613 ascent,
614 descent,
615 height,
616 }
617}
618
619pub fn line_extent(
622 engine: &impl crate::text::TextEngine,
623 font: &CanvasFont,
624 text: &str,
625) -> (Points, Points) {
626 let (ascent, descent, _) = laid_line(engine, font, text);
627 (ascent, descent)
628}
629
630fn laid_line(
632 engine: &impl crate::text::TextEngine,
633 font: &CanvasFont,
634 text: &str,
635) -> (Points, Points, Points) {
636 let mut attributed = crate::text::AttributedText {
637 no_wrap: true,
638 max_lines: 1,
639 ..Default::default()
640 };
641 attributed.push(if text.is_empty() { " " } else { text }, font.text_style());
643 let prepared = engine.prepare(&attributed);
644 let size = engine.measure(&prepared, None);
645 let layout = engine.layout(&prepared, size);
646 match engine.lines(&layout).first() {
647 Some(line) => (line.ascender, line.descender, line.height),
648 None => (
649 Points(font.size.0 * 0.8),
650 Points(font.size.0 * 0.2),
651 size.height,
652 ),
653 }
654}
655
656#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
658pub enum CanvasTextAlign {
659 #[default]
661 Start,
662 End,
664 Left,
666 Right,
668 Center,
670}
671
672#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
674pub enum CanvasTextBaseline {
675 #[default]
677 Alphabetic,
678 Top,
680 Hanging,
682 Middle,
684 Ideographic,
686 Bottom,
688}
689
690#[derive(Debug, Clone, PartialEq)]
692pub struct CanvasImage {
693 pub uri: Arc<str>,
695}
696
697impl CanvasImage {
698 pub fn density(&self) -> f32 {
702 crate::image::density(&self.uri)
703 }
704}
705
706#[derive(Debug, Clone, PartialEq, JsOps)]
710#[ops(cx = Drawing)]
711pub enum CanvasOp {
712 #[op(code = CV_SAVE)]
714 Save,
715 #[op(code = CV_RESTORE)]
717 Restore,
718 #[op(code = CV_TRANSLATE, method = "translate", params = "x, y")]
720 Translate(Num, Num),
721 #[op(code = CV_SCALE, method = "scale", params = "x, y")]
723 Scale(Num, Num),
724 #[op(code = CV_ROTATE, method = "rotate", params = "angle")]
726 Rotate(Num),
727 #[op(code = CV_TRANSFORM, method = "transform", params = "a, b, c, d, e, f")]
730 Transform([Num; 6]),
731 #[op(code = CV_SET_TRANSFORM, method = "setTransform", params = "a, b, c, d, e, f")]
736 SetTransform([Num; 6]),
737 #[op(code = CV_BEGIN_PATH, method = "beginPath")]
739 BeginPath,
740 #[op(nested)]
742 Path(PathOp),
743 #[op(code = CV_FILL)]
745 Fill(Option<Path>, FillRule),
746 #[op(code = CV_STROKE)]
748 Stroke(Option<Path>),
749 #[op(code = CV_CLIP)]
751 Clip(Option<Path>, FillRule),
752 #[op(code = CV_FILL_RECT, method = "fillRect", params = "x, y, w, h")]
755 FillRect([Num; 4]),
756 #[op(code = CV_STROKE_RECT, method = "strokeRect", params = "x, y, w, h")]
758 StrokeRect([Num; 4]),
759 #[op(code = CV_CLEAR_RECT, method = "clearRect", params = "x, y, w, h")]
761 ClearRect([Num; 4]),
762 #[op(code = CV_FILL_STYLE)]
764 FillStyle(Paint),
765 #[op(code = CV_STROKE_STYLE)]
767 StrokeStyle(Paint),
768 #[op(code = CV_LINE_WIDTH, property = "lineWidth", initial = "1")]
770 LineWidth(Num),
771 #[op(code = CV_LINE_CAP, property = "lineCap", initial = "\"butt\"")]
773 LineCap(LineCap),
774 #[op(code = CV_LINE_JOIN, property = "lineJoin", initial = "\"miter\"")]
776 LineJoin(LineJoin),
777 #[op(code = CV_MITER_LIMIT, property = "miterLimit", initial = "10", min = 1.0)]
780 MiterLimit(f32),
781 #[op(code = CV_LINE_DASH, with = crate::js::canvas::line_dash)]
783 LineDash(Arc<[Points]>),
784 #[op(code = CV_LINE_DASH_OFFSET, property = "lineDashOffset", initial = "0")]
786 LineDashOffset(Num),
787 #[op(code = CV_GLOBAL_ALPHA, property = "globalAlpha", initial = "1")]
789 GlobalAlpha(Num),
790 #[op(
793 code = CV_COMPOSITE,
794 property = "globalCompositeOperation",
795 initial = "\"source-over\""
796 )]
797 Composite(Composite),
798 #[op(code = CV_SHADOW_COLOR, property = "shadowColor", initial = "\"rgba(0,0,0,0)\"")]
800 ShadowColor(Color),
801 #[op(code = CV_SHADOW_BLUR, property = "shadowBlur", initial = "0", min = 0.0)]
803 ShadowBlur(Points),
804 #[op(code = CV_SHADOW_OFFSET)]
806 ShadowOffset(Point<Points>),
807 #[op(code = CV_FONT, property = "font", initial = "\"10px sans-serif\"")]
810 Font(CanvasFont),
811 #[op(
816 code = CV_FONT_VARIANT_NUMERIC,
817 property = "fontVariantNumeric",
818 initial = "\"normal\""
819 )]
820 FontVariantNumeric(FontVariant),
821 #[op(code = CV_TEXT_ALIGN, property = "textAlign", initial = "\"start\"")]
823 TextAlign(CanvasTextAlign),
824 #[op(code = CV_TEXT_BASELINE, property = "textBaseline", initial = "\"alphabetic\"")]
826 TextBaseline(CanvasTextBaseline),
827 #[op(code = CV_FILL_TEXT)]
829 FillText {
830 text: Arc<str>,
832 x: Num,
834 y: Num,
836 max_width: Option<Points>,
838 },
839 #[op(code = CV_STROKE_TEXT)]
841 StrokeText {
842 text: Arc<str>,
844 x: Num,
846 y: Num,
848 max_width: Option<Points>,
850 },
851 #[op(code = CV_DRAW_IMAGE)]
853 DrawImage {
854 image: CanvasImage,
856 source: Option<Bounds<ScaledPixels>>,
858 dest: [Num; 4],
860 },
861}
862
863impl CanvasOp {
864 pub fn paints(&self) -> bool {
867 matches!(
868 self,
869 CanvasOp::Fill(..)
870 | CanvasOp::Stroke(_)
871 | CanvasOp::FillRect(_)
872 | CanvasOp::StrokeRect(_)
873 | CanvasOp::ClearRect(_)
874 | CanvasOp::FillText { .. }
875 | CanvasOp::StrokeText { .. }
876 | CanvasOp::DrawImage { .. }
877 )
878 }
879}
880
881#[derive(Debug, Clone, PartialEq, Default)]
883pub struct Drawing {
884 pub ops: Vec<CanvasOp>,
886 pub slots: Vec<crate::animation::NodeId>,
888 pub nodes: Vec<CanvasNode>,
892 pub view_paints: Vec<(u32, ViewPaint)>,
900}
901
902#[derive(Debug, Clone, Copy, PartialEq)]
905pub enum ViewPaint {
906 Fill(crate::style::SvgPaint),
908 Stroke(crate::style::SvgPaint),
910 StrokeWidth,
913 StrokeDasharray,
916 FillCurrentColor,
920 StrokeCurrentColor,
923 Fit(ViewBoxFit),
927 Background {
936 area: Bounds<Points>,
938 rule: FillRule,
940 },
941}
942
943#[derive(Debug, Clone, Copy, PartialEq)]
950pub struct ViewBoxFit {
951 pub view_box: Bounds<Points>,
953 pub align: Option<(Percentage, Percentage)>,
958 pub slice: bool,
960 pub size: Size<Points>,
962}
963
964impl ViewBoxFit {
965 pub fn transform(&self, size: Size<Points>) -> [f32; 6] {
968 let Size { width, height } = self.view_box.size;
969 let (vw, vh) = (width.0, height.0);
970 let (w, h) = (size.width.0.max(0.0), size.height.0.max(0.0));
971 if !(vw > 0.0 && vh > 0.0) {
972 return [0.0; 6];
973 }
974 let (mut sx, mut sy) = (w / vw, h / vh);
975 let (ax, ay) = match self.align {
976 None => (0.0, 0.0),
977 Some((x, y)) => {
978 let s = if self.slice { sx.max(sy) } else { sx.min(sy) };
979 (sx, sy) = (s, s);
980 (x.0, y.0)
981 }
982 };
983 let origin = self.view_box.origin;
984 [
985 sx,
986 0.0,
987 0.0,
988 sy,
989 (w - vw * sx) * ax - origin.x.0 * sx,
990 (h - vh * sy) * ay - origin.y.0 * sy,
991 ]
992 }
993}
994
995#[derive(Debug, Clone, PartialEq, Default)]
1003#[non_exhaustive]
1004pub struct CanvasNode {
1005 pub bounds: Bounds<Points>,
1007 pub role: crate::AccessibilityRole,
1009 pub label: Arc<str>,
1011 pub test_id: Option<Arc<str>>,
1013 pub selected: bool,
1015}
1016
1017impl CanvasNode {
1018 pub fn new(
1020 bounds: Bounds<Points>,
1021 role: crate::AccessibilityRole,
1022 label: impl Into<Arc<str>>,
1023 ) -> Self {
1024 Self {
1025 bounds,
1026 role,
1027 label: label.into(),
1028 ..Self::default()
1029 }
1030 }
1031
1032 pub fn test_id(mut self, id: impl Into<Arc<str>>) -> Self {
1034 self.test_id = Some(id.into());
1035 self
1036 }
1037
1038 pub fn selected(mut self, selected: bool) -> Self {
1040 self.selected = selected;
1041 self
1042 }
1043}
1044
1045impl Drawing {
1046 pub fn paints_background(&self) -> bool {
1049 self.view_paints
1050 .iter()
1051 .any(|(_, v)| matches!(v, ViewPaint::Background { .. }))
1052 }
1053
1054 pub fn fit(&self) -> Option<ViewBoxFit> {
1056 self.view_paints.iter().find_map(|&(_, v)| match v {
1057 ViewPaint::Fit(fit) => Some(fit),
1058 _ => None,
1059 })
1060 }
1061
1062 pub fn painted(
1070 &self,
1071 paint: &crate::style::PaintStyle,
1072 current: Color,
1073 background: Color,
1074 images: &[crate::effects::Gradient],
1075 size: Size<Points>,
1076 ) -> Drawing {
1077 use crate::style::SvgPaint;
1078 let color = |p: SvgPaint| {
1079 Paint::Color(match p {
1080 SvgPaint::None => Color::TRANSPARENT,
1081 SvgPaint::CurrentColor => current,
1082 SvgPaint::Color(c) => c,
1083 })
1084 };
1085 let mut out = self.clone();
1086 for &(at, view) in &self.view_paints {
1087 let Some(op) = out.ops.get_mut(at as usize) else {
1088 continue;
1089 };
1090 *op = match view {
1091 ViewPaint::Fill(initial) => {
1092 CanvasOp::FillStyle(color(paint.fill.unwrap_or(initial)))
1093 }
1094 ViewPaint::Stroke(initial) => {
1095 CanvasOp::StrokeStyle(color(paint.stroke.unwrap_or(initial)))
1096 }
1097 ViewPaint::StrokeWidth => {
1098 CanvasOp::LineWidth(Num::Const(paint.stroke_width.map_or(1.0, |w| w.0)))
1099 }
1100 ViewPaint::StrokeDasharray => CanvasOp::LineDash(
1101 paint
1102 .stroke_dasharray
1103 .clone()
1104 .unwrap_or_else(|| Arc::from([])),
1105 ),
1106 ViewPaint::FillCurrentColor => CanvasOp::FillStyle(Paint::Color(current)),
1107 ViewPaint::StrokeCurrentColor => CanvasOp::StrokeStyle(Paint::Color(current)),
1108 ViewPaint::Fit(fit) => CanvasOp::Transform(fit.transform(size).map(Num::Const)),
1109 ViewPaint::Background { .. } => continue,
1111 };
1112 }
1113 out.view_paints = Vec::new();
1114 if !self.paints_background() {
1115 return out;
1116 }
1117 let ops = std::mem::take(&mut out.ops);
1118 let mut backgrounds = self.view_paints.iter().filter_map(|&(at, v)| match v {
1119 ViewPaint::Background { area, rule } => Some((at as usize, area, rule)),
1120 _ => None,
1121 });
1122 let mut next = backgrounds.next();
1123 for (i, op) in ops.into_iter().enumerate() {
1124 let Some((_, area, rule)) = next.filter(|&(at, ..)| at == i) else {
1125 out.ops.push(op);
1126 continue;
1127 };
1128 next = backgrounds.next();
1129 out.ops.push(CanvasOp::Save);
1130 if !background.is_transparent() {
1131 out.ops.push(CanvasOp::FillStyle(Paint::Color(background)));
1132 out.ops.push(CanvasOp::Fill(None, rule));
1133 }
1134 for image in images.iter().rev() {
1135 let Some(gradient) = CanvasGradient::from_css(image, area) else {
1136 log::warn!("an elliptical `radial-gradient()` fills no canvas shape");
1137 continue;
1138 };
1139 out.ops
1140 .push(CanvasOp::FillStyle(Paint::Gradient(Arc::new(gradient))));
1141 out.ops.push(CanvasOp::Fill(None, rule));
1142 }
1143 out.ops.push(CanvasOp::Restore);
1144 }
1145 out
1146 }
1147
1148 pub fn slot(&mut self, node: crate::animation::NodeId) -> u16 {
1150 match self.slots.iter().position(|&n| n == node) {
1151 Some(i) => i as u16,
1152 None => {
1153 self.slots.push(node);
1154 (self.slots.len() - 1) as u16
1155 }
1156 }
1157 }
1158
1159 pub fn images(&self) -> impl Iterator<Item = &CanvasImage> {
1161 self.ops.iter().filter_map(|op| match op {
1162 CanvasOp::DrawImage { image, .. } => Some(image),
1163 _ => None,
1164 })
1165 }
1166}
1167
1168impl<Cx> OpArg<Cx> for Points {
1170 fn read<L: HostList<Item: HostInput>>(
1171 r: &mut OpReader<'_, L>,
1172 cx: &mut Cx,
1173 ) -> Result<Option<Self>, OpsError> {
1174 Ok(<f32 as OpArg<Cx>>::read(r, cx)?.map(Points))
1175 }
1176
1177 fn ts(types: &mut TsTypes) -> String {
1178 <f32 as OpArg<Cx>>::ts(types)
1179 }
1180}
1181
1182impl<Cx> OpArg<Cx> for Option<Points> {
1184 fn read<L: HostList<Item: HostInput>>(
1185 r: &mut OpReader<'_, L>,
1186 cx: &mut Cx,
1187 ) -> Result<Option<Self>, OpsError> {
1188 Ok(<Option<f32> as OpArg<Cx>>::read(r, cx)?.map(|v| v.map(Points)))
1189 }
1190
1191 fn ts(types: &mut TsTypes) -> String {
1192 <Option<f32> as OpArg<Cx>>::ts(types)
1193 }
1194}
1195
1196impl<Cx> OpArg<Cx> for Point<Points> {
1198 const ARITY: usize = 2;
1199
1200 fn read<L: HostList<Item: HostInput>>(
1201 r: &mut OpReader<'_, L>,
1202 cx: &mut Cx,
1203 ) -> Result<Option<Self>, OpsError> {
1204 let x = <Points as OpArg<Cx>>::read(r, cx)?;
1205 let y = <Points as OpArg<Cx>>::read(r, cx)?;
1206 Ok(x.zip(y).map(|(x, y)| Point { x, y }))
1207 }
1208
1209 fn ts(types: &mut TsTypes) -> String {
1210 <Points as OpArg<Cx>>::ts(types)
1211 }
1212}
1213
1214pub fn arc_sweep(start: Radians, end: Radians, ccw: bool) -> Radians {
1219 Radians(sweep(start.0, end.0, ccw))
1220}
1221
1222pub(crate) fn sweep(start: f32, end: f32, ccw: bool) -> f32 {
1223 use std::f32::consts::TAU;
1224 if !ccw {
1225 if end - start >= TAU {
1226 TAU
1227 } else {
1228 (end - start).rem_euclid(TAU)
1229 }
1230 } else if start - end >= TAU {
1231 -TAU
1232 } else {
1233 -(start - end).rem_euclid(TAU)
1234 }
1235}
1236
1237pub fn fit_radii(size: Size<Points>, radii: Corners<Points>) -> Corners<Points> {
1241 let [tl, tr, br, bl] = fit(
1242 size.width.0,
1243 size.height.0,
1244 [
1245 radii.top_left.0,
1246 radii.top_right.0,
1247 radii.bottom_right.0,
1248 radii.bottom_left.0,
1249 ],
1250 );
1251 Corners {
1252 top_left: Points(tl),
1253 top_right: Points(tr),
1254 bottom_right: Points(br),
1255 bottom_left: Points(bl),
1256 }
1257}
1258
1259pub(crate) fn fit(w: f32, h: f32, radii: [f32; 4]) -> [f32; 4] {
1262 let r = radii.map(|r| r.max(0.0));
1263 let (w, h) = (w.abs(), h.abs());
1264 let sides = [r[0] + r[1], r[2] + r[3], r[0] + r[3], r[1] + r[2]];
1265 let limits = [w, w, h, h];
1266 let scale = sides
1267 .iter()
1268 .zip(limits)
1269 .filter(|(s, _)| **s > 0.0)
1270 .map(|(s, l)| l / s)
1271 .fold(1.0f32, f32::min);
1272 r.map(|r| r * scale)
1273}
1274
1275pub fn svg_path(d: &str) -> Path {
1280 parse_svg_path(d).into()
1281}
1282
1283pub fn parse_svg_path(d: &str) -> Vec<PathOp> {
1287 let mut out = Vec::new();
1288 let mut p = PathParser {
1289 s: d.as_bytes(),
1290 pos: 0,
1291 };
1292 let (mut x, mut y) = (0f32, 0f32);
1293 let (mut sx, mut sy) = (0f32, 0f32);
1294 let mut last_cubic: Option<(f32, f32)> = None;
1296 let mut last_quad: Option<(f32, f32)> = None;
1297 let mut command = 0u8;
1298 let c = |v: f32| Num::Const(v);
1299 loop {
1300 p.skip_separators();
1301 if p.pos >= p.s.len() {
1302 break;
1303 }
1304 let b = p.s[p.pos];
1305 if b.is_ascii_alphabetic() {
1306 command = b;
1307 p.pos += 1;
1308 } else if command == 0 {
1309 break;
1310 } else if command == b'M' {
1311 command = b'L';
1313 } else if command == b'm' {
1314 command = b'l';
1315 }
1316 let rel = command.is_ascii_lowercase();
1317 let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) };
1318 let upper = command.to_ascii_uppercase();
1319 let ok = (|| -> Option<()> {
1320 match upper {
1321 b'M' => {
1322 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1323 out.push(PathOp::MoveTo(c(nx), c(ny)));
1324 (x, y, sx, sy) = (nx, ny, nx, ny);
1325 last_cubic = None;
1326 last_quad = None;
1327 }
1328 b'L' => {
1329 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1330 out.push(PathOp::LineTo(c(nx), c(ny)));
1331 (x, y) = (nx, ny);
1332 last_cubic = None;
1333 last_quad = None;
1334 }
1335 b'H' => {
1336 x = p.number()? + ox;
1337 out.push(PathOp::LineTo(c(x), c(y)));
1338 last_cubic = None;
1339 last_quad = None;
1340 }
1341 b'V' => {
1342 y = p.number()? + oy;
1343 out.push(PathOp::LineTo(c(x), c(y)));
1344 last_cubic = None;
1345 last_quad = None;
1346 }
1347 b'C' | b'S' => {
1348 let (x1, y1) = if upper == b'C' {
1349 (p.number()? + ox, p.number()? + oy)
1350 } else {
1351 last_cubic.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1353 };
1354 let (x2, y2) = (p.number()? + ox, p.number()? + oy);
1355 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1356 out.push(PathOp::CubicTo([x1, y1, x2, y2, nx, ny].map(c)));
1357 last_cubic = Some((x2, y2));
1358 last_quad = None;
1359 (x, y) = (nx, ny);
1360 }
1361 b'Q' | b'T' => {
1362 let (x1, y1) = if upper == b'Q' {
1363 (p.number()? + ox, p.number()? + oy)
1364 } else {
1365 last_quad.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1366 };
1367 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1368 out.push(PathOp::QuadTo([x1, y1, nx, ny].map(c)));
1369 last_quad = Some((x1, y1));
1370 last_cubic = None;
1371 (x, y) = (nx, ny);
1372 }
1373 b'A' => {
1374 let rx = p.number()?.abs();
1375 let ry = p.number()?.abs();
1376 let rotation = p.number()?;
1377 let large = p.flag()?;
1378 let sweep = p.flag()?;
1379 let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1380 arc_to_cubics(&mut out, (x, y), (rx, ry), rotation, large, sweep, (nx, ny));
1381 (x, y) = (nx, ny);
1382 last_cubic = None;
1383 last_quad = None;
1384 }
1385 b'Z' => {
1386 out.push(PathOp::Close);
1387 (x, y) = (sx, sy);
1388 last_cubic = None;
1389 last_quad = None;
1390 command = 0;
1392 }
1393 _ => return None,
1394 }
1395 Some(())
1396 })();
1397 if ok.is_none() {
1398 break;
1399 }
1400 }
1401 out
1402}
1403
1404struct PathParser<'a> {
1405 s: &'a [u8],
1406 pos: usize,
1407}
1408
1409impl PathParser<'_> {
1410 fn skip_separators(&mut self) {
1411 while self.pos < self.s.len()
1412 && (self.s[self.pos].is_ascii_whitespace() || self.s[self.pos] == b',')
1413 {
1414 self.pos += 1;
1415 }
1416 }
1417
1418 fn number(&mut self) -> Option<f32> {
1419 self.skip_separators();
1420 let start = self.pos;
1421 let s = self.s;
1422 let mut i = self.pos;
1423 if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
1424 i += 1;
1425 }
1426 let mut digits = false;
1427 while i < s.len() && s[i].is_ascii_digit() {
1428 i += 1;
1429 digits = true;
1430 }
1431 if i < s.len() && s[i] == b'.' {
1432 i += 1;
1433 while i < s.len() && s[i].is_ascii_digit() {
1434 i += 1;
1435 digits = true;
1436 }
1437 }
1438 if !digits {
1439 return None;
1440 }
1441 if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
1442 let mut j = i + 1;
1443 if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
1444 j += 1;
1445 }
1446 if j < s.len() && s[j].is_ascii_digit() {
1447 while j < s.len() && s[j].is_ascii_digit() {
1448 j += 1;
1449 }
1450 i = j;
1451 }
1452 }
1453 self.pos = i;
1454 std::str::from_utf8(&s[start..i]).ok()?.parse().ok()
1455 }
1456
1457 fn flag(&mut self) -> Option<bool> {
1459 self.skip_separators();
1460 let b = *self.s.get(self.pos)?;
1461 self.pos += 1;
1462 match b {
1463 b'0' => Some(false),
1464 b'1' => Some(true),
1465 _ => None,
1466 }
1467 }
1468}
1469
1470fn arc_to_cubics(
1473 out: &mut Vec<PathOp>,
1474 from: (f32, f32),
1475 radii: (f32, f32),
1476 rotation_deg: f32,
1477 large: bool,
1478 sweep: bool,
1479 to: (f32, f32),
1480) {
1481 let c = |v: f64| Num::Const(v as f32);
1482 let (x1, y1) = (from.0 as f64, from.1 as f64);
1483 let (x2, y2) = (to.0 as f64, to.1 as f64);
1484 let (mut rx, mut ry) = (radii.0 as f64, radii.1 as f64);
1485 if (x1 == x2 && y1 == y2) || rx == 0.0 || ry == 0.0 {
1486 if x1 != x2 || y1 != y2 {
1487 out.push(PathOp::LineTo(c(x2), c(y2)));
1488 }
1489 return;
1490 }
1491 let phi = (rotation_deg as f64).to_radians();
1492 let (sin, cos) = phi.sin_cos();
1493 let dx = (x1 - x2) / 2.0;
1494 let dy = (y1 - y2) / 2.0;
1495 let x1p = cos * dx + sin * dy;
1496 let y1p = -sin * dx + cos * dy;
1497 let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
1499 if lambda > 1.0 {
1500 let s = lambda.sqrt();
1501 rx *= s;
1502 ry *= s;
1503 }
1504 let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
1505 let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
1506 let mut coef = (num / den).max(0.0).sqrt();
1507 if large == sweep {
1508 coef = -coef;
1509 }
1510 let cxp = coef * rx * y1p / ry;
1511 let cyp = -coef * ry * x1p / rx;
1512 let cx = cos * cxp - sin * cyp + (x1 + x2) / 2.0;
1513 let cy = sin * cxp + cos * cyp + (y1 + y2) / 2.0;
1514 let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
1515 let theta1 = angle(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
1516 let mut delta = angle(
1517 (x1p - cxp) / rx,
1518 (y1p - cyp) / ry,
1519 (-x1p - cxp) / rx,
1520 (-y1p - cyp) / ry,
1521 );
1522 if !sweep && delta > 0.0 {
1523 delta -= std::f64::consts::TAU;
1524 } else if sweep && delta < 0.0 {
1525 delta += std::f64::consts::TAU;
1526 }
1527 let segments = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
1529 let step = delta / segments as f64;
1530 let k = 4.0 / 3.0 * (step / 4.0).tan();
1531 let point = |t: f64| {
1532 let (s, co) = t.sin_cos();
1533 (
1534 cx + rx * co * cos - ry * s * sin,
1535 cy + rx * co * sin + ry * s * cos,
1536 )
1537 };
1538 let derivative = |t: f64| {
1539 let (s, co) = t.sin_cos();
1540 (-rx * s * cos - ry * co * sin, -rx * s * sin + ry * co * cos)
1541 };
1542 let mut t = theta1;
1543 for i in 0..segments {
1544 let t2 = t + step;
1545 let (p1x, p1y) = point(t);
1546 let (d1x, d1y) = derivative(t);
1547 let (p2x, p2y) = if i + 1 == segments {
1548 (x2, y2)
1549 } else {
1550 point(t2)
1551 };
1552 let (d2x, d2y) = derivative(t2);
1553 out.push(PathOp::CubicTo([
1554 c(p1x + k * d1x),
1555 c(p1y + k * d1y),
1556 c(p2x - k * d2x),
1557 c(p2y - k * d2y),
1558 c(p2x),
1559 c(p2y),
1560 ]));
1561 t = t2;
1562 }
1563}
1564
1565#[cfg(test)]
1566mod tests {
1567 use super::*;
1568 use crate::text::{AttributedText, TextEngine, TextLayout};
1569
1570 #[test]
1571 fn an_image_density_is_its_file_name_s() {
1572 let density = |uri: &str| CanvasImage { uri: uri.into() }.density();
1573 assert_eq!(density("asset:/logo@3x.png"), 3.0);
1574 assert_eq!(density("https://example.com/a/b@2x.jpg"), 2.0);
1575 assert_eq!(density("asset:/logo.png"), 1.0);
1576 }
1577
1578 #[test]
1583 fn css_gradients_become_canvas_gradients_over_a_box() {
1584 use crate::geometry::{bounds, point, size};
1585 let area = bounds(point(px(10.0), px(20.0)), size(px(100.0), px(50.0)));
1586 let one = |css: &str| crate::css::gradients(css).unwrap().remove(0);
1587 let gradient = |css: &str| CanvasGradient::from_css(&one(css), area);
1588 let down = gradient("linear-gradient(to bottom, #ff0000, #0000ff)").unwrap();
1589 assert_eq!(
1590 down.shape,
1591 GradientShape::Linear {
1592 start: point(px(60.0), px(20.0)),
1593 end: point(px(60.0), px(70.0)),
1594 }
1595 );
1596 assert_eq!(down.stops[0], (Percentage(0.0), Color(0xff00_00ff)));
1597 assert_eq!(
1598 down.stops[down.stops.len() - 1],
1599 (Percentage(1.0), Color(0x0000_ffff))
1600 );
1601 let right = gradient("linear-gradient(90deg, #ff0000, #0000ff)").unwrap();
1602 let GradientShape::Linear { start, end } = right.shape else {
1603 panic!("{right:?}")
1604 };
1605 assert!((start.x.0 - 10.0).abs() < 1e-3 && (start.y.0 - 45.0).abs() < 1e-3);
1606 assert!((end.x.0 - 110.0).abs() < 1e-3 && (end.y.0 - 45.0).abs() < 1e-3);
1607 let stripes =
1610 gradient("repeating-linear-gradient(to bottom, #ff0000 0%, #0000ff 25%)").unwrap();
1611 let at = |o: f32| {
1612 stripes
1613 .stops
1614 .iter()
1615 .filter(|(p, _)| (p.0 - o).abs() < 1e-4)
1616 .count()
1617 };
1618 assert!(
1619 at(0.25) >= 2 && at(0.5) >= 2 && at(0.75) >= 2,
1620 "{stripes:?}"
1621 );
1622 assert!(
1623 stripes
1624 .stops
1625 .iter()
1626 .all(|(p, _)| (0.0..=1.0).contains(&p.0))
1627 );
1628 let cut = gradient("linear-gradient(to bottom, #000000 0%, #ffffff 200%)").unwrap();
1630 assert_eq!(
1631 cut.stops[cut.stops.len() - 1],
1632 (Percentage(1.0), Color(0x8080_80ff))
1633 );
1634 assert!(gradient("radial-gradient(#ff0000, #0000ff)").is_none());
1635 let circle = gradient("radial-gradient(circle, #ff0000, #0000ff)").unwrap();
1636 assert!(matches!(circle.shape, GradientShape::Radial { .. }));
1637 }
1638
1639 #[test]
1643 fn a_drawing_fills_with_its_views_background() {
1644 use crate::geometry::{bounds, point, size};
1645 let area = bounds(point(px(0.0), px(0.0)), size(px(10.0), px(10.0)));
1646 let drawing = crate::element::Painter::new()
1647 .begin_path()
1648 .fill_background_from_view(area)
1649 .finish();
1650 assert!(drawing.paints_background());
1651 let images = crate::css::gradients("linear-gradient(#ff0000, #0000ff)").unwrap();
1652 let none = crate::style::PaintStyle::default();
1653 let painted = drawing.painted(
1654 &none,
1655 Color::TRANSPARENT,
1656 Color(0x00ff_00ff),
1657 &images,
1658 Size::default(),
1659 );
1660 assert!(painted.view_paints.is_empty());
1661 let ops = &painted.ops[1..];
1662 assert_eq!(ops[0], CanvasOp::Save);
1663 assert_eq!(
1664 ops[1],
1665 CanvasOp::FillStyle(Paint::Color(Color(0x00ff_00ff)))
1666 );
1667 assert_eq!(ops[2], CanvasOp::Fill(None, FillRule::NonZero));
1668 assert!(matches!(ops[3], CanvasOp::FillStyle(Paint::Gradient(_))));
1669 assert_eq!(ops[4], CanvasOp::Fill(None, FillRule::NonZero));
1670 assert_eq!(ops[5], CanvasOp::Restore);
1671 let bare = drawing.painted(
1673 &none,
1674 Color::TRANSPARENT,
1675 Color::TRANSPARENT,
1676 &[],
1677 Size::default(),
1678 );
1679 assert_eq!(&bare.ops[1..], [CanvasOp::Save, CanvasOp::Restore]);
1680 }
1681
1682 struct Hanging;
1685
1686 impl TextEngine for Hanging {
1687 type Prepared = String;
1688
1689 fn prepare(&self, text: &AttributedText) -> String {
1690 text.text.to_string()
1691 }
1692
1693 fn prepare_aligned(
1694 &self,
1695 text: &AttributedText,
1696 _: &crate::text::AttachmentAlignments,
1697 ) -> String {
1698 self.prepare(text)
1699 }
1700
1701 fn measure(&self, text: &String, _: Option<Points>) -> Size<Points> {
1702 let shown = text.trim_end_matches(|c: char| c.is_whitespace());
1703 Size::new(Points(10.0 * shown.chars().count() as f32), Points(12.0))
1704 }
1705
1706 fn layout(&self, _: &String, _: Size<Points>) -> TextLayout {
1707 TextLayout(std::sync::Arc::new(()))
1708 }
1709 }
1710
1711 #[test]
1712 fn trailing_white_space_advances_as_canvas_measures_it() {
1713 let font = CanvasFont::default();
1714 for (text, width) in [
1715 ("", 0.0),
1716 ("ab", 20.0),
1717 (" ", 10.0),
1718 (" ", 30.0),
1719 (" items: ", 90.0),
1720 ("a\t", 20.0),
1721 ("名字\u{3000}", 30.0),
1723 ("你好 ", 30.0),
1724 ("ab\n", 20.0),
1726 ] {
1727 assert_eq!(
1728 measure_line(&Hanging, &font, text),
1729 Points(width),
1730 "{text:?}"
1731 );
1732 assert_eq!(
1733 line_metrics(&Hanging, &font, text).width,
1734 Points(width),
1735 "{text:?}"
1736 );
1737 }
1738 }
1739
1740 fn consts(op: &PathOp) -> Vec<f32> {
1741 let v = |n: &Num| match n {
1742 Num::Const(v) => *v,
1743 Num::Slot(_) => f32::NAN,
1744 };
1745 match op {
1746 PathOp::MoveTo(a, b) | PathOp::LineTo(a, b) => vec![v(a), v(b)],
1747 PathOp::QuadTo(n) => n.iter().map(v).collect(),
1748 PathOp::CubicTo(n) => n.iter().map(v).collect(),
1749 _ => vec![],
1750 }
1751 }
1752
1753 #[test]
1754 fn svg_paths_parse_to_absolute_ops() {
1755 let ops = parse_svg_path("M10 20 l5-5 H30 v10 z m1 1 2 2");
1756 assert_eq!(ops.len(), 7);
1757 assert_eq!(consts(&ops[1]), vec![15.0, 15.0]);
1758 assert_eq!(consts(&ops[2]), vec![30.0, 15.0]);
1759 assert_eq!(consts(&ops[3]), vec![30.0, 25.0]);
1760 assert_eq!(ops[4], PathOp::Close);
1761 assert_eq!(consts(&ops[5]), vec![11.0, 21.0]);
1763 assert_eq!(consts(&ops[6]), vec![13.0, 23.0]);
1765 let ops = parse_svg_path("M.5.5L1e1-2");
1767 assert_eq!(consts(&ops[0]), vec![0.5, 0.5]);
1768 assert_eq!(consts(&ops[1]), vec![10.0, -2.0]);
1769 }
1770
1771 #[test]
1772 fn smooth_curves_reflect_control_points() {
1773 let ops = parse_svg_path("M0 0 C0 10 10 10 10 0 S20 -10 20 0");
1774 assert_eq!(consts(&ops[2]), vec![10.0, -10.0, 20.0, -10.0, 20.0, 0.0]);
1775 }
1776
1777 #[test]
1778 fn arcs_become_cubics_ending_on_the_point() {
1779 let ops = parse_svg_path("M0 0 A10 10 0 0120 0");
1781 assert_eq!(ops.len(), 3);
1782 let last = consts(&ops[2]);
1783 assert!((last[4] - 20.0).abs() < 1e-4 && last[5].abs() < 1e-4);
1784 let mid = consts(&ops[1]);
1786 assert!((mid[4] - 10.0).abs() < 1e-3 && (mid[5] + 10.0).abs() < 1e-3);
1787 }
1788
1789 #[test]
1790 fn bad_path_data_keeps_what_parsed() {
1791 let ops = parse_svg_path("M0 0 L10 10 L oops");
1792 assert_eq!(ops.len(), 2);
1793 }
1794
1795 #[test]
1796 fn arc_sweeps_follow_the_canvas_spec() {
1797 use std::f32::consts::{PI, TAU};
1798
1799 use crate::geometry::{radians, size};
1800 let sweep = |a, b, ccw| arc_sweep(radians(a), radians(b), ccw).0;
1801 assert_eq!(sweep(0.0, PI, false), PI);
1802 assert!((sweep(PI, 0.0, false) - PI).abs() < 1e-6);
1804 assert!((sweep(0.0, -PI / 2.0, false) - 1.5 * PI).abs() < 1e-5);
1805 assert_eq!(sweep(0.0, 3.0 * TAU, false), TAU);
1806 assert!((sweep(0.0, PI / 2.0, true) + 1.5 * PI).abs() < 1e-5);
1807 assert_eq!(sweep(TAU, 0.0, true), -TAU);
1808 let corners = |[top_left, top_right, bottom_right, bottom_left]: [f32; 4]| Corners {
1809 top_left: px(top_left),
1810 top_right: px(top_right),
1811 bottom_right: px(bottom_right),
1812 bottom_left: px(bottom_left),
1813 };
1814 assert_eq!(
1815 fit_radii(size(px(10.0), px(100.0)), corners([8.0, 8.0, 0.0, 0.0])),
1816 corners([5.0, 5.0, 0.0, 0.0])
1817 );
1818 }
1819
1820 #[test]
1821 fn fonts_parse_the_css_shorthand() {
1822 let f = CanvasFont::parse("italic bold 14px \"Inter\", sans-serif").unwrap();
1823 assert_eq!((f.size, f.weight, f.italic), (px(14.0), 700, true));
1824 assert_eq!(f.family.as_deref(), Some("\"Inter\", sans-serif"));
1825 assert_eq!(
1826 crate::style::font_families(f.family.as_deref().unwrap()).collect::<Vec<_>>(),
1827 vec![
1828 crate::style::FamilyName::Named("Inter"),
1829 crate::style::FamilyName::System,
1830 ]
1831 );
1832 let single = CanvasFont::parse("14px \"Inter\"").unwrap();
1833 assert_eq!(single.family.as_deref(), Some("Inter"));
1834 let quoted_generic = CanvasFont::parse("14px \"serif\"").unwrap();
1835 assert_eq!(
1836 crate::style::font_families(quoted_generic.family.as_deref().unwrap())
1837 .collect::<Vec<_>>(),
1838 vec![crate::style::FamilyName::Named("serif")]
1839 );
1840 let f = CanvasFont::parse("600 12px/1.5 system-ui").unwrap();
1841 assert_eq!((f.size, f.weight, f.family), (px(12.0), 600, None));
1842 let f = CanvasFont::parse("small-caps tabular-nums 13px system-ui").unwrap();
1843 assert_eq!(
1844 f.variant.0,
1845 FontVariant::SMALL_CAPS | FontVariant::TABULAR_NUMS
1846 );
1847 let numeric = f.with_numeric(FontVariant(FontVariant::OLDSTYLE_NUMS));
1848 assert_eq!(
1849 numeric.variant.0,
1850 FontVariant::SMALL_CAPS | FontVariant::OLDSTYLE_NUMS
1851 );
1852 assert_eq!(f.with_numeric(FontVariant::default()), f);
1853 assert!(CanvasFont::parse("wide 13px system-ui").is_none());
1854 assert!(CanvasFont::parse("bold").is_none());
1855 assert!(CanvasFont::parse("14px").is_none());
1856 assert!(CanvasFont::parse("14px , ").is_none());
1857 }
1858}