SPB Git

Repository Public

InkConversion.swift 10.7 KB 182 lines swift

1// SP Notes iOS2// File: Core/Ink/InkConversion.swift3// Description: `PKDrawing` ⇄ `InkDocument` (`spn-ink-1`, SPEC §2). PencilKit → ink: every visible part of every stroke is sampled4//              along its path at a fixed parametric step, simplified, and written with its tool, colour, width and pressures.5//              Ink → PencilKit: the polyline is resampled at a fixed distance and used as the control points of a B-spline, so a6//              drawing made on the web or on the Mac (no `pk` attachment) opens in PencilKit with the same strokes.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import CoreGraphics11import PencilKit12import SPNotesCore13import UIKit1415/// Conversion between PencilKit and the neutral ink format.16///17/// Mapping (the doc comment of Core's `InkTool` is the reference):18/// - ink type: `pen`, `pencil`, `monoline`, `fountainPen`, `watercolor`, `crayon` → `pen`; `marker` → `marker`, or `highlighter` when19///   its colour is translucent. Back: `pen` → `.pen`, `marker` → `.marker`, `highlighter` → `.marker` with the colour's alpha20///   (`InkRenderer.highlighterOpacity` when the stored colour is opaque). The exact PencilKit ink type is also written in the21///   stroke's `pkInk` field (an unknown key for the other editors, which keep it) so a pencil stays a pencil without the `pk` file.22/// - colour: sRGB `#rrggbbaa`.23/// - width: the widest `PKStrokePoint.size.width` of the stroke — its width at full pressure.24/// - pressure: the force as PencilKit applied it, normalised to 0…1 against the stroke's full-pressure width (the inverse of25///   `InkRenderer.penWidth`), so the neutral renderers draw the widths PencilKit drew. `monoline` writes 1 everywhere.26///   Back: `size` = `InkRenderer.penWidth(width, pressure)` and `force` = pressure.27enum InkConversion {28    struct Options: Sendable {29        /// Step of the sampling along a `PKStrokePath`, in units of its parameter (1 = one control point).30        var parametricStep: CGFloat = 0.2531        /// Ramer–Douglas–Peucker tolerance applied to the sampled points, in canvas units.32        var tolerance: Double = 0.233        var pressureTolerance: Double = 0.0334        /// Distance between the control points of a stroke rebuilt from ink, in canvas units.35        var rebuildStep: Double = 136        static let standard = Options()37    }3839    /// Field of an ink stroke holding the PencilKit ink type it was drawn with.40    static let inkTypeField = "pkInk"4142    // MARK: PencilKit → ink4344    static func inkDocument(from drawing: PKDrawing, canvasSize: CGSize, options: Options = .standard) -> InkDocument {45        var document = InkDocument(width: round2(Double(canvasSize.width)), height: round2(Double(canvasSize.height)))46        document.strokes = drawing.strokes.flatMap { inkStrokes(from: $0, options: options) }47        return document48    }4950    /// One ink stroke per visible range of the PencilKit stroke (a bitmap eraser cuts a stroke into several ranges).51    static func inkStrokes(from stroke: PKStroke, options: Options = .standard) -> [InkStroke] {52        let path = stroke.path53        guard path.count > 0 else { return [] }54        let transform = stroke.transform55        let scale = sqrt(abs(transform.a * transform.d - transform.b * transform.c))56        let ranges: [ClosedRange<CGFloat>] = stroke.mask == nil ? [0...CGFloat(max(0, path.count - 1))] : stroke.maskedPathRanges57        let (tool, color) = toolAndColor(of: stroke.ink)58        let monoline = stroke.ink.inkType == .monoline59        var result: [InkStroke] = []60        for range in ranges {61            var samples: [(CGPoint, CGFloat)] = []62            for point in path.interpolatedPoints(in: range, by: .parametricStep(options.parametricStep)) {63                samples.append((point.location.applying(transform), max(point.size.width, point.size.height) * scale))64            }65            guard !samples.isEmpty else { continue }66            let width = max(samples.map(\.1).max() ?? 1, 0.1)67            var ink = InkStroke(tool: tool, color: color, width: round2(Double(width)), points: samples.map { location, size in68                InkPoint(x: round2(Double(location.x)), y: round2(Double(location.y)), pressure: monoline ? 1 : round3(pressure(forSize: size, width: width)))69            })70            ink[inkTypeField] = .string(stroke.ink.inkType.rawValue)71            ink = ink.simplified(tolerance: options.tolerance, pressureTolerance: options.pressureTolerance)72            // the pressure is always written, so that a reader which defaults a missing pressure differently reads the same value73            ink.points = ink.points.map { InkPoint(x: $0.x, y: $0.y, pressure: $0.pressure) }74            result.append(ink)75        }76        return result77    }7879    /// The pressure giving `size` for a stroke of nominal `width`: Core's single width law (`InkRenderer.pressure(forWidth:nominal:)`,80    /// shared with the web since Core 2.0 final).81    static func pressure(forSize size: CGFloat, width: CGFloat) -> Double { InkRenderer.pressure(forWidth: size, nominal: width) }8283    static func toolAndColor(of ink: PKInk) -> (InkTool, InkColor) {84        let color = inkColor(ink.color)85        if ink.inkType == .marker { return (color.alpha < 255 ? .highlighter : .marker, color) }86        return (.pen, color)87    }8889    static func inkColor(_ color: UIColor) -> InkColor {90        let space = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB()91        if let converted = color.cgColor.converted(to: space, intent: .defaultIntent, options: nil), let c = converted.components, c.count >= 4 {92            return InkColor(red: Double(c[0]), green: Double(c[1]), blue: Double(c[2]), alpha: Double(c[3]))93        }94        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 195        color.getRed(&r, green: &g, blue: &b, alpha: &a)96        return InkColor(red: Double(r), green: Double(g), blue: Double(b), alpha: Double(a))97    }9899    static func uiColor(_ color: InkColor) -> UIColor {100        UIColor(red: CGFloat(color.red) / 255, green: CGFloat(color.green) / 255, blue: CGFloat(color.blue) / 255, alpha: CGFloat(color.alpha) / 255)101    }102103    // MARK: ink → PencilKit104105    static func drawing(from document: InkDocument, options: Options = .standard) -> PKDrawing {106        PKDrawing(strokes: document.strokes.compactMap { stroke(from: $0, options: options) })107    }108109    static func ink(for stroke: InkStroke) -> PKInk {110        var color = uiColor(stroke.color)111        if stroke.tool == .highlighter {112            if stroke.color.alpha == 255 { color = color.withAlphaComponent(CGFloat(InkRenderer.highlighterOpacity)) }113            return PKInk(.marker, color: color)114        }115        if stroke.tool == .marker { return PKInk(.marker, color: stroke.color.alpha == 255 ? color : color.withAlphaComponent(1)) }116        // a pen, or a tool this build does not know (drawn like a pen): the PencilKit ink it was drawn with when it is recorded117        if let raw = stroke[inkTypeField]?.stringValue, let type = PKInk.InkType(rawValue: raw), type != .marker { return PKInk(type, color: color) }118        return PKInk(.pen, color: color)119    }120121    static func stroke(from stroke: InkStroke, options: Options = .standard) -> PKStroke? {122        let points = stroke.points.filter { $0.x.isFinite && $0.y.isFinite }123        guard !points.isEmpty, stroke.width > 0, stroke.width.isFinite else { return nil }124        let variable = stroke.tool != .marker && stroke.tool != .highlighter125        let dense = resample(points, step: max(0.25, options.rebuildStep))126        let controls = dense.enumerated().map { index, point -> PKStrokePoint in127            let pressure = min(1, max(0, point.pressure.isFinite ? point.pressure : 1))128            let size = variable ? InkRenderer.penWidth(CGFloat(stroke.width), pressure) : CGFloat(stroke.width)129            return PKStrokePoint(location: point.cgPoint, timeOffset: Double(index) * 0.004, size: CGSize(width: size, height: size), opacity: 1,130                                 force: CGFloat(pressure), azimuth: 0, altitude: .pi / 2)131        }132        return PKStroke(ink: ink(for: stroke), path: PKStrokePath(controlPoints: controls, creationDate: Date()))133    }134135    /// The polyline with a point every `step` at most (positions and pressures interpolated linearly); its vertices are kept.136    static func resample(_ points: [InkPoint], step: Double) -> [InkPoint] {137        guard points.count > 1 else { return points }138        var out: [InkPoint] = [points[0]]139        for i in 1..<points.count {140            let a = points[i - 1], b = points[i]141            let length = hypot(b.x - a.x, b.y - a.y)142            let pieces = max(1, Int((length / step).rounded(.up)))143            for k in 1...pieces {144                let t = Double(k) / Double(pieces)145                out.append(InkPoint(x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t, pressure: a.pressure + (b.pressure - a.pressure) * t))146            }147        }148        return out149    }150151    // MARK: canvas152153    /// Where a drawing sits on its canvas when it is saved.154    struct Placement: Equatable {155        /// Translation to apply to the drawing before it is written (zero when nothing moves).156        var offset: CGSize157        var size: CGSize158    }159160    static let margin: CGFloat = 24161    static let minimumCanvas = CGSize(width: 120, height: 80)162163    /// A new drawing is cropped to its strokes plus a margin. A drawing that already has a canvas keeps its origin: the canvas only164    /// grows (and everything shifts only if strokes went past the top or the left edge).165    static func placement(of drawing: PKDrawing, existingCanvas: CGSize?) -> Placement {166        var bounds = drawing.bounds167        if bounds.isNull || bounds.isInfinite || bounds.isEmpty { bounds = .zero }168        if let existing = existingCanvas, existing.width > 0, existing.height > 0 {169            let dx = bounds.minX < 0 ? -bounds.minX + margin : 0, dy = bounds.minY < 0 ? -bounds.minY + margin : 0170            let size = CGSize(width: max(existing.width + dx, (bounds.maxX + dx + margin).rounded(.up)), height: max(existing.height + dy, (bounds.maxY + dy + margin).rounded(.up)))171            return Placement(offset: CGSize(width: dx, height: dy), size: size)172        }173        guard drawing.strokes.isEmpty == false else { return Placement(offset: .zero, size: minimumCanvas) }174        let offset = CGSize(width: (margin - bounds.minX).rounded(), height: (margin - bounds.minY).rounded())175        let size = CGSize(width: max(minimumCanvas.width, (bounds.width + 2 * margin).rounded(.up)), height: max(minimumCanvas.height, (bounds.height + 2 * margin).rounded(.up)))176        return Placement(offset: offset, size: size)177    }178179    private static func round2(_ value: Double) -> Double { (value * 100).rounded() / 100 }180    private static func round3(_ value: Double) -> Double { (value * 1000).rounded() / 1000 }181}182
Files main
Menu

Theme