Repository Public
1// SP Notes iOS2// File: Features/Drawing/DrawingScreen.swift3// Description: The full-screen PencilKit editor shared by the `drawing` block (2.0) and the 1.0 drawings (picture + PencilKit4// source): tool picker with pens, highlighter, vector and bitmap erasers, lasso and ruler; undo / redo; a growing5// paper; finger or Pencil-only input; smart shapes; handwriting → text for a framed region; paper background.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import PencilKit10import SPNotesCore11import SPNotesDesign12import SwiftUI13import UIKit1415/// What the 1.0 drawing editor hands back on "Terminé".16struct DrawingResult: Sendable {17 /// `PKDrawing.dataRepresentation()` — the editable source, to store next to the picture.18 var drawingData: Data19 /// The drawing on white at 2x, cropped to its bounds plus a margin.20 var png: Data21 /// Handwriting the user chose to insert below the drawing (never recognised or inserted without being asked); nil when none.22 var recognizedText: String?23 /// True when the drawing has no stroke.24 var isEmpty: Bool25}2627/// Rendering of a drawing for export, independent of the screen's appearance.28enum DrawingRenderer {29 static let margin: CGFloat = 2430 static let scale: CGFloat = 23132 /// PNG on white, light appearance (black ink stays black), cropped to the strokes plus `margin`. An empty drawing gives a small white picture.33 @MainActor34 static func png(of drawing: PKDrawing) -> Data {35 image(of: drawing).pngData() ?? Data()36 }3738 @MainActor39 static func image(of drawing: PKDrawing) -> UIImage {40 var bounds = drawing.bounds41 if bounds.isNull || bounds.isInfinite || bounds.isEmpty { bounds = CGRect(x: 0, y: 0, width: 64, height: 64) }42 return image(of: drawing, in: bounds.insetBy(dx: -margin, dy: -margin).integral, background: .white)43 }4445 /// The part `rect` of the drawing at 2×, as in light mode, on `background` (nil = transparent).46 @MainActor47 static func image(of drawing: PKDrawing, in rect: CGRect, background: UIColor?) -> UIImage {48 // 2×, less for a canvas so large that the bitmap would pass 8192 px on a side49 let scale = max(0.25, min(Self.scale, CGFloat(InkRenderer.maxPixels) / max(rect.width, rect.height, 1)))50 var ink: UIImage?51 // PencilKit adapts ink colours to the current appearance: render as in light mode so the export matches paper.52 UITraitCollection(userInterfaceStyle: .light).performAsCurrent { ink = drawing.image(from: rect, scale: scale) }53 let format = UIGraphicsImageRendererFormat()54 format.scale = scale55 format.opaque = background != nil56 format.preferredRange = .standard // 8-bit sRGB: a preview is a PNG that travels, not a wide-gamut 16-bit picture57 return UIGraphicsImageRenderer(size: rect.size, format: format).image { context in58 if let background {59 background.setFill()60 context.fill(CGRect(origin: .zero, size: rect.size))61 }62 ink?.draw(in: CGRect(origin: .zero, size: rect.size))63 }64 }65}6667/// The paper behind a drawing (`background` attribute of the `drawing` node).68enum DrawingPaper {69 static let none = "none"70 static let white = "white"7172 /// The colour to paint, nil for a transparent drawing.73 static func color(_ attr: String) -> UIColor? {74 switch InkBackground(attr: attr) {75 case .none: nil76 case .white: .white77 case .color(let color): InkConversion.uiColor(color)78 }79 }8081 static func isDark(_ color: UIColor) -> Bool {82 let c = InkConversion.inkColor(color)83 return 0.2126 * Double(c.red) + 0.7152 * Double(c.green) + 0.0722 * Double(c.blue) < 11084 }85}8687/// What the editor hands back on "Terminé".88struct DrawingEditorOutput {89 var drawing: PKDrawing90 var background: String91 /// Recognised handwriting the user asked to insert below the drawing, as Markdown, in the order asked.92 var insertions: [String]93}9495/// The 1.0 entry point, kept: `DrawingScreen(drawingData: existing) { result in … } onCancel: { … }` in a full-screen cover.96struct DrawingScreen: View {97 /// Existing `PKDrawing` data to continue, or nil for a blank sheet.98 var drawingData: Data?99 /// Offers « Texte manuscrit » (recognition of a framed region, on request).100 var recognizesHandwriting = true101 var onDone: @MainActor (DrawingResult) -> Void102 var onCancel: @MainActor () -> Void103104 init(drawingData: Data? = nil, recognizesHandwriting: Bool = true, onDone: @escaping @MainActor (DrawingResult) -> Void, onCancel: @escaping @MainActor () -> Void) {105 self.drawingData = drawingData106 self.recognizesHandwriting = recognizesHandwriting107 self.onDone = onDone108 self.onCancel = onCancel109 }110111 var body: some View {112 DrawingEditor(drawing: drawingData.flatMap { try? PKDrawing(data: $0) } ?? PKDrawing(), background: DrawingPaper.none, offersBackground: false,113 offersHandwriting: recognizesHandwriting, canInsertText: recognizesHandwriting, onDone: { output in114 let text = output.insertions.joined(separator: "\n\n")115 onDone(DrawingResult(drawingData: output.drawing.dataRepresentation(), png: DrawingRenderer.png(of: output.drawing),116 recognizedText: text.isEmpty ? nil : text, isEmpty: output.drawing.strokes.isEmpty))117 }, onCancel: onCancel)118 }119}120121/// The editor itself: canvas, navigation bar (Annuler / Terminé) and the glass toolbar.122struct DrawingEditor: View {123 var title: LocalizedStringKey = "Dessin"124 var drawing: PKDrawing125 var background: String126 var offersBackground = true127 var offersHandwriting = true128 /// False for a read-only note: the recognised text can be copied, not inserted.129 var canInsertText = true130 var isSaving = false131 var recognizer: any HandwritingRecognizing = VisionHandwritingRecognizer()132 var onDone: @MainActor (DrawingEditorOutput) -> Void133 var onCancel: @MainActor () -> Void134135 @State private var model = DrawingModel()136 @State private var confirmsDiscard = false137 @State private var confirmsClear = false138 @State private var fingerDrawing = DrawingModel.defaultFingerDrawing139 @Environment(\.accessibilityReduceMotion) private var reduceMotion140141 var body: some View {142 NavigationStack {143 DrawingCanvas(model: model, initial: drawing, background: background, fingerDrawing: fingerDrawing)144 .ignoresSafeArea(edges: .bottom)145 .background(NVColor.bgElevated)146 .overlay(alignment: .top) { chrome }147 .navigationTitle(Text(title))148 .navigationBarTitleDisplayMode(.inline)149 .toolbar { toolbar }150 .interactiveDismissDisabled(model.isDirty)151 }152 .confirmationDialog(Text("Abandonner les modifications du dessin ?"), isPresented: $confirmsDiscard, titleVisibility: .visible) {153 Button(role: .destructive) { onCancel() } label: { Text("Abandonner") }154 .accessibilityIdentifier("drawing-discard-confirm")155 Button(role: .cancel) {} label: { Text("Continuer le dessin") }156 }157 .confirmationDialog(Text("Effacer tout le dessin ?"), isPresented: $confirmsClear, titleVisibility: .visible) {158 Button(role: .destructive) { model.clear() } label: { Text("Tout effacer") }159 .accessibilityIdentifier("drawing-clear-confirm")160 Button(role: .cancel) {} label: { Text("Annuler") }161 }162 #if DEBUG163 .task {164 // screenshots: the words of the sample drawing are framed and read by Vision, as after a drag around them165 guard PencilDemo.route == "pencil-handwriting" else { return }166 try? await Task.sleep(for: .seconds(1.2))167 recognize(region: PencilDemo.wordsRegion)168 }169 #endif170 .sheet(item: Binding(get: { model.proposal }, set: { model.proposal = $0 })) { proposal in171 HandwritingSheet(proposal: proposal, canInsert: canInsertText, onInsert: { model.accept(proposal, replacingStrokes: false) },172 onReplace: { model.accept(proposal, replacingStrokes: true) }, onClose: { model.proposal = nil })173 }174 }175176 // MARK: chrome177178 private var chrome: some View {179 VStack(spacing: NVSpace.sm) {180 if model.isSelectingRegion {181 NVToolbarGlass {182 Image(systemName: "text.viewfinder").foregroundStyle(NVColor.accent).accessibilityHidden(true)183 Text("Encadre l’écriture à lire").nvFont(.uiStrong).foregroundStyle(NVColor.fg)184 Button { recognize(region: nil) } label: { Text("Tout le dessin").nvFont(.ui) }185 .buttonStyle(.bordered).accessibilityIdentifier("drawing-handwriting-all")186 Button { model.isSelectingRegion = false } label: { Text("Annuler").nvFont(.ui) }187 .buttonStyle(.borderless).accessibilityIdentifier("drawing-handwriting-cancel")188 }189 } else {190 tools191 }192 if model.isRecognizing {193 status(symbol: nil, text: Text("Lecture de l’écriture…"))194 } else if let kind = model.lastShape {195 status(symbol: DrawingModel.symbol(for: kind), text: Text(DrawingModel.name(for: kind)))196 .transition(.opacity)197 .accessibilityIdentifier("drawing-shape-toast")198 } else if !model.pendingInsertions.isEmpty {199 status(symbol: "text.insert", text: model.pendingInsertions.count == 1 ? Text("1 texte à insérer sous le dessin à l’enregistrement") : Text("\(model.pendingInsertions.count) textes à insérer sous le dessin à l’enregistrement"))200 .accessibilityIdentifier("drawing-pending-insertions")201 } else if !fingerDrawing && model.isEmpty {202 status(symbol: "applepencil", text: Text("Apple Pencil seulement — active « Doigt » pour dessiner au doigt"))203 }204 }205 .padding(.top, NVSpace.sm)206 .padding(.horizontal, NVSpace.md)207 .nvAnimation(.fast, value: model.lastShape)208 .nvAnimation(.fast, value: model.isSelectingRegion)209 .onChange(of: model.regionRequest) { _, region in210 guard let region else { return }211 model.regionRequest = nil212 recognize(region: region)213 }214 }215216 private func status(symbol: String?, text: Text) -> some View {217 HStack(spacing: NVSpace.xs) {218 if let symbol { Image(systemName: symbol).imageScale(.small).accessibilityHidden(true) } else { ProgressView().controlSize(.small) }219 text.nvFont(.micro).lineLimit(2).multilineTextAlignment(.center)220 }221 .foregroundStyle(NVColor.fgMuted)222 .padding(.horizontal, NVSpace.md)223 .padding(.vertical, NVSpace.xs + 1)224 .nvGlass(radius: NVRadius.pill)225 }226227 private var tools: some View {228 NVToolbarGlass(spacing: NVSpace.xs) {229 iconButton("arrow.uturn.backward", label: "Annuler le dernier trait", id: "drawing-undo") { model.undo() }230 .disabled(!model.canUndo)231 iconButton("arrow.uturn.forward", label: "Rétablir le trait", id: "drawing-redo") { model.redo() }232 .disabled(!model.canRedo)233 divider234 toggle("Formes", symbol: "square.on.circle", isOn: model.shapesEnabled, id: "drawing-shapes-toggle",235 hint: "Activé : un trait qui dessine une ligne, une flèche, un rectangle, un triangle ou une ellipse est redressé.") {236 model.shapesEnabled.toggle()237 Haptics.selection()238 }239 if offersHandwriting {240 iconButton("text.viewfinder", label: "Texte manuscrit", id: "drawing-handwriting") { model.isSelectingRegion = true }241 .disabled(model.isEmpty || model.isRecognizing)242 }243 divider244 toggle("Doigt", symbol: fingerDrawing ? "hand.draw.fill" : "hand.draw", isOn: fingerDrawing, id: "drawing-finger-toggle",245 hint: "Désactivé : seul l’Apple Pencil dessine, le doigt fait défiler.") {246 fingerDrawing.toggle()247 UserDefaults.standard.set(fingerDrawing, forKey: DrawingModel.fingerDrawingKey)248 Haptics.selection()249 }250 if offersBackground {251 Menu {252 Picker(selection: Binding(get: { model.background }, set: { model.setBackground($0) })) {253 Label("Papier blanc", systemImage: "doc").tag(DrawingPaper.white)254 Label("Transparent", systemImage: "square.dashed").tag(DrawingPaper.none)255 if model.background != DrawingPaper.white && model.background != DrawingPaper.none {256 Label("Couleur d’origine", systemImage: "paintpalette").tag(model.background)257 }258 } label: { Text("Fond du dessin") }259 } label: {260 Image(systemName: "doc.richtext").frame(minWidth: 40, minHeight: 40).contentShape(Rectangle())261 }262 .accessibilityLabel(Text("Fond du dessin"))263 .accessibilityIdentifier("drawing-background")264 }265 iconButton("trash", label: "Tout effacer", id: "drawing-clear", role: .destructive) { confirmsClear = true }266 .disabled(model.isEmpty)267 }268 .tint(NVColor.fg)269 }270271 private var divider: some View { Rectangle().fill(NVColor.lineStrong).frame(width: 1, height: 22).padding(.horizontal, NVSpace.xxs).accessibilityHidden(true) }272273 private func iconButton(_ symbol: String, label: LocalizedStringKey, id: String, role: ButtonRole? = nil, action: @escaping () -> Void) -> some View {274 Button(role: role, action: action) { Image(systemName: symbol).frame(minWidth: 40, minHeight: 40).contentShape(Rectangle()) }275 .accessibilityLabel(Text(label))276 .accessibilityIdentifier(id)277 }278279 private func toggle(_ title: LocalizedStringKey, symbol: String, isOn: Bool, id: String, hint: LocalizedStringKey, action: @escaping () -> Void) -> some View {280 Button(action: action) {281 HStack(spacing: NVSpace.xs) {282 Image(systemName: symbol).imageScale(.medium)283 Text(title).nvFont(.uiStrong).lineLimit(1)284 }285 .foregroundStyle(isOn ? NVColor.accentFg : NVColor.fg)286 .padding(.horizontal, NVSpace.md)287 .frame(minHeight: 36)288 .background(isOn ? AnyShapeStyle(NVColor.accent) : AnyShapeStyle(NVColor.bgHover), in: Capsule())289 .contentShape(Capsule())290 }291 .buttonStyle(.plain)292 .accessibilityLabel(Text(title))293 .accessibilityValue(isOn ? Text("Activé") : Text("Désactivé"))294 .accessibilityHint(Text(hint))295 .accessibilityAddTraits(isOn ? .isSelected : [])296 .accessibilityIdentifier(id)297 }298299 @ToolbarContentBuilder private var toolbar: some ToolbarContent {300 ToolbarItem(placement: .cancellationAction) {301 Button { if model.isDirty { confirmsDiscard = true } else { onCancel() } } label: { Text("Annuler") }302 .disabled(isSaving)303 .accessibilityIdentifier("drawing-cancel")304 }305 ToolbarItem(placement: .confirmationAction) {306 if isSaving {307 ProgressView().accessibilityLabel(Text("Enregistrement du dessin"))308 } else {309 Button { onDone(DrawingEditorOutput(drawing: model.drawing, background: model.background, insertions: model.pendingInsertions)) } label: { Text("Terminé").bold() }310 .accessibilityIdentifier("drawing-done")311 }312 }313 }314315 private func recognize(region: CGRect?) {316 model.isSelectingRegion = false317 let drawing = model.drawing, recognizer = recognizer318 model.isRecognizing = true319 Task { @MainActor in320 let proposal = await HandwritingPipeline.recognize(drawing, region: region, recognizer: recognizer)321 model.isRecognizing = false322 // nothing framed: an empty proposal still opens the sheet, which says so323 model.proposal = proposal ?? HandwritingProposal(strokeIndices: [], result: HandwritingResult(lines: []))324 }325 }326}327328/// State of the canvas shared between the SwiftUI chrome and the PencilKit view.329@MainActor @Observable330final class DrawingModel {331 static let fingerDrawingKey = "drawing.fingerDrawing"332 static let shapesKey = "drawing.shapes"333 /// On an iPad the Pencil draws and the finger scrolls (palm rejection) unless the user chose otherwise; on an iPhone the finger draws.334 static var defaultFingerDrawing: Bool {335 (UserDefaults.standard.object(forKey: fingerDrawingKey) as? Bool) ?? (UIDevice.current.userInterfaceIdiom != .pad)336 }337338 fileprivate(set) var canUndo = false339 fileprivate(set) var canRedo = false340 fileprivate(set) var isEmpty = true341 /// True once the drawing differs from what was opened.342 fileprivate(set) var isDirty = false343 /// « Formes »: a stroke that draws one of the five shapes is replaced by the clean shape when it ends.344 var shapesEnabled = UserDefaults.standard.bool(forKey: DrawingModel.shapesKey) {345 didSet { UserDefaults.standard.set(shapesEnabled, forKey: DrawingModel.shapesKey) }346 }347 /// The shape that just replaced a stroke (shown briefly).348 fileprivate(set) var lastShape: RecognizedShape.Kind?349 /// The user is framing the handwriting to read.350 var isSelectingRegion = false { didSet { canvasController?.setRegionSelection(isSelectingRegion) } }351 /// The framed region, in drawing coordinates; consumed by the editor.352 var regionRequest: CGRect?353 var isRecognizing = false354 var proposal: HandwritingProposal?355 private(set) var pendingInsertions: [String] = []356 /// `background` attribute; empty until the editor sets it.357 var background = ""358359 @ObservationIgnored fileprivate weak var canvas: PKCanvasView?360 @ObservationIgnored fileprivate weak var canvasController: DrawingCanvasController?361 @ObservationIgnored private var toastTask: Task<Void, Never>?362363 var drawing: PKDrawing { canvas?.drawing ?? PKDrawing() }364365 func undo() { canvas?.undoManager?.undo(); refresh() }366 func redo() { canvas?.undoManager?.redo(); refresh() }367368 /// Removes every stroke; undoable.369 func clear() {370 guard let canvas else { return }371 DrawingCanvasController.setDrawing(PKDrawing(), on: canvas, actionName: String(localized: "Tout effacer"))372 isDirty = true373 refresh()374 }375376 func setBackground(_ value: String) {377 guard value != background else { return }378 background = value379 isDirty = true380 canvasController?.applyBackground(value)381 }382383 /// The user's answer to a recognition: the text is queued for insertion below the drawing when it is saved; with384 /// `replacingStrokes` the strokes that were read are removed from the drawing (undoable).385 func accept(_ proposal: HandwritingProposal, replacingStrokes: Bool) {386 self.proposal = nil387 guard !proposal.result.isEmpty else { return }388 pendingInsertions.append(proposal.result.markdown)389 isDirty = true390 if replacingStrokes, let canvas {391 DrawingCanvasController.setDrawing(HandwritingPipeline.drawing(canvas.drawing, removing: proposal.strokeIndices), on: canvas, actionName: String(localized: "Remplacer par du texte"))392 refresh()393 }394 Haptics.success()395 }396397 fileprivate func shapeSnapped(_ kind: RecognizedShape.Kind) {398 lastShape = kind399 Haptics.tap()400 UIAccessibility.post(notification: .announcement, argument: DrawingModel.name(for: kind))401 toastTask?.cancel()402 #if DEBUG403 if PencilDemo.route != nil { return } // screenshots: the name of the shape stays404 #endif405 toastTask = Task { [weak self] in406 try? await Task.sleep(for: .seconds(1.6))407 if !Task.isCancelled { self?.lastShape = nil }408 }409 }410411 fileprivate func refresh() {412 canUndo = canvas?.undoManager?.canUndo ?? false413 canRedo = canvas?.undoManager?.canRedo ?? false414 isEmpty = canvas?.drawing.strokes.isEmpty ?? true415 }416417 static func name(for kind: RecognizedShape.Kind) -> String {418 switch kind {419 case .line: String(localized: "Ligne")420 case .arrow: String(localized: "Flèche")421 case .rectangle: String(localized: "Rectangle")422 case .ellipse: String(localized: "Ellipse")423 case .triangle: String(localized: "Triangle")424 }425 }426427 static func symbol(for kind: RecognizedShape.Kind) -> String {428 switch kind {429 case .line: "line.diagonal"430 case .arrow: "arrow.up.right"431 case .rectangle: "rectangle"432 case .ellipse: "oval"433 case .triangle: "triangle"434 }435 }436}437438private struct DrawingCanvas: UIViewControllerRepresentable {439 let model: DrawingModel440 let initial: PKDrawing441 let background: String442 let fingerDrawing: Bool443444 func makeUIViewController(context: Context) -> DrawingCanvasController {445 if model.background.isEmpty { model.background = background }446 return DrawingCanvasController(model: model, initial: initial, fingerDrawing: fingerDrawing)447 }448449 func updateUIViewController(_ controller: DrawingCanvasController, context: Context) {450 controller.setFingerDrawing(fingerDrawing)451 }452}453454final class DrawingCanvasController: UIViewController, PKCanvasViewDelegate {455 private let model: DrawingModel456 let canvas = PKCanvasView()457 private let toolPicker = PKToolPicker(toolItems: DrawingCanvasController.toolItems())458 private var fingerDrawing: Bool459 /// The delegate also fires for programmatic changes: ignored until the initial drawing is in place.460 private var isLoaded = false461 private var strokeCount = 0462 private var regionView: RegionSelectionView?463 /// The paper: at least the screen, and always more room below and right of the strokes.464 private static let minimumPaper = CGSize(width: 1024, height: 1400)465466 /// Pens, a highlighter (a translucent marker — written as `highlighter` in the ink format), both erasers, lasso and ruler.467 static func toolItems() -> [PKToolPickerItem] {468 [469 PKToolPickerInkingItem(type: .pen, color: .black, width: 3),470 PKToolPickerInkingItem(type: .pencil, color: .black, width: 4),471 PKToolPickerInkingItem(type: .monoline, color: UIColor(red: 0.18, green: 0.36, blue: 0.86, alpha: 1), width: 3),472 PKToolPickerInkingItem(type: .marker, color: UIColor(red: 0.86, green: 0.15, blue: 0.15, alpha: 1), width: 12, identifier: "ai.spboucher.spnotes.marker"),473 PKToolPickerInkingItem(type: .marker, color: UIColor(red: 1, green: 0.84, blue: 0.29, alpha: 0.4), width: 24, identifier: "ai.spboucher.spnotes.highlighter"),474 PKToolPickerEraserItem(type: .vector),475 PKToolPickerEraserItem(type: .bitmap, width: 18),476 PKToolPickerLassoItem(),477 PKToolPickerRulerItem(),478 ]479 }480481 init(model: DrawingModel, initial: PKDrawing, fingerDrawing: Bool) {482 self.model = model483 self.fingerDrawing = fingerDrawing484 super.init(nibName: nil, bundle: nil)485 canvas.drawing = initial486 strokeCount = initial.strokes.count487 }488489 @available(*, unavailable)490 required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }491492 override func viewDidLoad() {493 super.viewDidLoad()494 canvas.isOpaque = true495 canvas.drawingPolicy = fingerDrawing ? .anyInput : .pencilOnly496 canvas.minimumZoomScale = 0.5497 canvas.maximumZoomScale = 4498 canvas.bouncesZoom = true499 canvas.alwaysBounceVertical = true500 canvas.alwaysBounceHorizontal = true501 canvas.contentInsetAdjustmentBehavior = .always502 canvas.contentInset.top = 64 // room for the floating toolbar above the first strokes503 canvas.accessibilityIdentifier = "drawing-canvas"504 canvas.accessibilityLabel = String(localized: "Zone de dessin")505 canvas.translatesAutoresizingMaskIntoConstraints = false506 view.addSubview(canvas)507 NSLayoutConstraint.activate([508 canvas.topAnchor.constraint(equalTo: view.topAnchor), canvas.bottomAnchor.constraint(equalTo: view.bottomAnchor),509 canvas.leadingAnchor.constraint(equalTo: view.leadingAnchor), canvas.trailingAnchor.constraint(equalTo: view.trailingAnchor),510 ])511 canvas.delegate = self512 model.canvas = canvas513 model.canvasController = self514 applyBackground(model.background)515 toolPicker.addObserver(canvas)516 toolPicker.setVisible(true, forFirstResponder: canvas)517 }518519 override func viewDidLayoutSubviews() {520 super.viewDidLayoutSubviews()521 updatePaperSize()522 regionView?.frame = view.bounds523 }524525 override func viewDidAppear(_ animated: Bool) {526 super.viewDidAppear(animated)527 canvas.becomeFirstResponder() // shows the tool picker528 applyBackground(model.background)529 isLoaded = true530 model.refresh()531 #if DEBUG532 // screenshots: a rough rectangle arrives on the canvas as if just drawn; « Formes » straightens it through the real path533 if PencilDemo.route == "pencil-drawing" {534 model.shapesEnabled = true535 DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in536 guard let self else { return }537 var drawing = self.canvas.drawing538 drawing.strokes.append(PencilSamples.roughRectangle())539 self.canvas.drawing = drawing540 }541 }542 #endif543 }544545 override func viewWillDisappear(_ animated: Bool) {546 super.viewWillDisappear(animated)547 toolPicker.setVisible(false, forFirstResponder: canvas)548 toolPicker.removeObserver(canvas)549 canvas.resignFirstResponder()550 }551552 func setFingerDrawing(_ enabled: Bool) {553 guard enabled != fingerDrawing else { return }554 fingerDrawing = enabled555 canvas.drawingPolicy = enabled ? .anyInput : .pencilOnly556 }557558 /// Transparent drawing: the paper follows the appearance and PencilKit adapts the ink to it. A drawing with a paper is shown559 /// on that paper whatever the appearance, with the ink as it will be exported.560 func applyBackground(_ attr: String) {561 if let color = DrawingPaper.color(attr) {562 canvas.backgroundColor = color563 canvas.overrideUserInterfaceStyle = DrawingPaper.isDark(color) ? .dark : .light564 } else {565 canvas.backgroundColor = UIColor(named: "Surface") ?? .systemBackground566 canvas.overrideUserInterfaceStyle = .unspecified567 }568 // the colours offered by the picker are shown as they will be on this paper569 toolPicker.colorUserInterfaceStyle = canvas.overrideUserInterfaceStyle == .unspecified ? traitCollection.userInterfaceStyle : canvas.overrideUserInterfaceStyle570 }571572 /// Grows the paper so there is always blank room past the strokes (never shrinks while drawing: the content would jump).573 private func updatePaperSize() {574 let bounds = canvas.drawing.bounds575 let used = bounds.isNull || bounds.isInfinite ? CGSize.zero : CGSize(width: bounds.maxX, height: bounds.maxY)576 let visible = canvas.bounds.size577 let zoom = max(canvas.zoomScale, 0.01)578 let wanted = CGSize(width: max(Self.minimumPaper.width, visible.width, used.width + visible.width / 2),579 height: max(Self.minimumPaper.height, visible.height, used.height + visible.height))580 let current = CGSize(width: canvas.contentSize.width / zoom, height: canvas.contentSize.height / zoom)581 let next = CGSize(width: max(current.width, wanted.width), height: max(current.height, wanted.height))582 if abs(next.width - current.width) > 0.5 || abs(next.height - current.height) > 0.5 {583 canvas.contentSize = CGSize(width: next.width * zoom, height: next.height * zoom)584 }585 }586587 // MARK: undoable replacement of the drawing588589 /// Sets the drawing as one undo step (undo restores the previous drawing, redo the new one).590 static func setDrawing(_ drawing: PKDrawing, on canvas: PKCanvasView, actionName: String) {591 let previous = canvas.drawing592 canvas.undoManager?.registerUndo(withTarget: canvas) { canvas in593 MainActor.assumeIsolated { setDrawing(previous, on: canvas, actionName: actionName) }594 }595 canvas.undoManager?.setActionName(actionName)596 canvas.drawing = drawing597 }598599 /// « Formes »: replaces the last stroke by the shape it draws, as one undo step that brings the hand-drawn stroke back.600 @discardableResult601 static func snapLastStroke(on canvas: PKCanvasView) -> ShapeMatch? {602 guard let snapped = ShapeSnapping.snappingLastStroke(of: canvas.drawing) else { return nil }603 setDrawing(snapped.drawing, on: canvas, actionName: String(localized: "Forme"))604 return snapped.match605 }606607 // MARK: PKCanvasViewDelegate608609 func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {610 updatePaperSize()611 let count = canvasView.drawing.strokes.count612 let added = count == strokeCount + 1613 strokeCount = count614 if isLoaded { model.isDirty = true }615 model.refresh()616 guard isLoaded, added, model.shapesEnabled, canvasView.undoManager?.isUndoing != true, canvasView.undoManager?.isRedoing != true,617 canvasView.tool is PKInkingTool else { return }618 // after PencilKit has finished recording the stroke (and its own undo step)619 DispatchQueue.main.async { [weak self] in620 guard let self, self.canvas.drawing.strokes.count == count else { return }621 if let match = Self.snapLastStroke(on: self.canvas) {622 self.strokeCount = self.canvas.drawing.strokes.count623 self.model.shapeSnapped(match.shape.kind)624 self.model.refresh()625 }626 }627 }628629 func canvasViewDidEndUsingTool(_ canvasView: PKCanvasView) { model.refresh() }630631 // MARK: framing a region (handwriting)632633 func setRegionSelection(_ active: Bool) {634 if active, regionView == nil {635 let overlay = RegionSelectionView(frame: view.bounds)636 overlay.onSelect = { [weak self] rect in637 guard let self else { return }638 // overlay → canvas content → drawing coordinates639 let inCanvas = self.canvas.convert(rect, from: overlay)640 let zoom = max(self.canvas.zoomScale, 0.01)641 self.model.regionRequest = CGRect(x: inCanvas.minX / zoom, y: inCanvas.minY / zoom, width: inCanvas.width / zoom, height: inCanvas.height / zoom)642 }643 view.addSubview(overlay)644 regionView = overlay645 } else if !active {646 regionView?.removeFromSuperview()647 regionView = nil648 }649 }650}651652/// A transparent layer over the canvas on which the user drags a rectangle around the handwriting to read.653final class RegionSelectionView: UIView {654 var onSelect: ((CGRect) -> Void)?655 private let frameLayer = CAShapeLayer()656 private var origin: CGPoint?657658 override init(frame: CGRect) {659 super.init(frame: frame)660 backgroundColor = UIColor.black.withAlphaComponent(0.06)661 isAccessibilityElement = true662 accessibilityIdentifier = "drawing-region-overlay"663 accessibilityLabel = String(localized: "Encadre l’écriture à lire")664 accessibilityTraits = .allowsDirectInteraction665 frameLayer.fillColor = UIColor.tintColor.withAlphaComponent(0.10).cgColor666 frameLayer.strokeColor = UIColor.tintColor.cgColor667 frameLayer.lineWidth = 2668 frameLayer.lineDashPattern = [8, 5]669 layer.addSublayer(frameLayer)670 addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(pan(_:))))671 }672673 @available(*, unavailable)674 required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }675676 @objc private func pan(_ gesture: UIPanGestureRecognizer) {677 let point = gesture.location(in: self)678 switch gesture.state {679 case .began:680 let translation = gesture.translation(in: self)681 origin = CGPoint(x: point.x - translation.x, y: point.y - translation.y)682 case .changed:683 guard let origin else { return }684 frameLayer.path = UIBezierPath(roundedRect: Self.rect(origin, point), cornerRadius: 6).cgPath685 case .ended:686 guard let origin else { return }687 let rect = Self.rect(origin, point)688 self.origin = nil689 frameLayer.path = nil690 if rect.width > 12, rect.height > 12 { onSelect?(rect) }691 default:692 origin = nil693 frameLayer.path = nil694 }695 }696697 static func rect(_ a: CGPoint, _ b: CGPoint) -> CGRect {698 CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(a.x - b.x), height: abs(a.y - b.y))699 }700}701