Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/MediaBlocks/InkEditorModel.swift3// Description: Model of the mouse / trackpad / touch ink editor: tools (pen, marker, highlighter, eraser by stroke hit4// test), colour, width, undo / redo, simplification of each finished stroke, and the mapping between the view5// and the canvas units of `spn-ink-1`. Produces an `InkDocument`; the preview PNG comes from `InkRenderer`.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import CoreGraphics10import Foundation11import Observation12import SPNotesDocument1314/// Aspect-fit mapping between a view and the canvas units of an ink document.15public struct InkCanvasMapping: Sendable, Equatable {16 public var scale: Double17 public var offset: CGPoint1819 public init(canvas: CGSize, in view: CGSize) {20 guard canvas.width > 0, canvas.height > 0, view.width > 0, view.height > 0 else { scale = 1; offset = .zero; return }21 scale = min(view.width / canvas.width, view.height / canvas.height)22 offset = CGPoint(x: (view.width - canvas.width * scale) / 2, y: (view.height - canvas.height * scale) / 2)23 }2425 public func toCanvas(_ point: CGPoint) -> CGPoint { CGPoint(x: (point.x - offset.x) / scale, y: (point.y - offset.y) / scale) }26 public func toView(_ point: CGPoint) -> CGPoint { CGPoint(x: point.x * scale + offset.x, y: point.y * scale + offset.y) }27 public func canvasRect(_ size: CGSize) -> CGRect { CGRect(x: offset.x, y: offset.y, width: size.width * scale, height: size.height * scale) }28}2930@Observable @MainActor31public final class InkEditorModel {32 public enum Tool: String, Sendable, CaseIterable, Identifiable {33 case pen, marker, highlighter, eraser34 public var id: String { rawValue }35 var inkTool: InkTool? {36 switch self {37 case .pen: return .pen38 case .marker: return .marker39 case .highlighter: return .highlighter40 case .eraser: return nil41 }42 }43 /// Default nominal width in canvas units.44 public var defaultWidth: Double {45 switch self {46 case .pen: return 2.547 case .marker: return 648 case .highlighter: return 1649 case .eraser: return 1250 }51 }52 }5354 /// The ink colours offered (data of the drawing, not UI tokens): graphite, ultramarine, red, green, amber, yellow.55 public static let palette: [InkColor] = ["#151922ff", "#2f5ddbff", "#cc272eff", "#008b4eff", "#d98b09ff", "#ffd54aff"].compactMap(InkColor.init(hex:))5657 public private(set) var document: InkDocument58 public let original: InkDocument59 public var tool: Tool = .pen { didSet { if tool != oldValue { width = tool.defaultWidth } } }60 public var color: InkColor = InkEditorModel.palette[0]61 public var width: Double = Tool.pen.defaultWidth62 /// The stroke being drawn (not yet in the document).63 public private(set) var liveStroke: InkStroke?64 /// Tolerance of the simplification of a finished stroke, in canvas units.65 public var simplifyTolerance = 0.66667 @ObservationIgnored private var undoStack: [InkDocument] = []68 @ObservationIgnored private var redoStack: [InkDocument] = []69 @ObservationIgnored private var erasedInGesture = false70 public private(set) var canUndo = false71 public private(set) var canRedo = false7273 public init(document: InkDocument) {74 self.document = document75 original = document76 }7778 public var hasChanges: Bool { document != original }7980 private func push() {81 undoStack.append(document)82 if undoStack.count > 200 { undoStack.removeFirst() }83 redoStack = []84 refresh()85 }8687 private func refresh() { canUndo = !undoStack.isEmpty; canRedo = !redoStack.isEmpty }8889 /// Starts a stroke (or an erase gesture) at a point in canvas units.90 public func begin(at point: CGPoint, pressure: Double = 1) {91 erasedInGesture = false92 if let inkTool = tool.inkTool {93 liveStroke = InkStroke(tool: inkTool, color: color, width: width, points: [InkPoint(x: point.x, y: point.y, pressure: pressure)])94 } else {95 erase(at: point)96 }97 }9899 public func move(to point: CGPoint, pressure: Double = 1) {100 if tool == .eraser { erase(at: point); return }101 guard var stroke = liveStroke else { return }102 if let last = stroke.points.last, hypot(last.x - point.x, last.y - point.y) < 0.25 { return }103 stroke.points.append(InkPoint(x: point.x, y: point.y, pressure: pressure))104 liveStroke = stroke105 }106107 public func end() {108 defer { liveStroke = nil }109 guard let stroke = liveStroke, !stroke.points.isEmpty else { return }110 push()111 document.strokes.append(stroke.simplified(tolerance: simplifyTolerance))112 }113114 public func cancelStroke() { liveStroke = nil }115116 /// Removes every stroke passing within the eraser's radius of the point (a whole erase gesture is one undo step).117 private func erase(at point: CGPoint) {118 let hits = document.strokeIndices(near: point, radius: width / 2)119 guard !hits.isEmpty else { return }120 if !erasedInGesture { push(); erasedInGesture = true }121 for index in hits.sorted(by: >) { document.strokes.remove(at: index) }122 }123124 public func clear() {125 guard !document.strokes.isEmpty else { return }126 push()127 document.strokes = []128 }129130 public func undo() {131 guard let previous = undoStack.popLast() else { return }132 redoStack.append(document)133 document = previous134 refresh()135 }136137 public func redo() {138 guard let next = redoStack.popLast() else { return }139 undoStack.append(document)140 document = next141 refresh()142 }143144 /// The PNG the caller uploads as the `preview` attachment of a `drawing` node (2×, transparent unless the node145 /// has a background).146 public func previewPNG(background: String = "none", scale: CGFloat = 2) -> Data? {147 InkDrawingExport.previewPNG(document, background: background, scale: scale)148 }149}150151/// What a caller needs to store an edited drawing: write `ink` (JSON) + `preview` (PNG) and set `pk: null` because the152/// ink was changed without PencilKit (SPEC §2).153public enum InkDrawingExport {154 public static func inkJSON(_ document: InkDocument) -> Data { document.jsonData() }155156 public static func previewPNG(_ document: InkDocument, background: String = "none", scale: CGFloat = 2) -> Data? {157 InkRenderer.pngData(document, scale: scale, background: InkBackground(attr: background), crop: .canvas)158 }159160 /// Uploads both files and returns the node updated for them (`pk` cleared). Throws the loader's failure (offline…)161 /// without changing anything.162 public static func store(_ document: InkDocument, into block: DrawingBlock, pageId: String?, loader: FeatureAttachmentLoader) async throws -> DrawingBlock {163 guard let png = previewPNG(document, background: block.background) else {164 throw FeatureFailure(kind: .other, message: L("L'aperçu du dessin n'a pas pu être produit."))165 }166 let ink = try await loader.upload(inkJSON(document), filename: "dessin.spn-ink.json", mimeType: "application/json", pageId: pageId)167 let preview = try await loader.upload(png, filename: "dessin.png", mimeType: "image/png", pageId: pageId)168 var out = block169 out.setInk(attachmentId: ink, preview: preview, width: document.width, height: document.height, pk: nil)170 return out171 }172}173