Repository Public
1// SP Notes iOS2// File: Features/Drawing/PencilDebugRoutes.swift3// Description: DEBUG only. Opens the Pencil screens directly at launch for screenshots and reviews, with sample content made by4// the real code paths: `SPNOTES_OPEN=pencil-drawing | pencil-handwriting | pencil-missing | pdf-annotate | pdf-list`5// (with `SPNOTES_STORE=memory SPNOTES_SESSION=local`). Nothing here exists in a release build.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI1011extension View {12 /// Applied once at the root of the app; a no-op in release builds.13 func pencilDebugRoute() -> some View {14 #if DEBUG15 modifier(PencilDebugRoute())16 #else17 self18 #endif19 }20}2122#if DEBUG23import CoreText24import PDFKit25import PencilKit26import SPNotesCore27import UIKit2829enum PencilDemo {30 /// The route asked for at launch, if any.31 static let route = ProcessInfo.processInfo.environment["SPNOTES_OPEN"].flatMap { $0.hasPrefix("pencil-") || $0.hasPrefix("pdf-") ? $0 : nil }32 /// Where the typed-letter strokes of the sample drawing are (drawing coordinates).33 static let wordsRegion = CGRect(x: 40, y: 330, width: 640, height: 130)34}3536/// PencilKit strokes following the outlines of typed text: what a careful hand would trace. Used by the sample drawing and by37/// the tests of the handwriting pipeline (Vision reads them in the simulator, where nobody can write with a Pencil).38@MainActor39enum TypedStrokes {40 static func strokes(_ text: String, at origin: CGPoint, size: CGFloat = 64, width: CGFloat = 2.5, color: UIColor = .black) -> [PKStroke] {41 let font = CTFontCreateWithName("Helvetica-Bold" as CFString, size, nil)42 let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font]))43 var strokes: [PKStroke] = []44 for run in CTLineGetGlyphRuns(line) as? [CTRun] ?? [] {45 let count = CTRunGetGlyphCount(run)46 var glyphs = [CGGlyph](repeating: 0, count: count), positions = [CGPoint](repeating: .zero, count: count)47 CTRunGetGlyphs(run, CFRange(location: 0, length: count), &glyphs)48 CTRunGetPositions(run, CFRange(location: 0, length: count), &positions)49 for (glyph, position) in zip(glyphs, positions) {50 guard let path = CTFontCreatePathForGlyph(font, glyph, nil) else { continue }51 // glyph space is y-up: flipped onto the canvas52 var transform = CGAffineTransform(translationX: origin.x + position.x, y: origin.y).scaledBy(x: 1, y: -1)53 guard let placed = path.copy(using: &transform) else { continue }54 for contour in contours(of: placed) where contour.count > 1 {55 let points = contour.enumerated().map { PKStrokePoint(location: $1, timeOffset: Double($0) * 0.002, size: CGSize(width: width, height: width), opacity: 1, force: 1, azimuth: 0, altitude: .pi / 2) }56 strokes.append(PKStroke(ink: PKInk(.monoline, color: color), path: PKStrokePath(controlPoints: points, creationDate: Date())))57 }58 }59 }60 return strokes61 }6263 /// The subpaths of a path, curves flattened, a point every ~1.5 pt so the B-spline follows the outline closely.64 static func contours(of path: CGPath) -> [[CGPoint]] {65 var all: [[CGPoint]] = [], current: [CGPoint] = []66 func add(_ p: CGPoint) {67 if let last = current.last {68 let d = hypot(p.x - last.x, p.y - last.y), n = max(1, Int(d / 1.5))69 for k in 1...n { current.append(CGPoint(x: last.x + (p.x - last.x) * CGFloat(k) / CGFloat(n), y: last.y + (p.y - last.y) * CGFloat(k) / CGFloat(n))) }70 } else { current.append(p) }71 }72 path.applyWithBlock { element in73 let e = element.pointee74 switch e.type {75 case .moveToPoint:76 if current.count > 1 { all.append(current) }77 current = [e.points[0]]78 case .addLineToPoint: add(e.points[0])79 case .addQuadCurveToPoint:80 guard let start = current.last else { return }81 for i in 1...8 { let t = CGFloat(i) / 8, u = 1 - t; add(CGPoint(x: u * u * start.x + 2 * u * t * e.points[0].x + t * t * e.points[1].x, y: u * u * start.y + 2 * u * t * e.points[0].y + t * t * e.points[1].y)) }82 case .addCurveToPoint:83 guard let start = current.last else { return }84 for i in 1...10 {85 let t = CGFloat(i) / 10, u = 1 - t86 add(CGPoint(x: u * u * u * start.x + 3 * u * u * t * e.points[0].x + 3 * u * t * t * e.points[1].x + t * t * t * e.points[2].x,87 y: u * u * u * start.y + 3 * u * u * t * e.points[0].y + 3 * u * t * t * e.points[1].y + t * t * t * e.points[2].y))88 }89 case .closeSubpath:90 if let first = current.first { add(first) }91 if current.count > 1 { all.append(current) }92 current = []93 @unknown default: break94 }95 }96 if current.count > 1 { all.append(current) }97 return all98 }99}100101@MainActor102enum PencilSamples {103 static func hand(_ points: [CGPoint], type: PKInk.InkType = .pen, color: UIColor = .black, width: CGFloat = 4) -> PKStroke {104 // a wobble like a hand's, the same on every launch105 var seed: UInt64 = 0x5EED106 func noise() -> CGFloat { seed = seed &* 6364136223846793005 &+ 1442695040888963407; return CGFloat(seed >> 40) / CGFloat(1 << 24) - 0.5 }107 var dense: [CGPoint] = []108 for i in 1..<points.count {109 let a = points[i - 1], b = points[i], n = max(2, Int(hypot(b.x - a.x, b.y - a.y) / 6))110 for k in (i == 1 ? 0 : 1)...n { let t = CGFloat(k) / CGFloat(n); dense.append(CGPoint(x: a.x + (b.x - a.x) * t + noise() * 2.2, y: a.y + (b.y - a.y) * t + noise() * 2.2)) }111 }112 let controls = dense.enumerated().map { PKStrokePoint(location: $1, timeOffset: Double($0) * 0.01, size: CGSize(width: width, height: width), opacity: 1, force: 1, azimuth: 0, altitude: .pi / 2) }113 return PKStroke(ink: PKInk(type, color: color), path: PKStrokePath(controlPoints: controls, creationDate: Date()))114 }115116 static let blue = UIColor(red: 0.18, green: 0.36, blue: 0.86, alpha: 1)117118 /// A sketch: shapes that went through « Formes » (drawn by "hand", then snapped by the recogniser), a highlighter stroke,119 /// a free curve, and two words traced letter by letter.120 static func drawing() -> PKDrawing {121 var drawing = PKDrawing()122 func addSnapped(_ stroke: PKStroke) {123 drawing.strokes.append(stroke)124 if let snapped = ShapeSnapping.snappingLastStroke(of: drawing) { drawing = snapped.drawing }125 }126 addSnapped(hand([CGPoint(x: 60, y: 70), CGPoint(x: 280, y: 74), CGPoint(x: 276, y: 210), CGPoint(x: 58, y: 206), CGPoint(x: 60, y: 70)], color: blue))127 addSnapped(hand((0...40).map { i in let t = CGFloat(i) / 40 * 2 * .pi; return CGPoint(x: 560 + 90 * cos(t), y: 140 + 70 * sin(t)) }, color: UIColor(red: 0.8, green: 0.15, blue: 0.18, alpha: 1)))128 addSnapped(hand([CGPoint(x: 300, y: 140), CGPoint(x: 450, y: 140), CGPoint(x: 422, y: 122), CGPoint(x: 450, y: 140), CGPoint(x: 424, y: 160)]))129 addSnapped(hand([CGPoint(x: 760, y: 210), CGPoint(x: 860, y: 60), CGPoint(x: 950, y: 212), CGPoint(x: 760, y: 210)], color: UIColor(red: 0, green: 0.55, blue: 0.3, alpha: 1)))130 drawing.strokes.append(hand([CGPoint(x: 330, y: 396), CGPoint(x: 600, y: 396)], type: .marker, color: UIColor(red: 1, green: 0.84, blue: 0.29, alpha: 0.4), width: 26))131 drawing.strokes.append(contentsOf: TypedStrokes.strokes("Bonjour Pencil", at: CGPoint(x: 60, y: 420), size: 72, width: 3))132 drawing.strokes.append(hand((0...60).map { i in let t = CGFloat(i) / 60; return CGPoint(x: 80 + 560 * t, y: 560 + 36 * sin(t * 9)) }, type: .pencil, color: blue, width: 5))133 return drawing134 }135136 /// A hand-drawn rectangle not yet snapped (the demo adds it to the canvas, « Formes » does the rest).137 static func roughRectangle() -> PKStroke {138 hand([CGPoint(x: 720, y: 330), CGPoint(x: 960, y: 336), CGPoint(x: 955, y: 470), CGPoint(x: 716, y: 462), CGPoint(x: 720, y: 330)], color: UIColor(red: 0.5, green: 0.25, blue: 0.82, alpha: 1))139 }140141 static func pdf() -> Data {142 let size = CGSize(width: 612, height: 792)143 let title = UIFont(name: "Georgia-Bold", size: 26) ?? .boldSystemFont(ofSize: 26), body = UIFont(name: "Georgia", size: 15) ?? .systemFont(ofSize: 15)144 let paragraph = NSMutableParagraphStyle()145 paragraph.lineSpacing = 6146 let texts = [147 ("Méthode du revenu", "La valeur d’un immeuble de rapport découle des revenus qu’il produit. On établit d’abord le revenu brut potentiel, puis on retranche les inoccupations et les mauvaises créances pour obtenir le revenu brut effectif.\n\nLe revenu net d’exploitation s’obtient en soustrayant les dépenses d’exploitation normalisées. Il est ensuite converti en valeur au moyen d’un taux global d’actualisation tiré du marché.\n\nUne hausse d’un dollar du revenu net se traduit, à un taux de 5,5 %, par environ dix-huit dollars de valeur : c’est l’effet de levier de la capitalisation."),148 ("Taux global d’actualisation", "Le taux se dégage des ventes comparables : on divise le revenu net de chaque immeuble vendu par son prix de vente. Les écarts s’expliquent par l’âge, l’emplacement et la qualité des baux.\n\nUn taux plus faible signale un risque perçu moindre ou une croissance attendue des loyers."),149 ]150 return UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size: size)).pdfData { context in151 for (index, text) in texts.enumerated() {152 context.beginPage()153 (text.0 as NSString).draw(at: CGPoint(x: 72, y: 84), withAttributes: [.font: title])154 (text.1 as NSString).draw(in: CGRect(x: 72, y: 140, width: 468, height: 560), withAttributes: [.font: body, .paragraphStyle: paragraph])155 ("\(index + 1)" as NSString).draw(at: CGPoint(x: 300, y: 740), withAttributes: [.font: body])156 }157 }158 }159}160161private struct PencilDebugRoute: ViewModifier {162 @Environment(AppModel.self) private var app163 @State private var screen: Screen?164165 struct Screen: Identifiable {166 let id = UUID()167 let view: AnyView168 }169170 func body(content: Content) -> some View {171 content172 .task {173 guard let route = PencilDemo.route, screen == nil else { return }174 try? await Task.sleep(for: .milliseconds(600)) // the root interface first175 screen = await make(route)176 }177 .fullScreenCover(item: $screen) { $0.view }178 }179180 private func context(_ noteId: String) -> BlockDetailContext {181 BlockDetailContext(app: app, noteId: noteId, isEditable: true, commit: { _ in }, insertMarkdownBelow: { _ in }, open: { _ in }, dismiss: { screen = nil })182 }183184 private func make(_ route: String) async -> Screen? {185 guard let noteId = try? await app.createNote(title: "Démo Pencil") else { return nil }186 switch route {187 case "pencil-drawing", "pencil-handwriting":188 guard let saved = try? await DrawingBlockIO.save(PencilSamples.drawing(), background: DrawingPaper.white, into: DrawingBlock(width: 1024, height: 700), app: app, noteId: noteId) else { return nil }189 return Screen(view: AnyView(DrawingBlockScreen(node: saved.block.node(), context: context(noteId))))190 case "pencil-missing":191 var block = DrawingBlock(width: 300, height: 200)192 block.ink = UUID().uuidString.lowercased()193 block.preview = UUID().uuidString.lowercased()194 return Screen(view: AnyView(DrawingBlockScreen(node: block.node(), context: context(noteId))))195 case "pdf-annotate", "pdf-list":196 guard let node = try? await app.attach(data: PencilSamples.pdf(), filename: "methode-du-revenu.pdf", mime: "application/pdf", to: noteId),197 let id = try? DrawingBlockIO.attachmentId(of: node), let url = try? await app.localFile(forAttachment: id), let document = PDFDocument(url: url) else { return nil }198 var block = PDFBlock(attachmentId: id, name: "methode-du-revenu.pdf")199 // annotations made by the real factories: a highlight from a text selection, an ink stroke, two notes200 if let selection = document.findString("revenu net d’exploitation", withOptions: []).first {201 PDFAnnotationFactory.highlights(from: selection, in: document).forEach { block.add($0) }202 }203 // a selection running over two lines204 if let page = document.page(at: 0), let text = page.string, let range = text.range(of: "c’est l’effet de levier de la\\s+capitalisation", options: .regularExpression),205 let selection = page.selection(for: NSRange(range, in: text)) {206 PDFAnnotationFactory.highlights(from: selection, in: document, color: PDFAnnotationFactory.highlightColors[1]).forEach { block.add($0) }207 }208 let underline = (0...50).map { i -> CGPoint in let t = CGFloat(i) / 50; return CGPoint(x: 70 + 250 * t, y: 118 + 3 * sin(t * 14)) }209 if let ink = PDFAnnotationFactory.ink(viewPoints: underline, in: CGSize(width: 612, height: 792), page: 1, color: PDFAnnotationFactory.inkColors[0], lineWidth: 2.5) { block.add(ink) }210 let circle = (0...48).map { i -> CGPoint in let t = CGFloat(i) / 48 * 2 * .pi * 1.03; return CGPoint(x: 150 + 52 * cos(t), y: 350 + 15 * sin(t)) }211 if let ink = PDFAnnotationFactory.ink(viewPoints: circle, in: CGSize(width: 612, height: 792), page: 1, color: PDFAnnotationFactory.inkColors[1], lineWidth: 2) { block.add(ink) }212 block.add(PDFAnnotationFactory.note(at: PDFPoint(x: 0.92, y: 0.24), page: 1, pageAspect: 612.0 / 792, text: "Vérifier le taux d’inoccupation retenu dans le TP3."))213 block.add(PDFAnnotationFactory.note(at: PDFPoint(x: 0.9, y: 0.3), page: 2, pageAspect: 612.0 / 792, text: "Comparer avec les ventes du Plateau."))214 if let selection = document.findString("ventes comparables", withOptions: []).first {215 PDFAnnotationFactory.highlights(from: selection, in: document, color: PDFAnnotationFactory.highlightColors[2]).forEach { block.add($0) }216 }217 let model = PDFAnnotationModel(block: block, isEditable: true, commit: { _ in })218 return Screen(view: AnyView(PDFAnnotationScreen(model: model, context: context(noteId), showsList: route == "pdf-list")))219 default: return nil220 }221 }222}223#endif224