Commit 679feafa authored by Kourser's avatar Kourser
Browse files

feat: surligner un PDF, déplacer une signature, exporter une copie

Les trois manques que j'avais nommés.

Le surlignage pose une annotation par ligne, pas une par sélection : un
passage courant sur trois lignes n'est pas un rectangle, et une seule
boîte autour peindrait les marges et les interlignes. Les couleurs sont
celles de l'EPUB, mais translucides — un surlignage PDF se pose
par-dessus les glyphes et non derrière, donc opaque il cacherait les
mots qu'il marque.

Une signature posée se déplace au doigt et se retaille par sa poignée
d'angle. La largeur commande et la hauteur suit, pour qu'une signature
ne soit jamais étirée hors de forme ; et elle est bornée à la feuille,
parce qu'une signature traînée hors page ne laisse plus rien à
rattraper. Les poignées n'apparaissent qu'en mode signature : toujours
visibles, elles gêneraient le dessin et la pose des notes.

L'export passe par la feuille de partage et produit une copie nommée
d'après le livre — « 7407.pdf » ne dit rien au destinataire. Une copie,
pas l'original : ce qui sort de l'app est un instantané, le fichier que
Podbook continue de lire reste celui de son conteneur.

Au passage, la couleur d'annotation est devenue multiplateforme : elle
était sous `#if canImport(UIKit)` alors que le lecteur PDF compile
aussi sur macOS, et seul le build iOS le montrait.

Vérifié à l'écran : « verifier » surligné en vert et toujours lisible,
signature déplacée puis agrandie en gardant ses proportions, feuille de
partage avec un PDF de 306 ko dont la vignette porte les annotations.

Co-Authored-By: default avatarClaude Opus 5 <noreply@anthropic.com>
parent 6b75f557
Loading
Loading
Loading
Loading
+13 −0
Changes for CHANGELOG.md: 13 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,19 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).
## [Non publié]

### Ajouté
- Surlignage du texte d'un PDF, dans les cinq mêmes couleurs que l'EPUB. Une
  annotation par ligne et non une par sélection : un passage sur trois lignes
  n'est pas un rectangle, et une seule boîte peindrait les marges et les
  interlignes. La couleur est translucide — un surlignage PDF se pose
  par-dessus les glyphes, pas derrière, donc opaque il cacherait les mots
  qu'il marque.
- Une signature posée se déplace au doigt et se redimensionne par sa poignée
  d'angle. La largeur commande, la hauteur suit : une signature ne doit jamais
  être étirée. Elle ne peut pas sortir de la feuille, sinon il ne resterait
  rien à rattraper.
- Export d'une copie annotée par la feuille de partage, nommée d'après le
  livre. Une copie et non l'original : ce qui sort de l'app est un instantané,
  le fichier que Podbook continue de lire reste le sien.
- Trois outils d'annotation PDF au lieu d'un : dessin, note tapée au clavier,
  signature.
- Le dessin au doigt se règle. `PKCanvasView.default` refuse le doigt dès
+26 −0
Changes for Packages/Core/Sources/PodbookUI/Annotations/BookAnnotation.swift: 26 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -82,3 +82,29 @@ public struct BookAnnotation: Codable, Sendable, Hashable, Identifiable {
        return !note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }
}

#if canImport(UIKit)
import UIKit
public typealias AnnotationColor = UIColor
#elseif canImport(AppKit)
import AppKit
public typealias AnnotationColor = NSColor
#endif

