Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

36.4 KB
Raw Blame
//! A 2D context over one CoreGraphics bitmap context (premultiplied RGBA8, sRGB).
//!
//! Coordinate spaces: the CG context's root CTM flips y once, so "device" below means canvas
//! pixels, y down. The current path is kept in device space (each point transformed by the CTM at
//! the time it is added, as the canvas spec requires); Path2D objects are kept in their own space
//! and transformed when used. Clipping lives in the CG graphics state, so canvas `save()` /
//! `restore()` map onto CG's gstate stack; everything else (paint, line, shadow, composite, font)
//! is canvas state applied per draw call inside a nested gstate.
use std::rc::Rc;

use objc2_core_foundation::{CFRetained, CGAffineTransform, CGFloat, CGPoint, CGRect, CGSize};
use objc2_core_graphics::{
    CGBitmapContextCreate, CGBlendMode, CGColor, CGContext, CGGradient, CGGradientDrawingOptions, CGImage, CGImageAlphaInfo, CGInterpolationQuality,
    CGLineCap, CGLineJoin, CGMutablePath, CGPath,
};

use crate::codec::{premul, srgb, unpremul};
use crate::fonts::{self, Font, ParsedFont};
use crate::text;

pub(crate) const IDENTITY: CGAffineTransform = CGAffineTransform { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 };

/// `t1` then `t2`.
pub(crate) fn concat(t1: &CGAffineTransform, t2: &CGAffineTransform) -> CGAffineTransform {
    CGAffineTransform {
        a: t1.a * t2.a + t1.b * t2.c,
        b: t1.a * t2.b + t1.b * t2.d,
        c: t1.c * t2.a + t1.d * t2.c,
        d: t1.c * t2.b + t1.d * t2.d,
        tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx,
        ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty,
    }
}

pub(crate) fn apply(t: &CGAffineTransform, x: f64, y: f64) -> (f64, f64) {
    (t.a * x + t.c * y + t.tx, t.b * x + t.d * y + t.ty)
}

pub(crate) fn invert(t: &CGAffineTransform) -> Option<CGAffineTransform> {
    let det = t.a * t.d - t.b * t.c;
    if det == 0.0 || !det.is_finite() {
        return None;
    }
    let a = t.d / det;
    let b = -t.b / det;
    let c = -t.c / det;
    let d = t.a / det;
    Some(CGAffineTransform { a, b, c, d, tx: -(a * t.tx + c * t.ty), ty: -(b * t.tx + d * t.ty) })
}

fn rect(x: f64, y: f64, w: f64, h: f64) -> CGRect {
    CGRect { origin: CGPoint { x, y }, size: CGSize { width: w, height: h } }
}

// ----------------------------------------------------------------------------------- paths

/// A path under construction, in its own coordinate space.
pub(crate) struct Path {
    pub cg: CFRetained<CGMutablePath>,
    /// a subpath is open (there is a current point)
    pub has_current: bool,
}

impl Default for Path {
    fn default() -> Self {
        Path { cg: CGMutablePath::new(), has_current: false }
    }
}

fn finite(v: &[f64]) -> bool {
    v.iter().all(|x| x.is_finite())
}

