Repository Public
1// SP Notes Core2// File: Sources/SPNotesDocument/InkRenderer.swift3// Description: Pure CoreGraphics rendering of an ink document to a CGImage or PNG, shared by the macOS and iOS4// apps for the `preview` attachment of `drawing` nodes. No UIKit, AppKit or PencilKit.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreGraphics10import ImageIO1112/// What is painted behind the strokes. Mirrors the `background` attribute of a `drawing` node.13public enum InkBackground: Sendable, Hashable {14 /// Transparent.15 case none16 case white17 case color(InkColor)1819 /// From the node attribute: `"none"`, `"white"`, or a `#rrggbb[aa]` colour; anything else is transparent.20 public init(attr: String?) {21 switch attr {22 case "white"?: self = .white23 case let s?: self = InkColor(hex: s).map(InkBackground.color) ?? .none24 default: self = .none25 }26 }2728 var inkColor: InkColor? {29 switch self {30 case .none: return nil31 case .white: return .white32 case .color(let c): return c33 }34 }35}3637/// The part of the canvas an image covers.38public enum InkCrop: Sendable, Hashable {39 /// The whole canvas (`width` × `height`).40 case canvas41 /// The bounding box of the strokes grown by `padding` canvas units, clipped to nothing (it may exceed the canvas).42 case content(padding: Double)43 /// An explicit rectangle in canvas units.44 case rect(CGRect)45}4647public enum InkRenderer {48 /// Largest side of a rendered bitmap, in pixels.49 public static let maxPixels = 81925051 /// Opacity applied to a highlighter stroke whose colour is opaque.52 public static let highlighterOpacity = 0.45354 /// The canvas rectangle an image would cover; nil when it is empty.55 public static func frame(of document: InkDocument, crop: InkCrop = .canvas) -> CGRect? {56 let r: CGRect57 switch crop {58 case .canvas: r = CGRect(origin: .zero, size: document.size)59 case .content(let padding):60 let box = document.boundingBox61 if box.isNull { return nil }62 r = box.insetBy(dx: -max(0, padding), dy: -max(0, padding))63 case .rect(let rect): r = rect.standardized64 }65 guard !r.isNull, r.width.isFinite, r.height.isFinite, r.width > 0, r.height > 0 else { return nil }66 return r67 }6869 /// Renders the document. `scale` is pixels per canvas unit (reduced when the bitmap would exceed `maxPixels`).70 /// Returns nil when the area is empty (zero-sized canvas, nothing drawn with `.content`).71 public static func image(_ document: InkDocument, scale: CGFloat = 2, background: InkBackground = .none, crop: InkCrop = .canvas) -> CGImage? {72 guard let frame = frame(of: document, crop: crop), scale > 0, scale.isFinite else { return nil }73 let s = min(scale, CGFloat(maxPixels) / max(frame.width, frame.height))74 let w = max(1, Int((frame.width * s).rounded(.up))), h = max(1, Int((frame.height * s).rounded(.up)))75 guard let space = CGColorSpace(name: CGColorSpace.sRGB),76 let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: space,77 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }78 if let bg = background.inkColor {79 ctx.setFillColor(cgColor(bg, space))80 ctx.fill(CGRect(x: 0, y: 0, width: w, height: h))81 }82 // Canvas coordinates have their origin at the top-left; CoreGraphics bitmaps at the bottom-left.83 ctx.translateBy(x: 0, y: CGFloat(h))84 ctx.scaleBy(x: s, y: -s)85 ctx.translateBy(x: -frame.minX, y: -frame.minY)86 draw(document, in: ctx)87 return ctx.makeImage()88 }8990 /// PNG bytes of `image(…)`; nil when there is nothing to render.91 public static func pngData(_ document: InkDocument, scale: CGFloat = 2, background: InkBackground = .none, crop: InkCrop = .canvas) -> Data? {92 image(document, scale: scale, background: background, crop: crop).flatMap(pngData(of:))93 }9495 /// PNG encoding of any image.96 public static func pngData(of image: CGImage) -> Data? {97 let data = NSMutableData()98 guard let dest = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil) else { return nil }99 CGImageDestinationAddImage(dest, image, nil)100 return CGImageDestinationFinalize(dest) ? data as Data : nil101 }102103 /// Draws the strokes into a context whose user space is already the canvas space (origin top-left, y down).104 /// Lets an app draw live ink in its own view or layer.105 public static func draw(_ document: InkDocument, in ctx: CGContext) {106 for stroke in document.strokes { draw(stroke, in: ctx) }107 }108109 /// Draws one stroke (see `draw(_:in:)`).110 public static func draw(_ stroke: InkStroke, in ctx: CGContext) {111 let pts = stroke.points.filter { $0.x.isFinite && $0.y.isFinite }112 let width = CGFloat(stroke.width)113 guard !pts.isEmpty, width > 0, width.isFinite else { return }114 let color = stroke.color115 let space = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB()116 let opaque = cgColor(InkColor(red: color.red, green: color.green, blue: color.blue, alpha: 255), space)117 let highlighter = stroke.tool == .highlighter118 var alpha = CGFloat(color.opacity)119 if highlighter, color.alpha == 255 { alpha = CGFloat(highlighterOpacity) }120 guard alpha > 0 else { return }121122 ctx.saveGState()123 defer { ctx.restoreGState() }124 if highlighter { ctx.setBlendMode(.multiply) }125 // The stroke is drawn opaque inside a layer composited once, so overlapping segments do not darken.126 ctx.setAlpha(alpha)127 ctx.beginTransparencyLayer(auxiliaryInfo: nil)128 defer { ctx.endTransparencyLayer() }129 ctx.setStrokeColor(opaque)130 ctx.setFillColor(opaque)131 ctx.setLineJoin(.round)132 ctx.setLineCap(highlighter ? .square : .round)133134 if pts.count == 1 {135 let w = stroke.tool == .pen || !stroke.tool.isKnown ? penWidth(width, pts[0].pressure) : width136 let r = CGRect(x: CGFloat(pts[0].x) - w / 2, y: CGFloat(pts[0].y) - w / 2, width: w, height: w)137 if highlighter { ctx.fill(r) } else { ctx.fillEllipse(in: r) }138 return139 }140 if stroke.tool == .marker || highlighter {141 ctx.setLineWidth(width)142 ctx.addPath(smoothPath(pts))143 ctx.strokePath()144 return145 }146 // Pen (and unknown tools): one smooth piece per point, its width following the pressure.147 func mid(_ a: InkPoint, _ b: InkPoint) -> CGPoint { CGPoint(x: (a.x + b.x) / 2, y: (a.y + b.y) / 2) }148 let n = pts.count149 for i in 0..<n {150 let from = i == 0 ? pts[0].cgPoint : mid(pts[i - 1], pts[i])151 let to = i == n - 1 ? pts[n - 1].cgPoint : mid(pts[i], pts[i + 1])152 ctx.setLineWidth(penWidth(width, pts[i].pressure))153 ctx.move(to: from)154 if i == 0 || i == n - 1 { ctx.addLine(to: to) } else { ctx.addQuadCurve(to: to, control: pts[i].cgPoint) }155 ctx.strokePath()156 }157 }158159 /// Width of a pen at a given pressure: 35 % of the nominal width at pressure 0, all of it at pressure 1.160 public static func penWidth(_ width: CGFloat, _ pressure: Double) -> CGFloat {161 let p = CGFloat(min(1, max(0, pressure.isFinite ? pressure : 1)))162 return max(0.1, width * (0.35 + 0.65 * p))163 }164165 /// The pressure that draws a pen stroke `width` wide for a nominal width: the inverse of `penWidth` (clamped to166 /// 0…1). Editors that measure a width (PencilKit, a tablet) store this pressure so that every platform draws the same line.167 public static func pressure(forWidth width: CGFloat, nominal: CGFloat) -> Double {168 guard nominal > 0, width.isFinite, nominal.isFinite else { return 1 }169 return Double(min(1, max(0, (width / nominal - 0.35) / 0.65)))170 }171172 /// The smoothed centre line through the points (quadratic curves between segment midpoints).173 public static func smoothPath(_ points: [InkPoint]) -> CGPath {174 let path = CGMutablePath()175 guard let first = points.first else { return path }176 path.move(to: first.cgPoint)177 guard points.count > 2 else {178 if points.count == 2 { path.addLine(to: points[1].cgPoint) }179 return path180 }181 for i in 1..<(points.count - 1) {182 let m = CGPoint(x: (points[i].x + points[i + 1].x) / 2, y: (points[i].y + points[i + 1].y) / 2)183 path.addQuadCurve(to: m, control: points[i].cgPoint)184 }185 path.addLine(to: points[points.count - 1].cgPoint)186 return path187 }188189 static func cgColor(_ c: InkColor, _ space: CGColorSpace) -> CGColor {190 CGColor(colorSpace: space, components: [CGFloat(c.red) / 255, CGFloat(c.green) / 255, CGFloat(c.blue) / 255, CGFloat(c.alpha) / 255])191 ?? CGColor(gray: 0, alpha: CGFloat(c.alpha) / 255)192 }193}194