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