impl Path {
    pub fn clear(&mut self) {
        self.cg = CGMutablePath::new();
        self.has_current = false;
    }
    fn current(&self) -> (f64, f64) {
        let p = CGPath::current_point(Some(&self.cg));
        (p.x, p.y)
    }
    pub fn move_to(&mut self, m: &CGAffineTransform, x: f64, y: f64) {
        if !finite(&[x, y]) {
            return;
        }
        let (dx, dy) = apply(m, x, y);
        unsafe { CGMutablePath::move_to_point(Some(&self.cg), std::ptr::null(), dx, dy) };
        self.has_current = true;
    }
    pub fn line_to(&mut self, m: &CGAffineTransform, x: f64, y: f64) {
        if !finite(&[x, y]) {
            return;
        }
        if !self.has_current {
            return self.move_to(m, x, y);
        }
        let (dx, dy) = apply(m, x, y);
        unsafe { CGMutablePath::add_line_to_point(Some(&self.cg), std::ptr::null(), dx, dy) };
    }
    pub fn quad_to(&mut self, m: &CGAffineTransform, cx: f64, cy: f64, x: f64, y: f64) {
        if !finite(&[cx, cy, x, y]) {
            return;
        }
        if !self.has_current {
            self.move_to(m, cx, cy);
        }
        let (a, b) = apply(m, cx, cy);
        let (c, d) = apply(m, x, y);
        unsafe { CGMutablePath::add_quad_curve_to_point(Some(&self.cg), std::ptr::null(), a, b, c, d) };
    }
    #[allow(clippy::too_many_arguments)]
    pub fn bezier_to(&mut self, m: &CGAffineTransform, c1x: f64, c1y: f64, c2x: f64, c2y: f64, x: f64, y: f64) {
        if !finite(&[c1x, c1y, c2x, c2y, x, y]) {
            return;
        }
        if !self.has_current {
            self.move_to(m, c1x, c1y);
        }
        let (a, b) = apply(m, c1x, c1y);
        let (c, d) = apply(m, c2x, c2y);
        let (e, f) = apply(m, x, y);
        unsafe { CGMutablePath::add_curve_to_point(Some(&self.cg), std::ptr::null(), a, b, c, d, e, f) };
    }
    pub fn close(&mut self) {
        if self.has_current {
            CGMutablePath::close_subpath(Some(&self.cg));
        }
    }
    /// Elliptical arc of the unit circle mapped by `m` (CSS/canvas angle semantics).
    fn arc_unit(&mut self, m: &CGAffineTransform, start: f64, end: f64, ccw: bool) {
        let (start, end) = canonical_angles(start, end, ccw);
        let sweep = end - start;
        let had = self.has_current;
        if !had {
            // CGPathAddRelativeArc starts a new subpath at the arc start on an empty path, but a path
            // that only has closed subpaths still has a "current point"; begin explicitly.
            let (x, y) = apply(m, start.cos(), start.sin());
            unsafe { CGMutablePath::move_to_point(Some(&self.cg), std::ptr::null(), x, y) };
        }
        unsafe { CGMutablePath::add_relative_arc(Some(&self.cg), m, 0.0, 0.0, 1.0, start, sweep) };
        self.has_current = true;
    }
    #[allow(clippy::too_many_arguments)]
    pub fn arc(&mut self, m: &CGAffineTransform, x: f64, y: f64, r: f64, start: f64, end: f64, ccw: bool) {
        self.ellipse(m, x, y, r, r, 0.0, start, end, ccw)
    }
    #[allow(clippy::too_many_arguments)]
    pub fn ellipse(&mut self, m: &CGAffineTransform, x: f64, y: f64, rx: f64, ry: f64, rot: f64, start: f64, end: f64, ccw: bool) {
        if !finite(&[x, y, rx, ry, rot, start, end]) || rx < 0.0 || ry < 0.0 {
            return;
        }
        if rx == 0.0 || ry == 0.0 {
            // Degenerate: Chrome draws the line through the arc's end points.
            let (s, e) = canonical_angles(start, end, ccw);
            let pt = |a: f64| {
                let (c, s_) = (a.cos() * rx, a.sin() * ry);
                (x + c * rot.cos() - s_ * rot.sin(), y + c * rot.sin() + s_ * rot.cos())
            };
            let (sx, sy) = pt(s);
            self.line_to(m, sx, sy);
            let (ex, ey) = pt(e);
            self.line_to(m, ex, ey);
            return;
        }
        let local = CGAffineTransform { a: rx * rot.cos(), b: rx * rot.sin(), c: -ry * rot.sin(), d: ry * rot.cos(), tx: x, ty: y };
        let full = concat(&local, m);
        self.arc_unit(&full, start, end, ccw);
    }
    /// `arcTo` per the canvas spec, computed in the space of `m`'s input (user space).
    #[allow(clippy::too_many_arguments)]
    pub fn arc_to(&mut self, m: &CGAffineTransform, x1: f64, y1: f64, x2: f64, y2: f64, r: f64) {
        if !finite(&[x1, y1, x2, y2, r]) || r < 0.0 {
            return;
        }
        if !self.has_current {
            self.move_to(m, x1, y1);
        }
        let Some(inv) = invert(m) else { return };
        let (dx, dy) = self.current();
        let (x0, y0) = apply(&inv, dx, dy);
        let eq = |a: f64, b: f64, c: f64, d: f64| (a - c).abs() < 1e-9 && (b - d).abs() < 1e-9;
        if eq(x0, y0, x1, y1) || eq(x1, y1, x2, y2) || r == 0.0 {
            return self.line_to(m, x1, y1);
        }
        let (v1x, v1y) = (x0 - x1, y0 - y1);
        let (v2x, v2y) = (x2 - x1, y2 - y1);
        let l1 = v1x.hypot(v1y);
        let l2 = v2x.hypot(v2y);
        let cross = v1x * v2y - v1y * v2x;
        if cross.abs() <= 1e-9 * l1 * l2 {
            return self.line_to(m, x1, y1);
        }
        let (u1x, u1y) = (v1x / l1, v1y / l1);
        let (u2x, u2y) = (v2x / l2, v2y / l2);
        let cos = (u1x * u2x + u1y * u2y).clamp(-1.0, 1.0);
        let half = cos.acos() / 2.0;
        let dist = r / half.tan();
        let (t1x, t1y) = (x1 + u1x * dist, y1 + u1y * dist);
        let (t2x, t2y) = (x1 + u2x * dist, y1 + u2y * dist);
        let (bx, by) = (u1x + u2x, u1y + u2y);
        let bl = bx.hypot(by);
        let cd = r / half.sin();
        let (cx, cy) = (x1 + bx / bl * cd, y1 + by / bl * cd);
        let a0 = (t1y - cy).atan2(t1x - cx);
        let a1 = (t2y - cy).atan2(t2x - cx);
        let mut delta = a1 - a0;
        while delta > std::f64::consts::PI {
            delta -= std::f64::consts::TAU;
        }
        while delta < -std::f64::consts::PI {
            delta += std::f64::consts::TAU;
        }
        self.line_to(m, t1x, t1y);
        let local = CGAffineTransform { a: r, b: 0.0, c: 0.0, d: r, tx: cx, ty: cy };
        let full = concat(&local, m);
        unsafe { CGMutablePath::add_relative_arc(Some(&self.cg), &full, 0.0, 0.0, 1.0, a0, delta) };
    }
    pub fn rect(&mut self, m: &CGAffineTransform, x: f64, y: f64, w: f64, h: f64) {
        if !finite(&[x, y, w, h]) {
            return;
        }
        self.move_to(m, x, y);
        self.line_to(m, x + w, y);
        self.line_to(m, x + w, y + h);
        self.line_to(m, x, y + h);
        self.close();
    }
    /// `roundRect` with radii already normalized by the caller: `r` = [tl.x, tl.y, tr.x, tr.y,
    /// br.x, br.y, bl.x, bl.y] (spec steps up to scaling done in JS).
    pub fn round_rect(&mut self, m: &CGAffineTransform, x: f64, y: f64, w: f64, h: f64, r: [f64; 8]) {
        if !finite(&[x, y, w, h]) || !finite(&r) {
            return;
        }
        let [tlx, tly, trx, try_, brx, bry, blx, bly] = r;
        self.move_to(m, x + tlx, y);
        self.line_to(m, x + w - trx, y);
        self.corner(m, x + w - trx, y + try_, trx, try_, -std::f64::consts::FRAC_PI_2);
        self.line_to(m, x + w, y + h - bry);
        self.corner(m, x + w - brx, y + h - bry, brx, bry, 0.0);
        self.line_to(m, x + blx, y + h);
        self.corner(m, x + blx, y + h - bly, blx, bly, std::f64::consts::FRAC_PI_2);
        self.line_to(m, x, y + tly);
        self.corner(m, x + tlx, y + tly, tlx, tly, std::f64::consts::PI);
        self.close();
        self.move_to(m, x, y);
    }
    fn corner(&mut self, m: &CGAffineTransform, cx: f64, cy: f64, rx: f64, ry: f64, start: f64) {
        if rx <= 0.0 || ry <= 0.0 {
            return;
        }
        let local = CGAffineTransform { a: rx, b: 0.0, c: 0.0, d: ry, tx: cx, ty: cy };
        let full = concat(&local, m);
        unsafe { CGMutablePath::add_relative_arc(Some(&self.cg), &full, 0.0, 0.0, 1.0, start, std::f64::consts::FRAC_PI_2) };
    }
    pub fn add_path(&mut self, other: &CGPath, m: &CGAffineTransform) {
        unsafe { CGMutablePath::add_path(Some(&self.cg), m, Some(other)) };
        if !CGPath::is_empty(Some(other)) {
            self.has_current = true;
        }
    }
    /// A copy transformed by `m`.
    pub fn transformed(&self, m: &CGAffineTransform) -> CFRetained<CGPath> {
        unsafe { CGPath::new_copy_by_transforming_path(Some(&self.cg), m) }.unwrap_or_else(|| CGPath::new_copy(Some(&self.cg)).unwrap())
    }
}

