| 1 | //! `anyrender` backend on CoreGraphics + CoreText (Apple platforms only): the same |
| 2 | //! blitz-paint scene that `vello_cpu` rasterises, drawn by the platform instead. |
| 3 | //! Glyphs go through `CTFontDrawGlyphs` from the very font file parley shaped |
| 4 | //! with, so text antialiasing, hinting and colour emoji are the system's own; |
| 5 | //! fills, strokes, gradients, images and clips go to the CGContext over the |
| 6 | //! caller's RGBA buffer. Layout, cascade and shaping stay in Rust — only the |
| 7 | //! pixels change hands (docs/blitz-experiment.md, "PaintScene on CoreGraphics"). |
| 8 | //! |
| 9 | //! Selected with `TWB_BACKEND=cg` or `twb_set_backend(handle, "cg")`. Raw FFI, |
| 10 | //! no new crates. Known gaps: `Extend::Repeat`/`Reflect` gradients draw once, |
| 11 | //! sweep gradients are 96 flat wedges, CSS filters are ignored, gradient text |
| 12 | //! takes its first stop colour. |
| 13 | |
| 14 | #![allow(non_upper_case_globals, non_snake_case, clippy::too_many_arguments)] |
| 15 | |
| 16 | use anyrender::{Filter, Glyph, ImageRenderer, NormalizedCoord, Paint, PaintRef, PaintScene, RenderContext}; |
| 17 | use kurbo::{Affine, Cap, Join, PathEl, Point, Rect, RoundedRect, Shape, Stroke}; |
| 18 | use peniko::color::Srgb; |
| 19 | use peniko::{BlendMode, Color, ColorStops, Compose, Extend, Fill, FontData, Gradient, GradientKind, ImageAlphaType, ImageBrushRef, ImageData, ImageFormat |
| 20 | use skrifa::MetadataProvider; |
| 21 | use std::collections::HashMap; |
| 22 | use std::ffi::{c_char, c_void}; |
| 23 | use std::ptr::null; |
| 24 | use std::sync::{Arc, Mutex, OnceLock}; |
| 25 | |
| 26 | const TOLERANCE: f64 = 0.1; |
| 27 | |
| 28 | // ───────────────────────── FFI ───────────────────────── |
| 29 | |
| 30 | type CFTypeRef = *const c_void; |
| 31 | type CFDataRef = *const c_void; |
| 32 | type CFStringRef = *const c_void; |
| 33 | type CFArrayRef = *const c_void; |
| 34 | type CFDictionaryRef = *const c_void; |
| 35 | type CFNumberRef = *const c_void; |
| 36 | type CFIndex = isize; |
| 37 | type CGContextRef = *mut c_void; |
| 38 | type CGColorSpaceRef = *mut c_void; |
| 39 | type CGPathRef = *mut c_void; |
| 40 | type CGGradientRef = *mut c_void; |
| 41 | type CGImageRef = *mut c_void; |
| 42 | type CGDataProviderRef = *mut c_void; |
| 43 | type CTFontRef = *const c_void; |
| 44 | type CTFontDescriptorRef = *const c_void; |
| 45 | type CGGlyph = u16; |
| 46 | |
| 47 | #[repr(C)] |
| 48 | #[derive(Clone, Copy)] |
| 49 | struct CGPoint { |
| 50 | x: f64, |
| 51 | y: f64, |
| 52 | } |
| 53 | #[repr(C)] |
| 54 | #[derive(Clone, Copy)] |
| 55 | struct CGSize { |
| 56 | width: f64, |
| 57 | height: f64, |
| 58 | } |
| 59 | #[repr(C)] |
| 60 | #[derive(Clone, Copy)] |
| 61 | struct CGRect { |
| 62 | origin: CGPoint, |
| 63 | size: CGSize, |
| 64 | } |
| 65 | #[repr(C)] |
| 66 | #[derive(Clone, Copy)] |
| 67 | struct CGAffineTransform { |
| 68 | a: f64, |
| 69 | b: f64, |
| 70 | c: f64, |
| 71 | d: f64, |
| 72 | tx: f64, |
| 73 | ty: f64, |
| 74 | } |
| 75 | |
| 76 | const kCFStringEncodingUTF8: u32 = 0x0800_0100; |
| 77 | const kCFNumberSInt32Type: CFIndex = 3; |
| 78 | const kCFNumberDoubleType: CFIndex = 13; |
| 79 | const kCGImageAlphaPremultipliedLast: u32 = 1; |
| 80 | const kCGImageAlphaPremultipliedFirst: u32 = 2; |
| 81 | const kCGImageAlphaLast: u32 = 3; |
| 82 | const kCGImageAlphaFirst: u32 = 4; |
| 83 | const kCGBitmapByteOrder32Little: u32 = 2 << 12; |
| 84 | const kCGBitmapByteOrder32Big: u32 = 4 << 12; |
| 85 | const kCGGradientDrawsBeforeStartLocation: u32 = 1; |
| 86 | const kCGGradientDrawsAfterEndLocation: u32 = 2; |
| 87 | const kCGTextFill: i32 = 0; |
| 88 | const kCGTextStroke: i32 = 1; |
| 89 | const kCGRenderingIntentDefault: i32 = 0; |
| 90 | |
| 91 | #[link(name = "CoreFoundation", kind = "framework")] |
| 92 | extern "C" { |
| 93 | static kCFTypeDictionaryKeyCallBacks: c_void; |
| 94 | static kCFTypeDictionaryValueCallBacks: c_void; |
| 95 | fn CFRelease(cf: CFTypeRef); |
| 96 | fn CFDataCreate(allocator: *const c_void, bytes: *const u8, length: CFIndex) -> CFDataRef; |
| 97 | fn CFStringGetCString(s: CFStringRef, buffer: *mut c_char, size: CFIndex, encoding: u32) -> u8; |
| 98 | fn CFArrayGetCount(array: CFArrayRef) -> CFIndex; |
| 99 | fn CFArrayGetValueAtIndex(array: CFArrayRef, idx: CFIndex) -> *const c_void; |
| 100 | fn CFDictionaryCreate( |
| 101 | allocator: *const c_void, |
| 102 | keys: *const *const c_void, |
| 103 | values: *const *const c_void, |
| 104 | count: CFIndex, |
| 105 | key_callbacks: *const c_void, |
| 106 | value_callbacks: *const c_void, |
| 107 | ) -> CFDictionaryRef; |
| 108 | fn CFNumberCreate(allocator: *const c_void, the_type: CFIndex, value: *const c_void) -> CFNumberRef; |
| 109 | } |
| 110 | |
| 111 | #[link(name = "CoreGraphics", kind = "framework")] |
| 112 | extern "C" { |
| 113 | fn CGColorSpaceCreateDeviceRGB() -> CGColorSpaceRef; |
| 114 | fn CGColorSpaceRelease(space: CGColorSpaceRef); |
| 115 | fn CGBitmapContextCreate( |
| 116 | data: *mut c_void, |
| 117 | width: usize, |
| 118 | height: usize, |
| 119 | bits_per_component: usize, |
| 120 | bytes_per_row: usize, |
| 121 | space: CGColorSpaceRef, |
| 122 | bitmap_info: u32, |
| 123 | ) -> CGContextRef; |
| 124 | fn CGContextRelease(c: CGContextRef); |
| 125 | fn CGContextSaveGState(c: CGContextRef); |
| 126 | fn CGContextRestoreGState(c: CGContextRef); |
| 127 | fn CGContextConcatCTM(c: CGContextRef, t: CGAffineTransform); |
| 128 | fn CGContextTranslateCTM(c: CGContextRef, tx: f64, ty: f64); |
| 129 | fn CGContextScaleCTM(c: CGContextRef, sx: f64, sy: f64); |
| 130 | fn CGContextSetRGBFillColor(c: CGContextRef, r: f64, g: f64, b: f64, a: f64); |
| 131 | fn CGContextSetRGBStrokeColor(c: CGContextRef, r: f64, g: f64, b: f64, a: f64); |
| 132 | fn CGContextBeginPath(c: CGContextRef); |
| 133 | fn CGContextAddPath(c: CGContextRef, path: CGPathRef); |
| 134 | fn CGContextFillPath(c: CGContextRef); |
| 135 | fn CGContextEOFillPath(c: CGContextRef); |
| 136 | fn CGContextStrokePath(c: CGContextRef); |
| 137 | fn CGContextClip(c: CGContextRef); |
| 138 | fn CGContextEOClip(c: CGContextRef); |
| 139 | fn CGContextReplacePathWithStrokedPath(c: CGContextRef); |
| 140 | fn CGContextSetLineWidth(c: CGContextRef, width: f64); |
| 141 | fn CGContextSetLineJoin(c: CGContextRef, join: i32); |
| 142 | fn CGContextSetLineCap(c: CGContextRef, cap: i32); |
| 143 | fn CGContextSetMiterLimit(c: CGContextRef, limit: f64); |
| 144 | fn CGContextSetLineDash(c: CGContextRef, phase: f64, lengths: *const f64, count: usize); |
| 145 | fn CGContextSetAlpha(c: CGContextRef, alpha: f64); |
| 146 | fn CGContextSetBlendMode(c: CGContextRef, mode: i32); |
| 147 | fn CGContextBeginTransparencyLayer(c: CGContextRef, aux: *const c_void); |
| 148 | fn CGContextEndTransparencyLayer(c: CGContextRef); |
| 149 | fn CGContextSetShouldAntialias(c: CGContextRef, b: bool); |
| 150 | fn CGContextSetAllowsAntialiasing(c: CGContextRef, b: bool); |
| 151 | fn CGContextSetShouldSmoothFonts(c: CGContextRef, b: bool); |
| 152 | fn CGContextSetAllowsFontSmoothing(c: CGContextRef, b: bool); |
| 153 | fn CGContextSetShouldSubpixelPositionFonts(c: CGContextRef, b: bool); |
| 154 | fn CGContextSetAllowsFontSubpixelPositioning(c: CGContextRef, b: bool); |
| 155 | fn CGContextSetShouldSubpixelQuantizeFonts(c: CGContextRef, b: bool); |
| 156 | fn CGContextSetAllowsFontSubpixelQuantization(c: CGContextRef, b: bool); |
| 157 | fn CGContextSetTextMatrix(c: CGContextRef, t: CGAffineTransform); |
| 158 | fn CGContextSetTextDrawingMode(c: CGContextRef, mode: i32); |
| 159 | fn CGContextSetInterpolationQuality(c: CGContextRef, quality: i32); |
| 160 | fn CGContextDrawLinearGradient(c: CGContextRef, g: CGGradientRef, start: CGPoint, end: CGPoint, options: u32); |
| 161 | fn CGContextDrawRadialGradient( |
| 162 | c: CGContextRef, |
| 163 | g: CGGradientRef, |
| 164 | start_center: CGPoint, |
| 165 | start_radius: f64, |
| 166 | end_center: CGPoint, |
| 167 | end_radius: f64, |
| 168 | options: u32, |
| 169 | ); |
| 170 | fn CGGradientCreateWithColorComponents(space: CGColorSpaceRef, components: *const f64, locations: *const f64, count: usize) -> CGGradientRef; |
| 171 | fn CGGradientRelease(g: CGGradientRef); |
| 172 | fn CGContextDrawImage(c: CGContextRef, rect: CGRect, image: CGImageRef); |
| 173 | fn CGContextDrawTiledImage(c: CGContextRef, rect: CGRect, image: CGImageRef); |
| 174 | fn CGImageCreate( |
| 175 | width: usize, |
| 176 | height: usize, |
| 177 | bits_per_component: usize, |
| 178 | bits_per_pixel: usize, |
| 179 | bytes_per_row: usize, |
| 180 | space: CGColorSpaceRef, |
| 181 | bitmap_info: u32, |
| 182 | provider: CGDataProviderRef, |
| 183 | decode: *const f64, |
| 184 | should_interpolate: bool, |
| 185 | intent: i32, |
| 186 | ) -> CGImageRef; |
| 187 | fn CGImageRelease(image: CGImageRef); |
| 188 | fn CGDataProviderCreateWithCFData(data: CFDataRef) -> CGDataProviderRef; |
| 189 | fn CGDataProviderRelease(provider: CGDataProviderRef); |
| 190 | fn CGPathCreateMutable() -> CGPathRef; |
| 191 | fn CGPathMoveToPoint(path: CGPathRef, m: *const CGAffineTransform, x: f64, y: f64); |
| 192 | fn CGPathAddLineToPoint(path: CGPathRef, m: *const CGAffineTransform, x: f64, y: f64); |
| 193 | fn CGPathAddQuadCurveToPoint(path: CGPathRef, m: *const CGAffineTransform, cpx: f64, cpy: f64, x: f64, y: f64); |
| 194 | fn CGPathAddCurveToPoint(path: CGPathRef, m: *const CGAffineTransform, c1x: f64, c1y: f64, c2x: f64, c2y: f64, x |
| 195 | fn CGPathCloseSubpath(path: CGPathRef); |
| 196 | fn CGPathGetBoundingBox(path: CGPathRef) -> CGRect; |
| 197 | fn CGPathRelease(path: CGPathRef); |
| 198 | } |
| 199 | |
| 200 | #[link(name = "CoreText", kind = "framework")] |
| 201 | extern "C" { |
| 202 | static kCTFontVariationAttribute: CFStringRef; |
| 203 | fn CTFontCreateWithFontDescriptor(descriptor: CTFontDescriptorRef, size: f64, matrix: *const CGAffineTransform) -> CTFontRef; |
| 204 | fn CTFontCreateCopyWithAttributes(font: CTFontRef, size: f64, matrix: *const CGAffineTransform, attributes: CTFontDescriptorRef) -> CTFontRef; |
| 205 | fn CTFontDrawGlyphs(font: CTFontRef, glyphs: *const CGGlyph, positions: *const CGPoint, count: usize, context: CGContextRef); |
| 206 | fn CTFontCopyPostScriptName(font: CTFontRef) -> CFStringRef; |
| 207 | fn CTFontDescriptorCreateWithAttributes(attributes: CFDictionaryRef) -> CTFontDescriptorRef; |
| 208 | fn CTFontManagerCreateFontDescriptorsFromData(data: CFDataRef) -> CFArrayRef; |
| 209 | } |
| 210 | |
| 211 | // ───────────────────────── helpers ───────────────────────── |
| 212 | |
| 213 | fn cg_affine(a: Affine) -> CGAffineTransform { |
| 214 | let [a0, b, c, d, tx, ty] = a.as_coeffs(); |
| 215 | CGAffineTransform { a: a0, b, c, d, tx, ty } |
| 216 | } |
| 217 | |
| 218 | fn pt(p: Point) -> CGPoint { |
| 219 | CGPoint { x: p.x, y: p.y } |
| 220 | } |
| 221 | |
| 222 | fn rgba(c: Color) -> [f64; 4] { |
| 223 | let [r, g, b, a] = c.components; |
| 224 | [r.clamp(0.0, 1.0) as f64, g.clamp(0.0, 1.0) as f64, b.clamp(0.0, 1.0) as |
| 225 | } |
| 226 | |
| 227 | fn cf_to_string(s: CFStringRef) -> String { |
| 228 | if s.is_null() { |
| 229 | return String::new(); |
| 230 | } |
| 231 | let mut buf = vec![0u8; 512]; |
| 232 | let ok = unsafe { CFStringGetCString(s, buf.as_mut_ptr() as *mut c_char, buf.len() as CFIndex, kCFStringEncodingUTF8) }; |
| 233 | if ok == 0 { |
| 234 | return String::new(); |
| 235 | } |
| 236 | let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); |
| 237 | String::from_utf8_lossy(&buf[..end]).into_owned() |
| 238 | } |
| 239 | |
| 240 | /// A CGPath from any kurbo shape; `transform` bakes an affine into the points |
| 241 | /// (for clips, which must not disturb the CTM). |
| 242 | unsafe fn cg_path(shape: &impl Shape, transform: Option<Affine>) -> CGPathRef { |
| 243 | let path = CGPathCreateMutable(); |
| 244 | let t = |p: Point| transform.map_or(p, |a| a * p); |
| 245 | let mut open = false; |
| 246 | for el in shape.path_elements(TOLERANCE) { |
| 247 | match el { |
| 248 | PathEl::MoveTo(p) => { |
| 249 | let p = t(p); |
| 250 | CGPathMoveToPoint(path, null(), p.x, p.y); |
| 251 | open = true; |
| 252 | } |
| 253 | PathEl::LineTo(p) => { |
| 254 | let p = t(p); |
| 255 | if open { |
| 256 | CGPathAddLineToPoint(path, null(), p.x, p.y); |
| 257 | } else { |
| 258 | CGPathMoveToPoint(path, null(), p.x, p.y); |
| 259 | open = true; |
| 260 | } |
| 261 | } |
| 262 | PathEl::QuadTo(c, p) => { |
| 263 | let (c, p) = (t(c), t(p)); |
| 264 | if !open { |
| 265 | CGPathMoveToPoint(path, null(), c.x, c.y); |
| 266 | open = true; |
| 267 | } |
| 268 | CGPathAddQuadCurveToPoint(path, null(), c.x, c.y, p.x, p.y); |
| 269 | } |
| 270 | PathEl::CurveTo(c1, c2, p) => { |
| 271 | let (c1, c2, p) = (t(c1), t(c2), t(p)); |
| 272 | if !open { |
| 273 | CGPathMoveToPoint(path, null(), c1.x, c1.y); |
| 274 | open = true; |
| 275 | } |
| 276 | CGPathAddCurveToPoint(path, null(), c1.x, c1.y, c2.x, c2.y, p.x, p.y); |
| 277 | } |
| 278 | PathEl::ClosePath => { |
| 279 | if open { |
| 280 | CGPathCloseSubpath(path); |
| 281 | } |
| 282 | open = false; |
| 283 | } |
| 284 | } |
| 285 | } |
| 286 | path |
| 287 | } |
| 288 | |
| 289 | fn blend_mode(b: BlendMode) -> i32 { |
| 290 | // CGBlendMode numbering; peniko's HardLight/SoftLight are swapped relative to CG. |
| 291 | match b.compose { |
| 292 | Compose::SrcOver => match b.mix { |
| 293 | Mix::Normal => 0, |
| 294 | Mix::Multiply => 1, |
| 295 | Mix::Screen => 2, |
| 296 | Mix::Overlay => 3, |
| 297 | Mix::Darken => 4, |
| 298 | Mix::Lighten => 5, |
| 299 | Mix::ColorDodge => 6, |
| 300 | Mix::ColorBurn => 7, |
| 301 | Mix::HardLight => 9, |
| 302 | Mix::SoftLight => 8, |
| 303 | Mix::Difference => 10, |
| 304 | Mix::Exclusion => 11, |
| 305 | Mix::Hue => 12, |
| 306 | Mix::Saturation => 13, |
| 307 | Mix::Color => 14, |
| 308 | Mix::Luminosity => 15, |
| 309 | }, |
| 310 | Compose::Clear => 16, |
| 311 | Compose::Copy => 17, |
| 312 | Compose::SrcIn => 18, |
| 313 | Compose::SrcOut => 19, |
| 314 | Compose::SrcAtop => 20, |
| 315 | Compose::DestOver => 21, |
| 316 | Compose::DestIn => 22, |
| 317 | Compose::DestOut => 23, |
| 318 | Compose::DestAtop => 24, |
| 319 | Compose::Xor => 25, |
| 320 | Compose::Plus | Compose::PlusLighter => 27, |
| 321 | Compose::Dest => 0, |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | fn is_plain(b: BlendMode) -> bool { |
| 326 | matches!(b.compose, Compose::SrcOver) && matches!(b.mix, Mix::Normal) |
| 327 | } |
| 328 | |
| 329 | /// Colour at `t` along the stops, linearly in sRGB (what CG does too). |
| 330 | fn sample_stops(stops: &ColorStops, t: f32) -> [f64; 4] { |
| 331 | let n = stops.len(); |
| 332 | if n == 0 { |
| 333 | return [0.0; 4]; |
| 334 | } |
| 335 | let col = |i: usize| stops[i].color.to_alpha_color::<Srgb>(); |
| 336 | if t <= stops[0].offset { |
| 337 | return rgba(col(0)); |
| 338 | } |
| 339 | for i in 1..n { |
| 340 | if t <= stops[i].offset { |
| 341 | let (a, b) = (stops[i - 1], stops[i]); |
| 342 | let span = (b.offset - a.offset).max(1e-6); |
| 343 | let f = ((t - a.offset) / span).clamp(0.0, 1.0); |
| 344 | let ca = col(i - 1).components; |
| 345 | let cb = col(i).components; |
| 346 | let mut out = [0.0; 4]; |
| 347 | for k in 0..4 { |
| 348 | out[k] = (ca[k] + (cb[k] - ca[k]) * f).clamp(0.0, 1.0) as f64; |
| 349 | } |
| 350 | return out; |
| 351 | } |
| 352 | } |
| 353 | rgba(col(n - 1)) |
| 354 | } |
| 355 | |
| 356 | // ───────────────────────── font cache ───────────────────────── |
| 357 | |
| 358 | #[derive(Hash, PartialEq, Eq)] |
| 359 | struct FontKey { |
| 360 | blob: u64, |
| 361 | index: u32, |
| 362 | size: u32, |
| 363 | coords: Vec<i16>, |
| 364 | } |
| 365 | |
| 366 | struct Fonts { |
| 367 | /// (blob id, face index) → CTFont at a nominal size, created from the font bytes. |
| 368 | base: HashMap<(u64, u32), usize>, |
| 369 | sized: HashMap<FontKey, usize>, |
| 370 | } |
| 371 | unsafe impl Send for Fonts {} |
| 372 | static FONTS: OnceLock<Mutex<Fonts>> = OnceLock::new(); |
| 373 | |
| 374 | fn fonts() -> &'static Mutex<Fonts> { |
| 375 | FONTS.get_or_init(|| Mutex::new(Fonts { base: HashMap::new(), sized: HashMap::new() })) |
| 376 | } |
| 377 | |
| 378 | /// The PostScript name skrifa reads from the face; the fallback lookup key. |
| 379 | fn postscript_name(font: &FontData) -> Option<String> { |
| 380 | let fr = skrifa::FontRef::from_index(font.data.data(), font.index).ok()?; |
| 381 | fr.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).english_or_first().map(|s| s.to_string()) |
| 382 | } |
| 383 | |
| 384 | /// User-space values for the non-default variation axes (normalized F2Dot14 → axis units). |
| 385 | fn axis_values(font: &FontData, coords: &[NormalizedCoord]) -> Vec<(u32, f64)> { |
| 386 | let Ok(fr) = skrifa::FontRef::from_index(font.data.data(), font.index) else { return Vec::new() }; |
| 387 | let mut out = Vec::new(); |
| 388 | for (i, axis) in fr.axes().iter().enumerate() { |
| 389 | let n = coords.get(i).copied().unwrap_or(0) as f64 / 16384.0; |
| 390 | if n == 0.0 { |
| 391 | continue; |
| 392 | } |
| 393 | let (min, def, max) = (axis.min_value() as f64, axis.default_value() as f64, axis.max_value() as f64); |
| 394 | let v = if n < 0.0 { def + n * (def - min) } else { def + n * (max - def) }; |
| 395 | out.push((u32::from_be_bytes(axis.tag().to_be_bytes()), v)); |
| 396 | } |
| 397 | out |
| 398 | } |
| 399 | |
| 400 | unsafe fn base_font(font: &FontData) -> CTFontRef { |
| 401 | let key = (font.data.id(), font.index); |
| 402 | if let Some(&f) = fonts().lock().unwrap().base.get(&key) { |
| 403 | return f as CTFontRef; |
| 404 | } |
| 405 | let mut created: CTFontRef = null(); |
| 406 | // Open the very bytes parley shaped with. CoreText lists one descriptor per face of a |
| 407 | // collection, but for a variable font it lists every named instance (SF: 369, Ultralight |
| 408 | // first), so the face is picked by the PostScript name skrifa reads from the default |
| 409 | // instance; the collection index is the fallback. Hidden system fonts cannot be |
| 410 | // created by name (".SFNS-Regular" yields Times), hence no name lookup. |
| 411 | let want = postscript_name(font); |
| 412 | let bytes = font.data.data(); |
| 413 | let data = CFDataCreate(null(), bytes.as_ptr(), bytes.len() as CFIndex); |
| 414 | if !data.is_null() { |
| 415 | let descs = CTFontManagerCreateFontDescriptorsFromData(data); |
| 416 | if !descs.is_null() { |
| 417 | let n = CFArrayGetCount(descs); |
| 418 | let mut by_index: CTFontRef = null(); |
| 419 | for i in 0..n { |
| 420 | let f = CTFontCreateWithFontDescriptor(CFArrayGetValueAtIndex(descs, i), 12.0, null()); |
| 421 | if f.is_null() { |
| 422 | continue; |
| 423 | } |
| 424 | let ps = CTFontCopyPostScriptName(f); |
| 425 | let name = cf_to_string(ps); |
| 426 | if !ps.is_null() { |
| 427 | CFRelease(ps); |
| 428 | } |
| 429 | if want.as_deref() == Some(name.as_str()) { |
| 430 | created = f; |
| 431 | break; |
| 432 | } |
| 433 | if i == font.index as CFIndex || (by_index.is_null() && i == 0) { |
| 434 | if !by_index.is_null() { |
| 435 | CFRelease(by_index); |
| 436 | } |
| 437 | by_index = f; |
| 438 | } else { |
| 439 | CFRelease(f); |
| 440 | } |
| 441 | } |
| 442 | if created.is_null() { |
| 443 | created = by_index; |
| 444 | } else if !by_index.is_null() { |
| 445 | CFRelease(by_index); |
| 446 | } |
| 447 | CFRelease(descs); |
| 448 | } |
| 449 | CFRelease(data); |
| 450 | } |
| 451 | if created.is_null() { |
| 452 | log::warn!("CoreText could not open font blob {} face {}", font.data.id(), font.index); |
| 453 | } |
| 454 | fonts().lock().unwrap().base.insert(key, created as usize); |
| 455 | created |
| 456 | } |
| 457 | |
| 458 | unsafe fn sized_font(font: &FontData, size: f32, coords: &[NormalizedCoord]) -> CTFontRef { |
| 459 | let key = FontKey { blob: font.data.id(), index: font.index, size: size.to_bits(), coords: coords.to_vec() }; |
| 460 | if let Some(&f) = fonts().lock().unwrap().sized.get(&key) { |
| 461 | return f as CTFontRef; |
| 462 | } |
| 463 | let base = base_font(font); |
| 464 | let mut out: CTFontRef = null(); |
| 465 | if !base.is_null() { |
| 466 | let axes = axis_values(font, coords); |
| 467 | if axes.is_empty() { |
| 468 | out = CTFontCreateCopyWithAttributes(base, size as f64, null(), null()); |
| 469 | } else { |
| 470 | let mut keys: Vec<CFNumberRef> = Vec::new(); |
| 471 | let mut vals: Vec<CFNumberRef> = Vec::new(); |
| 472 | for (tag, v) in &axes { |
| 473 | let t = *tag as i32; |
| 474 | keys.push(CFNumberCreate(null(), kCFNumberSInt32Type, &t as *const i32 as *const c_void)); |
| 475 | vals.push(CFNumberCreate(null(), kCFNumberDoubleType, v as *const f64 as *const c_void)); |
| 476 | } |
| 477 | let variation = CFDictionaryCreate( |
| 478 | null(), |
| 479 | keys.as_ptr() as *const *const c_void, |
| 480 | vals.as_ptr() as *const *const c_void, |
| 481 | keys.len() as CFIndex, |
| 482 | &kCFTypeDictionaryKeyCallBacks, |
| 483 | &kCFTypeDictionaryValueCallBacks, |
| 484 | ); |
| 485 | let attr_key: CFStringRef = kCTFontVariationAttribute; |
| 486 | let attrs = CFDictionaryCreate(null(), &attr_key, &variation, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); |
| 487 | let desc = CTFontDescriptorCreateWithAttributes(attrs); |
| 488 | out = CTFontCreateCopyWithAttributes(base, size as f64, null(), desc); |
| 489 | CFRelease(desc); |
| 490 | CFRelease(attrs); |
| 491 | CFRelease(variation); |
| 492 | for k in keys.into_iter().chain(vals) { |
| 493 | CFRelease(k); |
| 494 | } |
| 495 | } |
| 496 | } |
| 497 | let mut cache = fonts().lock().unwrap(); |
| 498 | if cache.sized.len() > 4096 { |
| 499 | for (_, f) in cache.sized.drain() { |
| 500 | if f != 0 { |
| 501 | CFRelease(f as CFTypeRef); |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | cache.sized.insert(key, out as usize); |
| 506 | out |
| 507 | } |
| 508 | |
| 509 | // ───────────────────────── image cache ───────────────────────── |
| 510 | |
| 511 | struct Images(HashMap<u64, usize>); |
| 512 | unsafe impl Send for Images {} |
| 513 | static IMAGES: OnceLock<Mutex<Images>> = OnceLock::new(); |
| 514 | |
| 515 | unsafe fn cg_image_from_rgba(width: usize, height: usize, bytes: &[u8], bitmap_info: u32) -> CGImageRef { |
| 516 | if width == 0 || height == 0 || bytes.len() < width * height * 4 { |
| 517 | return std::ptr::null_mut(); |
| 518 | } |
| 519 | let data = CFDataCreate(null(), bytes.as_ptr(), (width * height * 4) as CFIndex); |
| 520 | let provider = CGDataProviderCreateWithCFData(data); |
| 521 | let space = CGColorSpaceCreateDeviceRGB(); |
| 522 | let img = CGImageCreate(width, height, 8, 32, width * 4, space, bitmap_info, provider, null(), true, kCGRenderingIntentDefault); |
| 523 | CGColorSpaceRelease(space); |
| 524 | CGDataProviderRelease(provider); |
| 525 | CFRelease(data); |
| 526 | img |
| 527 | } |
| 528 | |
| 529 | unsafe fn cached_image(image: &ImageData) -> CGImageRef { |
| 530 | let cache = IMAGES.get_or_init(|| Mutex::new(Images(HashMap::new()))); |
| 531 | let id = image.data.id(); |
| 532 | if let Some(&p) = cache.lock().unwrap().0.get(&id) { |
| 533 | return p as CGImageRef; |
| 534 | } |
| 535 | let info = match (image.format, image.alpha_type) { |
| 536 | (ImageFormat::Rgba8, ImageAlphaType::AlphaPremultiplied) => kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big, |
| 537 | (ImageFormat::Rgba8, ImageAlphaType::Alpha) => kCGImageAlphaLast | kCGBitmapByteOrder32Big, |
| 538 | (ImageFormat::Bgra8, ImageAlphaType::AlphaPremultiplied) => kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little, |
| 539 | (ImageFormat::Bgra8, ImageAlphaType::Alpha) => kCGImageAlphaFirst | kCGBitmapByteOrder32Little, |
| 540 | _ => return std::ptr::null_mut(), |
| 541 | }; |
| 542 | let img = cg_image_from_rgba(image.width as usize, image.height as usize, image.data.data(), info); |
| 543 | let mut cache = cache.lock().unwrap(); |
| 544 | if cache.0.len() > 256 { |
| 545 | for (_, p) in cache.0.drain() { |
| 546 | if p != 0 { |
| 547 | CGImageRelease(p as CGImageRef); |
| 548 | } |
| 549 | } |
| 550 | } |
| 551 | cache.0.insert(id, img as usize); |
| 552 | img |
| 553 | } |
| 554 | |
| 555 | // ───────────────────────── blurred rounded rect ───────────────────────── |
| 556 | // Analytic Gaussian blur of a rounded rectangle (Evan Wallace's approximation, the |
| 557 | // same family vello_cpu uses), so `draw_box_shadow` matches the vello backend. |
| 558 | |
| 559 | fn erf(x: f64) -> f64 { |
| 560 | let s = x.signum(); |
| 561 | let a = x.abs(); |
| 562 | let mut t = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; |
| 563 | t *= t; |
| 564 | s - s / (t * t) |
| 565 | } |
| 566 | |
| 567 | fn gaussian(x: f64, sigma: f64) -> f64 { |
| 568 | (-(x * x) / (2.0 * sigma * sigma)).exp() / ((2.0 * std::f64::consts::PI). |
| 569 | } |
| 570 | |
| 571 | fn shadow_x(x: f64, y: f64, sigma: f64, corner: f64, half: (f64, f64)) -> f64 { |
| 572 | let delta = (half.1 - corner - y.abs()).min(0.0); |
| 573 | let curved = half.0 - corner + (corner * corner - delta * delta).max(0.0).sqrt(); |
| 574 | let k = 0.5f64.sqrt() / sigma; |
| 575 | let lo = 0.5 + 0.5 * erf((x - curved) * k); |
| 576 | let hi = 0.5 + 0.5 * erf((x + curved) * k); |
| 577 | hi - lo |
| 578 | } |
| 579 | |
| 580 | fn rounded_box_shadow(rect: Rect, p: Point, sigma: f64, corner: f64) -> f64 { |
| 581 | let center = rect.center(); |
| 582 | let half = (rect.width() / 2.0, rect.height() / 2.0); |
| 583 | let (px, py) = (p.x - center.x, p.y - center.y); |
| 584 | let low = py - half.1; |
| 585 | let high = py + half.1; |
| 586 | let start = (-3.0 * sigma).clamp(low, high); |
| 587 | let end = (3.0 * sigma).clamp(low, high); |
| 588 | let step = (end - start) / 4.0; |
| 589 | let mut y = start + step * 0.5; |
| 590 | let mut value = 0.0; |
| 591 | for _ in 0..4 { |
| 592 | value += shadow_x(px, py - y, sigma, corner, half) * gaussian(y, sigma) * step; |
| 593 | y += step; |
| 594 | } |
| 595 | value.clamp(0.0, 1.0) |
| 596 | } |
| 597 | |
| 598 | // ───────────────────────── the scene ───────────────────────── |
| 599 | |
| 600 | pub struct CgScene { |
| 601 | ctx: CGContextRef, |
| 602 | /// For each pushed layer: whether a transparency layer was begun. |
| 603 | layers: Vec<bool>, |
| 604 | } |
| 605 | |
| 606 | impl CgScene { |
| 607 | unsafe fn set_fill(&self, c: [f64; 4]) { |
| 608 | CGContextSetRGBFillColor(self.ctx, c[0], c[1], c[2], c[3]); |
| 609 | } |
| 610 | |
| 611 | unsafe fn set_stroke(&self, c: [f64; 4]) { |
| 612 | CGContextSetRGBStrokeColor(self.ctx, c[0], c[1], c[2], c[3]); |
| 613 | } |
| 614 | |
| 615 | unsafe fn clip_current_path(&self, fill: Fill) { |
| 616 | match fill { |
| 617 | Fill::NonZero => CGContextClip(self.ctx), |
| 618 | Fill::EvenOdd => CGContextEOClip(self.ctx), |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | unsafe fn draw_gradient(&self, g: &Gradient, bbox: CGRect) { |
| 623 | let n = g.stops.len(); |
| 624 | if n == 0 { |
| 625 | return; |
| 626 | } |
| 627 | if n == 1 { |
| 628 | self.set_fill(rgba(g.stops[0].color.to_alpha_color::<Srgb>())); |
| 629 | let p = cg_path(&Rect::new(bbox.origin.x, bbox.origin.y, bbox.origin.x + bbox.size.width, bbox. |
| 630 | CGContextBeginPath(self.ctx); |
| 631 | CGContextAddPath(self.ctx, p); |
| 632 | CGContextFillPath(self.ctx); |
| 633 | CGPathRelease(p); |
| 634 | return; |
| 635 | } |
| 636 | let options = if g.extend == Extend::Pad { kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation } else { 0 }; |
| 637 | match &g.kind { |
| 638 | GradientKind::Linear(l) => { |
| 639 | let (comps, locs) = Self::ramp(&g.stops); |
| 640 | let space = CGColorSpaceCreateDeviceRGB(); |
| 641 | let grad = CGGradientCreateWithColorComponents(space, comps.as_ptr(), locs.as_ptr(), n); |
| 642 | CGContextDrawLinearGradient(self.ctx, grad, pt(l.start), pt(l.end), options); |
| 643 | CGGradientRelease(grad); |
| 644 | CGColorSpaceRelease(space); |
| 645 | } |
| 646 | GradientKind::Radial(r) => { |
| 647 | let (comps, locs) = Self::ramp(&g.stops); |
| 648 | let space = CGColorSpaceCreateDeviceRGB(); |
| 649 | let grad = CGGradientCreateWithColorComponents(space, comps.as_ptr(), locs.as_ptr(), n); |
| 650 | CGContextDrawRadialGradient(self.ctx, grad, pt(r.start_center), r.start_radius as f64, pt(r.end_center), r.end_radius as f64, options); |
| 651 | CGGradientRelease(grad); |
| 652 | CGColorSpaceRelease(space); |
| 653 | } |
| 654 | GradientKind::Sweep(s) => { |
| 655 | // No native conic gradient in CG: 96 flat wedges around the centre. |
| 656 | let c = s.center; |
| 657 | let corners = [ |
| 658 | (bbox.origin.x, bbox.origin.y), |
| 659 | (bbox.origin.x + bbox.size.width, bbox.origin.y), |
| 660 | (bbox.origin.x, bbox.origin.y + bbox.size.height), |
| 661 | (bbox.origin.x + bbox.size.width, bbox.origin.y + bbox.size.height), |
| 662 | ]; |
| 663 | let radius = corners.iter().map(|(x, y)| ((x - c.x).powi(2) + (y - c.y). |
| 664 | let (a0, a1) = (s.start_angle as f64, s.end_angle as f64); |
| 665 | let span = if (a1 - a0).abs() < 1e-6 { std::f64::consts::TAU } else { a1 - a0 }; |
| 666 | let wedges = 96; |
| 667 | let step = std::f64::consts::TAU / wedges as f64; |
| 668 | for i in 0..wedges { |
| 669 | let th0 = a0 + i as f64 * step; |
| 670 | let th1 = th0 + step * 1.02; |
| 671 | let mid = (th0 + step * 0.5 - a0) / span; |
| 672 | let t = match g.extend { |
| 673 | Extend::Pad => mid.clamp(0.0, 1.0), |
| 674 | Extend::Repeat => mid.rem_euclid(1.0), |
| 675 | Extend::Reflect => { |
| 676 | let m = mid.rem_euclid(2.0); |
| 677 | if m > 1.0 { 2.0 - m } else { m } |
| 678 | } |
| 679 | }; |
| 680 | self.set_fill(sample_stops(&g.stops, t as f32)); |
| 681 | let path = CGPathCreateMutable(); |
| 682 | CGPathMoveToPoint(path, null(), c.x, c.y); |
| 683 | CGPathAddLineToPoint(path, null(), c.x + radius * th0.cos(), c.y + radius * th0.sin()); |
| 684 | CGPathAddLineToPoint(path, null(), c.x + radius * th1.cos(), c.y + radius * th1.sin()); |
| 685 | CGPathCloseSubpath(path); |
| 686 | CGContextBeginPath(self.ctx); |
| 687 | CGContextAddPath(self.ctx, path); |
| 688 | CGContextFillPath(self.ctx); |
| 689 | CGPathRelease(path); |
| 690 | } |
| 691 | } |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | fn ramp(stops: &ColorStops) -> (Vec<f64>, Vec<f64>) { |
| 696 | let mut comps = Vec::with_capacity(stops.len() * 4); |
| 697 | let mut locs = Vec::with_capacity(stops.len()); |
| 698 | for s in stops.iter() { |
| 699 | comps.extend_from_slice(&rgba(s.color.to_alpha_color::<Srgb>())); |
| 700 | locs.push(s.offset.clamp(0.0, 1.0) as f64); |
| 701 | } |
| 702 | (comps, locs) |
| 703 | } |
| 704 | |
| 705 | /// Draws an image brush over the current clip: image px (0,0)-(w,h) in the current user space. |
| 706 | unsafe fn draw_image_brush(&self, brush: ImageBrushRef<'_>) { |
| 707 | let img = cached_image(brush.image); |
| 708 | if img.is_null() { |
| 709 | return; |
| 710 | } |
| 711 | let (w, h) = (brush.image.width as f64, brush.image.height as f64); |
| 712 | CGContextSetInterpolationQuality( |
| 713 | self.ctx, |
| 714 | match brush.sampler.quality { |
| 715 | ImageQuality::Low => 1, |
| 716 | ImageQuality::Medium => 2, |
| 717 | ImageQuality::High => 3, |
| 718 | }, |
| 719 | ); |
| 720 | if brush.sampler.alpha < 1.0 { |
| 721 | CGContextSetAlpha(self.ctx, brush.sampler.alpha.clamp(0.0, 1.0) as f64); |
| 722 | } |
| 723 | // CG images are y-up: flip the image box. |
| 724 | CGContextTranslateCTM(self.ctx, 0.0, h); |
| 725 | CGContextScaleCTM(self.ctx, 1.0, -1.0); |
| 726 | let rect = CGRect { origin: CGPoint { x: 0.0, y: 0.0 }, size: CGSize { width: w, height: h } }; |
| 727 | if brush.sampler.x_extend == Extend::Repeat || brush.sampler.y_extend == Extend::Repeat { |
| 728 | CGContextDrawTiledImage(self.ctx, rect, img); |
| 729 | } else { |
| 730 | CGContextDrawImage(self.ctx, rect, img); |
| 731 | } |
| 732 | } |
| 733 | |
| 734 | /// Fills or clips the current path with `paint`; the path is already on the context. |
| 735 | unsafe fn paint_current_path(&self, fill: Fill, paint: PaintRef<'_>, brush_transform: Option<Affine>, bbox: CGRect) { |
| 736 | match paint { |
| 737 | Paint::Solid(c) => { |
| 738 | self.set_fill(rgba(c)); |
| 739 | match fill { |
| 740 | Fill::NonZero => CGContextFillPath(self.ctx), |
| 741 | Fill::EvenOdd => CGContextEOFillPath(self.ctx), |
| 742 | } |
| 743 | } |
| 744 | Paint::Gradient(g) => { |
| 745 | self.clip_current_path(fill); |
| 746 | if let Some(bt) = brush_transform { |
| 747 | CGContextConcatCTM(self.ctx, cg_affine(bt)); |
| 748 | } |
| 749 | self.draw_gradient(g, bbox); |
| 750 | } |
| 751 | Paint::Image(img) => { |
| 752 | self.clip_current_path(fill); |
| 753 | if let Some(bt) = brush_transform { |
| 754 | CGContextConcatCTM(self.ctx, cg_affine(bt)); |
| 755 | } |
| 756 | self.draw_image_brush(img); |
| 757 | } |
| 758 | Paint::Resource(_) | Paint::Custom(_) => {} |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | unsafe fn set_stroke_style(&self, style: &Stroke) { |
| 763 | CGContextSetLineWidth(self.ctx, style.width); |
| 764 | CGContextSetLineJoin( |
| 765 | self.ctx, |
| 766 | match style.join { |
| 767 | Join::Miter => 0, |
| 768 | Join::Round => 1, |
| 769 | Join::Bevel => 2, |
| 770 | }, |
| 771 | ); |
| 772 | CGContextSetLineCap( |
| 773 | self.ctx, |
| 774 | match style.start_cap { |
| 775 | Cap::Butt => 0, |
| 776 | Cap::Round => 1, |
| 777 | Cap::Square => 2, |
| 778 | }, |
| 779 | ); |
| 780 | CGContextSetMiterLimit(self.ctx, style.miter_limit); |
| 781 | if !style.dash_pattern.is_empty() { |
| 782 | let dashes: Vec<f64> = style.dash_pattern.iter().copied().collect(); |
| 783 | CGContextSetLineDash(self.ctx, style.dash_offset, dashes.as_ptr(), dashes.len()); |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | fn finish(&mut self) { |
| 788 | while !self.layers.is_empty() { |
| 789 | self.pop_layer(); |
| 790 | } |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | impl RenderContext for CgScene {} |
| 795 | |
| 796 | impl PaintScene for CgScene { |
| 797 | fn reset(&mut self) {} |
| 798 | |
| 799 | fn push_layer( |
| 800 | &mut self, |
| 801 | fill: Fill, |
| 802 | blend: impl Into<BlendMode>, |
| 803 | alpha: f32, |
| 804 | transform: Affine, |
| 805 | clip: &impl Shape, |
| 806 | _filter: Option<Arc<Filter>>, |
| 807 | _backdrop_filter: Option<Arc<Filter>>, |
| 808 | ) { |
| 809 | let blend = blend.into(); |
| 810 | unsafe { |
| 811 | CGContextSaveGState(self.ctx); |
| 812 | let path = cg_path(clip, Some(transform)); |
| 813 | CGContextBeginPath(self.ctx); |
| 814 | CGContextAddPath(self.ctx, path); |
| 815 | self.clip_current_path(fill); |
| 816 | CGPathRelease(path); |
| 817 | let composite = alpha < 1.0 || !is_plain(blend); |
| 818 | if composite { |
| 819 | CGContextSetAlpha(self.ctx, alpha.clamp(0.0, 1.0) as f64); |
| 820 | CGContextSetBlendMode(self.ctx, blend_mode(blend)); |
| 821 | CGContextBeginTransparencyLayer(self.ctx, null()); |
| 822 | } |
| 823 | self.layers.push(composite); |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | fn push_clip_layer(&mut self, fill: Fill, transform: Affine, clip: &impl Shape) { |
| 828 | unsafe { |
| 829 | CGContextSaveGState(self.ctx); |
| 830 | let path = cg_path(clip, Some(transform)); |
| 831 | CGContextBeginPath(self.ctx); |
| 832 | CGContextAddPath(self.ctx, path); |
| 833 | self.clip_current_path(fill); |
| 834 | CGPathRelease(path); |
| 835 | self.layers.push(false); |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | fn pop_layer(&mut self) { |
| 840 | if let Some(composite) = self.layers.pop() { |
| 841 | unsafe { |
| 842 | if composite { |
| 843 | CGContextEndTransparencyLayer(self.ctx); |
| 844 | } |
| 845 | CGContextRestoreGState(self.ctx); |
| 846 | } |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | fn stroke<'a>(&mut self, style: &Stroke, transform: Affine, brush: impl Into<PaintRef<'a>>, brush_transform: |
| 851 | let paint: PaintRef<'a> = brush.into(); |
| 852 | unsafe { |
| 853 | CGContextSaveGState(self.ctx); |
| 854 | CGContextConcatCTM(self.ctx, cg_affine(transform)); |
| 855 | let path = cg_path(shape, None); |
| 856 | let bbox = CGPathGetBoundingBox(path); |
| 857 | CGContextBeginPath(self.ctx); |
| 858 | CGContextAddPath(self.ctx, path); |
| 859 | CGPathRelease(path); |
| 860 | self.set_stroke_style(style); |
| 861 | match paint { |
| 862 | Paint::Solid(c) => { |
| 863 | self.set_stroke(rgba(c)); |
| 864 | CGContextStrokePath(self.ctx); |
| 865 | } |
| 866 | other => { |
| 867 | CGContextReplacePathWithStrokedPath(self.ctx); |
| 868 | self.paint_current_path(Fill::NonZero, other, brush_transform, bbox); |
| 869 | } |
| 870 | } |
| 871 | CGContextRestoreGState(self.ctx); |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | fn fill<'a>(&mut self, style: Fill, transform: Affine, brush: impl Into<PaintRef<'a>>, brush_transform: |
| 876 | let paint: PaintRef<'a> = brush.into(); |
| 877 | unsafe { |
| 878 | CGContextSaveGState(self.ctx); |
| 879 | CGContextConcatCTM(self.ctx, cg_affine(transform)); |
| 880 | let path = cg_path(shape, None); |
| 881 | let bbox = CGPathGetBoundingBox(path); |
| 882 | CGContextBeginPath(self.ctx); |
| 883 | CGContextAddPath(self.ctx, path); |
| 884 | CGPathRelease(path); |
| 885 | self.paint_current_path(style, paint, brush_transform, bbox); |
| 886 | CGContextRestoreGState(self.ctx); |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | fn draw_glyphs<'a, 's: 'a>( |
| 891 | &'s mut self, |
| 892 | font: &'a FontData, |
| 893 | font_size: f32, |
| 894 | _hint: bool, |
| 895 | normalized_coords: &'a [NormalizedCoord], |
| 896 | _embolden: kurbo::Vec2, |
| 897 | style: impl Into<StyleRef<'a>>, |
| 898 | brush: impl Into<PaintRef<'a>>, |
| 899 | brush_alpha: f32, |
| 900 | transform: Affine, |
| 901 | glyph_transform: Option<Affine>, |
| 902 | glyphs: impl Iterator<Item = Glyph> + Clone, |
| 903 | ) { |
| 904 | let paint: PaintRef<'a> = brush.into(); |
| 905 | let mut color = match paint { |
| 906 | Paint::Solid(c) => rgba(c), |
| 907 | Paint::Gradient(g) => sample_stops(&g.stops, 0.0), |
| 908 | _ => return, |
| 909 | }; |
| 910 | color[3] *= brush_alpha.clamp(0.0, 1.0) as f64; |
| 911 | let mut ids: Vec<CGGlyph> = Vec::new(); |
| 912 | let mut positions: Vec<CGPoint> = Vec::new(); |
| 913 | for g in glyphs { |
| 914 | if g.id > u16::MAX as u32 { |
| 915 | continue; |
| 916 | } |
| 917 | ids.push(g.id as CGGlyph); |
| 918 | // y negated: the run is drawn with the CTM flipped back to y-up (below). |
| 919 | positions.push(CGPoint { x: g.x as f64, y: -(g.y as f64) }); |
| 920 | } |
| 921 | if ids.is_empty() { |
| 922 | return; |
| 923 | } |
| 924 | unsafe { |
| 925 | let ct = sized_font(font, font_size, normalized_coords); |
| 926 | if ct.is_null() { |
| 927 | return; |
| 928 | } |
| 929 | CGContextSaveGState(self.ctx); |
| 930 | CGContextConcatCTM(self.ctx, cg_affine(transform)); |
| 931 | // Glyph outlines are y-up in font space and CoreText refuses a mirrored text |
| 932 | // matrix, so flip the CTM back to y-up for the run and negate the baselines. |
| 933 | // A glyph transform (synthetic italic skew) is conjugated into that space. |
| 934 | CGContextScaleCTM(self.ctx, 1.0, -1.0); |
| 935 | let tm = Affine::FLIP_Y * glyph_transform.unwrap_or(Affine::IDENTITY) * Affine::FLIP_Y; |
| 936 | CGContextSetTextMatrix(self.ctx, cg_affine(tm)); |
| 937 | match style.into() { |
| 938 | StyleRef::Fill(_) => { |
| 939 | CGContextSetTextDrawingMode(self.ctx, kCGTextFill); |
| 940 | self.set_fill(color); |
| 941 | } |
| 942 | StyleRef::Stroke(s) => { |
| 943 | CGContextSetTextDrawingMode(self.ctx, kCGTextStroke); |
| 944 | self.set_stroke(color); |
| 945 | self.set_stroke_style(s); |
| 946 | } |
| 947 | } |
| 948 | CTFontDrawGlyphs(ct, ids.as_ptr(), positions.as_ptr(), ids.len(), self.ctx); |
| 949 | CGContextRestoreGState(self.ctx); |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | fn draw_box_shadow(&mut self, transform: Affine, rect: Rect, brush: Color, radius: f64, std_dev: f64) { |
| 954 | let color = rgba(brush); |
| 955 | if color[3] <= 0.0 || rect.is_zero_area() && std_dev <= 0.0 { |
| 956 | return; |
| 957 | } |
| 958 | if std_dev < 0.05 { |
| 959 | self.fill(Fill::NonZero, transform, brush, None, &RoundedRect::from_rect(rect, radius)); |
| 960 | return; |
| 961 | } |
| 962 | let sigma = std_dev; |
| 963 | let pad = (3.0 * sigma).ceil(); |
| 964 | let x0 = (rect.x0 - pad).floor(); |
| 965 | let y0 = (rect.y0 - pad).floor(); |
| 966 | let x1 = (rect.x1 + pad).ceil(); |
| 967 | let y1 = (rect.y1 + pad).ceil(); |
| 968 | let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize); |
| 969 | if w == 0 || h == 0 || w * h > 16_000_000 { |
| 970 | return; |
| 971 | } |
| 972 | let corner = radius.clamp(0.0, rect.width().min(rect.height()) / 2.0); |
| 973 | let mut px = vec![0u8; w * h * 4]; |
| 974 | for j in 0..h { |
| 975 | for i in 0..w { |
| 976 | let p = Point::new(x0 + i as f64 + 0.5, y0 + j as f64 + 0.5); |
| 977 | let a = rounded_box_shadow(rect, p, sigma, corner) * color[3]; |
| 978 | if a <= 0.0 { |
| 979 | continue; |
| 980 | } |
| 981 | let o = (j * w + i) * 4; |
| 982 | px[o] = (color[0] * a * 255.0 + 0.5) as u8; |
| 983 | px[o + 1] = (color[1] * a * 255.0 + 0.5) as u8; |
| 984 | px[o + 2] = (color[2] * a * 255.0 + 0.5) as u8; |
| 985 | px[o + 3] = (a * 255.0 + 0.5) as u8; |
| 986 | } |
| 987 | } |
| 988 | unsafe { |
| 989 | let img = cg_image_from_rgba(w, h, &px, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); |
| 990 | if img.is_null() { |
| 991 | return; |
| 992 | } |
| 993 | CGContextSaveGState(self.ctx); |
| 994 | CGContextConcatCTM(self.ctx, cg_affine(transform)); |
| 995 | CGContextTranslateCTM(self.ctx, x0, y0 + h as f64); |
| 996 | CGContextScaleCTM(self.ctx, 1.0, -1.0); |
| 997 | CGContextSetInterpolationQuality(self.ctx, 1); |
| 998 | CGContextDrawImage(self.ctx, CGRect { origin: CGPoint { x: 0.0, y: 0.0 }, size: CGSize { width: w as f64, height |
| 999 | CGContextRestoreGState(self.ctx); |
| 1000 | CGImageRelease(img); |
| 1001 | } |
| 1002 | } |
| 1003 | } |
| 1004 | |
| 1005 | // ───────────────────────── the image renderer ───────────────────────── |
| 1006 | |
| 1007 | /// Paints an anyrender scene into a premultiplied RGBA8 buffer through a CGBitmapContext. |
| 1008 | pub struct CgImageRenderer { |
| 1009 | width: u32, |
| 1010 | height: u32, |
| 1011 | } |
| 1012 | |
| 1013 | impl RenderContext for CgImageRenderer {} |
| 1014 | |
| 1015 | impl ImageRenderer for CgImageRenderer { |
| 1016 | type ScenePainter<'a> = CgScene; |
| 1017 | |
| 1018 | fn new(width: u32, height: u32) -> Self { |
| 1019 | Self { width, height } |
| 1020 | } |
| 1021 | |
| 1022 | fn resize(&mut self, width: u32, height: u32) { |
| 1023 | self.width = width; |
| 1024 | self.height = height; |
| 1025 | } |
| 1026 | |
| 1027 | fn reset(&mut self) {} |
| 1028 | |
| 1029 | fn render_to_vec<F: FnOnce(&mut Self::ScenePainter<'_>)>(&mut self, draw_fn: F, vec: &mut Vec |
| 1030 | vec.resize(self.width as usize * self.height as usize * 4, 0); |
| 1031 | self.render(draw_fn, vec); |
| 1032 | } |
| 1033 | |
| 1034 | fn render<F: FnOnce(&mut Self::ScenePainter<'_>)>(&mut self, draw_fn: F, buffer: &mut [u8 |
| 1035 | let (w, h) = (self.width as usize, self.height as usize); |
| 1036 | if w == 0 || h == 0 || buffer.len() < w * h * 4 { |
| 1037 | return; |
| 1038 | } |
| 1039 | buffer[..w * h * 4].fill(0); |
| 1040 | unsafe { |
| 1041 | let space = CGColorSpaceCreateDeviceRGB(); |
| 1042 | let ctx = CGBitmapContextCreate(buffer.as_mut_ptr() as *mut c_void, w, h, 8, w * 4, space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); |
| 1043 | CGColorSpaceRelease(space); |
| 1044 | if ctx.is_null() { |
| 1045 | log::error!("CGBitmapContextCreate failed for {w}×{h}"); |
| 1046 | return; |
| 1047 | } |
| 1048 | // y-down like the scene; text the way UIKit/AppKit layers draw it: grayscale |
| 1049 | // antialiasing, subpixel positioning, no LCD smoothing on a transparent bitmap. |
| 1050 | CGContextTranslateCTM(ctx, 0.0, h as f64); |
| 1051 | CGContextScaleCTM(ctx, 1.0, -1.0); |
| 1052 | CGContextSetAllowsAntialiasing(ctx, true); |
| 1053 | CGContextSetShouldAntialias(ctx, true); |
| 1054 | CGContextSetAllowsFontSmoothing(ctx, false); |
| 1055 | CGContextSetShouldSmoothFonts(ctx, false); |
| 1056 | CGContextSetAllowsFontSubpixelPositioning(ctx, true); |
| 1057 | CGContextSetShouldSubpixelPositionFonts(ctx, true); |
| 1058 | CGContextSetAllowsFontSubpixelQuantization(ctx, false); |
| 1059 | CGContextSetShouldSubpixelQuantizeFonts(ctx, false); |
| 1060 | let mut scene = CgScene { ctx, layers: Vec::new() }; |
| 1061 | draw_fn(&mut scene); |
| 1062 | scene.finish(); |
| 1063 | CGContextRelease(ctx); |
| 1064 | } |
| 1065 | } |
| 1066 | } |
| 1067 | |
| 1068 | /// Diagnostics: what CoreText calls the face behind a parley font (None when it could not be opened). |
| 1069 | pub fn coretext_name(font: &FontData) -> Option<String> { |
| 1070 | unsafe { |
| 1071 | let f = base_font(font); |
| 1072 | if f.is_null() { |
| 1073 | return None; |
| 1074 | } |
| 1075 | let ps = CTFontCopyPostScriptName(f); |
| 1076 | let s = cf_to_string(ps); |
| 1077 | if !ps.is_null() { |
| 1078 | CFRelease(ps); |
| 1079 | } |
| 1080 | Some(s) |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | #[cfg(test)] |
| 1085 | mod tests { |
| 1086 | use super::*; |
| 1087 | use anyrender::render_to_buffer; |
| 1088 | use kurbo::BezPath; |
| 1089 | use peniko::color::palette::css::{BLACK, BLUE, RED}; |
| 1090 | |
| 1091 | fn pixel(buf: &[u8], w: usize, x: usize, y: usize) -> [u8; 4] { |
| 1092 | let i = (y * w + x) * 4; |
| 1093 | [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] |
| 1094 | } |
| 1095 | |
| 1096 | #[test] |
| 1097 | fn fills_land_y_down_in_rgba() { |
| 1098 | let buf = render_to_buffer::<CgImageRenderer, _>( |
| 1099 | |s| { |
| 1100 | s.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0.0, 0.0, 100.0, 50.0)); |
| 1101 | s.fill(Fill::NonZero, Affine::translate((80.0, 80.0)), BLUE, None, &Rect::new(0.0, 0.0, 10.0, |
| 1102 | }, |
| 1103 | 100, |
| 1104 | 100, |
| 1105 | ); |
| 1106 | assert_eq!(pixel(&buf, 100, 50, 25), [255, 0, 0, 255], "top half red"); |
| 1107 | assert_eq!(pixel(&buf, 100, 50, 75), [0, 0, 0, 0], "bottom half empty"); |
| 1108 | assert_eq!(pixel(&buf, 100, 85, 85), [0, 0, 255, 255], "translated square"); |
| 1109 | } |
| 1110 | |
| 1111 | #[test] |
| 1112 | fn clip_layers_respect_fill_rule() { |
| 1113 | let path = BezPath::from_svg("M0 0H100V100H0Z M25 25H75V75H25Z").unwrap(); |
| 1114 | for (fill, composite) in [(Fill::NonZero, false), (Fill::EvenOdd, false), (Fill::NonZero, true), (Fill::EvenOdd, true)] { |
| 1115 | let buf = render_to_buffer::<CgImageRenderer, _>( |
| 1116 | |s| { |
| 1117 | if composite { |
| 1118 | s.push_layer(fill, Mix::Normal, 0.5, Affine::IDENTITY, &path, None, None); |
| 1119 | } else { |
| 1120 | s.push_clip_layer(fill, Affine::IDENTITY, &path); |
| 1121 | } |
| 1122 | s.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0.0, 0.0, 100.0, 100.0)); |
| 1123 | s.pop_layer(); |
| 1124 | }, |
| 1125 | 100, |
| 1126 | 100, |
| 1127 | ); |
| 1128 | let edge = pixel(&buf, 100, 10, 10); |
| 1129 | let hole = pixel(&buf, 100, 50, 50); |
| 1130 | // Premultiplied: a half-transparent layer halves red too. |
| 1131 | let want = if composite { 128 } else { 255 }; |
| 1132 | assert!((edge[3] as i32 - want).abs() <= 2 && (edge[0] as i32 - want).abs() |
| 1133 | if fill == Fill::EvenOdd { |
| 1134 | assert_eq!(hole, [0, 0, 0, 0], "even-odd hole"); |
| 1135 | } else { |
| 1136 | assert_eq!(hole, edge, "non-zero fills the hole"); |
| 1137 | } |
| 1138 | } |
| 1139 | } |
| 1140 | |
| 1141 | #[test] |
| 1142 | fn box_shadow_sits_under_the_rect() { |
| 1143 | let buf = render_to_buffer::<CgImageRenderer, _>( |
| 1144 | |s| s.draw_box_shadow(Affine::IDENTITY, Rect::new(40.0, 40.0, 60.0, 60.0), BLACK, 0.0, 4.0), |
| 1145 | 100, |
| 1146 | 100, |
| 1147 | ); |
| 1148 | assert!(pixel(&buf, 100, 50, 50)[3] > 240, "centre opaque: {:?}", pixel(&buf, 100, 50, 50)); |
| 1149 | let edge = pixel(&buf, 100, 50, 64)[3]; |
| 1150 | assert!(edge > 10 && edge < 200, "edge blurred: {edge}"); |
| 1151 | assert_eq!(pixel(&buf, 100, 10, 10)[3], 0, "far away clear"); |
| 1152 | assert_eq!(pixel(&buf, 100, 50, 80)[3], 0, "beyond 3σ clear"); |
| 1153 | } |
| 1154 | |
| 1155 | #[test] |
| 1156 | fn system_fonts_resolve_to_their_default_instance() { |
| 1157 | use peniko::Blob; |
| 1158 | for path in ["/System/Library/Fonts/SFNS.ttf", "/System/Library/Fonts/Apple Color Emoji.ttc", "/System/Library/Fonts/Helvetica.ttc"] { |
| 1159 | let Ok(bytes) = std::fs::read(path) else { continue }; |
| 1160 | let font = FontData { data: Blob::new(Arc::new(bytes)), index: 0 }; |
| 1161 | let want = postscript_name(&font); |
| 1162 | assert_eq!(coretext_name(&font), want, "{path}"); |
| 1163 | } |
| 1164 | } |
| 1165 | |
| 1166 | #[test] |
| 1167 | fn gradient_fill_spans_the_shape() { |
| 1168 | let g = Gradient::new_linear((0.0, 0.0), (100.0, 0.0)).with_stops([RED, BLUE]); |
| 1169 | let buf = render_to_buffer::<CgImageRenderer, _>(|s| s.fill(Fill::NonZero, Affine::IDENTITY, &g, None, &Rect |
| 1170 | let left = pixel(&buf, 100, 2, 50); |
| 1171 | let right = pixel(&buf, 100, 97, 50); |
| 1172 | assert!(left[0] > 200 && left[2] < 60, "left red: {left:?}"); |
| 1173 | assert!(right[2] > 200 && right[0] < 60, "right blue: {right:?}"); |
| 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | |
| 1178 | |
| 1179 | |