#if canImport(UIKit) || canImport(AppKit)
public extension BookAnnotation.Tint {
    /// The colour a PDF annotation is painted with.
    ///
    /// Translucent on purpose: a PDF highlight sits *over* the glyphs rather
    /// than behind them, so an opaque colour hides the very words it marks.
    var platformColor: AnnotationColor {
        switch self {
        case .yellow: AnnotationColor.systemYellow.withAlphaComponent(0.45)
        case .green: AnnotationColor.systemGreen.withAlphaComponent(0.4)
        case .blue: AnnotationColor.systemBlue.withAlphaComponent(0.35)
        case .pink: AnnotationColor.systemPink.withAlphaComponent(0.35)
        case .purple: AnnotationColor.systemPurple.withAlphaComponent(0.35)
        }
    }
}
#endif
+97 −0
Changes for Packages/Core/Sources/PodbookUI/Reader/PDFMarkupView.swift: 97 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -124,6 +124,9 @@ struct PDFMarkupView: View {
                        if tool != .draw {
                            placementLayer(page: pdfPage, size: size)
                        }
                        if tool == .signature {
                            signatureHandles(page: pdfPage, size: size)
                        }
                        noteMarkers(page: pdfPage, size: size)
                    }
                    .frame(width: size.width, height: size.height)
@@ -250,6 +253,100 @@ struct PDFMarkupView: View {
        }
    }

    /// A placed signature can be dragged, and pulled bigger or smaller by its
    /// corner.
    ///
    /// Only in signature mode: handles that are always on would sit in the way
    /// of drawing and of placing notes, and a signature is something you
    /// adjust once and then leave alone.
    private func signatureHandles(page pdfPage: PDFPage, size: CGSize) -> some View {
        ForEach(Array(signaturesPlaced(on: pdfPage).enumerated()), id: \.offset) { _, annotation in
            let frame = canvasRect(from: annotation.bounds, page: pdfPage, canvas: size)
            ZStack(alignment: .bottomTrailing) {
                RoundedRectangle(cornerRadius: 4)
                    .strokeBorder(.tint, style: StrokeStyle(lineWidth: 1, dash: [4, 3]))
                    .contentShape(Rectangle())
                    .gesture(
                        DragGesture()
                            .onChanged { value in
                                move(annotation, by: value.translation, page: pdfPage, canvas: size)
                            }
                            .onEnded { _ in documentChanged() }
                    )
                Circle()
                    .fill(.tint)
                    .frame(width: 22, height: 22)
                    .offset(x: 11, y: 11)
                    .gesture(
                        DragGesture()
                            .onChanged { value in
                                resize(annotation, by: value.translation, page: pdfPage, canvas: size)
                            }
                            .onEnded { _ in documentChanged() }
                    )
                    .accessibilityLabel("Redimensionner la signature")
            }
            .frame(width: frame.width, height: frame.height)
            .position(x: frame.midX, y: frame.midY)
        }
    }

    private func signaturesPlaced(on page: PDFPage) -> [PDFAnnotation] {
        page.annotations.filter { $0.contents == PDFMarkupNames.signature }
    }

    /// Drags are applied live, so the signature follows the finger; the
    /// document is only written once the finger lifts.
    private func move(
        _ annotation: PDFAnnotation, by translation: CGSize, page: PDFPage, canvas: CGSize
    ) {
        let scale = page.bounds(for: .mediaBox).width / max(canvas.width, 1)
        var bounds = annotation.bounds
        bounds.origin.x += translation.width * scale
        // Canvas down is page up.
        bounds.origin.y -= translation.height * scale
        annotation.bounds = clamped(bounds, in: page)
        revision += 1
    }

    private func resize(
        _ annotation: PDFAnnotation, by translation: CGSize, page: PDFPage, canvas: CGSize
    ) {
        let scale = page.bounds(for: .mediaBox).width / max(canvas.width, 1)
        var bounds = annotation.bounds
        let ratio = bounds.height / max(bounds.width, 1)
        // The corner drives the width; the height follows, so a signature is
        // never stretched out of shape.
        let width = max(60, bounds.width + translation.width * scale)
        let height = width * ratio
        bounds.origin.y += bounds.height - height
        bounds.size = CGSize(width: width, height: height)
        annotation.bounds = clamped(bounds, in: page)
        revision += 1
    }

    /// Keeps it on the sheet: a signature dragged off the page is gone for
    /// good, with nothing left to grab.
    private func clamped(_ rect: CGRect, in page: PDFPage) -> CGRect {
        let limits = page.bounds(for: .mediaBox)
        var rect = rect
        rect.origin.x = min(max(rect.minX, 0), max(limits.width - rect.width, 0))
        rect.origin.y = min(max(rect.minY, 0), max(limits.height - rect.height, 0))
        return rect
    }

    private func canvasRect(from rect: CGRect, page: PDFPage, canvas: CGSize) -> CGRect {
        let bounds = page.bounds(for: .mediaBox)
        guard bounds.width > 0 else { return .zero }
        let scale = canvas.width / bounds.width
        return CGRect(
            x: rect.minX * scale,
            y: (bounds.height - rect.maxY) * scale,
            width: rect.width * scale,
            height: rect.height * scale
        )
    }

    private func notes(on page: PDFPage) -> [PDFAnnotation] {
        page.annotations.filter { $0.type == "Text" }
    }