/// Chrome's arc angle canonicalization (start in [0, 2π), sweep per the spec rules).
fn canonical_angles(start: f64, end: f64, ccw: bool) -> (f64, f64) {
    use std::f64::consts::TAU;
    let mut s = start % TAU;
    if s < 0.0 {
        s += TAU;
    }
    let e = end + (s - start);
    let new_end = if !ccw && e - s >= TAU {
        s + TAU
    } else if ccw && s - e >= TAU {
        s - TAU
    } else if !ccw && s > e {
        s + (TAU - (s - e) % TAU)
    } else if ccw && s < e {
        s - (TAU - (e - s) % TAU)
    } else {
        e
    };
    (s, new_end)
}

// ----------------------------------------------------------------------------------- paint

pub(crate) struct Gradient {
    pub kind: GradientKind,
    pub stops: Vec<(f64, [f64; 4])>,
    pub cg: Option<CFRetained<CGGradient>>,
}

#[derive(Clone, Copy)]
pub(crate) enum GradientKind {
    Linear(f64, f64, f64, f64),
    Radial(f64, f64, f64, f64, f64, f64),
    Conic(f64, f64, f64),
}

impl Gradient {
    pub fn new(kind: GradientKind) -> Self {
        Gradient { kind, stops: Vec::new(), cg: None }
    }
    pub fn add_stop(&mut self, offset: f64, rgba: [f64; 4]) {
        // Keep insertion order among equal offsets (stable sort by offset).
        let at = self.stops.iter().position(|(o, _)| *o > offset).unwrap_or(self.stops.len());
        self.stops.insert(at, (offset, rgba));
        self.cg = None;
    }
    fn cg(&mut self) -> Option<CFRetained<CGGradient>> {
        if self.stops.is_empty() {
            return None;
        }
        if self.cg.is_none() {
            let mut comps: Vec<CGFloat> = Vec::with_capacity(self.stops.len() * 4 + 8);
            let mut locs: Vec<CGFloat> = Vec::with_capacity(self.stops.len() + 2);
            for (o, c) in &self.stops {
                comps.extend_from_slice(c);
                locs.push(*o);
            }
            if self.stops.len() == 1 {
                comps.extend_from_slice(&self.stops[0].1);
                locs = vec![0.0, 1.0];
            }
            self.cg = unsafe { CGGradient::with_color_components(Some(&srgb()), comps.as_ptr(), locs.as_ptr(), locs.len()) };
        }
        self.cg.clone()
    }
}

