Repository Public
1// SP Notes iOS2// File: Features/PDF/PDFPageOverlay.swift3// Description: What sits over each page of the PDF view: a layer drawing the annotations of the block (highlights, ink, note pins)4// and a transparent PencilKit canvas that captures new ink. Nothing is ever added to the PDF itself.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import PencilKit9import SPNotesCore10import UIKit1112/// The overlay of one page. Its bounds are the displayed page.13final class PDFPageOverlayView: UIView, PKCanvasViewDelegate {14 let pageNumber: Int15 let canvas = PKCanvasView()16 private let highlights = CALayer()17 private let marks = CALayer()18 private var annotations: [PDFAnnotation] = []19 private var isClearing = false20 /// A stroke was drawn: its points in this view's coordinates, the ink used.21 var onStroke: (([CGPoint], PKInk, CGFloat) -> Void)?2223 init(pageNumber: Int) {24 self.pageNumber = pageNumber25 super.init(frame: .zero)26 isOpaque = false27 backgroundColor = .clear28 // highlights darken what is under them, like a real highlighter, so the text stays black29 highlights.compositingFilter = "multiplyBlendMode"30 layer.addSublayer(highlights)31 layer.addSublayer(marks)32 canvas.backgroundColor = .clear33 canvas.isOpaque = false34 canvas.isScrollEnabled = false35 canvas.overrideUserInterfaceStyle = .light // ink colours as chosen, whatever the appearance: a PDF page is paper36 canvas.delegate = self37 canvas.autoresizingMask = [.flexibleWidth, .flexibleHeight]38 canvas.accessibilityIdentifier = "pdf-ink-canvas-\(pageNumber)"39 addSubview(canvas)40 }4142 @available(*, unavailable)43 required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }4445 override func layoutSubviews() {46 super.layoutSubviews()47 canvas.frame = bounds48 redraw()49 }5051 func show(_ annotations: [PDFAnnotation]) {52 self.annotations = annotations53 redraw()54 }5556 func configure(inkEnabled: Bool, fingerDrawing: Bool, tool: PKInkingTool) {57 canvas.isUserInteractionEnabled = inkEnabled58 canvas.drawingPolicy = fingerDrawing ? .anyInput : .pencilOnly59 canvas.tool = tool60 }6162 private func redraw() {63 CATransaction.begin()64 CATransaction.setDisableActions(true)65 highlights.frame = bounds66 marks.frame = bounds67 highlights.sublayers?.forEach { $0.removeFromSuperlayer() }68 marks.sublayers?.forEach { $0.removeFromSuperlayer() }69 for layer in Self.layers(for: annotations, in: bounds.size) {70 if layer.name == PDFAnnotationKind.highlight.rawValue { highlights.addSublayer(layer) } else { marks.addSublayer(layer) }71 }72 CATransaction.commit()73 }7475 /// The layers drawing annotations on a page shown at `size` (also used to render a page with its annotations to a picture).76 static func layers(for annotations: [PDFAnnotation], in size: CGSize) -> [CALayer] {77 guard size.width > 0, size.height > 0 else { return [] }78 return annotations.compactMap { annotation -> CALayer? in79 let color = PDFAnnotationFactory.color(annotation.color)80 switch annotation.kind {81 case .ink:82 let points = PDFAnnotationFactory.viewPoints(of: annotation, in: size)83 guard let first = points.first else { return nil }84 let shape = CAShapeLayer()85 shape.name = PDFAnnotationKind.ink.rawValue86 let width = PDFAnnotationFactory.lineWidth(of: annotation, in: size)87 if points.count == 1 {88 shape.path = UIBezierPath(ovalIn: CGRect(x: first.x - width / 2, y: first.y - width / 2, width: width, height: width)).cgPath89 shape.fillColor = color.cgColor90 } else {91 shape.path = InkRenderer.smoothPath(points.map { InkPoint(x: Double($0.x), y: Double($0.y)) })92 shape.fillColor = nil93 shape.strokeColor = color.cgColor94 shape.lineWidth = width95 shape.lineCap = .round96 shape.lineJoin = .round97 }98 shape.opacity = Float(PDFAnnotationFactory.opacity(of: annotation))99 return shape100 case .note:101 guard let rect = annotation.rects.first.map({ PDFPageGeometry.viewRect($0, in: size) }) else { return nil }102 let pin = CAShapeLayer()103 pin.name = PDFAnnotationKind.note.rawValue104 let side = max(14, min(rect.width, rect.height))105 let box = CGRect(x: rect.midX - side / 2, y: rect.midY - side / 2, width: side, height: side)106 // a small sheet with a folded corner107 let path = UIBezierPath(roundedRect: box, cornerRadius: side * 0.18)108 for i in 1...3 {109 let y = box.minY + side * (0.2 + 0.2 * CGFloat(i))110 path.move(to: CGPoint(x: box.minX + side * 0.24, y: y))111 path.addLine(to: CGPoint(x: box.maxX - side * (i == 3 ? 0.44 : 0.24), y: y))112 }113 pin.path = path.cgPath114 pin.fillColor = color.cgColor115 pin.strokeColor = UIColor(red: 0.08, green: 0.10, blue: 0.13, alpha: 0.75).cgColor116 pin.lineWidth = max(1, side * 0.07)117 pin.shadowColor = UIColor.black.cgColor118 pin.shadowOpacity = 0.25119 pin.shadowRadius = 2120 pin.shadowOffset = CGSize(width: 0, height: 1)121 return pin122 default:123 // highlight, and any kind this build does not know: its rectangles124 let rects = annotation.rects.map { PDFPageGeometry.viewRect($0, in: size) }125 guard !rects.isEmpty else { return nil }126 let shape = CAShapeLayer()127 shape.name = PDFAnnotationKind.highlight.rawValue128 let path = UIBezierPath()129 rects.forEach { path.append(UIBezierPath(roundedRect: $0.insetBy(dx: -1, dy: -0.5), cornerRadius: 2)) }130 shape.path = path.cgPath131 shape.fillColor = color.withAlphaComponent(0.4).cgColor132 return shape133 }134 }135 }136137 // MARK: PKCanvasViewDelegate138139 func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {140 guard !isClearing, let stroke = canvasView.drawing.strokes.last else { return }141 let points = stroke.path.interpolatedPoints(by: .parametricStep(0.5)).map { $0.location.applying(stroke.transform) }142 let width = stroke.path.interpolatedPoints(by: .parametricStep(1)).map { max($0.size.width, $0.size.height) }.max() ?? 2.5143 // the stroke now lives in the block's attributes and is drawn by the annotation layer: the canvas is only an input surface144 isClearing = true145 canvasView.drawing = PKDrawing()146 isClearing = false147 onStroke?(points, stroke.ink, width)148 }149}150