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/// Flattens a slice of [`CanvasPathVerb`]s (including cubic/quadratic Bézier curves and arcs)
907/// into translated polyline subpaths `Vec<Vec<(f32, f32)>>`.
908pub fn flatten_canvas_verbs(
909    verbs: &[CanvasPathVerb],
910    origin_x: f32,
911    origin_y: f32,
912) -> Vec<Vec<(f32, f32)>> {
913    let mut subpaths: Vec<Vec<(f32, f32)>> = Vec::new();
914    let mut cur_sub: Vec<(f32, f32)> = Vec::new();
915    let mut current = (origin_x, origin_y);
916    let mut start = (origin_x, origin_y);
917
918    for verb in verbs {
919        match *verb {
920            CanvasPathVerb::MoveTo(x, y) => {
921                if cur_sub.len() >= 2 {
922                    subpaths.push(std::mem::take(&mut cur_sub));
923                } else {
924                    cur_sub.clear();
925                }
926                current = (x + origin_x, y + origin_y);
927                start = current;
928                cur_sub.push(current);
929            }
930            CanvasPathVerb::LineTo(x, y) => {
931                let next = (x + origin_x, y + origin_y);
932                if cur_sub.is_empty() {
933                    cur_sub.push(current);
934                }
935                cur_sub.push(next);
936                current = next;
937            }
938            CanvasPathVerb::QuadraticCurveTo { cpx, cpy, x, y } => {
939                let p0 = current;
940                let p1 = (cpx + origin_x, cpy + origin_y);
941                let p2 = (x + origin_x, y + origin_y);
942                if cur_sub.is_empty() {
943                    cur_sub.push(p0);
944                }
945                let approx_len = ((p1.0 - p0.0).hypot(p1.1 - p0.1)
946                    + (p2.0 - p1.0).hypot(p2.1 - p1.1))
947                .max(1.0);
948                let steps = ((approx_len / 4.0).ceil() as usize).clamp(12, 64);
949                for i in 1..=steps {
950                    let t = i as f32 / steps as f32;
951                    let mt = 1.0 - t;
952                    let px = mt * mt * p0.0 + 2.0 * mt * t * p1.0 + t * t * p2.0;
953                    let py = mt * mt * p0.1 + 2.0 * mt * t * p1.1 + t * t * p2.1;
954                    cur_sub.push((px, py));
955                }
956                current = p2;
957            }
958            CanvasPathVerb::BezierCurveTo {
959                cp1x,
960                cp1y,
961                cp2x,
962                cp2y,
963                x,
964                y,
965            } => {
966                let p0 = current;
967                let p1 = (cp1x + origin_x, cp1y + origin_y);
968                let p2 = (cp2x + origin_x, cp2y + origin_y);
969                let p3 = (x + origin_x, y + origin_y);
970                if cur_sub.is_empty() {
971                    cur_sub.push(p0);
972                }
973                let approx_len = ((p1.0 - p0.0).hypot(p1.1 - p0.1)
974                    + (p2.0 - p1.0).hypot(p2.1 - p1.1)
975                    + (p3.0 - p2.0).hypot(p3.1 - p2.1))
976                .max(1.0);
977                let steps = ((approx_len / 4.0).ceil() as usize).clamp(16, 80);
978                for i in 1..=steps {
979                    let t = i as f32 / steps as f32;
980                    let mt = 1.0 - t;
981                    let mt2 = mt * mt;
982                    let t2 = t * t;
983                    let px = mt2 * mt * p0.0
984                        + 3.0 * mt2 * t * p1.0
985                        + 3.0 * mt * t2 * p2.0
986                        + t2 * t * p3.0;
987                    let py = mt2 * mt * p0.1
988                        + 3.0 * mt2 * t * p1.1
989                        + 3.0 * mt * t2 * p2.1
990                        + t2 * t * p3.1;
991                    cur_sub.push((px, py));
992                }
993                current = p3;
994            }
995            CanvasPathVerb::Arc {
996                cx,
997                cy,
998                radius,
999                start_angle,
1000                end_angle,
1001                counter_clockwise,
1002            } => {
1003                let acx = cx + origin_x;
1004                let acy = cy + origin_y;
1005                let mut sweep = end_angle - start_angle;
1006                if counter_clockwise {
1007                    if sweep >= 0.0 {
1008                        sweep -= std::f32::consts::TAU;
1009                    }
1010                } else if sweep <= 0.0 && (end_angle - start_angle).abs() > 1e-5 {
1011                    sweep += std::f32::consts::TAU;
1012                }
1013                let steps = ((radius.abs() * sweep.abs() / 3.0).ceil() as usize).clamp(16, 96);
1014                for i in 0..=steps {
1015                    let a = start_angle + sweep * (i as f32 / steps as f32);
1016                    let pt = (acx + radius * a.cos(), acy + radius * a.sin());
1017                    if i == 0 && cur_sub.is_empty() {
1018                        start = pt;
1019                    }
1020                    cur_sub.push(pt);
1021                    current = pt;
1022                }
1023            }
1024            CanvasPathVerb::Close => {
1025                if !cur_sub.is_empty() && current != start {
1026                    cur_sub.push(start);
1027                    current = start;
1028                }
1029                if cur_sub.len() >= 2 {
1030                    subpaths.push(std::mem::take(&mut cur_sub));
1031                } else {
1032                    cur_sub.clear();
1033                }
1034            }
1035        }
1036    }
1037
1038    if cur_sub.len() >= 2 {
1039        subpaths.push(cur_sub);
1040    }
1041    subpaths
1042}
1043
1044/// Computes the axis-aligned bounding box of `verbs` shifted by `(origin_x, origin_y)`.
1045pub fn canvas_verbs_bounds(verbs: &[CanvasPathVerb], origin_x: f32, origin_y: f32) -> Option<Rect> {
1046    let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
1047    let mut min_x = f32::INFINITY;
1048    let mut min_y = f32::INFINITY;
1049    let mut max_x = f32::NEG_INFINITY;
1050    let mut max_y = f32::NEG_INFINITY;
1051    for sub in &subpaths {
1052        for &(x, y) in sub {
1053            min_x = min_x.min(x);
1054            min_y = min_y.min(y);
1055            max_x = max_x.max(x);
1056            max_y = max_y.max(y);
1057        }
1058    }
1059    if min_x.is_finite() && min_y.is_finite() && max_x >= min_x && max_y >= min_y {
1060        Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
1061    } else {
1062        None
1063    }
1064}
1065
1066/// Measures `text` using the active font styling and registered platform text measurer,
1067/// falling back to the inline headless OpenType/glyph estimator when no platform backend is registered.
1068pub fn measure_canvas_text_metrics(
1069    text: &str,
1070    font_size: f32,
1071    font_family: &str,
1072    font_weight: u16,
1073    italic: bool,
1074) -> CanvasTextMetrics {
1075    let size = font_size.max(0.0);
1076    if size <= 0.0 {
1077        return CanvasTextMetrics::default();
1078    }
1079    let primary_family = font_family
1080        .split(',')
1081        .next()
1082        .map(str::trim)
1083        .map(|s| s.trim_matches(|c| c == '\'' || c == '"'))
1084        .filter(|s| !s.is_empty())
1085        .unwrap_or("sans-serif");
1086    let family_atom = strata_primitives::atom::intern(primary_family);
1087    let mono = strata_layout::text::is_monospace_family(family_atom)
1088        || font_family.to_ascii_lowercase().contains("mono");
1089    let weight = strata_style::types::FontWeight::from_u16(font_weight);
1090    let style = if italic {
1091        strata_style::types::FontStyle::Italic
1092    } else {
1093        strata_style::types::FontStyle::Normal
1094    };
1095    let (width, height) = if text.is_empty() {
1096        let h = strata_layout::text::measure_text_bounds_styled_with_family(
1097            " ",
1098            size,
1099            1.0,
1100            None,
1101            mono,
1102            family_atom,
1103            weight,
1104            style,
1105        )
1106        .1;
1107        (0.0, h)
1108    } else {
1109        strata_layout::text::measure_text_bounds_styled_with_family(
1110            text,
1111            size,
1112            1.0,
1113            None,
1114            mono,
1115            family_atom,
1116            weight,
1117            style,
1118        )
1119    };
1120    let (font_ascent, font_descent) = if let Some(metrics_fn) = strata_layout::text::get_font_metrics() {
1121        let (asc, desc, _gap) = metrics_fn(family_atom, size, font_weight >= 600);
1122        (asc.max(0.0), desc.max(0.0))
1123    } else {
1124        (size * 0.8, size * 0.2)
1125    };
1126    CanvasTextMetrics {
1127        width,
1128        height: height.max(font_ascent + font_descent),
1129        actual_bounding_box_ascent: font_ascent,
1130        actual_bounding_box_descent: font_descent,
1131        font_bounding_box_ascent: font_ascent,
1132        font_bounding_box_descent: font_descent,
1133    }
1134}
1135
1136#[derive(Clone)]
1137struct RasterState {
1138    clip: Option<Rect>,
1139    clip_polys: Vec<Vec<Vec<(f32, f32)>>>,
1140    line_dash: Vec<f32>,
1141    dash_offset: f32,
1142    line_cap: CanvasLineCap,
1143    line_join: CanvasLineJoin,
1144}
1145
1146pub fn point_in_subpaths_even_odd(subpaths: &[Vec<(f32, f32)>], px: f32, py: f32) -> bool {
1147    let mut inside = false;
1148    for sub in subpaths {
1149        if sub.len() < 3 {
1150            continue;
1151        }
1152        let mut j = sub.len() - 1;
1153        for i in 0..sub.len() {
1154            let (xi, yi) = sub[i];
1155            let (xj, yj) = sub[j];
1156            let intersects =
1157                ((yi > py) != (yj > py)) && (px < (xj - xi) * (py - yi) / (yj - yi) + xi);
1158            if intersects {
1159                inside = !inside;
1160            }
1161            j = i;
1162        }
1163    }
1164    inside
1165}
1166
1167fn point_passes_clip(state: &RasterState, x: f32, y: f32) -> bool {
1168    if let Some(c) = state.clip {
1169        if x < c.x || x >= c.max_x() || y < c.y || y >= c.max_y() {
1170            return false;
1171        }
1172    }
1173    for poly in &state.clip_polys {
1174        if !point_in_subpaths_even_odd(poly, x, y) {
1175            return false;
1176        }
1177    }
1178    true
1179}
1180
1181fn rasterize_fill_subpaths(
1182    fb: &mut FrameBuffer,
1183    subpaths: &[Vec<(f32, f32)>],
1184    color: Color,
1185    state: &RasterState,
1186) {
1187    let mut min_x = f32::INFINITY;
1188    let mut min_y = f32::INFINITY;
1189    let mut max_x = f32::NEG_INFINITY;
1190    let mut max_y = f32::NEG_INFINITY;
1191    for sub in subpaths {
1192        for &(x, y) in sub {
1193            min_x = min_x.min(x);
1194            min_y = min_y.min(y);
1195            max_x = max_x.max(x);
1196            max_y = max_y.max(y);
1197        }
1198    }
1199    if !min_x.is_finite() || max_x <= min_x || max_y <= min_y {
1200        return;
1201    }
1202
1203    let x0 = (min_x.floor() as isize).max(0) as usize;
1204    let x1 = (max_x.ceil() as usize).min(fb.width);
1205    let y0 = (min_y.floor() as isize).max(0) as usize;
1206    let y1 = (max_y.ceil() as usize).min(fb.height);
1207
1208    for y in y0..y1 {
1209        let py = y as f32 + 0.5;
1210        for x in x0..x1 {
1211            let px = x as f32 + 0.5;
1212            if !point_passes_clip(state, px, py) {
1213                continue;
1214            }
1215            if point_in_subpaths_even_odd(subpaths, px, py) {
1216                fb.set_pixel(x, y, color);
1217            }
1218        }
1219    }
1220}
1221
1222#[derive(Clone, Copy)]
1223struct StrokeSeg {
1224    x0: f32,
1225    y0: f32,
1226    x1: f32,
1227    y1: f32,
1228    tx: f32,
1229    ty: f32,
1230    nx: f32,
1231    ny: f32,
1232    len: f32,
1233    cap0: CanvasLineCap,
1234    cap1: CanvasLineCap,
1235}
1236
1237impl StrokeSeg {
1238    fn from_pts(p0: (f32, f32), p1: (f32, f32), cap0: CanvasLineCap, cap1: CanvasLineCap) -> Self {
1239        let vx = p1.0 - p0.0;
1240        let vy = p1.1 - p0.1;
1241        let len = vx.hypot(vy);
1242        let (tx, ty) = if len > 1e-6 {
1243            (vx / len, vy / len)
1244        } else {
1245            (1.0, 0.0)
1246        };
1247        Self {
1248            x0: p0.0,
1249            y0: p0.1,
1250            x1: p1.0,
1251            y1: p1.1,
1252            tx,
1253            ty,
1254            nx: -ty,
1255            ny: tx,
1256            len,
1257            cap0,
1258            cap1,
1259        }
1260    }
1261
1262    #[inline]
1263    fn signed_dist(&self, px: f32, py: f32, half_lw: f32) -> f32 {
1264        let wx = px - self.x0;
1265        let wy = py - self.y0;
1266        if self.len <= 1e-6 {
1267            return if self.cap0 == CanvasLineCap::Round || self.cap1 == CanvasLineCap::Round {
1268                wx.hypot(wy) - half_lw
1269            } else if self.cap0 == CanvasLineCap::Square || self.cap1 == CanvasLineCap::Square {
1270                let dx = wx.abs() - half_lw;
1271                let dy = wy.abs() - half_lw;
1272                dx.max(0.0).hypot(dy.max(0.0)) + dx.max(dy).min(0.0)
1273            } else {
1274                f32::INFINITY
1275            };
1276        }
1277
1278        let s = wx * self.tx + wy * self.ty;
1279        let u = (wx * self.nx + wy * self.ny).abs();
1280        let s0 = if self.cap0 == CanvasLineCap::Square {
1281            -half_lw
1282        } else {
1283            0.0
1284        };
1285        let s1 = if self.cap1 == CanvasLineCap::Square {
1286            self.len + half_lw
1287        } else {
1288            self.len
1289        };
1290        let dx = (s0 - s).max(s - s1);
1291        let dy = u - half_lw;
1292        let mut sd = dx.max(0.0).hypot(dy.max(0.0)) + dx.max(dy).min(0.0);
1293        if self.cap0 == CanvasLineCap::Round {
1294            sd = sd.min(s.hypot(u) - half_lw);
1295        }
1296        if self.cap1 == CanvasLineCap::Round {
1297            sd = sd.min((s - self.len).hypot(u) - half_lw);
1298        }
1299        sd
1300    }
1301
1302    #[inline]
1303    fn bounds_px(&self, half_lw: f32, fb_w: usize, fb_h: usize) -> (usize, usize, usize, usize) {
1304        let pad = half_lw * 1.5 + 2.0;
1305        let x0 = ((self.x0.min(self.x1) - pad).floor() as isize).max(0) as usize;
1306        let x1 = ((self.x0.max(self.x1) + pad).ceil() as usize).min(fb_w);
1307        let y0 = ((self.y0.min(self.y1) - pad).floor() as isize).max(0) as usize;
1308        let y1 = ((self.y0.max(self.y1) + pad).ceil() as usize).min(fb_h);
1309        (x0, y0, x1, y1)
1310    }
1311}
1312
1313#[derive(Clone, Copy)]
1314struct StrokeJoin {
1315    jx: f32,
1316    jy: f32,
1317    t0x: f32,
1318    t0y: f32,
1319    t1x: f32,
1320    t1y: f32,
1321}
1322
1323impl StrokeJoin {
1324    #[inline]
1325    fn signed_dist(&self, px: f32, py: f32, half_lw: f32, join: CanvasLineJoin) -> f32 {
1326        let dpx = px - self.jx;
1327        let dpy = py - self.jy;
1328        let dot_t = self.t0x * self.t1x + self.t0y * self.t1y;
1329        if dot_t > 0.9999 {
1330            return f32::INFINITY;
1331        }
1332        let cross = self.t0x * self.t1y - self.t0y * self.t1x;
1333        let sd_disk = dpx.hypot(dpy) - half_lw;
1334        if cross.abs() < 1e-4 && dot_t < 0.0 {
1335            return if join == CanvasLineJoin::Round {
1336                sd_disk
1337            } else {
1338                f32::INFINITY
1339            };
1340        }
1341        if join == CanvasLineJoin::Round {
1342            return sd_disk;
1343        }
1344
1345        let sign = if cross > 0.0 { -1.0 } else { 1.0 };
1346        let n0x = sign * (-self.t0y);
1347        let n0y = sign * self.t0x;
1348        let n1x = sign * (-self.t1y);
1349        let n1y = sign * self.t1x;
1350
1351        let sum_x = n0x + n1x;
1352        let sum_y = n0y + n1y;
1353        let sum_len = sum_x.hypot(sum_y);
1354        if sum_len <= 1e-5 {
1355            return f32::INFINITY;
1356        }
1357        let bis_x = sum_x / sum_len;
1358        let bis_y = sum_y / sum_len;
1359
1360        let miter_ratio = 2.0 / sum_len;
1361        let use_bevel = join == CanvasLineJoin::Bevel || miter_ratio > 10.0;
1362        if use_bevel {
1363            let d_bevel = half_lw * sum_len * 0.5;
1364            let sd_bevel = dpx * bis_x + dpy * bis_y - d_bevel;
1365            sd_disk.max(sd_bevel)
1366        } else {
1367            let sd0 = dpx * n0x + dpy * n0y - half_lw;
1368            let sd1 = dpx * n1x + dpy * n1y - half_lw;
1369            let sd_back0 = -(dpx * self.t0x + dpy * self.t0y);
1370            let sd_back1 = dpx * self.t1x + dpy * self.t1y;
1371            let sd_wedge = sd0.max(sd1).max(sd_back0).max(sd_back1);
1372            sd_disk.min(sd_wedge)
1373        }
1374    }
1375
1376    #[inline]
1377    fn bounds_px(
1378        &self,
1379        half_lw: f32,
1380        join: CanvasLineJoin,
1381        fb_w: usize,
1382        fb_h: usize,
1383    ) -> (usize, usize, usize, usize) {
1384        let pad = match join {
1385            CanvasLineJoin::Miter => half_lw * 10.0 + 2.0,
1386            CanvasLineJoin::Round | CanvasLineJoin::Bevel => half_lw + 2.0,
1387        };
1388        let x0 = ((self.jx - pad).floor() as isize).max(0) as usize;
1389        let x1 = ((self.jx + pad).ceil() as usize).min(fb_w);
1390        let y0 = ((self.jy - pad).floor() as isize).max(0) as usize;
1391        let y1 = ((self.jy + pad).ceil() as usize).min(fb_h);
1392        (x0, y0, x1, y1)
1393    }
1394}
1395
1396fn rasterize_stroke_run(
1397    fb: &mut FrameBuffer,
1398    pts: &[(f32, f32)],
1399    closed: bool,
1400    color: Color,
1401    line_width: f32,
1402    state: &RasterState,
1403) {
1404    if pts.len() < 2 {
1405        return;
1406    }
1407
1408    let mut clean: Vec<(f32, f32)> = Vec::with_capacity(pts.len());
1409    for &p in pts {
1410        if clean
1411            .last()
1412            .is_none_or(|&prev| (p.0 - prev.0).hypot(p.1 - prev.1) > 1e-4)
1413        {
1414            clean.push(p);
1415        }
1416    }
1417    if closed && clean.len() >= 2 {
1418        let first = clean[0];
1419        let last = *clean.last().unwrap();
1420        if (first.0 - last.0).hypot(first.1 - last.1) > 1e-4 {
1421            clean.push(first);
1422        }
1423    }
1424    if clean.len() < 2 {
1425        let seg = StrokeSeg::from_pts(pts[0], pts[0], state.line_cap, state.line_cap);
1426        rasterize_stroke_primitives(fb, &[seg], &[], color, line_width, state);
1427        return;
1428    }
1429
1430    let seg_count = clean.len() - 1;
1431    let is_loop = closed && seg_count >= 2;
1432    let mut segs = Vec::with_capacity(seg_count);
1433    for (i, w) in clean.windows(2).enumerate() {
1434        let cap0 = if i == 0 && !is_loop {
1435            state.line_cap
1436        } else {
1437            CanvasLineCap::Butt
1438        };
1439        let cap1 = if i + 1 == seg_count && !is_loop {
1440            state.line_cap
1441        } else {
1442            CanvasLineCap::Butt
1443        };
1444        segs.push(StrokeSeg::from_pts(w[0], w[1], cap0, cap1));
1445    }
1446
1447    let mut joins = Vec::with_capacity(if is_loop { seg_count } else { seg_count - 1 });
1448    for i in 1..seg_count {
1449        joins.push(StrokeJoin {
1450            jx: segs[i].x0,
1451            jy: segs[i].y0,
1452            t0x: segs[i - 1].tx,
1453            t0y: segs[i - 1].ty,
1454            t1x: segs[i].tx,
1455            t1y: segs[i].ty,
1456        });
1457    }
1458    if is_loop {
1459        let last = segs[seg_count - 1];
1460        joins.push(StrokeJoin {
1461            jx: segs[0].x0,
1462            jy: segs[0].y0,
1463            t0x: last.tx,
1464            t0y: last.ty,
1465            t1x: segs[0].tx,
1466            t1y: segs[0].ty,
1467        });
1468    }
1469
1470    rasterize_stroke_primitives(fb, &segs, &joins, color, line_width, state);
1471}
1472
1473fn rasterize_stroke_primitives(
1474    fb: &mut FrameBuffer,
1475    segs: &[StrokeSeg],
1476    joins: &[StrokeJoin],
1477    color: Color,
1478    line_width: f32,
1479    state: &RasterState,
1480) {
1481    if segs.is_empty() || color.a == 0 {
1482        return;
1483    }
1484    let half_lw = line_width * 0.5;
1485
1486    if segs.len() == 1 && joins.is_empty() {
1487        let seg = segs[0];
1488        let (x0, y0, x1, y1) = seg.bounds_px(half_lw, fb.width, fb.height);
1489        for y in y0..y1 {
1490            let py = y as f32 + 0.5;
1491            if let Some(c) = state.clip {
1492                if py < c.y || py >= c.max_y() {
1493                    continue;
1494                }
1495            }
1496            for x in x0..x1 {
1497                let px = x as f32 + 0.5;
1498                if !point_passes_clip(state, px, py) {
1499                    continue;
1500                }
1501                let sd = seg.signed_dist(px, py, half_lw);
1502                let cov = (0.5 - sd).clamp(0.0, 1.0);
1503                if cov > 0.005 {
1504                    fb.set_pixel(
1505                        x,
1506                        y,
1507                        Color::rgba(
1508                            color.r,
1509                            color.g,
1510                            color.b,
1511                            (color.a() * cov * 255.0).round() as u8,
1512                        ),
1513                    );
1514                }
1515            }
1516        }
1517        return;
1518    }
1519
1520    let mut min_x = usize::MAX;
1521    let mut min_y = usize::MAX;
1522    let mut max_x = 0usize;
1523    let mut max_y = 0usize;
1524    let seg_boxes: Vec<(usize, usize, usize, usize)> = segs
1525        .iter()
1526        .map(|s| {
1527            let b = s.bounds_px(half_lw, fb.width, fb.height);
1528            min_x = min_x.min(b.0);
1529            min_y = min_y.min(b.1);
1530            max_x = max_x.max(b.2);
1531            max_y = max_y.max(b.3);
1532            b
1533        })
1534        .collect();
1535    let join_boxes: Vec<(usize, usize, usize, usize)> = joins
1536        .iter()
1537        .map(|j| {
1538            let b = j.bounds_px(half_lw, state.line_join, fb.width, fb.height);
1539            min_x = min_x.min(b.0);
1540            min_y = min_y.min(b.1);
1541            max_x = max_x.max(b.2);
1542            max_y = max_y.max(b.3);
1543            b
1544        })
1545        .collect();
1546
1547    if let Some(c) = state.clip {
1548        min_x = min_x.max((c.x.floor() as isize).max(0) as usize);
1549        min_y = min_y.max((c.y.floor() as isize).max(0) as usize);
1550        max_x = max_x.min((c.max_x().ceil() as usize).min(fb.width));
1551        max_y = max_y.min((c.max_y().ceil() as usize).min(fb.height));
1552    }
1553    if min_x >= max_x || min_y >= max_y {
1554        return;
1555    }
1556
1557    const TILE: usize = 256;
1558    let mut tile_sd: Vec<f32> = Vec::new();
1559    let mut ty0 = min_y;
1560    while ty0 < max_y {
1561        let ty1 = (ty0 + TILE).min(max_y);
1562        let th = ty1 - ty0;
1563        let mut tx0 = min_x;
1564        while tx0 < max_x {
1565            let tx1 = (tx0 + TILE).min(max_x);
1566            let tw = tx1 - tx0;
1567            let len = tw * th;
1568            tile_sd.clear();
1569            tile_sd.resize(len, f32::INFINITY);
1570
1571            let mut touched = false;
1572            for (seg, &(sx0, sy0, sx1, sy1)) in segs.iter().zip(&seg_boxes) {
1573                let ox0 = tx0.max(sx0);
1574                let oy0 = ty0.max(sy0);
1575                let ox1 = tx1.min(sx1);
1576                let oy1 = ty1.min(sy1);
1577                if ox0 >= ox1 || oy0 >= oy1 {
1578                    continue;
1579                }
1580                touched = true;
1581                for y in oy0..oy1 {
1582                    let py = y as f32 + 0.5;
1583                    let row = (y - ty0) * tw;
1584                    for x in ox0..ox1 {
1585                        let px = x as f32 + 0.5;
1586                        let idx = row + (x - tx0);
1587                        let sd = seg.signed_dist(px, py, half_lw);
1588                        if sd < tile_sd[idx] {
1589                            tile_sd[idx] = sd;
1590                        }
1591                    }
1592                }
1593            }
1594
1595            for (join, &(jx0, jy0, jx1, jy1)) in joins.iter().zip(&join_boxes) {
1596                let ox0 = tx0.max(jx0);
1597                let oy0 = ty0.max(jy0);
1598                let ox1 = tx1.min(jx1);
1599                let oy1 = ty1.min(jy1);
1600                if ox0 >= ox1 || oy0 >= oy1 {
1601                    continue;
1602                }
1603                touched = true;
1604                for y in oy0..oy1 {
1605                    let py = y as f32 + 0.5;
1606                    let row = (y - ty0) * tw;
1607                    for x in ox0..ox1 {
1608                        let px = x as f32 + 0.5;
1609                        let idx = row + (x - tx0);
1610                        let sd = join.signed_dist(px, py, half_lw, state.line_join);
1611                        if sd < tile_sd[idx] {
1612                            tile_sd[idx] = sd;
1613                        }
1614                    }
1615                }
1616            }
1617
1618            if touched {
1619                for y in ty0..ty1 {
1620                    let py = y as f32 + 0.5;
1621                    let row = (y - ty0) * tw;
1622                    for x in tx0..tx1 {
1623                        let sd = tile_sd[row + (x - tx0)];
1624                        if sd >= 0.5 {
1625                            continue;
1626                        }
1627                        let px = x as f32 + 0.5;
1628                        if !point_passes_clip(state, px, py) {
1629                            continue;
1630                        }
1631                        let cov = (0.5 - sd).clamp(0.0, 1.0);
1632                        if cov > 0.005 {
1633                            fb.set_pixel(
1634                                x,
1635                                y,
1636                                Color::rgba(
1637                                    color.r,
1638                                    color.g,
1639                                    color.b,
1640                                    (color.a() * cov * 255.0).round() as u8,
1641                                ),
1642                            );
1643                        }
1644                    }
1645                }
1646            }
1647
1648            tx0 = tx1;
1649        }
1650        ty0 = ty1;
1651    }
1652}
1653
1654fn rasterize_polyline(
1655    fb: &mut FrameBuffer,
1656    pts: &[(f32, f32)],
1657    color: Color,
1658    line_width: f32,
1659    state: &RasterState,
1660) {
1661    if pts.len() < 2 {
1662        return;
1663    }
1664
1665    let is_closed = pts.len() >= 3
1666        && (pts[0].0 - pts[pts.len() - 1].0).hypot(pts[0].1 - pts[pts.len() - 1].1) <= 1e-3;
1667
1668    let period: f32 = state.line_dash.iter().copied().sum();
1669    if state.line_dash.is_empty() || period <= 1e-4 {
1670        rasterize_stroke_run(fb, pts, is_closed, color, line_width, state);
1671        return;
1672    }
1673
1674    let mut phase = state.dash_offset.rem_euclid(period);
1675    let mut dash_idx = 0usize;
1676    while dash_idx < state.line_dash.len() && phase >= state.line_dash[dash_idx] {
1677        phase -= state.line_dash[dash_idx];
1678        dash_idx = (dash_idx + 1) % state.line_dash.len();
1679    }
1680    let mut rem = (state.line_dash[dash_idx] - phase).max(0.0);
1681
1682    let mut runs: Vec<Vec<(f32, f32)>> = Vec::new();
1683    let mut cur_run: Vec<(f32, f32)> = Vec::new();
1684    let started_on = dash_idx.is_multiple_of(2) && rem > 1e-4;
1685
1686    for seg in pts.windows(2) {
1687        let (x0, y0) = seg[0];
1688        let (x1, y1) = seg[1];
1689        let dx = x1 - x0;
1690        let dy = y1 - y0;
1691        let seg_len = dx.hypot(dy);
1692        if seg_len <= 1e-4 {
1693            continue;
1694        }
1695        let mut cursor = 0.0_f32;
1696        while cursor < seg_len {
1697            if rem <= 1e-4 {
1698                dash_idx = (dash_idx + 1) % state.line_dash.len();
1699                rem = state.line_dash[dash_idx];
1700                if !dash_idx.is_multiple_of(2) && cur_run.len() >= 2 {
1701                    runs.push(std::mem::take(&mut cur_run));
1702                } else if !dash_idx.is_multiple_of(2) {
1703                    cur_run.clear();
1704                }
1705                if rem <= 1e-4 {
1706                    break;
1707                }
1708            }
1709            let step = rem.min(seg_len - cursor);
1710            let t0 = cursor / seg_len;
1711            let t1 = (cursor + step) / seg_len;
1712            if dash_idx.is_multiple_of(2) {
1713                let p_start = (x0 + dx * t0, y0 + dy * t0);
1714                let p_end = (x0 + dx * t1, y0 + dy * t1);
1715                if cur_run.is_empty() {
1716                    cur_run.push(p_start);
1717                }
1718                cur_run.push(p_end);
1719            }
1720            cursor += step;
1721            rem -= step;
1722        }
1723    }
1724    let ended_on = !cur_run.is_empty();
1725    if cur_run.len() >= 2 {
1726        runs.push(cur_run);
1727    }
1728
1729    if is_closed && started_on && ended_on && runs.len() >= 2 {
1730        let mut last = runs.pop().unwrap();
1731        let first = runs.remove(0);
1732        last.extend(first.into_iter().skip(1));
1733        rasterize_stroke_run(fb, &last, false, color, line_width, state);
1734    } else if is_closed && started_on && ended_on && runs.len() == 1 {
1735        rasterize_stroke_run(fb, &runs[0], true, color, line_width, state);
1736        return;
1737    }
1738
1739    for run in &runs {
1740        rasterize_stroke_run(fb, run, false, color, line_width, state);
1741    }
1742}
1743
1744/// Software analytical anti-aliased rasterization of canvas commands directly onto a FrameBuffer.
1745pub fn rasterize_canvas_commands(
1746    fb: &mut FrameBuffer,
1747    commands: &[CanvasCommand],
1748    origin_x: f32,
1749    origin_y: f32,
1750    clip: Option<Rect>,
1751) {
1752    let mut state = RasterState {
1753        clip,
1754        clip_polys: Vec::new(),
1755        line_dash: Vec::new(),
1756        dash_offset: 0.0,
1757        line_cap: CanvasLineCap::Butt,
1758        line_join: CanvasLineJoin::Miter,
1759    };
1760    let mut stack: Vec<RasterState> = Vec::new();
1761
1762    for cmd in commands {
1763        match cmd {
1764            CanvasCommand::Save => {
1765                stack.push(state.clone());
1766            }
1767            CanvasCommand::Restore => {
1768                if let Some(prev) = stack.pop() {
1769                    state = prev;
1770                }
1771            }
1772            CanvasCommand::SetLineDash { segments, offset } => {
1773                state.line_dash = segments.clone();
1774                state.dash_offset = *offset;
1775            }
1776            CanvasCommand::SetLineCap(cap) => {
1777                state.line_cap = *cap;
1778            }
1779            CanvasCommand::SetLineJoin(join) => {
1780                state.line_join = *join;
1781            }
1782            CanvasCommand::ClipPath { verbs } => {
1783                let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
1784                if let Some(bbox) = canvas_verbs_bounds(verbs, origin_x, origin_y) {
1785                    state.clip = match state.clip {
1786                        Some(existing) => existing.intersect(bbox).or(Some(Rect::zero())),
1787                        None => Some(bbox),
1788                    };
1789                }
1790                if !subpaths.is_empty() {
1791                    state.clip_polys.push(subpaths);
1792                }
1793            }
1794            CanvasCommand::FillRect { bounds, color } => {
1795                let translated = Rect::new(
1796                    bounds.x + origin_x,
1797                    bounds.y + origin_y,
1798                    bounds.width,
1799                    bounds.height,
1800                );
1801                if state.clip_polys.is_empty() {
1802                    fb.draw_rect(translated, *color, state.clip);
1803                } else {
1804                    let poly = vec![vec![
1805                        (translated.x, translated.y),
1806                        (translated.max_x(), translated.y),
1807                        (translated.max_x(), translated.max_y()),
1808                        (translated.x, translated.max_y()),
1809                        (translated.x, translated.y),
1810                    ]];
1811                    rasterize_fill_subpaths(fb, &poly, *color, &state);
1812                }
1813            }
1814            CanvasCommand::ClearRect { bounds } => {
1815                let translated = Rect::new(
1816                    bounds.x + origin_x,
1817                    bounds.y + origin_y,
1818                    bounds.width,
1819                    bounds.height,
1820                );
1821                fb.clear_rect(translated, Color::TRANSPARENT);
1822            }
1823            CanvasCommand::StrokeRect {
1824                bounds,
1825                color,
1826                line_width,
1827            } => {
1828                let translated = Rect::new(
1829                    bounds.x + origin_x,
1830                    bounds.y + origin_y,
1831                    bounds.width,
1832                    bounds.height,
1833                );
1834                if state.line_dash.is_empty() && state.clip_polys.is_empty() {
1835                    let lw = *line_width;
1836                    fb.draw_rect(
1837                        Rect::new(translated.x, translated.y, translated.width, lw),
1838                        *color,
1839                        state.clip,
1840                    );
1841                    fb.draw_rect(
1842                        Rect::new(translated.x, translated.max_y() - lw, translated.width, lw),
1843                        *color,
1844                        state.clip,
1845                    );
1846                    fb.draw_rect(
1847                        Rect::new(translated.x, translated.y, lw, translated.height),
1848                        *color,
1849                        state.clip,
1850                    );
1851                    fb.draw_rect(
1852                        Rect::new(translated.max_x() - lw, translated.y, lw, translated.height),
1853                        *color,
1854                        state.clip,
1855                    );
1856                } else {
1857                    let pts = [
1858                        (translated.x, translated.y),
1859                        (translated.max_x(), translated.y),
1860                        (translated.max_x(), translated.max_y()),
1861                        (translated.x, translated.max_y()),
1862                        (translated.x, translated.y),
1863                    ];
1864                    rasterize_polyline(fb, &pts, *color, *line_width, &state);
1865                }
1866            }
1867            CanvasCommand::DrawLine {
1868                p0,
1869                p1,
1870                color,
1871                line_width,
1872            } => {
1873                let pts = [(p0.0 + origin_x, p0.1 + origin_y), (p1.0 + origin_x, p1.1 + origin_y)];
1874                rasterize_polyline(fb, &pts, *color, *line_width, &state);
1875            }
1876            CanvasCommand::DrawCircle {
1877                center,
1878                radius,
1879                fill_color,
1880                stroke_color,
1881                line_width,
1882            } => {
1883                let cx = center.0 + origin_x;
1884                let cy = center.1 + origin_y;
1885                let r = *radius;
1886                let lw = *line_width;
1887
1888                if let Some(fc) = fill_color {
1889                    let min_x = ((cx - r - lw).floor() as isize).max(0) as usize;
1890                    let max_x = ((cx + r + lw).ceil() as usize).min(fb.width);
1891                    let min_y = ((cy - r - lw).floor() as isize).max(0) as usize;
1892                    let max_y = ((cy + r + lw).ceil() as usize).min(fb.height);
1893
1894                    for y in min_y..max_y {
1895                        let py = y as f32 + 0.5;
1896                        let dy = py - cy;
1897                        for x in min_x..max_x {
1898                            let px = x as f32 + 0.5;
1899                            if !point_passes_clip(&state, px, py) {
1900                                continue;
1901                            }
1902                            let dx = px - cx;
1903                            let dist = (dx * dx + dy * dy).sqrt();
1904                            let coverage = (0.5 + r - dist).clamp(0.0, 1.0);
1905                            if coverage > 0.005 {
1906                                fb.set_pixel(
1907                                    x,
1908                                    y,
1909                                    Color::rgba(
1910                                        fc.r,
1911                                        fc.g,
1912                                        fc.b,
1913                                        (fc.a() * coverage * 255.0) as u8,
1914                                    ),
1915                                );
1916                            }
1917                        }
1918                    }
1919                }
1920
1921                if let Some(sc) = stroke_color {
1922                    if !state.line_dash.is_empty() {
1923                        let steps = ((r * std::f32::consts::TAU / 3.0).ceil() as usize).clamp(24, 128);
1924                        let pts: Vec<(f32, f32)> = (0..=steps)
1925                            .map(|i| {
1926                                let a = (i as f32 / steps as f32) * std::f32::consts::TAU;
1927                                (cx + r * a.cos(), cy + r * a.sin())
1928                            })
1929                            .collect();
1930                        rasterize_polyline(fb, &pts, *sc, lw, &state);
1931                    } else {
1932                        let min_x = ((cx - r - lw).floor() as isize).max(0) as usize;
1933                        let max_x = ((cx + r + lw).ceil() as usize).min(fb.width);
1934                        let min_y = ((cy - r - lw).floor() as isize).max(0) as usize;
1935                        let max_y = ((cy + r + lw).ceil() as usize).min(fb.height);
1936                        for y in min_y..max_y {
1937                            let py = y as f32 + 0.5;
1938                            let dy = py - cy;
1939                            for x in min_x..max_x {
1940                                let px = x as f32 + 0.5;
1941                                if !point_passes_clip(&state, px, py) {
1942                                    continue;
1943                                }
1944                                let dx = px - cx;
1945                                let dist = (dx * dx + dy * dy).sqrt();
1946                                let stroke_dist = (dist - r).abs();
1947                                let coverage = (0.5 + lw * 0.5 - stroke_dist).clamp(0.0, 1.0);
1948                                if coverage > 0.005 {
1949                                    fb.set_pixel(
1950                                        x,
1951                                        y,
1952                                        Color::rgba(
1953                                            sc.r,
1954                                            sc.g,
1955                                            sc.b,
1956                                            (sc.a() * coverage * 255.0) as u8,
1957                                        ),
1958                                    );
1959                                }
1960                            }
1961                        }
1962                    }
1963                }
1964            }
1965            CanvasCommand::DrawPath {
1966                verbs,
1967                fill_color,
1968                stroke_color,
1969                line_width,
1970            } => {
1971                let subpaths = flatten_canvas_verbs(verbs, origin_x, origin_y);
1972                if let Some(fc) = fill_color {
1973                    rasterize_fill_subpaths(fb, &subpaths, *fc, &state);
1974                }
1975                if let Some(sc) = stroke_color {
1976                    for sub in &subpaths {
1977                        rasterize_polyline(fb, sub, *sc, *line_width, &state);
1978                    }
1979                }
1980            }
1981            CanvasCommand::FillText {
1982                text,
1983                x,
1984                y,
1985                color,
1986                font_size,
1987                font_family,
1988                font_weight,
1989                italic,
1990                text_align,
1991                text_baseline,
1992                max_width,
1993                ..
1994            }
1995            | CanvasCommand::StrokeText {
1996                text,
1997                x,
1998                y,
1999                color,
2000                font_size,
2001                font_family,
2002                font_weight,
2003                italic,
2004                text_align,
2005                text_baseline,
2006                max_width,
2007                ..
2008            } => {
2009                let metrics = measure_canvas_text_metrics(
2010                    text,
2011                    *font_size,
2012                    font_family,
2013                    *font_weight,
2014                    *italic,
2015                );
2016                let measured_w = if let Some(mw) = *max_width {
2017                    metrics.width.min(mw.max(0.0))
2018                } else {
2019                    metrics.width
2020                };
2021                let est_h = metrics.height.max(*font_size);
2022                let tx = origin_x
2023                    + match text_align {
2024                        CanvasTextAlign::Left | CanvasTextAlign::Start => *x,
2025                        CanvasTextAlign::Center => *x - measured_w * 0.5,
2026                        CanvasTextAlign::Right | CanvasTextAlign::End => *x - measured_w,
2027                    };
2028                let ty = origin_y
2029                    + match text_baseline {
2030                        CanvasTextBaseline::Top | CanvasTextBaseline::Hanging => *y,
2031                        CanvasTextBaseline::Middle => *y - est_h * 0.5,
2032                        CanvasTextBaseline::Bottom | CanvasTextBaseline::Ideographic => *y - est_h,
2033                        CanvasTextBaseline::Alphabetic => *y - metrics.font_bounding_box_ascent,
2034                    };
2035                fb.draw_text((tx, ty), text, *font_size, *color, state.clip);
2036            }
2037        }
2038    }
2039}
2040
2041#[cfg(test)]
2042mod tests {
2043    use super::*;
2044
2045    #[test]
2046    fn test_transform2d_operations() {
2047        let mut t = Transform2D::IDENTITY;
2048        t.translate(100.0, 50.0);
2049        let p = t.transform_xy(10.0, 20.0);
2050        assert_eq!(p, (110.0, 70.0));
2051
2052        let mut s = Transform2D::IDENTITY;
2053        s.scale_mut(2.0, 3.0);
2054        let p2 = s.transform_xy(10.0, 10.0);
2055        assert_eq!(p2, (20.0, 30.0));
2056    }
2057
2058    #[test]
2059    fn test_canvas_context_recording() {
2060        let mut ctx = Canvas2DContext::new(400.0, 300.0);
2061
2062        ctx.set_fill_style(Color::rgb(255, 0, 0));
2063        ctx.fill_rect(10.0, 10.0, 80.0, 50.0);
2064
2065        ctx.set_stroke_style(Color::rgb(0, 0, 255));
2066        ctx.set_line_width(2.0);
2067        ctx.begin_path();
2068        ctx.move_to(0.0, 0.0);
2069        ctx.line_to(100.0, 100.0);
2070        ctx.stroke();
2071
2072        assert_eq!(ctx.commands().len(), 2);
2073    }
2074
2075    #[test]
2076    fn test_canvas_rasterize_to_framebuffer() {
2077        let mut fb = FrameBuffer::new(200, 200);
2078        let mut ctx = Canvas2DContext::new(200.0, 200.0);
2079
2080        ctx.set_fill_style(Color::rgb(0, 255, 0));
2081        ctx.fill_rect(20.0, 20.0, 40.0, 40.0);
2082
2083        ctx.rasterize(&mut fb, 0.0, 0.0, None);
2084
2085        // Center of rect (40, 40) must be green
2086        let pixel = fb.get_pixel(40, 40);
2087        assert_eq!(pixel, Color::rgb(0, 255, 0));
2088
2089        // Outside rect (5, 5) must be transparent
2090        assert_eq!(fb.get_pixel(5, 5), Color::TRANSPARENT);
2091    }
2092
2093    #[test]
2094    fn test_canvas_bezier_dash_clip_and_text() {
2095        let (size, family, weight, italic) =
2096            parse_canvas_font("italic bold 14px/1.2 'JetBrains Mono', monospace");
2097        assert!((size - 14.0).abs() < 0.01);
2098        assert_eq!(family, "JetBrains Mono, monospace");
2099        assert_eq!(weight, 700);
2100        assert!(italic);
2101
2102        // Dashed horizontal line leaves transparent gaps
2103        let mut fb = FrameBuffer::new(200, 100);
2104        let mut ctx = Canvas2DContext::new(200.0, 100.0);
2105        ctx.set_stroke_style(Color::rgb(255, 0, 0));
2106        ctx.set_line_width(2.0);
2107        ctx.set_line_dash(&[10.0, 10.0]);
2108        ctx.begin_path();
2109        ctx.move_to(0.0, 20.0);
2110        ctx.line_to(100.0, 20.0);
2111        ctx.stroke();
2112        ctx.rasterize(&mut fb, 0.0, 0.0, None);
2113        assert!(fb.get_pixel(5, 20).r > 200, "dash on-segment must be drawn");
2114        assert_eq!(fb.get_pixel(15, 20), Color::TRANSPARENT, "dash gap must stay empty");
2115
2116        // Clip restricts fill_rect, and restore removes clip
2117        let mut fb_clip = FrameBuffer::new(100, 100);
2118        let mut c2 = Canvas2DContext::new(100.0, 100.0);
2119        c2.save();
2120        c2.begin_path();
2121        c2.rect(10.0, 10.0, 30.0, 30.0);
2122        c2.clip();
2123        c2.set_fill_style(Color::rgb(0, 200, 255));
2124        c2.fill_rect(0.0, 0.0, 100.0, 100.0);
2125        c2.restore();
2126        c2.set_fill_style(Color::rgb(255, 255, 0));
2127        c2.fill_rect(60.0, 60.0, 20.0, 20.0);
2128        c2.rasterize(&mut fb_clip, 0.0, 0.0, None);
2129        assert_eq!(fb_clip.get_pixel(25, 25), Color::rgb(0, 200, 255));
2130        assert_eq!(fb_clip.get_pixel(5, 5), Color::TRANSPARENT);
2131        assert_eq!(fb_clip.get_pixel(70, 70), Color::rgb(255, 255, 0));
2132
2133        // Cubic & quadratic bezier + fill_text + stroke_text
2134        let mut fb_curve = FrameBuffer::new(160, 120);
2135        let mut c3 = Canvas2DContext::new(160.0, 120.0);
2136        c3.set_stroke_style(Color::rgb(50, 255, 50));
2137        c3.set_line_width(2.0);
2138        c3.begin_path();
2139        c3.move_to(10.0, 60.0);
2140        c3.quadratic_curve_to(50.0, 10.0, 90.0, 60.0);
2141        c3.bezier_curve_to(110.0, 90.0, 130.0, 90.0, 150.0, 60.0);
2142        c3.stroke();
2143        c3.set_font("bold 12px monospace");
2144        c3.set_text_align(CanvasTextAlign::Left);
2145        c3.set_text_baseline(CanvasTextBaseline::Top);
2146        c3.set_fill_style(Color::rgb(255, 255, 255));
2147        c3.fill_text("CLK_0", 10.0, 5.0);
2148        c3.stroke_text("OUT", 80.0, 5.0);
2149        c3.rasterize(&mut fb_curve, 0.0, 0.0, None);
2150
2151        // Quadratic curve midpoint at t=0.5 is (50, 35)
2152        assert!(
2153            fb_curve.get_pixel(50, 35).g > 150,
2154            "quadratic curve midpoint should be lit"
2155        );
2156        // Text region (10..60, 5..20) should have non-transparent white pixels
2157        let mut lit_text = 0usize;
2158        for y in 5..22 {
2159            for x in 10..60 {
2160                if fb_curve.get_pixel(x, y).a > 0 {
2161                    lit_text += 1;
2162                }
2163            }
2164        }
2165        assert!(lit_text > 5, "fill_text should rasterize visible glyph pixels");
2166    }
2167
2168    #[test]
2169    fn test_canvas_measure_text_metrics() {
2170        let mut ctx = Canvas2DContext::new(400.0, 200.0);
2171        ctx.set_font("12px monospace");
2172        let empty = ctx.measure_text("");
2173        assert_eq!(empty.width, 0.0);
2174        assert!(empty.height > 0.0);
2175
2176        let short = ctx.measure_text("VREF");
2177        let long = ctx.measure_text("VREF_BUFFERED_OUT");
2178        assert!(short.width > 0.0);
2179        assert!(long.width > short.width * 2.0);
2180        assert!(short.font_bounding_box_ascent > 0.0);
2181        assert!(short.font_bounding_box_descent > 0.0);
2182
2183        ctx.set_font("24px sans-serif");
2184        let bigger = ctx.measure_text("VREF");
2185        assert!(bigger.width > short.width * 1.4);
2186        assert!(bigger.height > short.height * 1.4);
2187    }
2188
2189    #[test]
2190    fn test_canvas_round_rect_and_clip() {
2191        let mut fb = FrameBuffer::new(120, 80);
2192        let mut ctx = Canvas2DContext::new(120.0, 80.0);
2193
2194        // Huge radius on a 40x20 box clamps to 10px capsule corners cleanly
2195        ctx.set_fill_style(Color::rgb(20, 180, 240));
2196        ctx.begin_path();
2197        ctx.round_rect(10.0, 10.0, 40.0, 20.0, 100.0);
2198        ctx.fill();
2199
2200        // Asymmetric radii: sharp TL (0), rounded TR (8), sharp BR (0), rounded BL (8)
2201        ctx.save();
2202        ctx.begin_path();
2203        ctx.round_rect(60.0, 10.0, 40.0, 30.0, [0.0, 8.0, 0.0, 8.0]);
2204        ctx.clip();
2205        ctx.set_fill_style(Color::rgb(255, 160, 0));
2206        ctx.fill_rect(60.0, 10.0, 40.0, 30.0);
2207        ctx.restore();
2208
2209        ctx.rasterize(&mut fb, 0.0, 0.0, None);
2210
2211        // Center of capsule is filled
2212        assert_eq!(fb.get_pixel(30, 20), Color::rgb(20, 180, 240));
2213        // Outer corner (10, 10) of capsule is cut away
2214        assert_eq!(fb.get_pixel(10, 10), Color::TRANSPARENT);
2215
2216        // Clipped asymmetric rect: sharp TL (60, 10) is filled, rounded TR (99, 10) is clipped
2217        assert_eq!(fb.get_pixel(60, 10), Color::rgb(255, 160, 0));
2218        assert_eq!(fb.get_pixel(99, 10), Color::TRANSPARENT);
2219        assert_eq!(fb.get_pixel(99, 39), Color::rgb(255, 160, 0));
2220        assert_eq!(fb.get_pixel(60, 39), Color::TRANSPARENT);
2221    }
2222
2223    #[test]
2224    fn test_canvas_line_cap_and_line_join_and_save_restore() {
2225        let mut ctx = Canvas2DContext::new(120.0, 120.0);
2226        assert_eq!(ctx.line_cap(), CanvasLineCap::Butt);
2227        assert_eq!(ctx.line_join(), CanvasLineJoin::Miter);
2228
2229        ctx.save();
2230        ctx.set_line_cap(CanvasLineCap::Square);
2231        ctx.set_line_join(CanvasLineJoin::Bevel);
2232        assert_eq!(ctx.line_cap(), CanvasLineCap::Square);
2233        assert_eq!(ctx.line_join(), CanvasLineJoin::Bevel);
2234        ctx.restore();
2235        assert_eq!(ctx.line_cap(), CanvasLineCap::Butt);
2236        assert_eq!(ctx.line_join(), CanvasLineJoin::Miter);
2237
2238        // Caps test: horizontal line (20, 30) -> (60, 30), lw = 10 (half_lw = 5)
2239        let draw_cap = |cap: CanvasLineCap| {
2240            let mut fb = FrameBuffer::new(90, 60);
2241            let mut c = Canvas2DContext::new(90.0, 60.0);
2242            c.set_stroke_style(Color::rgb(255, 0, 0));
2243            c.set_line_width(10.0);
2244            c.set_line_cap(cap);
2245            c.begin_path();
2246            c.move_to(20.0, 30.0);
2247            c.line_to(60.0, 30.0);
2248            c.stroke();
2249            c.rasterize(&mut fb, 0.0, 0.0, None);
2250            fb
2251        };
2252
2253        let fb_butt = draw_cap(CanvasLineCap::Butt);
2254        let fb_round = draw_cap(CanvasLineCap::Round);
2255        let fb_square = draw_cap(CanvasLineCap::Square);
2256
2257        // Butt stops at x=20
2258        assert_eq!(fb_butt.get_pixel(18, 30), Color::TRANSPARENT);
2259        // Round extends along axis to x=17, but NOT out to corner (15, 26) (dist=5.70 > 5)
2260        assert!(fb_round.get_pixel(17, 30).a > 200);
2261        assert_eq!(fb_round.get_pixel(15, 26), Color::TRANSPARENT);
2262        // Square extends to corner (15, 26) (|-4.5| <= 5, |-3.5| <= 5)
2263        assert!(fb_square.get_pixel(15, 26).a > 200);
2264
2265        // Joins test: 90-degree corner at (50, 30) with lw = 10 (half_lw = 5)
2266        let draw_join = |join: CanvasLineJoin| {
2267            let mut fb = FrameBuffer::new(90, 90);
2268            let mut c = Canvas2DContext::new(90.0, 90.0);
2269            c.set_stroke_style(Color::rgb(0, 255, 0));
2270            c.set_line_width(10.0);
2271            c.set_line_join(join);
2272            c.begin_path();
2273            c.move_to(10.0, 30.0);
2274            c.line_to(50.0, 30.0);
2275            c.line_to(50.0, 70.0);
2276            c.stroke();
2277            c.rasterize(&mut fb, 0.0, 0.0, None);
2278            fb
2279        };
2280
2281        let fb_miter = draw_join(CanvasLineJoin::Miter);
2282        let fb_round_j = draw_join(CanvasLineJoin::Round);
2283        let fb_bevel = draw_join(CanvasLineJoin::Bevel);
2284
2285        // Miter reaches outer corner (54, 26), while Round & Bevel do not
2286        assert!(fb_miter.get_pixel(54, 26).a > 200);
2287        assert_eq!(fb_round_j.get_pixel(54, 26), Color::TRANSPARENT);
2288        assert_eq!(fb_bevel.get_pixel(54, 26), Color::TRANSPARENT);
2289
2290        // Round fills (53, 27) (dist ~4.24 < 5), whereas Bevel chord misses it
2291        assert!(fb_round_j.get_pixel(53, 27).a > 200);
2292        assert_eq!(fb_bevel.get_pixel(53, 27), Color::TRANSPARENT);
2293        // Inside bevel triangle (51, 29) is lit
2294        assert!(fb_bevel.get_pixel(51, 29).a > 200);
2295    }
2296}