pub(crate) struct Pattern {
    pub image: CFRetained<CGImage>,
    pub width: f64,
    pub height: f64,
    pub repeat_x: bool,
    pub repeat_y: bool,
    pub transform: CGAffineTransform,
}

#[derive(Clone)]
pub(crate) enum Paint {
    Color(CFRetained<CGColor>, f64),
    Gradient(Rc<std::cell::RefCell<Gradient>>),
    Pattern(Rc<Pattern>),
}

impl Paint {
    pub fn color(r: f64, g: f64, b: f64, a: f64) -> Paint {
        Paint::Color(CGColor::new_srgb(r, g, b, a), a)
    }
    fn is_invisible(&self) -> bool {
        matches!(self, Paint::Color(_, a) if *a <= 0.0)
    }
}

const UNBOUNDED: [i32; 5] = [17, 18, 19, 22, 24]; // copy, source-in, source-out, destination-in, destination-atop

pub(crate) fn composite_from_name(name: &str) -> Option<i32> {
    Some(match name {
        "source-over" => 0,
        "source-in" => 18,
        "source-out" => 19,
        "source-atop" => 20,
        "destination-over" => 21,
        "destination-in" => 22,
        "destination-out" => 23,
        "destination-atop" => 24,
        "lighter" | "plus-lighter" => 27,
        "copy" => 17,
        "xor" => 25,
        "multiply" => 1,
        "screen" => 2,
        "overlay" => 3,
        "darken" => 4,
        "lighten" => 5,
        "color-dodge" => 6,
        "color-burn" => 7,
        "hard-light" => 9,
        "soft-light" => 8,
        "difference" => 10,
        "exclusion" => 11,
        "hue" => 12,
        "saturation" => 13,
        "color" => 14,
        "luminosity" => 15,
        _ => return None,
    })
}

#[derive(Clone)]
pub(crate) struct State {
    pub ctm: CGAffineTransform,
    pub fill: Paint,
    pub stroke: Paint,
    pub line_width: f64,
    pub cap: CGLineCap,
    pub join: CGLineJoin,
    pub miter: f64,
    pub dash: Vec<f64>,
    pub dash_offset: f64,
    pub alpha: f64,
    pub blend: i32,
    pub shadow_x: f64,
    pub shadow_y: f64,
    pub shadow_blur: f64,
    pub shadow_color: Option<(CFRetained<CGColor>, f64)>,
    pub smoothing: bool,
    pub smoothing_quality: u8,
    pub font: Rc<ParsedFont>,
    pub resolved: Option<Rc<Font>>,
    /// 0 start, 1 end, 2 left, 3 right, 4 center
    pub align: u8,
    /// 0 alphabetic, 1 top, 2 hanging, 3 middle, 4 ideographic, 5 bottom
    pub baseline: u8,
    pub rtl: bool,
    pub letter_spacing: f64,
    pub word_spacing: f64,
    pub kerning: bool,
}

thread_local! {
    static DEFAULT_FONT: Rc<ParsedFont> = Rc::new(fonts::parse_shorthand("10px sans-serif").unwrap());
}

impl Default for State {
    fn default() -> Self {
        let black = Paint::color(0.0, 0.0, 0.0, 1.0);
        State {
            ctm: IDENTITY,
            fill: black.clone(),
            stroke: black,
            line_width: 1.0,
            cap: CGLineCap::Butt,
            join: CGLineJoin::Miter,
            miter: 10.0,
            dash: Vec::new(),
            dash_offset: 0.0,
            alpha: 1.0,
            blend: 0,
            shadow_x: 0.0,
            shadow_y: 0.0,
            shadow_blur: 0.0,
            shadow_color: None,
            smoothing: true,
            smoothing_quality: 0,
            font: DEFAULT_FONT.with(|f| f.clone()),
            resolved: None,
            align: 0,
            baseline: 0,
            rtl: false,
            letter_spacing: 0.0,
            word_spacing: 0.0,
            kerning: true,
        }
    }
}

impl State {
    fn shadow_visible(&self) -> bool {
        matches!(&self.shadow_color, Some((_, a)) if *a > 0.0) && (self.shadow_blur > 0.0 || self.shadow_x != 0.0 || self.shadow_y != 0.0)
    }
    pub fn font(&mut self) -> Rc<Font> {
        if self.resolved.is_none() {
            self.resolved = Some(fonts::resolve_parsed(&self.font));
        }
        self.resolved.clone().unwrap()
    }
}

/// What a draw call paints with.
#[derive(Clone, Copy, PartialEq)]
enum Use {
    Fill,
    Stroke,
}

// ----------------------------------------------------------------------------------- canvas

pub(crate) struct Canvas {
    pub cg: Option<CFRetained<CGContext>>,
    pub width: u32,
    pub height: u32,
    pub state: State,
    pub stack: Vec<State>,
    pub path: Path,
    /// set by every call that may change pixels
    pub dirty: bool,
}