+97 −1
Changes for Packages/Core/Sources/PodbookUI/Views/ReaderView.swift: 97 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -33,6 +33,8 @@ public struct ReaderView: View {
    @Environment(\.dismiss) private var dismiss
    @State private var showingTranslation = false
    @State private var pdfSelection: String?
    /// The PDF reader's controller, so the toolbar can reach the selection.
    @State private var pdfController: PDFController?
    @State private var player: NarrationPlayer?
    /// Produced on demand rather than at open: walking a whole EPUB up front
    /// would stall the interface.
@@ -75,6 +77,18 @@ public struct ReaderView: View {
                                Label("Traduire", systemImage: "translate")
                            }
                        }
                        ToolbarItem {
                            Menu {
                                ForEach(BookAnnotation.Tint.allCases, id: \.self) { tint in
                                    Button(tint.label) {
                                        pdfController?.highlightSelection(tint)
                                        pdfSelection = nil
                                    }
                                }
                            } label: {
                                Label("Surligner", systemImage: "highlighter")
                            }
                        }
                    }
                    if textSource != nil {
                        ToolbarItem {
@@ -249,6 +263,7 @@ public struct ReaderView: View {
                locations: locations,
                preferences: services.readerPreferences,
                onSelection: { pdfSelection = $0 },
                onController: { pdfController = $0 },
                onNarrationSource: { source in textSource = source },
                onActivity: { clock.noteActivity() },
                markup: services.markup,
@@ -357,6 +372,52 @@ final class PDFController {

    var document: PDFKit.PDFDocument? { view?.document }

    /// Highlights what is selected, line by line.
    ///
    /// One annotation per line rather than one for the whole selection: a
    /// passage running over three lines is not a rectangle, and a single box
    /// around it would paint over the margins and the lines between.
    func highlightSelection(_ tint: BookAnnotation.Tint) {
        guard let view, let selection = view.currentSelection else { return }
        for line in selection.selectionsByLine() {
            for page in line.pages {
                let bounds = line.bounds(for: page)
                guard bounds.width > 1, bounds.height > 1 else { continue }
                let annotation = PDFAnnotation(
                    bounds: bounds, forType: .highlight, withProperties: nil
                )
                annotation.color = tint.platformColor
                annotation.contents = line.string
                page.addAnnotation(annotation)
            }
        }
        view.clearSelection()
        saveDocument()
    }

    /// A copy carrying the annotations, written to a temporary file for
    /// sharing.
    ///
    /// A copy and not the original: what leaves the app is a snapshot, and
    /// the file Podbook keeps reading stays the one in its own container.
    /// The name is the book's, because « 7407.pdf » tells the recipient
    /// nothing.
    func exportAnnotatedCopy(named title: String) -> URL? {
        guard let document, let data = document.dataRepresentation() else { return nil }
        let safe = title
            .components(separatedBy: CharacterSet(charactersIn: "/\\:?%*|\"<>"))
            .joined(separator: "-")
            .trimmingCharacters(in: .whitespacesAndNewlines)
        let name = (safe.isEmpty ? "Document" : safe) + " — annoté.pdf"
        let url = FileManager.default.temporaryDirectory.appendingPathComponent(name)
        do {
            try data.write(to: url, options: .atomic)
            return url
        } catch {
            return nil
        }
    }

    /// Writes the document back where it came from, marks included.
    ///
    /// The file is this app's own copy. Downloading the book again replaces
@@ -390,6 +451,7 @@ struct PDFReaderView: View {
    let locations: ReadingLocationStore
    let preferences: ReaderPreferencesStore
    let onSelection: (String?) -> Void
    var onController: (PDFController) -> Void = { _ in }
    let onNarrationSource: (@escaping (DigestScope) async -> [NarrationSegment]) -> Void
    var onActivity: () -> Void = {}
    var markup: PDFMarkupStore?
@@ -400,6 +462,7 @@ struct PDFReaderView: View {
    @State private var isChromeVisible = true
    @State private var scrubbing: Double?
    @State private var markingUp = false
    @State private var exported: URL?

    var body: some View {
        let initialPage = locations
@@ -415,7 +478,15 @@ struct PDFReaderView: View {
            onSelection: onSelection,
            onTap: { isChromeVisible.toggle() }
        )
        .onAppear { controller.onActivity = onActivity }
        .onAppear {
            controller.onActivity = onActivity
            onController(controller)
        }
        #if canImport(UIKit)
        .sheet(item: $exported) { url in
            ShareSheet(url: url)
        }
        #endif
        .modifier(PDFMarkupPresentation(
            isPresented: $markingUp,
            controller: controller,
@@ -482,6 +553,13 @@ struct PDFReaderView: View {
                    }
                    .accessibilityLabel("Annoter cette page")
                }

                #if canImport(UIKit)
                Button { exported = controller.exportAnnotatedCopy(named: file.title) } label: {
                    Image(systemName: "square.and.arrow.up")
                }
                .accessibilityLabel("Exporter une copie annotée")
                #endif
            }
            .buttonStyle(.plain)

@@ -713,3 +791,21 @@ enum PDFTextSource {
        return segments
    }
}

#if canImport(UIKit)
/// `URL` is not `Identifiable`, and `sheet(item:)` wants one.
extension URL: @retroactive Identifiable {
    public var id: String { absoluteString }
}

/// The system share sheet, for the annotated copy.
struct ShareSheet: UIViewControllerRepresentable {
    let url: URL

    func makeUIViewController(context: Context) -> UIActivityViewController {
        UIActivityViewController(activityItems: [url], applicationActivities: nil)
    }

    func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}
}
#endif
+24 −0
Changes for Packages/Core/Tests/PodbookUITests/DownloadedBookTests.swift: 24 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -263,3 +263,27 @@ struct AnnotationNameTests {
        #expect(PDFMarkupNames.markup != PDFMarkupNames.signature)
    }
}

@Suite("Couleurs de surlignage")
struct HighlightTintTests {
    @Test("Chaque teinte a un nom")
    func allNamed() {
        for tint in BookAnnotation.Tint.allCases {
            #expect(tint.label.isEmpty == false)
        }
    }

    #if canImport(UIKit)
    @Test("Un surlignage PDF est translucide")
    func translucent() {
        // Il se pose par-dessus les glyphes, pas derrière : opaque, il
        // cacherait les mots qu'il marque.
        for tint in BookAnnotation.Tint.allCases {
            var alpha: CGFloat = 0
            tint.platformColor.getWhite(nil, alpha: &alpha)
            #expect(alpha < 0.6, "\(tint.label) doit laisser lire le texte")
            #expect(alpha > 0.1, "\(tint.label) doit rester visible")
        }
    }
    #endif
}
Loading