Repository Public
1// SP Notes iOS2// File: Features/Drawing/DrawingBlockIO.swift3// Description: Reading and writing a `drawing` block (SPEC §2). Reading: the PencilKit data when the block has it (fast path),4// otherwise the strokes rebuilt from the `spn-ink-1` attachment (a drawing edited on the web or on the Mac). Writing:5// three attachments — ink JSON, PNG preview at 2×, PencilKit data — then the block attributes. Attachments replaced6// by a save are never deleted here.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import PencilKit11import SPNotesCore12import UIKit1314@MainActor15enum DrawingBlockIO {16 enum Origin: Equatable, Sendable {17 /// A block without any file yet.18 case new19 /// Read from the `pk` attachment.20 case pencilKit21 /// Rebuilt from the `ink` attachment (no usable `pk`).22 case rebuiltFromInk23 }2425 struct Loaded {26 var drawing: PKDrawing27 var origin: Origin28 /// The canvas the block declares (nil for a new block).29 var canvas: CGSize?30 }3132 enum Failure: Error, Equatable, Sendable {33 /// The files of the drawing are not on this device and could not be fetched.34 case filesMissing35 /// The files are here and cannot be read as a drawing.36 case unreadable37 /// The block only has a picture: there is nothing to edit.38 case previewOnly3940 var message: String {41 switch self {42 case .filesMissing: String(localized: "Les fichiers de ce dessin ne sont pas sur cet appareil pour l’instant. Ils seront disponibles une fois téléchargés. Rien n’a été modifié.")43 case .unreadable: String(localized: "Les données de ce dessin ne peuvent pas être lues par cette version. Rien n’a été modifié.")44 case .previewOnly: String(localized: "Ce dessin n’a qu’une image, sans tracé modifiable. Rien n’a été modifié.")45 }46 }47 }4849 static func load(_ block: DrawingBlock, app: AppModel) async -> Result<Loaded, Failure> {50 let canvas: CGSize? = block.width > 0 && block.height > 0 ? CGSize(width: block.width, height: block.height) : nil51 guard block.pk != nil || block.ink != nil else { return block.preview == nil ? .success(Loaded(drawing: PKDrawing(), origin: .new, canvas: nil)) : .failure(.previewOnly) }52 var failure = Failure.filesMissing53 if let id = block.pk {54 if let url = try? await app.localFile(forAttachment: id), let data = try? Data(contentsOf: url) {55 if let drawing = try? PKDrawing(data: data) { return .success(Loaded(drawing: drawing, origin: .pencilKit, canvas: canvas)) }56 failure = .unreadable57 }58 }59 if let id = block.ink {60 if let url = try? await app.localFile(forAttachment: id), let data = try? Data(contentsOf: url) {61 if let ink = try? InkDocument(data: data) {62 let size = ink.width > 0 && ink.height > 0 ? ink.size : canvas63 return .success(Loaded(drawing: InkConversion.drawing(from: ink), origin: .rebuiltFromInk, canvas: size))64 }65 failure = .unreadable66 }67 }68 return .failure(failure)69 }7071 struct Saved {72 var block: DrawingBlock73 var ink: InkDocument74 /// The drawing as written (moved onto its canvas).75 var drawing: PKDrawing76 /// Attachments the block referenced before this save. They are left in place: the editor's undo, the note's history,77 /// a conflict copy or a duplicated block may still show them.78 var replaced: [String]79 }8081 /// Writes `ink`, `preview` and `pk` as attachments of the note and returns the block pointing at them.82 static func save(_ drawing: PKDrawing, background: String, into block: DrawingBlock, app: AppModel, noteId: String) async throws -> Saved {83 let existing: CGSize? = block.width > 0 && block.height > 0 ? CGSize(width: block.width, height: block.height) : nil84 let placement = InkConversion.placement(of: drawing, existingCanvas: existing)85 let placed = placement.offset == .zero ? drawing : drawing.transformed(using: CGAffineTransform(translationX: placement.offset.width, y: placement.offset.height))86 let ink = InkConversion.inkDocument(from: placed, canvasSize: placement.size)87 let preview = DrawingRenderer.image(of: placed, in: CGRect(origin: .zero, size: placement.size), background: DrawingPaper.color(background)).pngData() ?? Data()88 let stem = "drawing-\(UUID().uuidString.lowercased())"89 let inkId = try attachmentId(of: await app.attach(data: ink.jsonData(), filename: stem + ".ink.json", mime: "application/json", to: noteId))90 let previewId = try attachmentId(of: await app.attach(data: preview, filename: stem + ".png", mime: "image/png", to: noteId))91 let pkId = try attachmentId(of: await app.attach(data: placed.dataRepresentation(), filename: stem + ".pkdrawing", mime: "application/octet-stream", to: noteId))92 var saved = block93 let replaced = [block.ink, block.preview, block.pk].compactMap { $0 }94 saved.setInk(attachmentId: inkId, preview: previewId, width: Double(placement.size.width), height: Double(placement.size.height), pk: pkId)95 saved.background = background96 return Saved(block: saved, ink: ink, drawing: placed, replaced: replaced)97 }9899 /// The id of the attachment behind the node `AppModel.attach` returns (an image or a file block).100 static func attachmentId(of node: PMNode) throws -> String {101 if let id = node.stringAttr("attachmentId") ?? AttachmentFiles.attachmentID(fromSource: node.stringAttr("src") ?? "") { return id }102 throw CocoaError(.fileWriteUnknown)103 }104105 // MARK: 1.0 drawings106107 /// Converts a 1.0 drawing (a picture + its PencilKit source found by name) into a `drawing` block. The 1.0 picture was108 /// rendered on white: the block gets a white paper so it looks the same. Nothing of the 1.0 drawing is deleted.109 static func convertLegacy(_ drawing: PKDrawing, imageNode: PMNode, app: AppModel, noteId: String) async throws -> Saved {110 var block = DrawingBlock(background: DrawingPaper.white)111 // the block takes the place of the picture: it keeps its block id, so links to it still land112 if let id = imageNode.stringAttr("id"), !id.isEmpty { block.id = id }113 return try await save(drawing, background: DrawingPaper.white, into: block, app: app, noteId: noteId)114 }115}116