impl Canvas {
    /// A context drawing into `data` (w×h premultiplied RGBA, already zeroed).
    pub fn new(data: *mut u8, width: u32, height: u32) -> Canvas {
        let cg = if width == 0 || height == 0 || data.is_null() {
            None
        } else {
            unsafe { CGBitmapContextCreate(data.cast(), width as usize, height as usize, 8, width as usize * 4, Some(&srgb()), CGImageAlphaInfo::PremultipliedLast.0) }
        };
        if let Some(cg) = &cg {
            // y-down canvas pixels on top of CG's y-up device space
            CGContext::translate_ctm(Some(cg), 0.0, height as f64);
            CGContext::scale_ctm(Some(cg), 1.0, -1.0);
            CGContext::set_should_antialias(Some(cg), true);
            CGContext::set_interpolation_quality(Some(cg), CGInterpolationQuality::Low);
            // Outer gstate: canvas save/restore push above this one.
            CGContext::save_g_state(Some(cg));
        }
        Canvas { cg, width, height, state: State::default(), stack: Vec::new(), path: Path::default(), dirty: false }
    }

    pub fn save(&mut self) {
        self.stack.push(self.state.clone());
        if let Some(cg) = &self.cg {
            CGContext::save_g_state(Some(cg));
        }
    }

    pub fn restore(&mut self) {
        if let Some(s) = self.stack.pop() {
            self.state = s;
            if let Some(cg) = &self.cg {
                CGContext::restore_g_state(Some(cg));
            }
        }
    }

    /// `ctx.reset()`: clear pixels, state, path and clip.
    pub fn reset(&mut self) {
        while !self.stack.is_empty() {
            self.restore();
        }
        if let Some(cg) = &self.cg {
            // drop the clip: back to the root gstate and push a fresh one
            CGContext::restore_g_state(Some(cg));
            CGContext::save_g_state(Some(cg));
        }
        self.state = State::default();
        self.path.clear();
        self.clear_all();
    }

    pub fn clear_all(&mut self) {
        if let Some(cg) = &self.cg {
            let data = objc2_core_graphics::CGBitmapContextGetData(Some(cg)) as *mut u8;
            if !data.is_null() {
                unsafe { std::ptr::write_bytes(data, 0, self.width as usize * self.height as usize * 4) };
            }
        }
        self.dirty = true;
    }

    fn invertible(&self) -> bool {
        invert(&self.state.ctm).is_some()
    }

    /// Run `draw` with the compositing state applied (alpha, blend, shadow), inside a
    /// transparency layer when the composite op affects pixels outside the shape (copy,
    /// source-in, …) or when several primitives must share one shadow.
    fn composite(&mut self, multi_primitive: bool, draw: impl FnOnce(&CGContext, &mut State)) {
        let Some(cg) = self.cg.clone() else { return };
        let s = &mut self.state;
        CGContext::save_g_state(Some(&cg));
        CGContext::set_alpha(Some(&cg), s.alpha);
        CGContext::set_blend_mode(Some(&cg), CGBlendMode(s.blend));
        let shadow = s.shadow_visible();
        if shadow {
            let (color, _) = s.shadow_color.as_ref().unwrap();
            // Shadow offsets are in device space (CG's base space is y-up); canvas blur is 2σ, CG's
            // blur parameter is σ·√2·… — calibrated against Chrome (see SHADOW_BLUR_SCALE).
            CGContext::set_shadow_with_color(Some(&cg), CGSize { width: s.shadow_x, height: -s.shadow_y }, s.shadow_blur * SHADOW_BLUR_SCALE, Some(color));
        }
        let layer = UNBOUNDED.contains(&s.blend) || (shadow && multi_primitive);
        if layer {
            unsafe { CGContext::begin_transparency_layer(Some(&cg), None) };
        }
        draw(&cg, s);
        if layer {
            CGContext::end_transparency_layer(Some(&cg));
        }
        CGContext::restore_g_state(Some(&cg));
        self.dirty = true;
    }

    fn paint_of(&self, u: Use) -> &Paint {
        if u == Use::Fill { &self.state.fill } else { &self.state.stroke }
    }

