Repository Public
1// SP Notes Core2// File: Sources/SPNotesDocument/Ink.swift3// Description: The platform-neutral ink format `spn-ink-1` of `drawing` nodes: lossless model (unknown fields kept),4// colours, stroke simplification, bounding boxes and hit testing. No UI framework.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreGraphics1011/// Errors thrown when reading an ink document.12public enum InkError: Error, Sendable, Hashable {13 /// The `format` field is not `spn-ink-1` (the value found, nil when absent or not a string).14 case unsupportedFormat(String?)15 /// The JSON is valid but is not an ink document (what is wrong).16 case invalid(String)17}1819/// The tool of a stroke. Unknown tool names are preserved and drawn like a pen.20///21/// PencilKit mapping used by the iOS app (PencilKit cannot be imported in this module):22/// `PKInkType.pen`, `.pencil`, `.monoline`, `.fountainPen`, `.watercolor`, `.crayon` → `.pen`23/// (`.monoline` should set every pressure to 1); `.marker` → `.marker`; a marker ink with alpha < 1 used as a24/// highlighter → `.highlighter`. Reverse: `.pen` → `PKInkType.pen`, `.marker` → `.marker`,25/// `.highlighter` → `.marker` with the colour's alpha. A `PKStrokePoint` maps to an `InkPoint` with26/// `location` → x / y (canvas units), `force` normalised to 0…1 → pressure, and the stroke's base width27/// (`PKStrokePoint.size.width` at full pressure) → `InkStroke.width`.28public struct InkTool: RawRepresentable, Sendable, Hashable, Codable, CustomStringConvertible {29 public var rawValue: String30 public init(rawValue: String) { self.rawValue = rawValue }3132 public static let pen = InkTool(rawValue: "pen")33 public static let marker = InkTool(rawValue: "marker")34 public static let highlighter = InkTool(rawValue: "highlighter")3536 /// Whether the tool is one of the three the format defines.37 public var isKnown: Bool { self == .pen || self == .marker || self == .highlighter }38 public var description: String { rawValue }39}4041/// An sRGB colour with alpha, written `#rrggbbaa`.42public struct InkColor: Sendable, Hashable, Codable, CustomStringConvertible {43 public var red: UInt844 public var green: UInt845 public var blue: UInt846 public var alpha: UInt84748 public init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8 = 255) {49 self.red = red50 self.green = green51 self.blue = blue52 self.alpha = alpha53 }5455 /// Components in 0…1 (clamped).56 public init(red: Double, green: Double, blue: Double, alpha: Double = 1) {57 func byte(_ v: Double) -> UInt8 { UInt8((min(1, max(0, v.isFinite ? v : 0)) * 255).rounded()) }58 self.init(red: byte(red), green: byte(green), blue: byte(blue), alpha: byte(alpha))59 }6061 /// Parses `#rrggbbaa` or `#rrggbb` (alpha 255), case-insensitive. Nil for anything else.62 public init?(hex: String) {63 let u = Array(hex.utf8)64 guard u.count == 9 || u.count == 7, u[0] == 0x23 else { return nil }65 var v: [UInt8] = []66 for b in u.dropFirst() {67 switch b {68 case 0x30...0x39: v.append(b - 0x30)69 case 0x41...0x46: v.append(b - 0x41 + 10)70 case 0x61...0x66: v.append(b - 0x61 + 10)71 default: return nil72 }73 }74 self.init(red: v[0] << 4 | v[1], green: v[2] << 4 | v[3], blue: v[4] << 4 | v[5], alpha: v.count == 8 ? v[6] << 4 | v[7] : 255)75 }7677 public static let black = InkColor(red: UInt8(0), green: 0, blue: 0)78 public static let white = InkColor(red: UInt8(255), green: 255, blue: 255)7980 /// `#rrggbbaa`, lowercase.81 public var hex: String {82 let d = Array("0123456789abcdef")83 return "#" + String([red, green, blue, alpha].flatMap { [d[Int($0 >> 4)], d[Int($0 & 15)]] })84 }85 public var description: String { hex }8687 /// The alpha in 0…1.88 public var opacity: Double { Double(alpha) / 255 }8990 public init(from decoder: Decoder) throws {91 let s = try decoder.singleValueContainer().decode(String.self)92 guard let c = InkColor(hex: s) else {93 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Invalid colour \(s)"))94 }95 self = c96 }9798 public func encode(to encoder: Encoder) throws {99 var c = encoder.singleValueContainer()100 try c.encode(hex)101 }102}103104/// One sample of a stroke, in canvas units (origin top-left, y down), with a pressure in 0…1.105public struct InkPoint: Sendable, Hashable {106 public var x: Double107 public var y: Double108 public var pressure: Double109 /// False for a point read as `[x, y]`: it is written back without a pressure as long as the pressure stays 1.110 var explicitPressure: Bool111112 public init(x: Double, y: Double, pressure: Double = 1) {113 self.x = x114 self.y = y115 self.pressure = pressure116 self.explicitPressure = true117 }118119 public var cgPoint: CGPoint { CGPoint(x: x, y: y) }120121 init(json: JSONValue) throws {122 guard case .array(let a) = json, a.count >= 2, let x = a[0].doubleValue, let y = a[1].doubleValue else {123 throw InkError.invalid("A point must be an array [x, y, pressure]")124 }125 self.x = x126 self.y = y127 if a.count >= 3 {128 guard let p = a[2].doubleValue else { throw InkError.invalid("The pressure of a point must be a number") }129 pressure = p130 explicitPressure = true131 } else {132 pressure = 1133 explicitPressure = false134 }135 }136137 var jsonValue: JSONValue {138 if !explicitPressure, pressure == 1 { return .array([InkJSON.number(x), InkJSON.number(y)]) }139 return .array([InkJSON.number(x), InkJSON.number(y), InkJSON.number(pressure)])140 }141}142143/// JSON helpers shared by the ink and canvas models.144enum InkJSON {145 /// A number as the models store it: an integral value is an integer (so `2.0` and `2` compare equal).146 static func number(_ d: Double) -> JSONValue {147 if d.isFinite, d == d.rounded(), abs(d) < 9.007199254740992e15 { return .int(Int64(d)) }148 return .double(d)149 }150151 /// The value with every integral double turned into an integer, recursively.152 static func normalized(_ v: JSONValue) -> JSONValue {153 switch v {154 case .double(let d): return number(d)155 case .array(let a): return .array(a.map(normalized))156 case .object(let o): return .object(o.mapValues(normalized))157 default: return v158 }159 }160161 static func normalized(_ o: [String: JSONValue]) -> [String: JSONValue] { o.mapValues(normalized) }162}163164/// One stroke. `fields` holds every key of the JSON object but `points`, so unknown keys round-trip.165public struct InkStroke: Sendable, Hashable, Codable {166 /// Every field of the stroke except `points` (known and unknown), as stored.167 public private(set) var fields: [String: JSONValue]168 public var points: [InkPoint]169170 public init(tool: InkTool = .pen, color: InkColor = .black, width: Double = 2, points: [InkPoint] = []) {171 fields = ["tool": .string(tool.rawValue), "color": .string(color.hex), "width": InkJSON.number(width)]172 self.points = points173 }174175 /// The tool; `pen` when the field is missing.176 public var tool: InkTool {177 get { InkTool(rawValue: fields["tool"]?.stringValue ?? "pen") }178 set { fields["tool"] = .string(newValue.rawValue) }179 }180181 /// The colour; opaque black when the field is missing or unreadable (the stored text is then kept until set).182 public var color: InkColor {183 get { fields["color"]?.stringValue.flatMap(InkColor.init(hex:)) ?? .black }184 set { fields["color"] = .string(newValue.hex) }185 }186187 /// The nominal width in canvas units (at pressure 1 for a pen).188 public var width: Double {189 get { fields["width"]?.doubleValue ?? 1 }190 set { fields["width"] = InkJSON.number(newValue) }191 }192193 /// Reads or writes any field but `points` (unknown ones included); nil removes the key.194 public subscript(field: String) -> JSONValue? {195 get { fields[field] }196 set { if field != "points" { fields[field] = newValue.map(InkJSON.normalized) } }197 }198199 public init(json: JSONValue) throws {200 guard case .object(var o) = json else { throw InkError.invalid("A stroke must be a JSON object") }201 guard case .array(let pts)? = o["points"] else { throw InkError.invalid("A stroke must have a points array") }202 points = try pts.map(InkPoint.init(json:))203 o["points"] = nil204 fields = InkJSON.normalized(o)205 }206207 public var jsonValue: JSONValue {208 var o = fields209 o["points"] = .array(points.map(\.jsonValue))210 return .object(o)211 }212213 public init(from decoder: Decoder) throws { try self.init(json: JSONValue(from: decoder)) }214 public func encode(to encoder: Encoder) throws { try jsonValue.encode(to: encoder) }215216 // MARK: Geometry217218 /// The box enclosing the stroke, half its width included; `.null` for a stroke without points.219 public var boundingBox: CGRect {220 guard let first = points.first else { return .null }221 var minX = first.x, maxX = first.x, minY = first.y, maxY = first.y222 for p in points.dropFirst() {223 minX = min(minX, p.x); maxX = max(maxX, p.x); minY = min(minY, p.y); maxY = max(maxY, p.y)224 }225 let h = max(0, width) / 2226 return CGRect(x: minX - h, y: minY - h, width: maxX - minX + 2 * h, height: maxY - minY + 2 * h)227 }228229 /// Distance from `point` to the centre line of the stroke; infinity for a stroke without points.230 public func distance(to point: CGPoint) -> Double {231 guard let first = points.first else { return .infinity }232 let px = Double(point.x), py = Double(point.y)233 var best = hypot(px - first.x, py - first.y)234 for i in points.indices.dropFirst() {235 best = min(best, InkGeometry.segmentDistance(px, py, points[i - 1], points[i]))236 }237 return best238 }239240 /// Whether the inked area (centre line thickened by half the width) comes within `radius` of `point`.241 public func hit(_ point: CGPoint, radius: Double = 0) -> Bool {242 distance(to: point) <= max(0, width) / 2 + max(0, radius)243 }244245 /// The stroke with fewer points: Ramer–Douglas–Peucker with `tolerance` in canvas units. A point is also246 /// kept when its pressure differs from the interpolation of its kept neighbours by more than247 /// `pressureTolerance`. The first and last points always stay; a tolerance ≤ 0 changes nothing.248 public func simplified(tolerance: Double, pressureTolerance: Double = 0.1) -> InkStroke {249 guard tolerance > 0, tolerance.isFinite, points.count > 2 else { return self }250 var keep = [Bool](repeating: false, count: points.count)251 keep[0] = true252 keep[points.count - 1] = true253 var stack = [(0, points.count - 1)]254 let pTol = pressureTolerance > 0 ? pressureTolerance : .infinity255 while let (a, b) = stack.popLast() {256 guard b > a + 1 else { continue }257 let pa = points[a], pb = points[b]258 var worst = 0.0, index = -1259 for i in (a + 1)..<b {260 let p = points[i]261 let (d, t) = InkGeometry.segmentDistanceAndParameter(p.x, p.y, pa, pb)262 let dp = abs(p.pressure - (pa.pressure + (pb.pressure - pa.pressure) * t))263 let score = max(d / tolerance, dp / pTol)264 if score > worst { worst = score; index = i }265 }266 if worst > 1, index > 0 {267 keep[index] = true268 stack.append((a, index))269 stack.append((index, b))270 }271 }272 var out = self273 out.points = points.indices.filter { keep[$0] }.map { points[$0] }274 return out275 }276}277278enum InkGeometry {279 static func segmentDistanceAndParameter(_ px: Double, _ py: Double, _ a: InkPoint, _ b: InkPoint) -> (Double, Double) {280 let dx = b.x - a.x, dy = b.y - a.y281 let len2 = dx * dx + dy * dy282 guard len2 > 0 else { return (hypot(px - a.x, py - a.y), 0) }283 let t = min(1, max(0, ((px - a.x) * dx + (py - a.y) * dy) / len2))284 return (hypot(px - (a.x + t * dx), py - (a.y + t * dy)), t)285 }286287 static func segmentDistance(_ px: Double, _ py: Double, _ a: InkPoint, _ b: InkPoint) -> Double {288 segmentDistanceAndParameter(px, py, a, b).0289 }290}291292/// An ink document (`spn-ink-1`): a canvas size and strokes. Unknown top-level and stroke fields are preserved;293/// numbers beyond the third of a point are not (the format defines exactly `[x, y, pressure]`).294public struct InkDocument: Sendable, Hashable, Codable {295 public static let format = "spn-ink-1"296297 /// Every top-level field except `strokes` (known and unknown), as stored.298 public private(set) var fields: [String: JSONValue]299 public var strokes: [InkStroke]300301 public init(width: Double, height: Double, strokes: [InkStroke] = []) {302 fields = ["format": .string(Self.format), "width": InkJSON.number(width), "height": InkJSON.number(height)]303 self.strokes = strokes304 }305306 /// Canvas width in canvas units.307 public var width: Double {308 get { fields["width"]?.doubleValue ?? 0 }309 set { fields["width"] = InkJSON.number(newValue) }310 }311312 /// Canvas height in canvas units.313 public var height: Double {314 get { fields["height"]?.doubleValue ?? 0 }315 set { fields["height"] = InkJSON.number(newValue) }316 }317318 public var size: CGSize { CGSize(width: width, height: height) }319 public var isEmpty: Bool { strokes.allSatisfy { $0.points.isEmpty } }320321 /// Reads or writes any top-level field but `strokes` and `format`; nil removes the key.322 public subscript(field: String) -> JSONValue? {323 get { fields[field] }324 set { if field != "strokes", field != "format" { fields[field] = newValue.map(InkJSON.normalized) } }325 }326327 /// Reads a document. Throws `InkError.unsupportedFormat` when `format` is not `spn-ink-1`.328 public init(json: JSONValue) throws {329 guard case .object(var o) = json else { throw InkError.invalid("An ink document must be a JSON object") }330 guard o["format"]?.stringValue == Self.format else { throw InkError.unsupportedFormat(o["format"]?.stringValue) }331 switch o["strokes"] {332 case .array(let items)?: strokes = try items.map(InkStroke.init(json:))333 case nil: throw InkError.invalid("An ink document must have a strokes array")334 default: throw InkError.invalid("strokes must be an array")335 }336 o["strokes"] = nil337 fields = InkJSON.normalized(o)338 }339340 /// Reads the bytes of an ink attachment. Throws `DocumentError.invalidJSON` or `InkError`.341 public init(data: Data) throws { try self.init(json: JSONValue(data: data)) }342343 public var jsonValue: JSONValue {344 var o = fields345 o["strokes"] = .array(strokes.map(\.jsonValue))346 return .object(o)347 }348349 /// Canonical JSON (sorted keys, no whitespace): the bytes to upload as the `ink` attachment.350 public func jsonData() -> Data { jsonValue.canonicalData() }351352 public init(from decoder: Decoder) throws { try self.init(json: JSONValue(from: decoder)) }353 public func encode(to encoder: Encoder) throws { try jsonValue.encode(to: encoder) }354355 // MARK: Geometry356357 /// The box enclosing every stroke; `.null` when nothing is drawn.358 public var boundingBox: CGRect { strokes.reduce(CGRect.null) { $0.union($1.boundingBox) } }359360 /// Every stroke simplified (see `InkStroke.simplified`); strokes left without points are removed.361 public func simplified(tolerance: Double, pressureTolerance: Double = 0.1) -> InkDocument {362 var out = self363 out.strokes = strokes.filter { !$0.points.isEmpty }.map { $0.simplified(tolerance: tolerance, pressureTolerance: pressureTolerance) }364 return out365 }366367 /// Indices of the strokes whose ink comes within `radius` of `point` (eraser by stroke).368 public func strokeIndices(near point: CGPoint, radius: Double) -> [Int] {369 strokes.indices.filter { strokes[$0].hit(point, radius: radius) }370 }371372 /// Indices of the strokes having at least one point inside `rect` (lasso / rectangular selection).373 public func strokeIndices(intersecting rect: CGRect) -> [Int] {374 strokes.indices.filter { i in375 strokes[i].boundingBox.intersects(rect) && strokes[i].points.contains { rect.contains($0.cgPoint) }376 }377 }378379 /// Number of points of all strokes.380 public var pointCount: Int { strokes.reduce(0) { $0 + $1.points.count } }381}382