Skip to main content

strata_render/
canvas2d.rs

1//! W3C-Compatible Immediate-Mode 2D Canvas Engine (`CanvasRenderingContext2D`).
2//!
3//! Provides immediate-mode vector drawing, affine 2D transformations, cubic & quadratic Bézier
4//! curves, dashed strokes, path clipping, text rendering, and analytical anti-aliased CPU/GPU
5//! rasterization.
6
7use crate::rasterizer::FrameBuffer;
8use strata_layout::Rect;
9pub use strata_primitives::geom::Transform2D;
10use strata_style::types::Color;
11
12/// Line termination cap style for [`Canvas2DContext::set_line_cap`].
13pub type CanvasLineCap = strata_layout::StrokeLineCap;
14
15/// Line segment junction style for [`Canvas2DContext::set_line_join`].
16pub type CanvasLineJoin = strata_layout::StrokeLineJoin;
17
18/// Measured text metrics returned by [`Canvas2DContext::measure_text`], modeled after HTML5
19/// `TextMetrics`.
20#[derive(Debug, Clone, Copy, PartialEq, Default)]
21pub struct CanvasTextMetrics {
22    /// Width of the inline text advance box in CSS pixels.
23    pub width: f32,
24    /// Total height of the measured text line in CSS pixels.
25    pub height: f32,
26    /// Distance from the baseline up to the bounding box top.
27    pub actual_bounding_box_ascent: f32,
28    /// Distance from the baseline down to the bounding box bottom.
29    pub actual_bounding_box_descent: f32,
30    /// Font-wide ascent above the baseline.
31    pub font_bounding_box_ascent: f32,
32    /// Font-wide descent below the baseline.
33    pub font_bounding_box_descent: f32,
34}
35
36/// Polymorphic corner radii input for [`Canvas2DContext::round_rect`], accepting a uniform scalar
37/// `f32`, 1–4 element CSS/HTML5 arrays/slices (`[tl, tr, br, bl]`), or
38/// [`strata_style::types::BorderRadius`].
39pub trait IntoRoundRectRadii {
40    fn into_round_rect_radii(self) -> [f32; 4];
41}
42
43impl IntoRoundRectRadii for f32 {
44    #[inline]
45    fn into_round_rect_radii(self) -> [f32; 4] {
46        [self, self, self, self]
47    }
48}
49
50impl IntoRoundRectRadii for [f32; 1] {
51    #[inline]
52    fn into_round_rect_radii(self) -> [f32; 4] {
53        [self[0], self[0], self[0], self[0]]
54    }
55}
56
57impl IntoRoundRectRadii for [f32; 2] {
58    #[inline]
59    fn into_round_rect_radii(self) -> [f32; 4] {
60        [self[0], self[1], self[0], self[1]]
61    }
62}
63
64impl IntoRoundRectRadii for [f32; 3] {
65    #[inline]
66    fn into_round_rect_radii(self) -> [f32; 4] {
67        [self[0], self[1], self[2], self[1]]
68    }
69}
70
71impl IntoRoundRectRadii for [f32; 4] {
72    #[inline]
73    fn into_round_rect_radii(self) -> [f32; 4] {
74        self
75    }
76}
77
78impl IntoRoundRectRadii for &[f32] {
79    #[inline]
80    fn into_round_rect_radii(self) -> [f32; 4] {
81        match self {
82            [] => [0.0; 4],
83            [a] => [*a, *a, *a, *a],
84            [a, b] => [*a, *b, *a, *b],
85            [a, b, c] => [*a, *b, *c, *b],
86            [a, b, c, d, ..] => [*a, *b, *c, *d],
87        }
88    }
89}
90
91impl IntoRoundRectRadii for strata_style::types::BorderRadius {
92    #[inline]
93    fn into_round_rect_radii(self) -> [f32; 4] {
94        [
95            self.top_left,
96            self.top_right,
97            self.bottom_right,
98            self.bottom_left,
99        ]
100    }
101}
102
103/// Horizontal text alignment for [`Canvas2DContext::fill_text`] and [`Canvas2DContext::stroke_text`].
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
105pub enum CanvasTextAlign {
106    #[default]
107    Left,
108    Center,
109    Right,
110    Start,
111    End,
112}
113
114/// Vertical text baseline for [`Canvas2DContext::fill_text`] and [`Canvas2DContext::stroke_text`].
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
116pub enum CanvasTextBaseline {
117    #[default]
118    Alphabetic,
119    Top,
120    Middle,
121    Bottom,
122    Hanging,
123    Ideographic,
124}
125
126/// Canvas path primitive verbs in transformed coordinates.
127#[derive(Debug, Clone, PartialEq)]
128pub enum CanvasPathVerb {
129    MoveTo(f32, f32),
130    LineTo(f32, f32),
131    QuadraticCurveTo {
132        cpx: f32,
133        cpy: f32,
134        x: f32,
135        y: f32,
136    },
137    BezierCurveTo {
138        cp1x: f32,
139        cp1y: f32,
140        cp2x: f32,
141        cp2y: f32,
142        x: f32,
143        y: f32,
144    },
145    Arc {
146        cx: f32,
147        cy: f32,
148        radius: f32,
149        start_angle: f32,
150        end_angle: f32,
151        counter_clockwise: bool,
152    },
153    Close,
154}
155
156/// Renderable 2D canvas drawing instruction.
157#[derive(Debug, Clone, PartialEq)]
158pub enum CanvasCommand {
159    FillRect {
160        bounds: Rect,
161        color: Color,
162    },
163    StrokeRect {
164        bounds: Rect,
165        color: Color,
166        line_width: f32,
167    },
168    ClearRect {
169        bounds: Rect,
170    },
171    DrawLine {
172        p0: (f32, f32),
173        p1: (f32, f32),
174        color: Color,
175        line_width: f32,
176    },
177    DrawCircle {
178        center: (f32, f32),
179        radius: f32,
180        fill_color: Option<Color>,
181        stroke_color: Option<Color>,
182        line_width: f32,
183    },
184    DrawPath {
185        verbs: Vec<CanvasPathVerb>,
186        fill_color: Option<Color>,
187        stroke_color: Option<Color>,
188        line_width: f32,
189    },
190    /// Pushes the active backend graphics state (clip region, dash state, line cap/join).
191    Save,
192    /// Pops the most recently pushed backend graphics state.
193    Restore,
194    /// Sets the stroke dash pattern (empty clears dashing) and phase offset.
195    SetLineDash {
196        segments: Vec<f32>,
197        offset: f32,
198    },
199    /// Sets the stroke line termination cap style (`Butt`, `Round`, `Square`).
200    SetLineCap(CanvasLineCap),
201    /// Sets the stroke corner join style (`Miter`, `Round`, `Bevel`).
202    SetLineJoin(CanvasLineJoin),
203    /// Intersects the active clip region with the given path until the matching `Restore`.
204    ClipPath {
205        verbs: Vec<CanvasPathVerb>,
206    },
207    /// Renders filled text at `(x, y)` in transformed canvas coordinates.
208    FillText {
209        text: String,
210        x: f32,
211        y: f32,
212        color: Color,
213        font: String,
214        font_size: f32,
215        font_family: String,
216        font_weight: u16,
217        italic: bool,
218        text_align: CanvasTextAlign,
219        text_baseline: CanvasTextBaseline,
220        max_width: Option<f32>,
221    },
222    /// Renders outlined/stroked text at `(x, y)` in transformed canvas coordinates.
223    StrokeText {
224        text: String,
225        x: f32,
226        y: f32,
227        color: Color,
228        line_width: f32,
229        font: String,
230        font_size: f32,
231        font_family: String,
232        font_weight: u16,
233        italic: bool,
234        text_align: CanvasTextAlign,
235        text_baseline: CanvasTextBaseline,
236        max_width: Option<f32>,
237    },
238}
239
240/// Parses a CSS/HTML5 Canvas `font` shorthand string (e.g. `"bold 12px monospace"`,
241/// `"italic 600 11px/1.4 'JetBrains Mono', monospace"`, `"10pt sans-serif"`) into
242/// `(font_size_px, font_family, font_weight, italic)`.
243pub fn parse_canvas_font(font: &str) -> (f32, String, u16, bool) {
244    let mut font_size = 12.0_f32;
245    let mut font_weight = 400_u16;
246    let mut italic = false;
247    let mut family_start: Option<usize> = None;
248
249    let bytes = font.as_bytes();
250    let mut i = 0usize;
251    while i < bytes.len() {
252        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
253            i += 1;
254        }
255        if i >= bytes.len() {
256            break;
257        }
258        let start = i;
259        while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
260            i += 1;
261        }
262        let token = &font[start..i];
263        let lower = token.to_ascii_lowercase();
264
265        if lower == "italic" || lower == "oblique" {
266            italic = true;
267            continue;
268        }
269        if lower == "bold" || lower == "bolder" {
270            font_weight = 700;
271            continue;
272        }
273        if lower == "lighter" {
274            font_weight = 300;
275            continue;
276        }
277        if lower == "normal" || lower == "small-caps" {
278            continue;
279        }
280        if let Ok(w) = lower.parse::<u16>() {
281            if (100..=900).contains(&w) {
282                font_weight = w;
283                continue;
284            }
285        }
286
287        // Size token: `12px`, `12.5px/1.4`, `10pt`, `1rem`, `1em`
288        let size_part = lower.split('/').next().unwrap_or("");
289        let parsed_px = if let Some(num) = size_part.strip_suffix("px") {
290            num.parse::<f32>().ok()
291        } else if let Some(num) = size_part.strip_suffix("pt") {
292            num.parse::<f32>().ok().map(|pt| pt * (4.0 / 3.0))
293        } else if let Some(num) = size_part.strip_suffix("rem") {
294            num.parse::<f32>().ok().map(|r| r * 16.0)
295        } else if let Some(num) = size_part.strip_suffix("em") {
296            num.parse::<f32>().ok().map(|e| e * 16.0)
297        } else {
298            None
299        };
300
301        if let Some(px) = parsed_px {
302            if px.is_finite() && px > 0.0 {
303                font_size = px;
304                family_start = Some(i);
305                break;
306            }
307        }
308    }
309
310    let raw_family = family_start.map(|idx| font[idx..].trim()).unwrap_or("");
311    let cleaned_family = raw_family
312        .split(',')
313        .map(|s| s.trim().trim_matches('\'').trim_matches('"').trim())
314        .filter(|s| !s.is_empty())
315        .collect::<Vec<_>>()
316        .join(", ");
317
318    let font_family = if cleaned_family.is_empty() {
319        "sans-serif".to_string()
320    } else {
321        cleaned_family
322    };
323
324    (font_size, font_family, font_weight, italic)
325}
326
327#[derive(Debug, Clone, PartialEq)]
328struct CanvasState {
329    transform: Transform2D,
330    fill_style: Color,
331    stroke_style: Color,
332    line_width: f32,
333    line_cap: CanvasLineCap,
334    line_join: CanvasLineJoin,
335    global_alpha: f32,
336    line_dash: Vec<f32>,
337    line_dash_offset: f32,
338    font: String,
339    font_size: f32,
340    font_family: String,
341    font_weight: u16,
342    font_italic: bool,
343    text_align: CanvasTextAlign,
344    text_baseline: CanvasTextBaseline,
345}
346
347impl Default for CanvasState {
348    fn default() -> Self {
349        Self {
350            transform: Transform2D::IDENTITY,
351            fill_style: Color::BLACK,
352            stroke_style: Color::BLACK,
353            line_width: 1.0,
354            line_cap: CanvasLineCap::Butt,
355            line_join: CanvasLineJoin::Miter,
356            global_alpha: 1.0,
357            line_dash: Vec::new(),
358            line_dash_offset: 0.0,
359            font: "12px sans-serif".to_string(),
360            font_size: 12.0,
361            font_family: "sans-serif".to_string(),
362            font_weight: 400,
363            font_italic: false,
364            text_align: CanvasTextAlign::Left,
365            text_baseline: CanvasTextBaseline::Alphabetic,
366        }
367    }
368}
369
370/// W3C-Compatible 2D Immediate-Mode Canvas Rendering Context.
371#[derive(Debug, Clone)]
372pub struct Canvas2DContext {
373    pub width: f32,
374    pub height: f32,
375    current_state: CanvasState,
376    state_stack: Vec<CanvasState>,
377    current_path: Vec<CanvasPathVerb>,
378    commands: Vec<CanvasCommand>,
379}
380
381impl Canvas2DContext {
382    pub fn new(width: f32, height: f32) -> Self {
383        Self {
384            width,
385            height,
386            current_state: CanvasState::default(),
387            state_stack: Vec::new(),
388            current_path: Vec::new(),
389            commands: Vec::new(),
390        }
391    }
392
393    // --- State Stack ---
394
395    pub fn save(&mut self) {
396        self.state_stack.push(self.current_state.clone());
397        self.commands.push(CanvasCommand::Save);
398    }
399
400    pub fn restore(&mut self) {
401        if let Some(state) = self.state_stack.pop() {
402            self.current_state = state;
403            self.commands.push(CanvasCommand::Restore);
404        }
405    }
406
407    // --- Transformations ---
408
409    pub fn translate(&mut self, dx: f32, dy: f32) {
410        self.current_state.transform.translate(dx, dy);
411    }
412
413    pub fn scale(&mut self, sx: f32, sy: f32) {
414        self.current_state.transform.scale_mut(sx, sy);
415    }
416
417    pub fn rotate(&mut self, radians: f32) {
418        self.current_state.transform.rotate_mut(radians);
419    }
420
421    pub fn transform(&mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
422        let other = Transform2D::from_w3c(a, b, c, d, e, f);
423        self.current_state.transform = self.current_state.transform.multiply(other);
424    }
425
426    pub fn set_transform(&mut self, transform: Transform2D) {
427        self.current_state.transform = transform;
428    }
429
430    pub fn get_transform(&self) -> Transform2D {
431        self.current_state.transform
432    }
433
434    pub fn reset_transform(&mut self) {
435        self.current_state.transform = Transform2D::IDENTITY;
436    }
437
438    // --- Styles ---
439
440    pub fn set_fill_style(&mut self, color: Color) {
441        self.current_state.fill_style = color;
442    }
443
444    pub fn set_stroke_style(&mut self, color: Color) {
445        self.current_state.stroke_style = color;
446    }
447
448    pub fn set_line_width(&mut self, width: f32) {
449        self.current_state.line_width = width.max(0.1);
450    }
451
452    /// Sets the stroke line termination cap style (`Butt`, `Round`, or `Square`).
453    pub fn set_line_cap(&mut self, cap: CanvasLineCap) {
454        self.current_state.line_cap = cap;
455        self.commands.push(CanvasCommand::SetLineCap(cap));
456    }
457
458    /// Returns the currently active stroke line cap style.
459    pub fn line_cap(&self) -> CanvasLineCap {
460        self.current_state.line_cap
461    }
462
463    /// Sets the stroke corner join style (`Miter`, `Round`, or `Bevel`).
464    pub fn set_line_join(&mut self, join: CanvasLineJoin) {
465        self.current_state.line_join = join;
466        self.commands.push(CanvasCommand::SetLineJoin(join));
467    }
468
469    /// Returns the currently active stroke corner join style.
470    pub fn line_join(&self) -> CanvasLineJoin {
471        self.current_state.line_join
472    }
473
474    pub fn set_global_alpha(&mut self, alpha: f32) {
475        self.current_state.global_alpha = alpha.clamp(0.0, 1.0);
476    }
477
478    /// Sets the stroke dash pattern (HTML5 `ctx.setLineDash(segments)`).
479    ///
480    /// Negative or non-finite values cause the call to be ignored per the HTML5 Canvas 2D spec;
481    /// an odd-length pattern is automatically concatenated with itself so dash/gap pairs repeat
482    /// cleanly; an empty slice restores solid strokes.
483    pub fn set_line_dash(&mut self, segments: &[f32]) {
484        if segments.iter().any(|&v| !v.is_finite() || v < 0.0) {
485            return;
486        }
487        let mut normalized = Vec::with_capacity(if segments.len() % 2 == 1 {
488            segments.len() * 2
489        } else {
490            segments.len()
491        });
492        normalized.extend_from_slice(segments);
493        if segments.len() % 2 == 1 {
494            normalized.extend_from_slice(segments);
495        }
496        self.current_state.line_dash = normalized.clone();
497        self.commands.push(CanvasCommand::SetLineDash {
498            segments: normalized,
499            offset: self.current_state.line_dash_offset,
500        });
501    }
502
503    /// Returns the currently active stroke dash pattern.
504    pub fn get_line_dash(&self) -> &[f32] {
505        &self.current_state.line_dash
506    }
507
508    /// Sets the stroke dash phase offset (`ctx.lineDashOffset`).
509    pub fn set_line_dash_offset(&mut self, offset: f32) {
510        if !offset.is_finite() {
511            return;
512        }
513        self.current_state.line_dash_offset = offset;
514        self.commands.push(CanvasCommand::SetLineDash {
515            segments: self.current_state.line_dash.clone(),
516            offset,
517        });
518    }
519
520    /// Returns the current stroke dash phase offset.
521    pub fn line_dash_offset(&self) -> f32 {
522        self.current_state.line_dash_offset
523    }
524
525    /// Sets the active CSS font shorthand (e.g. `"bold 12px monospace"`).
526    pub fn set_font(&mut self, font: impl Into<String>) {
527        let raw = font.into();
528        let (size, family, weight, italic) = parse_canvas_font(&raw);
529        self.current_state.font = raw;
530        self.current_state.font_size = size;
531        self.current_state.font_family = family;
532        self.current_state.font_weight = weight;
533        self.current_state.font_italic = italic;
534    }
535
536    /// Returns the active CSS font string.
537    pub fn font(&self) -> &str {
538        &self.current_state.font
539    }
540
541    /// Sets horizontal text alignment (`Left`, `Center`, `Right`, `Start`, `End`).
542    pub fn set_text_align(&mut self, align: CanvasTextAlign) {
543        self.current_state.text_align = align;
544    }
545
546    /// Sets vertical text baseline (`Alphabetic`, `Top`, `Middle`, `Bottom`, `Hanging`, `Ideographic`).
547    pub fn set_text_baseline(&mut self, baseline: CanvasTextBaseline) {
548        self.current_state.text_baseline = baseline;
549    }
550
551    /// Measures `text` using the active [`Self::set_font`] styling and registered platform
552    /// text measurer (PangoCairo when available, OpenType/inline shaping fallback headlessly).
553    pub fn measure_text(&self, text: &str) -> CanvasTextMetrics {
554        measure_canvas_text_metrics(
555            text,
556            self.current_state.font_size,
557            &self.current_state.font_family,
558            self.current_state.font_weight,
559            self.current_state.font_italic,
560        )
561    }
562
563    fn apply_alpha(&self, color: Color) -> Color {
564        if (self.current_state.global_alpha - 1.0).abs() < 1e-4 {
565            color
566        } else {
567            let (r, g, b, a) = color.to_f32();
568            Color::from_f32(r, g, b, a * self.current_state.global_alpha)
569        }
570    }
571
572    fn transform_scale(&self) -> f32 {
573        (self.current_state.transform.a.powi(2) + self.current_state.transform.b.powi(2)).sqrt()
574    }
575
576    // --- Path Construction ---
577
578    pub fn begin_path(&mut self) {
579        self.current_path.clear();
580    }
581
582    pub fn move_to(&mut self, x: f32, y: f32) {
583        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
584        self.current_path.push(CanvasPathVerb::MoveTo(tx, ty));
585    }
586
587    pub fn line_to(&mut self, x: f32, y: f32) {
588        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
589        self.current_path.push(CanvasPathVerb::LineTo(tx, ty));
590    }
591
592    /// Appends a quadratic Bézier curve from the current point to `(x, y)` using control point `(cpx, cpy)`.
593    pub fn quadratic_curve_to(&mut self, cpx: f32, cpy: f32, x: f32, y: f32) {
594        let (tcpx, tcpy) = self.current_state.transform.transform_xy(cpx, cpy);
595        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
596        self.current_path.push(CanvasPathVerb::QuadraticCurveTo {
597            cpx: tcpx,
598            cpy: tcpy,
599            x: tx,
600            y: ty,
601        });
602    }
603
604    /// Appends a cubic Bézier curve from the current point to `(x, y)` using control points
605    /// `(cp1x, cp1y)` and `(cp2x, cp2y)`.
606    pub fn bezier_curve_to(
607        &mut self,
608        cp1x: f32,
609        cp1y: f32,
610        cp2x: f32,
611        cp2y: f32,
612        x: f32,
613        y: f32,
614    ) {
615        let (tcp1x, tcp1y) = self.current_state.transform.transform_xy(cp1x, cp1y);
616        let (tcp2x, tcp2y) = self.current_state.transform.transform_xy(cp2x, cp2y);
617        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
618        self.current_path.push(CanvasPathVerb::BezierCurveTo {
619            cp1x: tcp1x,
620            cp1y: tcp1y,
621            cp2x: tcp2x,
622            cp2y: tcp2y,
623            x: tx,
624            y: ty,
625        });
626    }
627
628    pub fn arc(
629        &mut self,
630        cx: f32,
631        cy: f32,
632        radius: f32,
633        start_angle: f32,
634        end_angle: f32,
635        ccw: bool,
636    ) {
637        let (tcx, tcy) = self.current_state.transform.transform_xy(cx, cy);
638        let scale_x = self.transform_scale();
639        self.current_path.push(CanvasPathVerb::Arc {
640            cx: tcx,
641            cy: tcy,
642            radius: radius * scale_x,
643            start_angle,
644            end_angle,
645            counter_clockwise: ccw,
646        });
647    }
648
649    pub fn rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
650        self.move_to(x, y);
651        self.line_to(x + w, y);
652        self.line_to(x + w, y + h);
653        self.line_to(x, y + h);
654        self.close_path();
655    }
656
657    /// Adds a rounded rectangle subpath `(x, y, w, h)` with corner `radii` (uniform `f32`,
658    /// 1–4 element slice/array `[tl, tr, br, bl]`, or `BorderRadius`) per the HTML5 Canvas 2D
659    /// `roundRect` specification.
660    pub fn round_rect(&mut self, x: f32, y: f32, w: f32, h: f32, radii: impl IntoRoundRectRadii) {
661        let mut r = radii.into_round_rect_radii();
662        for v in &mut r {
663            *v = if v.is_finite() { (*v).max(0.0) } else { 0.0 };
664        }
665        let aw = w.abs();
666        let ah = h.abs();
667        if aw <= 1e-6 || ah <= 1e-6 {
668            self.rect(x, y, w, h);
669            return;
670        }
671        let mut scale = 1.0_f32;
672        let top = r[0] + r[1];
673        let right = r[1] + r[2];
674        let bottom = r[2] + r[3];
675        let left = r[3] + r[0];
676        if top > aw {
677            scale = scale.min(aw / top);
678        }
679        if bottom > aw {
680            scale = scale.min(aw / bottom);
681        }
682        if left > ah {
683            scale = scale.min(ah / left);
684        }
685        if right > ah {
686            scale = scale.min(ah / right);
687        }
688        let [tl, tr, br, bl] = [r[0] * scale, r[1] * scale, r[2] * scale, r[3] * scale];
689
690        let (x0, x1) = if w >= 0.0 { (x, x + w) } else { (x + w, x) };
691        let (y0, y1) = if h >= 0.0 { (y, y + h) } else { (y + h, y) };
692        const KAPPA: f32 = 0.552_284_8;
693
694        self.move_to(x0 + tl, y0);
695        self.line_to(x1 - tr, y0);
696        if tr > 0.0 {
697            let k = tr * KAPPA;
698            self.bezier_curve_to(x1 - tr + k, y0, x1, y0 + tr - k, x1, y0 + tr);
699        }
700        self.line_to(x1, y1 - br);
701        if br > 0.0 {
702            let k = br * KAPPA;
703            self.bezier_curve_to(x1, y1 - br + k, x1 - br + k, y1, x1 - br, y1);
704        }
705        self.line_to(x0 + bl, y1);
706        if bl > 0.0 {
707            let k = bl * KAPPA;
708            self.bezier_curve_to(x0 + bl - k, y1, x0, y1 - bl + k, x0, y1 - bl);
709        }
710        self.line_to(x0, y0 + tl);
711        if tl > 0.0 {
712            let k = tl * KAPPA;
713            self.bezier_curve_to(x0, y0 + tl - k, x0 + tl - k, y0, x0 + tl, y0);
714        }
715        self.close_path();
716    }
717
718    pub fn close_path(&mut self) {
719        self.current_path.push(CanvasPathVerb::Close);
720    }
721
722    /// Intersects the current clipping region with the current path.
723    ///
724    /// Wrap with [`Self::save`] and [`Self::restore`] to scope the clip region.
725    pub fn clip(&mut self) {
726        if self.current_path.is_empty() {
727            return;
728        }
729        self.commands.push(CanvasCommand::ClipPath {
730            verbs: self.current_path.clone(),
731        });
732    }
733
734    // --- Drawing Operations ---
735
736    pub fn fill_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
737        let (x0, y0) = self.current_state.transform.transform_xy(x, y);
738        let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
739        let min_x = x0.min(x1);
740        let max_x = x0.max(x1);
741        let min_y = y0.min(y1);
742        let max_y = y0.max(y1);
743
744        let color = self.apply_alpha(self.current_state.fill_style);
745        self.commands.push(CanvasCommand::FillRect {
746            bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
747            color,
748        });
749    }
750
751    pub fn stroke_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
752        let (x0, y0) = self.current_state.transform.transform_xy(x, y);
753        let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
754        let min_x = x0.min(x1);
755        let max_x = x0.max(x1);
756        let min_y = y0.min(y1);
757        let max_y = y0.max(y1);
758
759        let color = self.apply_alpha(self.current_state.stroke_style);
760        self.commands.push(CanvasCommand::StrokeRect {
761            bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
762            color,
763            line_width: self.current_state.line_width,
764        });
765    }
766
767    pub fn clear_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
768        let (x0, y0) = self.current_state.transform.transform_xy(x, y);
769        let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
770        let min_x = x0.min(x1);
771        let max_x = x0.max(x1);
772        let min_y = y0.min(y1);
773        let max_y = y0.max(y1);
774
775        self.commands.push(CanvasCommand::ClearRect {
776            bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
777        });
778    }
779
780    pub fn stroke(&mut self) {
781        if self.current_path.is_empty() {
782            return;
783        }
784        let color = self.apply_alpha(self.current_state.stroke_style);
785        self.commands.push(CanvasCommand::DrawPath {
786            verbs: self.current_path.clone(),
787            fill_color: None,
788            stroke_color: Some(color),
789            line_width: self.current_state.line_width,
790        });
791    }
792
793    pub fn fill(&mut self) {
794        if self.current_path.is_empty() {
795            return;
796        }
797        let color = self.apply_alpha(self.current_state.fill_style);
798        self.commands.push(CanvasCommand::DrawPath {
799            verbs: self.current_path.clone(),
800            fill_color: Some(color),
801            stroke_color: None,
802            line_width: self.current_state.line_width,
803        });
804    }
805
806    /// Renders filled text at `(x, y)` using the active `font`, `fill_style`, `text_align`, and `text_baseline`.
807    pub fn fill_text(&mut self, text: impl Into<String>, x: f32, y: f32) {
808        self.push_fill_text(text.into(), x, y, None);
809    }
810
811    /// Renders filled text at `(x, y)`, horizontally constrained to `max_width` pixels.
812    pub fn fill_text_with_max_width(
813        &mut self,
814        text: impl Into<String>,
815        x: f32,
816        y: f32,
817        max_width: f32,
818    ) {
819        self.push_fill_text(text.into(), x, y, Some(max_width.max(1.0)));
820    }
821
822    fn push_fill_text(&mut self, text: String, x: f32, y: f32, max_width: Option<f32>) {
823        if text.is_empty() {
824            return;
825        }
826        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
827        let scale = self.transform_scale().max(1e-3);
828        let color = self.apply_alpha(self.current_state.fill_style);
829        self.commands.push(CanvasCommand::FillText {
830            text,
831            x: tx,
832            y: ty,
833            color,
834            font: self.current_state.font.clone(),
835            font_size: self.current_state.font_size * scale,
836            font_family: self.current_state.font_family.clone(),
837            font_weight: self.current_state.font_weight,
838            italic: self.current_state.font_italic,
839            text_align: self.current_state.text_align,
840            text_baseline: self.current_state.text_baseline,
841            max_width: max_width.map(|mw| mw * scale),
842        });
843    }
844
845    /// Renders stroked/outlined text at `(x, y)` using the active `font`, `stroke_style`, and `line_width`.
846    pub fn stroke_text(&mut self, text: impl Into<String>, x: f32, y: f32) {
847        self.push_stroke_text(text.into(), x, y, None);
848    }
849
850    /// Renders stroked/outlined text at `(x, y)`, horizontally constrained to `max_width` pixels.
851    pub fn stroke_text_with_max_width(
852        &mut self,
853        text: impl Into<String>,
854        x: f32,
855        y: f32,
856        max_width: f32,
857    ) {
858        self.push_stroke_text(text.into(), x, y, Some(max_width.max(1.0)));
859    }
860
861    fn push_stroke_text(&mut self, text: String, x: f32, y: f32, max_width: Option<f32>) {
862        if text.is_empty() {
863            return;
864        }
865        let (tx, ty) = self.current_state.transform.transform_xy(x, y);
866        let scale = self.transform_scale().max(1e-3);
867        let color = self.apply_alpha(self.current_state.stroke_style);
868        self.commands.push(CanvasCommand::StrokeText {
869            text,
870            x: tx,
871            y: ty,
872            color,
873            line_width: self.current_state.line_width,
874            font: self.current_state.font.clone(),
875            font_size: self.current_state.font_size * scale,
876            font_family: self.current_state.font_family.clone(),
877            font_weight: self.current_state.font_weight,
878            italic: self.current_state.font_italic,
879            text_align: self.current_state.text_align,
880            text_baseline: self.current_state.text_baseline,
881            max_width: max_width.map(|mw| mw * scale),
882        });
883    }
884
885    /// Emits all recorded canvas commands.
886    pub fn finish(self) -> Vec<CanvasCommand> {
887        self.commands
888    }
889
890    pub fn commands(&self) -> &[CanvasCommand] {
891        &self.commands
892    }
893
894    /// Software analytical anti-aliased rasterization directly onto a FrameBuffer.
895    pub fn rasterize(
896        &self,
897        fb: &mut FrameBuffer,
898        origin_x: f32,
899        origin_y: f32,
900        clip: Option<Rect>,
901    ) {
902        rasterize_canvas_commands(fb, &self.commands, origin_x, origin_y, clip);
903    }
904}
905
906/// Thread-safe payload handle wrapping a UI-thread post-layout `on_paint` callback
907/// (`Rc<dyn Fn(&mut Canvas2DContext, f32, f32)>`).
908///
909/// Storing the `!Send` closure in a thread-local table keyed by an `Arc` drop-guard token allows
910/// callers to capture reactive [`Signal`](strata_dom::reactive::Signal)s and `Rc` handles freely
911/// while keeping `LayoutNode: Send + Sync` for parallel layout passes.
912#[derive(Debug)]
913pub struct Canvas2DPaintCallback {
914    token: u64,
915    origin_thread: std::thread::ThreadId,
916}
917
918type Canvas2DPaintFn = std::rc::Rc<dyn Fn(&mut Canvas2DContext, f32, f32)>;
919
920thread_local! {
921    static CANVAS2D_PAINT_HOOKS: std::cell::RefCell<std::collections::HashMap<u64, Canvas2DPaintFn>> =
922        std::cell::RefCell::new(std::collections::HashMap::new());
923}
924
925static NEXT_CANVAS2D_PAINT_TOKEN: std::sync::atomic::AtomicU64 =
926    std::sync::atomic::AtomicU64::new(1);
927
928impl Canvas2DPaintCallback {
929    /// Registers a post-layout `on_paint` closure on the current thread and returns an `Arc`
930    /// handle suitable for `Attribute::scene_payload_arc` / `ViewportSceneHandle`.
931    pub fn new(cb: Canvas2DPaintFn) -> std::sync::Arc<Self> {
932        let token = NEXT_CANVAS2D_PAINT_TOKEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
933        let origin_thread = std::thread::current().id();
934        CANVAS2D_PAINT_HOOKS.with(|hooks| {
935            hooks.borrow_mut().insert(token, cb);
936        });
937        std::sync::Arc::new(Self {
938            token,
939            origin_thread,
940        })
941    }
942
943    /// Invokes the registered paint closure with the resolved post-layout `(width, height)`
944    /// dimensions and returns the recorded [`CanvasCommand`] list.
945    pub fn paint(&self, width: f32, height: f32) -> Vec<CanvasCommand> {
946        let mut ctx = Canvas2DContext::new(width.max(0.0), height.max(0.0));
947        if std::thread::current().id() == self.origin_thread {
948            let cb_opt = CANVAS2D_PAINT_HOOKS.with(|hooks| hooks.borrow().get(&self.token).cloned());
949            if let Some(cb) = cb_opt {
950                cb(&mut ctx, width, height);
951            }
952        }
953        ctx.finish()
954    }
955}
956
957impl Drop for Canvas2DPaintCallback {
958    fn drop(&mut self) {
959        if std::thread::current().id() == self.origin_thread {
960            let _ = CANVAS2D_PAINT_HOOKS.try_with(|hooks| {
961                if let Ok(mut map) = hooks.try_borrow_mut() {
962                    map.remove(&self.token);
963                }
964            });
965        }
966    }
967}
968
969/// Flattens a slice of [`CanvasPathVerb`]s (including cubic/quadratic Bézier curves and arcs)
970/// into translated polyline subpaths `Vec<Vec<(f32, f32)>>`.
971pub fn flatten_canvas_verbs(
972    verbs: &[CanvasPathVerb],
973    origin_x: f32,
974    origin_y: f32,
975) -> Vec<Vec<(f32, f32)>> {
976    let mut subpaths: Vec<Vec<(f32, f32)>> = Vec::new();
977    let mut cur_sub: Vec<(f32, f32)> = Vec::new();
978    let mut current = (origin_x, origin_y);
979    let mut start = (origin_x, origin_y);
980
981    for verb in verbs {
982        match *verb {
983            CanvasPathVerb::MoveTo(x, y) => {
984                if cur_sub.len() >= 2 {
985                    subpaths.push(std::mem::take(&mut cur_sub));
986                } else {
987                    cur_sub.clear();
988                }
989                current = (x + origin_x, y + origin_y);
990                start = current;
991                cur_sub.push(current);
992            }
993            CanvasPathVerb::LineTo(x, y) => {
994                let next = (x + origin_x, y + origin_y);
995                if cur_sub.is_empty() {
996                    cur_sub.push(current);
997                }
998                cur_sub.push(next);
999                current = next;
1000            }
1001            CanvasPathVerb::QuadraticCurveTo { cpx, cpy, x, y } => {
1002                let p0 = current;
1003                let p1 = (cpx + origin_x, cpy + origin_y);
1004                let p2 = (x + origin_x, y + origin_y);
1005                if cur_sub.is_empty() {
1006                    cur_sub.push(p0);
1007                }
1008                let approx_len = ((p1.0 - p0.0).hypot(p1.1 - p0.1)
1009                    + (p2.0 - p1.0).hypot(p2.1 - p1.1))
1010                .max(1.0);
1011                let steps = ((approx_len / 4.0).ceil() as usize).clamp(12, 64);
1012                for i in 1..=steps {
1013                    let t = i as f32 / steps as f32;
1014                    let mt = 1.0 - t;
1015                    let px = mt * mt * p0.0 + 2.0 * mt * t * p1.0 + t * t * p2.0;
1016                    let py = mt * mt * p0.1 + 2.0 * mt * t * p1.1 + t * t * p2.1;
1017                    cur_sub.push((px, py));
1018                }
1019                current = p2;
1020            }
1021            CanvasPathVerb::BezierCurveTo {
1022                cp1x,
1023                cp1y,
1024                cp2x,
1025                cp2y,
1026                x,
1027                y,
1028            } => {
1029                let p0 = current;
1030                let p1 = (cp1x + origin_x, cp1y + origin_y);
1031                let p2 = (cp2x + origin_x, cp2y + origin_y);
1032                let p3 = (x + origin_x, y + origin_y);
1033                if cur_sub.is_empty() {
1034                    cur_sub.push(p0);
1035                }
1036                let approx_len = ((p1.0 - p0.0).hypot(p1.1 - p0.1)
1037                    + (p2.0 - p1.0).hypot(p2.1 - p1.1)
1038                    + (p3.0 - p2.0).hypot(p3.1 - p2.1))
1039                .max(1.0);
1040                let steps = ((approx_len / 4.0).ceil() as usize).clamp(16, 80);
1041                for i in 1..=steps {
1042                    let t = i as f32 / steps as f32;
1043                    let mt = 1.0 - t;
1044                    let mt2 = mt * mt;
1045                    let t2 = t * t;
1046                    let px = mt2 * mt * p0.0
1047                        + 3.0 * mt2 * t * p1.0
1048                        + 3.0 * mt * t2 * p2.0
1049                        + t2 * t * p3.0;
1050                    let py = mt2 * mt * p0.1
1051                        + 3.0 * mt2 * t * p1.1
1052                        + 3.0 * mt * t2 * p2.1
1053                        + t2 * t * p3.1;
1054                    cur_sub.push((px, py));
1055                }
1056                current = p3;
1057            }
1058            CanvasPathVerb::Arc {
1059                cx,
1060                cy,
1061                radius,
1062                start_angle,
1063                end_angle,
1064                counter_clockwise,
1065            } => {
1066                let acx = cx + origin_x;
1067                let acy = cy + origin_y;
1068                let mut sweep = end_angle - start_angle;
1069                if counter_clockwise {
1070                    if sweep >= 0.0 {
1071                        sweep -= std::f32::consts::TAU;
1072                    }
1073                } else if sweep <= 0.0 && (end_angle - start_angle).abs() > 1e-5 {
1074                    sweep += std::f32::consts::TAU;
1075                }
1076                let steps = ((radius.abs() * sweep.abs() / 3.0).ceil() as usize).clamp(16, 96);
1077                for i in 0..=steps {
1078                    let a = start_angle + sweep * (i as f32 / steps as f32);
1079                    let pt = (acx + radius * a.cos(), acy + radius * a.sin());
1080                    if i == 0 && cur_sub.is_empty() {
1081                        start = pt;
1082                    }
1083                    cur_sub.push(pt);
1084                    current = pt;
1085                }
1086            }
1087            CanvasPathVerb::Close => {
1088                if !cur_sub.is_empty() && current != start {
1089                    cur_sub.push(start);
1090                    current = start;
1091                }
1092                if cur_sub.len() >= 2 {
1093                    subpaths.push(std::mem::take(&mut cur_sub));
1094                } else {
1095                    cur_sub.clear();
1096                }
1097            }
1098        }
1099    }
1100
1101    if cur_sub.len() >= 2 {
1102        subpaths.push(cur_sub);
1103    }
1104    subpaths
1105}
1106
1107/// Computes the axis-aligned bounding box of `verbs` shifted by `(origin_x, origin_y)`.
1108pub fn canvas_verbs_bounds(verbs: &[CanvasPathVerb], origin_x: f32, origin_y: f32) -> Option<Rect> {
1109    let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
1110    let mut min_x = f32::INFINITY;
1111    let mut min_y = f32::INFINITY;
1112    let mut max_x = f32::NEG_INFINITY;
1113    let mut max_y = f32::NEG_INFINITY;
1114    for sub in &subpaths {
1115        for &(x, y) in sub {
1116            min_x = min_x.min(x);
1117            min_y = min_y.min(y);
1118            max_x = max_x.max(x);
1119            max_y = max_y.max(y);
1120        }
1121    }
1122    if min_x.is_finite() && min_y.is_finite() && max_x >= min_x && max_y >= min_y {
1123        Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
1124    } else {
1125        None
1126    }
1127}
1128
1129/// Measures `text` using the active font styling and registered platform text measurer,
1130/// falling back to the inline headless OpenType/glyph estimator when no platform backend is registered.
1131pub fn measure_canvas_text_metrics(
1132    text: &str,
1133    font_size: f32,
1134    font_family: &str,
1135    font_weight: u16,
1136    italic: bool,
1137) -> CanvasTextMetrics {
1138    let size = font_size.max(0.0);
1139    if size <= 0.0 {
1140        return CanvasTextMetrics::default();
1141    }
1142    let primary_family = font_family
1143        .split(',')
1144        .next()
1145        .map(str::trim)
1146        .map(|s| s.trim_matches(|c| c == '\'' || c == '"'))
1147        .filter(|s| !s.is_empty())
1148        .unwrap_or("sans-serif");
1149    let family_atom = strata_primitives::atom::intern(primary_family);
1150    let mono = strata_layout::text::is_monospace_family(family_atom)
1151        || font_family.to_ascii_lowercase().contains("mono");
1152    let weight = strata_style::types::FontWeight::from_u16(font_weight);
1153    let style = if italic {
1154        strata_style::types::FontStyle::Italic
1155    } else {
1156        strata_style::types::FontStyle::Normal
1157    };
1158    let (width, height) = if text.is_empty() {
1159        let h = strata_layout::text::measure_text_bounds_styled_with_family(
1160            " ",
1161            size,
1162            1.0,
1163            None,
1164            mono,
1165            family_atom,
1166            weight,
1167            style,
1168        )
1169        .1;
1170        (0.0, h)
1171    } else {
1172        strata_layout::text::measure_text_bounds_styled_with_family(
1173            text,
1174            size,
1175            1.0,
1176            None,
1177            mono,
1178            family_atom,
1179            weight,
1180            style,
1181        )
1182    };
1183    let (font_ascent, font_descent) = if let Some(metrics_fn) = strata_layout::text::get_font_metrics() {
1184        let (asc, desc, _gap) = metrics_fn(family_atom, size, font_weight >= 600);
1185        (asc.max(0.0), desc.max(0.0))
1186    } else {
1187        (size * 0.8, size * 0.2)
1188    };
1189    CanvasTextMetrics {
1190        width,
1191        height: height.max(font_ascent + font_descent),
1192        actual_bounding_box_ascent: font_ascent,
1193        actual_bounding_box_descent: font_descent,
1194        font_bounding_box_ascent: font_ascent,
1195        font_bounding_box_descent: font_descent,
1196    }
1197}
1198
1199#[derive(Clone)]
1200struct RasterState {
1201    clip: Option<Rect>,
1202    clip_polys: Vec<Vec<Vec<(f32, f32)>>>,
1203    line_dash: Vec<f32>,
1204    dash_offset: f32,
1205    line_cap: CanvasLineCap,
1206    line_join: CanvasLineJoin,
1207}
1208
1209pub fn point_in_subpaths_even_odd(subpaths: &[Vec<(f32, f32)>], px: f32, py: f32) -> bool {
1210    let mut inside = false;
1211    for sub in subpaths {
1212        if sub.len() < 3 {
1213            continue;
1214        }
1215        let mut j = sub.len() - 1;
1216        for i in 0..sub.len() {
1217            let (xi, yi) = sub[i];
1218            let (xj, yj) = sub[j];
1219            let intersects =
1220                ((yi > py) != (yj > py)) && (px < (xj - xi) * (py - yi) / (yj - yi) + xi);
1221            if intersects {
1222                inside = !inside;
1223            }
1224            j = i;
1225        }
1226    }
1227    inside
1228}
1229
1230fn point_passes_clip(state: &RasterState, x: f32, y: f32) -> bool {
1231    if let Some(c) = state.clip {
1232        if x < c.x || x >= c.max_x() || y < c.y || y >= c.max_y() {
1233            return false;
1234        }
1235    }
1236    for poly in &state.clip_polys {
1237        if !point_in_subpaths_even_odd(poly, x, y) {
1238            return false;
1239        }
1240    }
1241    true
1242}
1243
1244fn rasterize_fill_subpaths(
1245    fb: &mut FrameBuffer,
1246    subpaths: &[Vec<(f32, f32)>],
1247    color: Color,
1248    state: &RasterState,
1249) {
1250    let mut min_x = f32::INFINITY;
1251    let mut min_y = f32::INFINITY;
1252    let mut max_x = f32::NEG_INFINITY;
1253    let mut max_y = f32::NEG_INFINITY;
1254    for sub in subpaths {
1255        for &(x, y) in sub {
1256            min_x = min_x.min(x);
1257            min_y = min_y.min(y);
1258            max_x = max_x.max(x);
1259            max_y = max_y.max(y);
1260        }
1261    }
1262    if !min_x.is_finite() || max_x <= min_x || max_y <= min_y {
1263        return;
1264    }
1265
1266    let x0 = (min_x.floor() as isize).max(0) as usize;
1267    let x1 = (max_x.ceil() as usize).min(fb.width);
1268    let y0 = (min_y.floor() as isize).max(0) as usize;
1269    let y1 = (max_y.ceil() as usize).min(fb.height);
1270
1271    for y in y0..y1 {
1272        let py = y as f32 + 0.5;
1273        for x in x0..x1 {
1274            let px = x as f32 + 0.5;
1275            if !point_passes_clip(state, px, py) {
1276                continue;
1277            }
1278            if point_in_subpaths_even_odd(subpaths, px, py) {
1279                fb.set_pixel(x, y, color);
1280            }
1281        }
1282    }
1283}
1284
1285#[derive(Clone, Copy)]
1286struct StrokeSeg {
1287    x0: f32,
1288    y0: f32,
1289    x1: f32,
1290    y1: f32,
1291    tx: f32,
1292    ty: f32,
1293    nx: f32,
1294    ny: f32,
1295    len: f32,
1296    cap0: CanvasLineCap,
1297    cap1: CanvasLineCap,
1298}
1299
1300impl StrokeSeg {
1301    fn from_pts(p0: (f32, f32), p1: (f32, f32), cap0: CanvasLineCap, cap1: CanvasLineCap) -> Self {
1302        let vx = p1.0 - p0.0;
1303        let vy = p1.1 - p0.1;
1304        let len = vx.hypot(vy);
1305        let (tx, ty) = if len > 1e-6 {
1306            (vx / len, vy / len)
1307        } else {
1308            (1.0, 0.0)
1309        };
1310        Self {
1311            x0: p0.0,
1312            y0: p0.1,
1313            x1: p1.0,
1314            y1: p1.1,
1315            tx,
1316            ty,
1317            nx: -ty,
1318            ny: tx,
1319            len,
1320            cap0,
1321            cap1,
1322        }
1323    }
1324
1325    #[inline]
1326    fn signed_dist(&self, px: f32, py: f32, half_lw: f32) -> f32 {
1327        let wx = px - self.x0;
1328        let wy = py - self.y0;
1329        if self.len <= 1e-6 {
1330            return if self.cap0 == CanvasLineCap::Round || self.cap1 == CanvasLineCap::Round {
1331                wx.hypot(wy) - half_lw
1332            } else if self.cap0 == CanvasLineCap::Square || self.cap1 == CanvasLineCap::Square {
1333                let dx = wx.abs() - half_lw;
1334                let dy = wy.abs() - half_lw;
1335                dx.max(0.0).hypot(dy.max(0.0)) + dx.max(dy).min(0.0)
1336            } else {
1337                f32::INFINITY
1338            };
1339        }
1340
1341        let s = wx * self.tx + wy * self.ty;
1342        let u = (wx * self.nx + wy * self.ny).abs();
1343        let s0 = if self.cap0 == CanvasLineCap::Square {
1344            -half_lw
1345        } else {
1346            0.0
1347        };
1348        let s1 = if self.cap1 == CanvasLineCap::Square {
1349            self.len + half_lw
1350        } else {
1351            self.len
1352        };
1353        let dx = (s0 - s).max(s - s1);
1354        let dy = u - half_lw;
1355        let mut sd = dx.max(0.0).hypot(dy.max(0.0)) + dx.max(dy).min(0.0);
1356        if self.cap0 == CanvasLineCap::Round {
1357            sd = sd.min(s.hypot(u) - half_lw);
1358        }
1359        if self.cap1 == CanvasLineCap::Round {
1360            sd = sd.min((s - self.len).hypot(u) - half_lw);
1361        }
1362        sd
1363    }
1364
1365    #[inline]
1366    fn bounds_px(&self, half_lw: f32, fb_w: usize, fb_h: usize) -> (usize, usize, usize, usize) {
1367        let pad = half_lw * 1.5 + 2.0;
1368        let x0 = ((self.x0.min(self.x1) - pad).floor() as isize).max(0) as usize;
1369        let x1 = ((self.x0.max(self.x1) + pad).ceil() as usize).min(fb_w);
1370        let y0 = ((self.y0.min(self.y1) - pad).floor() as isize).max(0) as usize;
1371        let y1 = ((self.y0.max(self.y1) + pad).ceil() as usize).min(fb_h);
1372        (x0, y0, x1, y1)
1373    }
1374}
1375
1376#[derive(Clone, Copy)]
1377struct StrokeJoin {
1378    jx: f32,
1379    jy: f32,
1380    t0x: f32,
1381    t0y: f32,
1382    t1x: f32,
1383    t1y: f32,
1384}
1385
1386impl StrokeJoin {
1387    #[inline]
1388    fn signed_dist(&self, px: f32, py: f32, half_lw: f32, join: CanvasLineJoin) -> f32 {
1389        let dpx = px - self.jx;
1390        let dpy = py - self.jy;
1391        let dot_t = self.t0x * self.t1x + self.t0y * self.t1y;
1392        if dot_t > 0.9999 {
1393            return f32::INFINITY;
1394        }
1395        let cross = self.t0x * self.t1y - self.t0y * self.t1x;
1396        let sd_disk = dpx.hypot(dpy) - half_lw;
1397        if cross.abs() < 1e-4 && dot_t < 0.0 {
1398            return if join == CanvasLineJoin::Round {
1399                sd_disk
1400            } else {
1401                f32::INFINITY
1402            };
1403        }
1404        if join == CanvasLineJoin::Round {
1405            return sd_disk;
1406        }
1407
1408        let sign = if cross > 0.0 { -1.0 } else { 1.0 };
1409        let n0x = sign * (-self.t0y);
1410        let n0y = sign * self.t0x;
1411        let n1x = sign * (-self.t1y);
1412        let n1y = sign * self.t1x;
1413
1414        let sum_x = n0x + n1x;
1415        let sum_y = n0y + n1y;
1416        let sum_len = sum_x.hypot(sum_y);
1417        if sum_len <= 1e-5 {
1418            return f32::INFINITY;
1419        }
1420        let bis_x = sum_x / sum_len;
1421        let bis_y = sum_y / sum_len;
1422
1423        let miter_ratio = 2.0 / sum_len;
1424        let use_bevel = join == CanvasLineJoin::Bevel || miter_ratio > 10.0;
1425        if use_bevel {
1426            let d_bevel = half_lw * sum_len * 0.5;
1427            let sd_bevel = dpx * bis_x + dpy * bis_y - d_bevel;
1428            sd_disk.max(sd_bevel)
1429        } else {
1430            let sd0 = dpx * n0x + dpy * n0y - half_lw;
1431            let sd1 = dpx * n1x + dpy * n1y - half_lw;
1432            let sd_back0 = -(dpx * self.t0x + dpy * self.t0y);
1433            let sd_back1 = dpx * self.t1x + dpy * self.t1y;
1434            let sd_wedge = sd0.max(sd1).max(sd_back0).max(sd_back1);
1435            sd_disk.min(sd_wedge)
1436        }
1437    }
1438
1439    #[inline]
1440    fn bounds_px(
1441        &self,
1442        half_lw: f32,
1443        join: CanvasLineJoin,
1444        fb_w: usize,
1445        fb_h: usize,
1446    ) -> (usize, usize, usize, usize) {
1447        let pad = match join {
1448            CanvasLineJoin::Miter => half_lw * 10.0 + 2.0,
1449            CanvasLineJoin::Round | CanvasLineJoin::Bevel => half_lw + 2.0,
1450        };
1451        let x0 = ((self.jx - pad).floor() as isize).max(0) as usize;
1452        let x1 = ((self.jx + pad).ceil() as usize).min(fb_w);
1453        let y0 = ((self.jy - pad).floor() as isize).max(0) as usize;
1454        let y1 = ((self.jy + pad).ceil() as usize).min(fb_h);
1455        (x0, y0, x1, y1)
1456    }
1457}
1458
1459fn rasterize_stroke_run(
1460    fb: &mut FrameBuffer,
1461    pts: &[(f32, f32)],
1462    closed: bool,
1463    color: Color,
1464    line_width: f32,
1465    state: &RasterState,
1466) {
1467    if pts.len() < 2 {
1468        return;
1469    }
1470
1471    let mut clean: Vec<(f32, f32)> = Vec::with_capacity(pts.len());
1472    for &p in pts {
1473        if clean
1474            .last()
1475            .is_none_or(|&prev| (p.0 - prev.0).hypot(p.1 - prev.1) > 1e-4)
1476        {
1477            clean.push(p);
1478        }
1479    }
1480    if closed && clean.len() >= 2 {
1481        let first = clean[0];
1482        let last = *clean.last().unwrap();
1483        if (first.0 - last.0).hypot(first.1 - last.1) > 1e-4 {
1484            clean.push(first);
1485        }
1486    }
1487    if clean.len() < 2 {
1488        let seg = StrokeSeg::from_pts(pts[0], pts[0], state.line_cap, state.line_cap);
1489        rasterize_stroke_primitives(fb, &[seg], &[], color, line_width, state);
1490        return;
1491    }
1492
1493    let seg_count = clean.len() - 1;
1494    let is_loop = closed && seg_count >= 2;
1495    let mut segs = Vec::with_capacity(seg_count);
1496    for (i, w) in clean.windows(2).enumerate() {
1497        let cap0 = if i == 0 && !is_loop {
1498            state.line_cap
1499        } else {
1500            CanvasLineCap::Butt
1501        };
1502        let cap1 = if i + 1 == seg_count && !is_loop {
1503            state.line_cap
1504        } else {
1505            CanvasLineCap::Butt
1506        };
1507        segs.push(StrokeSeg::from_pts(w[0], w[1], cap0, cap1));
1508    }
1509
1510    let mut joins = Vec::with_capacity(if is_loop { seg_count } else { seg_count - 1 });
1511    for i in 1..seg_count {
1512        joins.push(StrokeJoin {
1513            jx: segs[i].x0,
1514            jy: segs[i].y0,
1515            t0x: segs[i - 1].tx,
1516            t0y: segs[i - 1].ty,
1517            t1x: segs[i].tx,
1518            t1y: segs[i].ty,
1519        });
1520    }
1521    if is_loop {
1522        let last = segs[seg_count - 1];
1523        joins.push(StrokeJoin {
1524            jx: segs[0].x0,
1525            jy: segs[0].y0,
1526            t0x: last.tx,
1527            t0y: last.ty,
1528            t1x: segs[0].tx,
1529            t1y: segs[0].ty,
1530        });
1531    }
1532
1533    rasterize_stroke_primitives(fb, &segs, &joins, color, line_width, state);
1534}
1535
1536fn rasterize_stroke_primitives(
1537    fb: &mut FrameBuffer,
1538    segs: &[StrokeSeg],
1539    joins: &[StrokeJoin],
1540    color: Color,
1541    line_width: f32,
1542    state: &RasterState,
1543) {
1544    if segs.is_empty() || color.a == 0 {
1545        return;
1546    }
1547    let half_lw = line_width * 0.5;
1548
1549    if segs.len() == 1 && joins.is_empty() {
1550        let seg = segs[0];
1551        let (x0, y0, x1, y1) = seg.bounds_px(half_lw, fb.width, fb.height);
1552        for y in y0..y1 {
1553            let py = y as f32 + 0.5;
1554            if let Some(c) = state.clip {
1555                if py < c.y || py >= c.max_y() {
1556                    continue;
1557                }
1558            }
1559            for x in x0..x1 {
1560                let px = x as f32 + 0.5;
1561                if !point_passes_clip(state, px, py) {
1562                    continue;
1563                }
1564                let sd = seg.signed_dist(px, py, half_lw);
1565                let cov = (0.5 - sd).clamp(0.0, 1.0);
1566                if cov > 0.005 {
1567                    fb.set_pixel(
1568                        x,
1569                        y,
1570                        Color::rgba(
1571                            color.r,
1572                            color.g,
1573                            color.b,
1574                            (color.a() * cov * 255.0).round() as u8,
1575                        ),
1576                    );
1577                }
1578            }
1579        }
1580        return;
1581    }
1582
1583    let mut min_x = usize::MAX;
1584    let mut min_y = usize::MAX;
1585    let mut max_x = 0usize;
1586    let mut max_y = 0usize;
1587    let seg_boxes: Vec<(usize, usize, usize, usize)> = segs
1588        .iter()
1589        .map(|s| {
1590            let b = s.bounds_px(half_lw, fb.width, fb.height);
1591            min_x = min_x.min(b.0);
1592            min_y = min_y.min(b.1);
1593            max_x = max_x.max(b.2);
1594            max_y = max_y.max(b.3);
1595            b
1596        })
1597        .collect();
1598    let join_boxes: Vec<(usize, usize, usize, usize)> = joins
1599        .iter()
1600        .map(|j| {
1601            let b = j.bounds_px(half_lw, state.line_join, fb.width, fb.height);
1602            min_x = min_x.min(b.0);
1603            min_y = min_y.min(b.1);
1604            max_x = max_x.max(b.2);
1605            max_y = max_y.max(b.3);
1606            b
1607        })
1608        .collect();
1609
1610    if let Some(c) = state.clip {
1611        min_x = min_x.max((c.x.floor() as isize).max(0) as usize);
1612        min_y = min_y.max((c.y.floor() as isize).max(0) as usize);
1613        max_x = max_x.min((c.max_x().ceil() as usize).min(fb.width));
1614        max_y = max_y.min((c.max_y().ceil() as usize).min(fb.height));
1615    }
1616    if min_x >= max_x || min_y >= max_y {
1617        return;
1618    }
1619
1620    const TILE: usize = 256;
1621    let mut tile_sd: Vec<f32> = Vec::new();
1622    let mut ty0 = min_y;
1623    while ty0 < max_y {
1624        let ty1 = (ty0 + TILE).min(max_y);
1625        let th = ty1 - ty0;
1626        let mut tx0 = min_x;
1627        while tx0 < max_x {
1628            let tx1 = (tx0 + TILE).min(max_x);
1629            let tw = tx1 - tx0;
1630            let len = tw * th;
1631            tile_sd.clear();
1632            tile_sd.resize(len, f32::INFINITY);
1633
1634            let mut touched = false;
1635            for (seg, &(sx0, sy0, sx1, sy1)) in segs.iter().zip(&seg_boxes) {
1636                let ox0 = tx0.max(sx0);
1637                let oy0 = ty0.max(sy0);
1638                let ox1 = tx1.min(sx1);
1639                let oy1 = ty1.min(sy1);
1640                if ox0 >= ox1 || oy0 >= oy1 {
1641                    continue;
1642                }
1643                touched = true;
1644                for y in oy0..oy1 {
1645                    let py = y as f32 + 0.5;
1646                    let row = (y - ty0) * tw;
1647                    for x in ox0..ox1 {
1648                        let px = x as f32 + 0.5;
1649                        let idx = row + (x - tx0);
1650                        let sd = seg.signed_dist(px, py, half_lw);
1651                        if sd < tile_sd[idx] {
1652                            tile_sd[idx] = sd;
1653                        }
1654                    }
1655                }
1656            }
1657
1658            for (join, &(jx0, jy0, jx1, jy1)) in joins.iter().zip(&join_boxes) {
1659                let ox0 = tx0.max(jx0);
1660                let oy0 = ty0.max(jy0);
1661                let ox1 = tx1.min(jx1);
1662                let oy1 = ty1.min(jy1);
1663                if ox0 >= ox1 || oy0 >= oy1 {
1664                    continue;
1665                }
1666                touched = true;
1667                for y in oy0..oy1 {
1668                    let py = y as f32 + 0.5;
1669                    let row = (y - ty0) * tw;
1670                    for x in ox0..ox1 {
1671                        let px = x as f32 + 0.5;
1672                        let idx = row + (x - tx0);
1673                        let sd = join.signed_dist(px, py, half_lw, state.line_join);
1674                        if sd < tile_sd[idx] {
1675                            tile_sd[idx] = sd;
1676                        }
1677                    }
1678                }
1679            }
1680
1681            if touched {
1682                for y in ty0..ty1 {
1683                    let py = y as f32 + 0.5;
1684                    let row = (y - ty0) * tw;
1685                    for x in tx0..tx1 {
1686                        let sd = tile_sd[row + (x - tx0)];
1687                        if sd >= 0.5 {
1688                            continue;
1689                        }
1690                        let px = x as f32 + 0.5;
1691                        if !point_passes_clip(state, px, py) {
1692                            continue;
1693                        }
1694                        let cov = (0.5 - sd).clamp(0.0, 1.0);
1695                        if cov > 0.005 {
1696                            fb.set_pixel(
1697                                x,
1698                                y,
1699                                Color::rgba(
1700                                    color.r,
1701                                    color.g,
1702                                    color.b,
1703                                    (color.a() * cov * 255.0).round() as u8,
1704                                ),
1705                            );
1706                        }
1707                    }
1708                }
1709            }
1710
1711            tx0 = tx1;
1712        }
1713        ty0 = ty1;
1714    }
1715}
1716
1717fn rasterize_polyline(
1718    fb: &mut FrameBuffer,
1719    pts: &[(f32, f32)],
1720    color: Color,
1721    line_width: f32,
1722    state: &RasterState,
1723) {
1724    if pts.len() < 2 {
1725        return;
1726    }
1727
1728    let is_closed = pts.len() >= 3
1729        && (pts[0].0 - pts[pts.len() - 1].0).hypot(pts[0].1 - pts[pts.len() - 1].1) <= 1e-3;
1730
1731    let period: f32 = state.line_dash.iter().copied().sum();
1732    if state.line_dash.is_empty() || period <= 1e-4 {
1733        rasterize_stroke_run(fb, pts, is_closed, color, line_width, state);
1734        return;
1735    }
1736
1737    let mut phase = state.dash_offset.rem_euclid(period);
1738    let mut dash_idx = 0usize;
1739    while dash_idx < state.line_dash.len() && phase >= state.line_dash[dash_idx] {
1740        phase -= state.line_dash[dash_idx];
1741        dash_idx = (dash_idx + 1) % state.line_dash.len();
1742    }
1743    let mut rem = (state.line_dash[dash_idx] - phase).max(0.0);
1744
1745    let mut runs: Vec<Vec<(f32, f32)>> = Vec::new();
1746    let mut cur_run: Vec<(f32, f32)> = Vec::new();
1747    let started_on = dash_idx.is_multiple_of(2) && rem > 1e-4;
1748
1749    for seg in pts.windows(2) {
1750        let (x0, y0) = seg[0];
1751        let (x1, y1) = seg[1];
1752        let dx = x1 - x0;
1753        let dy = y1 - y0;
1754        let seg_len = dx.hypot(dy);
1755        if seg_len <= 1e-4 {
1756            continue;
1757        }
1758        let mut cursor = 0.0_f32;
1759        while cursor < seg_len {
1760            if rem <= 1e-4 {
1761                dash_idx = (dash_idx + 1) % state.line_dash.len();
1762                rem = state.line_dash[dash_idx];
1763                if !dash_idx.is_multiple_of(2) && cur_run.len() >= 2 {
1764                    runs.push(std::mem::take(&mut cur_run));
1765                } else if !dash_idx.is_multiple_of(2) {
1766                    cur_run.clear();
1767                }
1768                if rem <= 1e-4 {
1769                    break;
1770                }
1771            }
1772            let step = rem.min(seg_len - cursor);
1773            let t0 = cursor / seg_len;
1774            let t1 = (cursor + step) / seg_len;
1775            if dash_idx.is_multiple_of(2) {
1776                let p_start = (x0 + dx * t0, y0 + dy * t0);
1777                let p_end = (x0 + dx * t1, y0 + dy * t1);
1778                if cur_run.is_empty() {
1779                    cur_run.push(p_start);
1780                }
1781                cur_run.push(p_end);
1782            }
1783            cursor += step;
1784            rem -= step;
1785        }
1786    }
1787    let ended_on = !cur_run.is_empty();
1788    if cur_run.len() >= 2 {
1789        runs.push(cur_run);
1790    }
1791
1792    if is_closed && started_on && ended_on && runs.len() >= 2 {
1793        let mut last = runs.pop().unwrap();
1794        let first = runs.remove(0);
1795        last.extend(first.into_iter().skip(1));
1796        rasterize_stroke_run(fb, &last, false, color, line_width, state);
1797    } else if is_closed && started_on && ended_on && runs.len() == 1 {
1798        rasterize_stroke_run(fb, &runs[0], true, color, line_width, state);
1799        return;
1800    }
1801
1802    for run in &runs {
1803        rasterize_stroke_run(fb, run, false, color, line_width, state);
1804    }
1805}
1806
1807/// Software analytical anti-aliased rasterization of canvas commands directly onto a FrameBuffer.
1808pub fn rasterize_canvas_commands(
1809    fb: &mut FrameBuffer,
1810    commands: &[CanvasCommand],
1811    origin_x: f32,
1812    origin_y: f32,
1813    clip: Option<Rect>,
1814) {
1815    let mut state = RasterState {
1816        clip,
1817        clip_polys: Vec::new(),
1818        line_dash: Vec::new(),
1819        dash_offset: 0.0,
1820        line_cap: CanvasLineCap::Butt,
1821        line_join: CanvasLineJoin::Miter,
1822    };
1823    let mut stack: Vec<RasterState> = Vec::new();
1824
1825    for cmd in commands {
1826        match cmd {
1827            CanvasCommand::Save => {
1828                stack.push(state.clone());
1829            }
1830            CanvasCommand::Restore => {
1831                if let Some(prev) = stack.pop() {
1832                    state = prev;
1833                }
1834            }
1835            CanvasCommand::SetLineDash { segments, offset } => {
1836                state.line_dash = segments.clone();
1837                state.dash_offset = *offset;
1838            }
1839            CanvasCommand::SetLineCap(cap) => {
1840                state.line_cap = *cap;
1841            }
1842            CanvasCommand::SetLineJoin(join) => {
1843                state.line_join = *join;
1844            }
1845            CanvasCommand::ClipPath { verbs } => {
1846                let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
1847                if let Some(bbox) = canvas_verbs_bounds(verbs, origin_x, origin_y) {
1848                    state.clip = match state.clip {
1849                        Some(existing) => existing.intersect(bbox).or(Some(Rect::zero())),
1850                        None => Some(bbox),
1851                    };
1852                }
1853                if !subpaths.is_empty() {
1854                    state.clip_polys.push(subpaths);
1855                }
1856            }
1857            CanvasCommand::FillRect { bounds, color } => {
1858                let translated = Rect::new(
1859                    bounds.x + origin_x,
1860                    bounds.y + origin_y,
1861                    bounds.width,
1862                    bounds.height,
1863                );
1864                if state.clip_polys.is_empty() {
1865                    fb.draw_rect(translated, *color, state.clip);
1866                } else {
1867                    let poly = vec![vec![
1868                        (translated.x, translated.y),
1869                        (translated.max_x(), translated.y),
1870                        (translated.max_x(), translated.max_y()),
1871                        (translated.x, translated.max_y()),
1872                        (translated.x, translated.y),
1873                    ]];
1874                    rasterize_fill_subpaths(fb, &poly, *color, &state);
1875                }
1876            }
1877            CanvasCommand::ClearRect { bounds } => {
1878                let translated = Rect::new(
1879                    bounds.x + origin_x,
1880                    bounds.y + origin_y,
1881                    bounds.width,
1882                    bounds.height,
1883                );
1884                fb.clear_rect(translated, Color::TRANSPARENT);
1885            }
1886            CanvasCommand::StrokeRect {
1887                bounds,
1888                color,
1889                line_width,
1890            } => {
1891                let translated = Rect::new(
1892                    bounds.x + origin_x,
1893                    bounds.y + origin_y,
1894                    bounds.width,
1895                    bounds.height,
1896                );
1897                if state.line_dash.is_empty() && state.clip_polys.is_empty() {
1898                    let lw = *line_width;
1899                    fb.draw_rect(
1900                        Rect::new(translated.x, translated.y, translated.width, lw),
1901                        *color,
1902                        state.clip,
1903                    );
1904                    fb.draw_rect(
1905                        Rect::new(translated.x, translated.max_y() - lw, translated.width, lw),
1906                        *color,
1907                        state.clip,
1908                    );
1909                    fb.draw_rect(
1910                        Rect::new(translated.x, translated.y, lw, translated.height),
1911                        *color,
1912                        state.clip,
1913                    );
1914                    fb.draw_rect(
1915                        Rect::new(translated.max_x() - lw, translated.y, lw, translated.height),
1916                        *color,
1917                        state.clip,
1918                    );
1919                } else {
1920                    let pts = [
1921                        (translated.x, translated.y),
1922                        (translated.max_x(), translated.y),
1923                        (translated.max_x(), translated.max_y()),
1924                        (translated.x, translated.max_y()),
1925                        (translated.x, translated.y),
1926                    ];
1927                    rasterize_polyline(fb, &pts, *color, *line_width, &state);
1928                }
1929            }
1930            CanvasCommand::DrawLine {
1931                p0,
1932                p1,
1933                color,
1934                line_width,
1935            } => {
1936                let pts = [(p0.0 + origin_x, p0.1 + origin_y), (p1.0 + origin_x, p1.1 + origin_y)];
1937                rasterize_polyline(fb, &pts, *color, *line_width, &state);
1938            }
1939            CanvasCommand::DrawCircle {
1940                center,
1941                radius,
1942                fill_color,
1943                stroke_color,
1944                line_width,
1945            } => {
1946                let cx = center.0 + origin_x;
1947                let cy = center.1 + origin_y;
1948                let r = *radius;
1949                let lw = *line_width;
1950
1951                if let Some(fc) = fill_color {
1952                    let min_x = ((cx - r - lw).floor() as isize).max(0) as usize;
1953                    let max_x = ((cx + r + lw).ceil() as usize).min(fb.width);
1954                    let min_y = ((cy - r - lw).floor() as isize).max(0) as usize;
1955                    let max_y = ((cy + r + lw).ceil() as usize).min(fb.height);
1956
1957                    for y in min_y..max_y {
1958                        let py = y as f32 + 0.5;
1959                        let dy = py - cy;
1960                        for x in min_x..max_x {
1961                            let px = x as f32 + 0.5;
1962                            if !point_passes_clip(&state, px, py) {
1963                                continue;
1964                            }
1965                            let dx = px - cx;
1966                            let dist = (dx * dx + dy * dy).sqrt();
1967                            let coverage = (0.5 + r - dist).clamp(0.0, 1.0);
1968                            if coverage > 0.005 {
1969                                fb.set_pixel(
1970                                    x,
1971                                    y,
1972                                    Color::rgba(
1973                                        fc.r,
1974                                        fc.g,
1975                                        fc.b,
1976                                        (fc.a() * coverage * 255.0) as u8,
1977                                    ),
1978                                );
1979                            }
1980                        }
1981                    }
1982                }
1983
1984                if let Some(sc) = stroke_color {
1985                    if !state.line_dash.is_empty() {
1986                        let steps = ((r * std::f32::consts::TAU / 3.0).ceil() as usize).clamp(24, 128);
1987                        let pts: Vec<(f32, f32)> = (0..=steps)
1988                            .map(|i| {
1989                                let a = (i as f32 / steps as f32) * std::f32::consts::TAU;
1990                                (cx + r * a.cos(), cy + r * a.sin())
1991                            })
1992                            .collect();
1993                        rasterize_polyline(fb, &pts, *sc, lw, &state);
1994                    } else {
1995                        let min_x = ((cx - r - lw).floor() as isize).max(0) as usize;
1996                        let max_x = ((cx + r + lw).ceil() as usize).min(fb.width);
1997                        let min_y = ((cy - r - lw).floor() as isize).max(0) as usize;
1998                        let max_y = ((cy + r + lw).ceil() as usize).min(fb.height);
1999                        for y in min_y..max_y {
2000                            let py = y as f32 + 0.5;
2001                            let dy = py - cy;
2002                            for x in min_x..max_x {
2003                                let px = x as f32 + 0.5;
2004                                if !point_passes_clip(&state, px, py) {
2005                                    continue;
2006                                }
2007                                let dx = px - cx;
2008                                let dist = (dx * dx + dy * dy).sqrt();
2009                                let stroke_dist = (dist - r).abs();
2010                                let coverage = (0.5 + lw * 0.5 - stroke_dist).clamp(0.0, 1.0);
2011                                if coverage > 0.005 {
2012                                    fb.set_pixel(
2013                                        x,
2014                                        y,
2015                                        Color::rgba(
2016                                            sc.r,
2017                                            sc.g,
2018                                            sc.b,
2019                                            (sc.a() * coverage * 255.0) as u8,
2020                                        ),
2021                                    );
2022                                }
2023                            }
2024                        }
2025                    }
2026                }
2027            }
2028            CanvasCommand::DrawPath {
2029                verbs,
2030                fill_color,
2031                stroke_color,
2032                line_width,
2033            } => {
2034                let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
2035                if let Some(fc) = fill_color {
2036                    rasterize_fill_subpaths(fb, &subpaths, *fc, &state);
2037                }
2038                if let Some(sc) = stroke_color {
2039                    for sub in &subpaths {
2040                        rasterize_polyline(fb, sub, *sc, *line_width, &state);
2041                    }
2042                }
2043            }
2044            CanvasCommand::FillText {
2045                text,
2046                x,
2047                y,
2048                color,
2049                font_size,
2050                font_family,
2051                font_weight,
2052                italic,
2053                text_align,
2054                text_baseline,
2055                max_width,
2056                ..
2057            }
2058            | CanvasCommand::StrokeText {
2059                text,
2060                x,
2061                y,
2062                color,
2063                font_size,
2064                font_family,
2065                font_weight,
2066                italic,
2067                text_align,
2068                text_baseline,
2069                max_width,
2070                ..
2071            } => {
2072                let metrics = measure_canvas_text_metrics(
2073                    text,
2074                    *font_size,
2075                    font_family,
2076                    *font_weight,
2077                    *italic,
2078                );
2079                let measured_w = if let Some(mw) = *max_width {
2080                    metrics.width.min(mw.max(0.0))
2081                } else {
2082                    metrics.width
2083                };
2084                let est_h = metrics.height.max(*font_size);
2085                let tx = origin_x
2086                    + match text_align {
2087                        CanvasTextAlign::Left | CanvasTextAlign::Start => *x,
2088                        CanvasTextAlign::Center => *x - measured_w * 0.5,
2089                        CanvasTextAlign::Right | CanvasTextAlign::End => *x - measured_w,
2090                    };
2091                let ty = origin_y
2092                    + match text_baseline {
2093                        CanvasTextBaseline::Top | CanvasTextBaseline::Hanging => *y,
2094                        CanvasTextBaseline::Middle => *y - est_h * 0.5,
2095                        CanvasTextBaseline::Bottom | CanvasTextBaseline::Ideographic => *y - est_h,
2096                        CanvasTextBaseline::Alphabetic => *y - metrics.font_bounding_box_ascent,
2097                    };
2098                fb.draw_text((tx, ty), text, *font_size, *color, state.clip);
2099            }
2100        }
2101    }
2102}
2103
2104#[cfg(test)]
2105mod tests {
2106    use super::*;
2107
2108    #[test]
2109    fn test_transform2d_operations() {
2110        let mut t = Transform2D::IDENTITY;
2111        t.translate(100.0, 50.0);
2112        let p = t.transform_xy(10.0, 20.0);
2113        assert_eq!(p, (110.0, 70.0));
2114
2115        let mut s = Transform2D::IDENTITY;
2116        s.scale_mut(2.0, 3.0);
2117        let p2 = s.transform_xy(10.0, 10.0);
2118        assert_eq!(p2, (20.0, 30.0));
2119    }
2120
2121    #[test]
2122    fn test_canvas_context_recording() {
2123        let mut ctx = Canvas2DContext::new(400.0, 300.0);
2124
2125        ctx.set_fill_style(Color::rgb(255, 0, 0));
2126        ctx.fill_rect(10.0, 10.0, 80.0, 50.0);
2127
2128        ctx.set_stroke_style(Color::rgb(0, 0, 255));
2129        ctx.set_line_width(2.0);
2130        ctx.begin_path();
2131        ctx.move_to(0.0, 0.0);
2132        ctx.line_to(100.0, 100.0);
2133        ctx.stroke();
2134
2135        assert_eq!(ctx.commands().len(), 2);
2136    }
2137
2138    #[test]
2139    fn test_canvas_rasterize_to_framebuffer() {
2140        let mut fb = FrameBuffer::new(200, 200);
2141        let mut ctx = Canvas2DContext::new(200.0, 200.0);
2142
2143        ctx.set_fill_style(Color::rgb(0, 255, 0));
2144        ctx.fill_rect(20.0, 20.0, 40.0, 40.0);
2145
2146        ctx.rasterize(&mut fb, 0.0, 0.0, None);
2147
2148        // Center of rect (40, 40) must be green
2149        let pixel = fb.get_pixel(40, 40);
2150        assert_eq!(pixel, Color::rgb(0, 255, 0));
2151
2152        // Outside rect (5, 5) must be transparent
2153        assert_eq!(fb.get_pixel(5, 5), Color::TRANSPARENT);
2154    }
2155
2156    #[test]
2157    fn test_canvas_bezier_dash_clip_and_text() {
2158        let (size, family, weight, italic) =
2159            parse_canvas_font("italic bold 14px/1.2 'JetBrains Mono', monospace");
2160        assert!((size - 14.0).abs() < 0.01);
2161        assert_eq!(family, "JetBrains Mono, monospace");
2162        assert_eq!(weight, 700);
2163        assert!(italic);
2164
2165        // Dashed horizontal line leaves transparent gaps
2166        let mut fb = FrameBuffer::new(200, 100);
2167        let mut ctx = Canvas2DContext::new(200.0, 100.0);
2168        ctx.set_stroke_style(Color::rgb(255, 0, 0));
2169        ctx.set_line_width(2.0);
2170        ctx.set_line_dash(&[10.0, 10.0]);
2171        ctx.begin_path();
2172        ctx.move_to(0.0, 20.0);
2173        ctx.line_to(100.0, 20.0);
2174        ctx.stroke();
2175        ctx.rasterize(&mut fb, 0.0, 0.0, None);
2176        assert!(fb.get_pixel(5, 20).r > 200, "dash on-segment must be drawn");
2177        assert_eq!(fb.get_pixel(15, 20), Color::TRANSPARENT, "dash gap must stay empty");
2178
2179        // Clip restricts fill_rect, and restore removes clip
2180        let mut fb_clip = FrameBuffer::new(100, 100);
2181        let mut c2 = Canvas2DContext::new(100.0, 100.0);
2182        c2.save();
2183        c2.begin_path();
2184        c2.rect(10.0, 10.0, 30.0, 30.0);
2185        c2.clip();
2186        c2.set_fill_style(Color::rgb(0, 200, 255));
2187        c2.fill_rect(0.0, 0.0, 100.0, 100.0);
2188        c2.restore();
2189        c2.set_fill_style(Color::rgb(255, 255, 0));
2190        c2.fill_rect(60.0, 60.0, 20.0, 20.0);
2191        c2.rasterize(&mut fb_clip, 0.0, 0.0, None);
2192        assert_eq!(fb_clip.get_pixel(25, 25), Color::rgb(0, 200, 255));
2193        assert_eq!(fb_clip.get_pixel(5, 5), Color::TRANSPARENT);
2194        assert_eq!(fb_clip.get_pixel(70, 70), Color::rgb(255, 255, 0));
2195
2196        // Cubic & quadratic bezier + fill_text + stroke_text
2197        let mut fb_curve = FrameBuffer::new(160, 120);
2198        let mut c3 = Canvas2DContext::new(160.0, 120.0);
2199        c3.set_stroke_style(Color::rgb(50, 255, 50));
2200        c3.set_line_width(2.0);
2201        c3.begin_path();
2202        c3.move_to(10.0, 60.0);
2203        c3.quadratic_curve_to(50.0, 10.0, 90.0, 60.0);
2204        c3.bezier_curve_to(110.0, 90.0, 130.0, 90.0, 150.0, 60.0);
2205        c3.stroke();
2206        c3.set_font("bold 12px monospace");
2207        c3.set_text_align(CanvasTextAlign::Left);
2208        c3.set_text_baseline(CanvasTextBaseline::Top);
2209        c3.set_fill_style(Color::rgb(255, 255, 255));
2210        c3.fill_text("CLK_0", 10.0, 5.0);
2211        c3.stroke_text("OUT", 80.0, 5.0);
2212        c3.rasterize(&mut fb_curve, 0.0, 0.0, None);
2213
2214        // Quadratic curve midpoint at t=0.5 is (50, 35)
2215        assert!(
2216            fb_curve.get_pixel(50, 35).g > 150,
2217            "quadratic curve midpoint should be lit"
2218        );
2219        // Text region (10..60, 5..20) should have non-transparent white pixels
2220        let mut lit_text = 0usize;
2221        for y in 5..22 {
2222            for x in 10..60 {
2223                if fb_curve.get_pixel(x, y).a > 0 {
2224                    lit_text += 1;
2225                }
2226            }
2227        }
2228        assert!(lit_text > 5, "fill_text should rasterize visible glyph pixels");
2229    }
2230
2231    #[test]
2232    fn test_canvas_measure_text_metrics() {
2233        let mut ctx = Canvas2DContext::new(400.0, 200.0);
2234        ctx.set_font("12px monospace");
2235        let empty = ctx.measure_text("");
2236        assert_eq!(empty.width, 0.0);
2237        assert!(empty.height > 0.0);
2238
2239        let short = ctx.measure_text("VREF");
2240        let long = ctx.measure_text("VREF_BUFFERED_OUT");
2241        assert!(short.width > 0.0);
2242        assert!(long.width > short.width * 2.0);
2243        assert!(short.font_bounding_box_ascent > 0.0);
2244        assert!(short.font_bounding_box_descent > 0.0);
2245
2246        ctx.set_font("24px sans-serif");
2247        let bigger = ctx.measure_text("VREF");
2248        assert!(bigger.width > short.width * 1.4);
2249        assert!(bigger.height > short.height * 1.4);
2250    }
2251
2252    #[test]
2253    fn test_canvas_round_rect_and_clip() {
2254        let mut fb = FrameBuffer::new(120, 80);
2255        let mut ctx = Canvas2DContext::new(120.0, 80.0);
2256
2257        // Huge radius on a 40x20 box clamps to 10px capsule corners cleanly
2258        ctx.set_fill_style(Color::rgb(20, 180, 240));
2259        ctx.begin_path();
2260        ctx.round_rect(10.0, 10.0, 40.0, 20.0, 100.0);
2261        ctx.fill();
2262
2263        // Asymmetric radii: sharp TL (0), rounded TR (8), sharp BR (0), rounded BL (8)
2264        ctx.save();
2265        ctx.begin_path();
2266        ctx.round_rect(60.0, 10.0, 40.0, 30.0, [0.0, 8.0, 0.0, 8.0]);
2267        ctx.clip();
2268        ctx.set_fill_style(Color::rgb(255, 160, 0));
2269        ctx.fill_rect(60.0, 10.0, 40.0, 30.0);
2270        ctx.restore();
2271
2272        ctx.rasterize(&mut fb, 0.0, 0.0, None);
2273
2274        // Center of capsule is filled
2275        assert_eq!(fb.get_pixel(30, 20), Color::rgb(20, 180, 240));
2276        // Outer corner (10, 10) of capsule is cut away
2277        assert_eq!(fb.get_pixel(10, 10), Color::TRANSPARENT);
2278
2279        // Clipped asymmetric rect: sharp TL (60, 10) is filled, rounded TR (99, 10) is clipped
2280        assert_eq!(fb.get_pixel(60, 10), Color::rgb(255, 160, 0));
2281        assert_eq!(fb.get_pixel(99, 10), Color::TRANSPARENT);
2282        assert_eq!(fb.get_pixel(99, 39), Color::rgb(255, 160, 0));
2283        assert_eq!(fb.get_pixel(60, 39), Color::TRANSPARENT);
2284    }
2285
2286    #[test]
2287    fn test_canvas_line_cap_and_line_join_and_save_restore() {
2288        let mut ctx = Canvas2DContext::new(120.0, 120.0);
2289        assert_eq!(ctx.line_cap(), CanvasLineCap::Butt);
2290        assert_eq!(ctx.line_join(), CanvasLineJoin::Miter);
2291
2292        ctx.save();
2293        ctx.set_line_cap(CanvasLineCap::Square);
2294        ctx.set_line_join(CanvasLineJoin::Bevel);
2295        assert_eq!(ctx.line_cap(), CanvasLineCap::Square);
2296        assert_eq!(ctx.line_join(), CanvasLineJoin::Bevel);
2297        ctx.restore();
2298        assert_eq!(ctx.line_cap(), CanvasLineCap::Butt);
2299        assert_eq!(ctx.line_join(), CanvasLineJoin::Miter);
2300
2301        // Caps test: horizontal line (20, 30) -> (60, 30), lw = 10 (half_lw = 5)
2302        let draw_cap = |cap: CanvasLineCap| {
2303            let mut fb = FrameBuffer::new(90, 60);
2304            let mut c = Canvas2DContext::new(90.0, 60.0);
2305            c.set_stroke_style(Color::rgb(255, 0, 0));
2306            c.set_line_width(10.0);
2307            c.set_line_cap(cap);
2308            c.begin_path();
2309            c.move_to(20.0, 30.0);
2310            c.line_to(60.0, 30.0);
2311            c.stroke();
2312            c.rasterize(&mut fb, 0.0, 0.0, None);
2313            fb
2314        };
2315
2316        let fb_butt = draw_cap(CanvasLineCap::Butt);
2317        let fb_round = draw_cap(CanvasLineCap::Round);
2318        let fb_square = draw_cap(CanvasLineCap::Square);
2319
2320        // Butt stops at x=20
2321        assert_eq!(fb_butt.get_pixel(18, 30), Color::TRANSPARENT);
2322        // Round extends along axis to x=17, but NOT out to corner (15, 26) (dist=5.70 > 5)
2323        assert!(fb_round.get_pixel(17, 30).a > 200);
2324        assert_eq!(fb_round.get_pixel(15, 26), Color::TRANSPARENT);
2325        // Square extends to corner (15, 26) (|-4.5| <= 5, |-3.5| <= 5)
2326        assert!(fb_square.get_pixel(15, 26).a > 200);
2327
2328        // Joins test: 90-degree corner at (50, 30) with lw = 10 (half_lw = 5)
2329        let draw_join = |join: CanvasLineJoin| {
2330            let mut fb = FrameBuffer::new(90, 90);
2331            let mut c = Canvas2DContext::new(90.0, 90.0);
2332            c.set_stroke_style(Color::rgb(0, 255, 0));
2333            c.set_line_width(10.0);
2334            c.set_line_join(join);
2335            c.begin_path();
2336            c.move_to(10.0, 30.0);
2337            c.line_to(50.0, 30.0);
2338            c.line_to(50.0, 70.0);
2339            c.stroke();
2340            c.rasterize(&mut fb, 0.0, 0.0, None);
2341            fb
2342        };
2343
2344        let fb_miter = draw_join(CanvasLineJoin::Miter);
2345        let fb_round_j = draw_join(CanvasLineJoin::Round);
2346        let fb_bevel = draw_join(CanvasLineJoin::Bevel);
2347
2348        // Miter reaches outer corner (54, 26), while Round & Bevel do not
2349        assert!(fb_miter.get_pixel(54, 26).a > 200);
2350        assert_eq!(fb_round_j.get_pixel(54, 26), Color::TRANSPARENT);
2351        assert_eq!(fb_bevel.get_pixel(54, 26), Color::TRANSPARENT);
2352
2353        // Round fills (53, 27) (dist ~4.24 < 5), whereas Bevel chord misses it
2354        assert!(fb_round_j.get_pixel(53, 27).a > 200);
2355        assert_eq!(fb_bevel.get_pixel(53, 27), Color::TRANSPARENT);
2356        // Inside bevel triangle (51, 29) is lit
2357        assert!(fb_bevel.get_pixel(51, 29).a > 200);
2358    }
2359}