    /// Fill or stroke a device-space path (`path`) with the current paint.
    fn draw_path(&mut self, path: &CGPath, u: Use, evenodd: bool) {
        if !self.invertible() || self.cg.is_none() {
            return;
        }
        let paint = self.paint_of(u).clone();
        if paint.is_invisible() && !UNBOUNDED.contains(&self.state.blend) {
            return;
        }
        let multi = !matches!(paint, Paint::Color(..));
        self.composite(multi, |cg, s| {
            match u {
                Use::Fill => {
                    CGContext::add_path(Some(cg), Some(path));
                    match &paint {
                        Paint::Color(c, _) => {
                            CGContext::set_fill_color_with_color(Some(cg), Some(c));
                            if evenodd { CGContext::eo_fill_path(Some(cg)) } else { CGContext::fill_path(Some(cg)) }
                        }
                        _ => {
                            if evenodd { CGContext::eo_clip(Some(cg)) } else { CGContext::clip(Some(cg)) }
                            fill_clip_with(cg, &paint, &s.ctm);
                        }
                    }
                }
                Use::Stroke => {
                    let inv = invert(&s.ctm).unwrap();
                    let user = unsafe { CGPath::new_copy_by_transforming_path(Some(path), &inv) };
                    CGContext::concat_ctm(Some(cg), s.ctm);
                    CGContext::add_path(Some(cg), user.as_deref());
                    apply_line_state(cg, s);
                    match &paint {
                        Paint::Color(c, _) => {
                            CGContext::set_stroke_color_with_color(Some(cg), Some(c));
                            CGContext::stroke_path(Some(cg));
                        }
                        _ => {
                            CGContext::replace_path_with_stroked_path(Some(cg));
                            CGContext::clip(Some(cg));
                            if let Some(inv) = invert(&s.ctm) {
                                CGContext::concat_ctm(Some(cg), inv);
                            }
                            fill_clip_with(cg, &paint, &s.ctm);
                        }
                    }
                }
            }
        });
    }

    pub fn fill(&mut self, path2d: Option<&Path>, evenodd: bool) {
        let p = match path2d {
            Some(p) => p.transformed(&self.state.ctm),
            None => CGPath::new_copy(Some(&self.path.cg)).unwrap(),
        };
        self.draw_path(&p, Use::Fill, evenodd);
    }

    pub fn stroke(&mut self, path2d: Option<&Path>) {
        let p = match path2d {
            Some(p) => p.transformed(&self.state.ctm),
            None => CGPath::new_copy(Some(&self.path.cg)).unwrap(),
        };
        self.draw_path(&p, Use::Stroke, false);
    }

    pub fn clip(&mut self, path2d: Option<&Path>, evenodd: bool) {
        let Some(cg) = self.cg.clone() else { return };
        let p = match path2d {
            Some(p) => p.transformed(&self.state.ctm),
            None => CGPath::new_copy(Some(&self.path.cg)).unwrap(),
        };
        CGContext::add_path(Some(&cg), Some(&p));
        if CGContext::is_path_empty(Some(&cg)) {
            // clipping to an empty path clips everything
            CGContext::clip_to_rect(Some(&cg), rect(0.0, 0.0, 0.0, 0.0));
        } else if evenodd {
            CGContext::eo_clip(Some(&cg));
        } else {
            CGContext::clip(Some(&cg));
        }
    }

    pub fn is_point_in_path(&self, path2d: Option<&Path>, x: f64, y: f64, evenodd: bool) -> bool {
        if !finite(&[x, y]) {
            return false;
        }
        // The point is in canvas pixel space (untransformed), the path in device space.
        let p = match path2d {
            Some(p) => p.transformed(&self.state.ctm),
            None => CGPath::new_copy(Some(&self.path.cg)).unwrap(),
        };
        unsafe { CGPath::contains_point(Some(&p), std::ptr::null(), CGPoint { x, y }, evenodd) }
    }

    pub fn is_point_in_stroke(&self, path2d: Option<&Path>, x: f64, y: f64) -> bool {
        let Some(inv) = invert(&self.state.ctm) else { return false };
        if !finite(&[x, y]) {
            return false;
        }
        let user = match path2d {
            Some(p) => CGPath::new_copy(Some(&p.cg)).unwrap(),
            None => unsafe { CGPath::new_copy_by_transforming_path(Some(&self.path.cg), &inv) }.unwrap(),
        };
        let s = &self.state;
        let stroked = unsafe { CGPath::new_copy_by_stroking_path(Some(&user), &s.ctm, s.line_width, s.cap, s.join, s.miter) };
        stroked.is_some_and(|sp| unsafe { CGPath::contains_point(Some(&sp), std::ptr::null(), CGPoint { x, y }, false) })
    }

    pub fn fill_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        if !finite(&[x, y, w, h]) || w == 0.0 || h == 0.0 {
            return;
        }
        let mut p = Path::default();
        p.rect(&self.state.ctm, x, y, w, h);
        self.draw_path(&p.cg.clone(), Use::Fill, false);
    }

    pub fn stroke_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        if !finite(&[x, y, w, h]) || (w == 0.0 && h == 0.0) {
            return;
        }
        let mut p = Path::default();
        let m = self.state.ctm;
        if w == 0.0 || h == 0.0 {
            p.move_to(&m, x, y);
            p.line_to(&m, x + w, y + h);
        } else {
            p.rect(&m, x, y, w, h);
        }
        self.draw_path(&p.cg.clone(), Use::Stroke, false);
    }

    pub fn clear_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        if !finite(&[x, y, w, h]) || !self.invertible() {
            return;
        }
        let Some(cg) = self.cg.clone() else { return };
        CGContext::save_g_state(Some(&cg));
        CGContext::concat_ctm(Some(&cg), self.state.ctm);
        CGContext::set_blend_mode(Some(&cg), CGBlendMode::Clear);
        CGContext::set_alpha(Some(&cg), 1.0);
        CGContext::add_rect(Some(&cg), rect(x, y, w, h));
        CGContext::fill_path(Some(&cg));
        CGContext::restore_g_state(Some(&cg));
        self.dirty = true;
    }

    /// `drawImage` with the source rect already normalized and clipped by the caller.
    #[allow(clippy::too_many_arguments)]
    pub fn draw_image(&mut self, img: &CGImage, iw: f64, ih: f64, sx: f64, sy: f64, sw: f64, sh: f64, dx: f64, dy: f64, dw: f64, dh: f64) {
        if !self.invertible() || sw <= 0.0 || sh <= 0.0 || dw == 0.0 || dh == 0.0 || !finite(&[sx, sy, sw, sh, dx, dy, dw, dh]) {
            return;
        }
        let integral = sx.fract() == 0.0 && sy.fract() == 0.0 && sw.fract() == 0.0 && sh.fract() == 0.0;
        let whole = sx == 0.0 && sy == 0.0 && sw == iw && sh == ih;
        let sub = if whole || !integral { None } else { CGImage::with_image_in_rect(Some(img), rect(sx, sy, sw, sh)) };
        let smoothing = self.state.smoothing;
        let quality = self.state.smoothing_quality;
        self.composite(false, |cg, s| {
            CGContext::concat_ctm(Some(cg), s.ctm);
            CGContext::set_interpolation_quality(
                Some(cg),
                if !smoothing {
                    CGInterpolationQuality::None
                } else {
                    match quality {
                        2 => CGInterpolationQuality::High,
                        1 => CGInterpolationQuality::Medium,
                        _ => CGInterpolationQuality::Low,
                    }
                },
            );
            // Images are y-up in CG: flip around the destination rect.
            if let Some(sub) = &sub {
                CGContext::translate_ctm(Some(cg), dx, dy + dh);
                CGContext::scale_ctm(Some(cg), 1.0, -1.0);
                CGContext::draw_image(Some(cg), rect(0.0, 0.0, dw, dh), Some(sub));
            } else if whole {
                CGContext::translate_ctm(Some(cg), dx, dy + dh);
                CGContext::scale_ctm(Some(cg), 1.0, -1.0);
                CGContext::draw_image(Some(cg), rect(0.0, 0.0, dw, dh), Some(img));
            } else {
                // Fractional source rect: clip to the destination and draw the whole image scaled
                // so the source rect lands on it.
                CGContext::clip_to_rect(Some(cg), rect(dx.min(dx + dw), dy.min(dy + dh), dw.abs(), dh.abs()));
                let kx = dw / sw;
                let ky = dh / sh;
                let ox = dx - sx * kx;
                let oy = dy - sy * ky;
                CGContext::translate_ctm(Some(cg), ox, oy + ih * ky);
                CGContext::scale_ctm(Some(cg), 1.0, -1.0);
                CGContext::draw_image(Some(cg), rect(0.0, 0.0, iw * kx, ih * ky), Some(img));
            }
        });
    }

    /// Unpremultiplied RGBA of a device-space rect into `out` (zeros outside the bitmap).
    pub fn get_image_data(&self, data: &[u8], sx: i64, sy: i64, sw: usize, sh: usize, out: &mut [u8]) {
        let (w, h) = (self.width as i64, self.height as i64);
        for row in 0..sh as i64 {
            let y = sy + row;
            let o = &mut out[row as usize * sw * 4..(row as usize + 1) * sw * 4];
            if y < 0 || y >= h {
                o.fill(0);
                continue;
            }
            for col in 0..sw as i64 {
                let x = sx + col;
                let d = &mut o[col as usize * 4..col as usize * 4 + 4];
                if x < 0 || x >= w {
                    d.fill(0);
                    continue;
                }
                let i = ((y * w + x) * 4) as usize;
                let a = data[i + 3];
                d[0] = unpremul(data[i], a);
                d[1] = unpremul(data[i + 1], a);
                d[2] = unpremul(data[i + 2], a);
                d[3] = a;
            }
        }
    }

    /// Write unpremultiplied RGBA (`src`, `sw`×`sh`) at (dx, dy), limited to the dirty rect.
    #[allow(clippy::too_many_arguments)]
    pub fn put_image_data(&mut self, data: &mut [u8], src: &[u8], sw: usize, sh: usize, dx: i64, dy: i64, dirty: (i64, i64, i64, i64)) {
        let (mut x0, mut y0, mut x1, mut y1) = dirty;
        x0 = x0.max(0);
        y0 = y0.max(0);
        x1 = x1.min(sw as i64);
        y1 = y1.min(sh as i64);
        let (w, h) = (self.width as i64, self.height as i64);
        for sy in y0..y1 {
            let ty = dy + sy;
            if ty < 0 || ty >= h {
                continue;
            }
            for sx in x0..x1 {
                let tx = dx + sx;
                if tx < 0 || tx >= w {
                    continue;
                }
                let s = ((sy * sw as i64 + sx) * 4) as usize;
                let t = ((ty * w + tx) * 4) as usize;
                let a = src[s + 3];
                data[t] = premul(src[s], a);
                data[t + 1] = premul(src[s + 1], a);
                data[t + 2] = premul(src[s + 2], a);
                data[t + 3] = a;
            }
        }
        self.dirty = true;
    }

    /// fillText / strokeText.
    pub fn draw_text(&mut self, txt: &[u16], x: f64, y: f64, max_width: Option<f64>, u: Use2) {
        if !finite(&[x, y]) || !self.invertible() || self.cg.is_none() {
            return;
        }
        if let Some(mw) = max_width {
            if !(mw > 0.0) {
                return;
            }
        }
        let font = self.state.font();
        let layout = text::layout(&font, txt, self.state.letter_spacing, self.state.word_spacing, self.state.kerning);
        if layout.runs.is_empty() {
            return;
        }
        let width = layout.width;
        let scale_x = match max_width {
            Some(mw) if mw < width && width > 0.0 => mw / width,
            _ => 1.0,
        };
        let w = width * scale_x;
        let dx = match (self.state.align, self.state.rtl) {
            (4, _) => -w / 2.0,
            (3, _) | (1, false) | (0, true) => -w,
            _ => 0.0,
        };
        let dy = text::baseline_offset(&font, self.state.baseline);
        let m = concat(&CGAffineTransform { a: scale_x, b: 0.0, c: 0.0, d: 1.0, tx: x + dx, ty: y + dy }, &self.state.ctm);
        let use_ = if u == Use2::Fill { Use::Fill } else { Use::Stroke };
        let paint = self.paint_of(use_).clone();
        self.composite(true, |cg, s| text::draw(cg, s, &layout, &m, &paint, u == Use2::Stroke));
    }
}

#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Use2 {
    Fill,
    Stroke,
}

/// CG's shadow blur parameter for a canvas `shadowBlur` (Chrome: Gaussian σ = blur / 2).
pub(crate) const SHADOW_BLUR_SCALE: f64 = 1.0;

pub(crate) fn apply_line_state(cg: &CGContext, s: &State) {
    CGContext::set_line_width(Some(cg), s.line_width);
    CGContext::set_line_cap(Some(cg), s.cap);
    CGContext::set_line_join(Some(cg), s.join);
    CGContext::set_miter_limit(Some(cg), s.miter);
    if !s.dash.is_empty() {
        unsafe { CGContext::set_line_dash(Some(cg), s.dash_offset, s.dash.as_ptr(), s.dash.len()) };
    }
}

/// Paint a gradient or pattern over the current clip. The CTM on entry is canvas pixels (device);
/// paint coordinates are in user space (`ctm`).
pub(crate) fn fill_clip_with(cg: &CGContext, paint: &Paint, ctm: &CGAffineTransform) {
    CGContext::concat_ctm(Some(cg), *ctm);
    match paint {
        Paint::Color(c, _) => {
            CGContext::set_fill_color_with_color(Some(cg), Some(c));
            let b = CGContext::clip_bounding_box(Some(cg));
            CGContext::fill_rect(Some(cg), b);
        }
        Paint::Gradient(g) => {
            let mut g = g.borrow_mut();
            let kind = g.kind;
            let Some(grad) = g.cg() else { return };
            let ext = CGGradientDrawingOptions::DrawsBeforeStartLocation | CGGradientDrawingOptions::DrawsAfterEndLocation;
            match kind {
                GradientKind::Linear(x0, y0, x1, y1) => {
                    if x0 == x1 && y0 == y1 {
                        return;
                    }
                    CGContext::draw_linear_gradient(Some(cg), Some(&grad), CGPoint { x: x0, y: y0 }, CGPoint { x: x1, y: y1 }, ext);
                }
                GradientKind::Radial(x0, y0, r0, x1, y1, r1) => {
                    if x0 == x1 && y0 == y1 && r0 == r1 {
                        return;
                    }
                    CGContext::draw_radial_gradient(Some(cg), Some(&grad), CGPoint { x: x0, y: y0 }, r0, CGPoint { x: x1, y: y1 }, r1, ext);
                }
                GradientKind::Conic(angle, x, y) => {
                    // CG's conic gradient runs counter-clockwise in its (y-up) space; under our
                    // y-flip that is clockwise on screen, like canvas. Mirror to keep the angle.
                    cg.draw_conic_gradient(Some(&grad), CGPoint { x, y }, -angle);
                }
            }
        }
        Paint::Pattern(p) => {
            CGContext::concat_ctm(Some(cg), p.transform);
            if !p.repeat_x || !p.repeat_y {
                let big = 1e7;
                let (x0, w) = if p.repeat_x { (-big, 2.0 * big) } else { (0.0, p.width) };
                let (y0, h) = if p.repeat_y { (-big, 2.0 * big) } else { (0.0, p.height) };
                CGContext::clip_to_rect(Some(cg), rect(x0, y0, w, h));
            }
            // Tiles are drawn y-up: flip so each tile is upright with its top-left at multiples
            // of the tile size.
            CGContext::scale_ctm(Some(cg), 1.0, -1.0);
            if p.repeat_x || p.repeat_y {
                CGContext::draw_tiled_image(Some(cg), rect(0.0, -p.height, p.width, p.height), Some(&p.image));
            } else {
                CGContext::draw_image(Some(cg), rect(0.0, -p.height, p.width, p.height), Some(&p.image));
            }
        }
    }
}