Commit c826f7a5 authored by Kourser's avatar Kourser
Browse files

feat: objectifs de lecture et annotation PDF à l'Apple Pencil

Les deux lignes du comparatif où Books gagnait encore.

L'objectif se compte en minutes et non en pages. Une page n'est pas une
unité : elle change avec la taille du texte, l'appareil et le livre.
Une minute est la même partout — et c'est la seule mesure qui compte
aussi bien la lecture que l'écoute, ce que Books ne sait pas faire
puisqu'il ne lit pas les ebooks à voix haute.

La série de jours ne se rompt pas sur une journée encore ouverte : à
huit heures du matin, quatre jours de suite ne doivent pas repartir de
zéro parce qu'on n'a pas encore lu.

Le temps est mesuré par une horloge qui verse toutes les trente secondes
au lieu d'attendre la fermeture — une soirée qui finit par un
force-quit compterait sinon pour rien — et qui s'arrête après dix
minutes sans tourner de page, parce qu'un livre ouvert sur le canapé
n'est pas un livre lu. Les deux lecteurs lui signalent leurs tournes.

Le rappel ne part pas les jours où l'objectif est déjà atteint : un
rappel qui arrive après coup apprend à ignorer les rappels.
L'autorisation n'est demandée qu'au moment où on active le rappel, et
le réglage par défaut n'arme rien — un interrupteur sur « oui » sans
autorisation demandée promet une notification qui n'arrivera jamais.

Côté PDF, PencilKit dans un mode dédié plutôt qu'une couche au-dessus
du lecteur : PDFView possède son défilement et rééchelonne ses pages, et
garder un canevas collé à une page qui bouge produit des traits qui
atterrissent à un centimètre de l'endroit dessiné. Les traits sont
gardés à part pour être repris, et aplatis dans le PDF pour rester
visibles en lecture.

Deux défauts trouvés en vérifiant à l'écran, tous deux invisibles à la
compilation. PKToolPicker.shared(for:) est obsolète et ne rend plus
rien : sans palette, pas de premier répondant, et un canevas où l'on
dessine sans que rien n'apparaisse. Et l'image des traits était
découpée aux dimensions de la page au lieu de celles du canevas, ce qui
posait le trait quatre lignes plus bas et débordant de la marge.

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

## [Non publié]

### Ajouté
- Objectif de lecture quotidien, en minutes. Une page n'est pas une unité — elle
  change avec la taille du texte, l'appareil et le livre — alors qu'une minute
  est la même partout, et c'est la seule mesure qui compte aussi bien la
  lecture que l'écoute.
- Série de jours consécutifs. Une journée encore ouverte ne rompt pas la série :
  à huit heures du matin, quatre jours de suite ne doivent pas être remis à zéro
  parce qu'on n'a pas encore lu.
- Statistiques : quinze derniers jours en barres, temps total, jours de lecture,
  livres finis cette année.
- Rappel quotidien à l'heure choisie, et rien les jours où l'objectif est déjà
  atteint — un rappel qui arrive après coup apprend à ignorer les rappels.
  L'autorisation n'est demandée qu'au moment où on l'active.
- Le temps est compté par une horloge qui verse toutes les trente secondes
  plutôt qu'à la fermeture, pour survivre à une app tuée, et qui s'arrête au
  bout de dix minutes sans tourner de page : un livre ouvert sur le canapé
  n'est pas un livre lu.
- Annotation des PDF à l'Apple Pencil, par PencilKit : palette d'outils
  complète, pression et inclinaison, rejet de la paume. Les traits sont gardés
  à part pour être repris, et aplatis dans le PDF pour rester visibles en
  lecture.


### Ajouté
- Un livre Calibre téléchargé apparaît dans « Sur l'appareil », avec son titre
  et son auteur. Le téléchargement n'écrivait que le fichier : sans le serveur,
+10 −2
Changes for Packages/Core/Sources/PodbookUI/Reader/EPUBReader.swift: 10 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -238,6 +238,9 @@ struct EPUBReaderView: View {
    private let annotations: AnnotationStore
    private let onTranslate: (String) -> Void
    private let onTextSource: (@escaping (DigestScope) async -> [NarrationSegment], String) -> Void
    /// Signalled on every page turn, so the reading clock can tell a book
    /// being read from a book left open.
    private let onActivity: () -> Void

    @State private var showingSettings = false
    @State private var showingContents = false
@@ -250,7 +253,8 @@ struct EPUBReaderView: View {
        preferences: ReaderPreferencesStore,
        annotations: AnnotationStore,
        onTranslate: @escaping (String) -> Void,
        onTextSource: @escaping (@escaping (DigestScope) async -> [NarrationSegment], String) -> Void
        onTextSource: @escaping (@escaping (DigestScope) async -> [NarrationSegment], String) -> Void,
        onActivity: @escaping () -> Void = {}
    ) {
        _model = State(initialValue: EPUBReaderModel(
            file: file, bookID: bookID, locations: locations, annotations: annotations
@@ -259,6 +263,7 @@ struct EPUBReaderView: View {
        self.annotations = annotations
        self.onTranslate = onTranslate
        self.onTextSource = onTextSource
        self.onActivity = onActivity
    }

    var body: some View {
@@ -332,7 +337,10 @@ struct EPUBReaderView: View {
                publication: publication,
                initialLocator: initialLocator,
                preferences: preferences.preferences,
                onLocationChange: { model.record($0) },
                onLocationChange: { locator in
                    model.record(locator)
                    onActivity()
                },
                onTranslate: onTranslate,
                onHighlight: { text, locator in model.highlight(text: text, locator: locator) },
                onTap: { model.toggleChrome() },
+85 −0
Changes for Packages/Core/Sources/PodbookUI/Reader/PDFMarkupStore.swift: 85 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import Observation

#if canImport(PencilKit)
import PencilKit
#endif

/// Pencil strokes drawn on a PDF, kept so they can be taken up again.
///
/// Two copies of the same marks exist, on purpose, and they answer different
/// questions. The stroke data lives here, page by page, because a drawing has
/// to be *editable* — undo, erase, add to it next week. And the same drawing
/// is flattened into the PDF itself as an annotation, because that is what
/// makes it *visible* while reading, scrolling and zooming, without Podbook
/// having to keep a canvas aligned with a page that PDFKit is moving around.
///
/// The PDF written to is the downloaded copy in this app's container, never
/// the file in the Calibre library. Pulling the book down again replaces it,
/// and the strokes kept here are what allows the marks to be put back.
@MainActor
@Observable
public final class PDFMarkupStore {
    private let root: URL

    public init(root: URL? = nil) {
        if let root {
            self.root = root
        } else {
            let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
                ?? FileManager.default.temporaryDirectory
            self.root = base.appendingPathComponent("Podbook/Markup", isDirectory: true)
        }
        try? FileManager.default.createDirectory(at: self.root, withIntermediateDirectories: true)
    }

    /// Raw stroke data for one page, or `nil` when the page is untouched.
    public func data(bookID: Int, page: Int) -> Data? {
        try? Data(contentsOf: file(bookID: bookID, page: page))
    }

    public func save(_ data: Data, bookID: Int, page: Int) {
        try? data.write(to: file(bookID: bookID, page: page), options: .atomic)
    }

    public func clear(bookID: Int, page: Int) {
        try? FileManager.default.removeItem(at: file(bookID: bookID, page: page))
    }

    /// Pages of this book that carry marks, in order.
    public func markedPages(bookID: Int) -> [Int] {
        let prefix = "\(bookID)-"
        let names = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []
        return names
            .filter { $0.hasPrefix(prefix) && $0.hasSuffix(".drawing") }
            .compactMap { Int($0.dropFirst(prefix.count).dropLast(".drawing".count)) }
            .sorted()
    }

    public func hasMarkup(bookID: Int, page: Int) -> Bool {
        FileManager.default.fileExists(atPath: file(bookID: bookID, page: page).path)
    }

    private func file(bookID: Int, page: Int) -> URL {
        root.appendingPathComponent("\(bookID)-\(page).drawing")
    }
}

#if canImport(PencilKit)
public extension PDFMarkupStore {
    func drawing(bookID: Int, page: Int) -> PKDrawing? {
        guard let data = data(bookID: bookID, page: page) else { return nil }
        return try? PKDrawing(data: data)
    }

    /// An empty drawing is an erased page, not a drawing: it is removed rather
    /// than stored, so « a page with marks » stays a true statement.
    func save(_ drawing: PKDrawing, bookID: Int, page: Int) {
        if drawing.strokes.isEmpty {
            clear(bookID: bookID, page: page)
        } else {
            save(drawing.dataRepresentation(), bookID: bookID, page: page)
        }
    }
}
#endif
+313 −0
Changes for Packages/Core/Sources/PodbookUI/Reader/PDFMarkupView.swift: 313 added lines, 0 removed lines.
Original line number Diff line number Diff line
import PDFKit
import SwiftUI

#if canImport(PencilKit) && canImport(UIKit)
import PencilKit
import UIKit

/// Drawing on a PDF page with the Apple Pencil.
///
/// A dedicated mode rather than a layer over the reader, and that is a
/// deliberate limit. `PDFView` owns its own scroll view, lays out pages as it
/// pleases and rescales them on zoom; keeping a canvas pinned to a moving,
/// zooming page is a fight that produces strokes landing a centimetre from
/// where they were drawn. So markup opens one page, fixed, at a known scale —
/// and what is drawn lands exactly where the pencil went.
///
/// The drawing policy is left at `.default`: that means pencil-only once a
/// Pencil has been paired, and finger otherwise. It is the behaviour someone
/// with a Pencil expects, and the one that lets a palm rest on the screen.
struct PDFMarkupView: View {
    let document: PDFDocument
    let bookID: Int
    let store: PDFMarkupStore
    /// The page markup opens on.
    let initialPage: Int
    /// Called when the page's marks change, so the reader can burn them in.
    /// The canvas size travels with the drawing: the strokes are in canvas
    /// coordinates, and without it the image is cropped from the wrong rect.
    let onCommit: (Int, PKDrawing, CGSize) -> Void

    @Environment(\.dismiss) private var dismiss
    @State private var page: Int
    @State private var drawing = PKDrawing()
    @State private var canvasSize: CGSize = .zero

    init(
        document: PDFDocument,
        bookID: Int,
        store: PDFMarkupStore,
        initialPage: Int,
        onCommit: @escaping (Int, PKDrawing, CGSize) -> Void
    ) {
        self.document = document
        self.bookID = bookID
        self.store = store
        self.initialPage = initialPage
        self.onCommit = onCommit
        _page = State(initialValue: initialPage)
    }

    var body: some View {
        NavigationStack {
            GeometryReader { proxy in
                if let pdfPage = document.page(at: page) {
                    let bounds = pdfPage.bounds(for: .mediaBox)
                    let scale = min(
                        proxy.size.width / bounds.width,
                        proxy.size.height / bounds.height
                    )
                    let size = CGSize(
                        width: bounds.width * scale, height: bounds.height * scale
                    )

                    PageCanvas(
                        page: pdfPage,
                        pageSize: size,
                        drawing: $drawing
                    )
                    .frame(width: size.width, height: size.height)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .onAppear { canvasSize = size }
                    .onChange(of: size) { _, new in canvasSize = new }
                } else {
                    ContentUnavailableView(
                        "Page introuvable", systemImage: "doc.questionmark"
                    )
                }
            }
            .background(Color(uiColor: .secondarySystemBackground))
            .navigationTitle("Page \(page + 1) sur \(document.pageCount)")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Terminé") {
                        commit()
                        dismiss()
                    }
                }
                ToolbarItem(placement: .primaryAction) {
                    Button(role: .destructive) {
                        drawing = PKDrawing()
                        commit()
                    } label: {
                        Label("Effacer la page", systemImage: "trash")
                    }
                    .disabled(drawing.strokes.isEmpty)
                }
                ToolbarItemGroup(placement: .bottomBar) {
                    Button { turn(to: page - 1) } label: {
                        Image(systemName: "chevron.left")
                    }
                    .disabled(page == 0)
                    Spacer()
                    Button { turn(to: page + 1) } label: {
                        Image(systemName: "chevron.right")
                    }
                    .disabled(page + 1 >= document.pageCount)
                }
            }
            .onAppear { drawing = store.drawing(bookID: bookID, page: page) ?? PKDrawing() }
        }
    }

    /// Committed on every page turn, not only on the way out: a stylus session
    /// that ends with the app being killed would otherwise lose the lot.
    private func turn(to target: Int) {
        guard target >= 0, target < document.pageCount else { return }
        commit()
        page = target
        drawing = store.drawing(bookID: bookID, page: target) ?? PKDrawing()
    }

    private func commit() {
        store.save(drawing, bookID: bookID, page: page)
        onCommit(page, drawing, canvasSize)
    }
}

/// The page, rendered once, with a canvas exactly on top of it.
private struct PageCanvas: UIViewRepresentable {
    let page: PDFPage
    let pageSize: CGSize
    @Binding var drawing: PKDrawing

    func makeCoordinator() -> Coordinator { Coordinator(drawing: $drawing) }

    func makeUIView(context: Context) -> UIView {
        let container = CanvasHost()

        let backdrop = UIImageView(image: page.thumbnail(of: pageSize, for: .mediaBox))
        backdrop.contentMode = .scaleAspectFit
        backdrop.translatesAutoresizingMaskIntoConstraints = false
        container.addSubview(backdrop)

        let canvas = PKCanvasView()
        canvas.backgroundColor = .clear
        canvas.isOpaque = false
        // `.default` is pencil-only once a Pencil is paired, finger otherwise.
        canvas.drawingPolicy = .default
        canvas.drawing = drawing
        canvas.delegate = context.coordinator
        canvas.translatesAutoresizingMaskIntoConstraints = false
        container.addSubview(canvas)
        context.coordinator.canvas = canvas

        NSLayoutConstraint.activate([
            backdrop.topAnchor.constraint(equalTo: container.topAnchor),
            backdrop.bottomAnchor.constraint(equalTo: container.bottomAnchor),
            backdrop.leadingAnchor.constraint(equalTo: container.leadingAnchor),
            backdrop.trailingAnchor.constraint(equalTo: container.trailingAnchor),
            canvas.topAnchor.constraint(equalTo: container.topAnchor),
            canvas.bottomAnchor.constraint(equalTo: container.bottomAnchor),
            canvas.leadingAnchor.constraint(equalTo: container.leadingAnchor),
            canvas.trailingAnchor.constraint(equalTo: container.trailingAnchor),
        ])

        // A tool has to be set explicitly: without one the canvas accepts
        // touches and draws nothing, which looks exactly like a dead view.
        canvas.tool = PKInkingTool(.pen, color: .systemBlue, width: 6)
        container.canvas = canvas
        return container
    }

    func updateUIView(_ view: UIView, context: Context) {
        guard let canvas = context.coordinator.canvas else { return }
        if canvas.drawing != drawing { canvas.drawing = drawing }
        if let backdrop = view.subviews.compactMap({ $0 as? UIImageView }).first {
            backdrop.image = page.thumbnail(of: pageSize, for: .mediaBox)
        }
    }

    /// Shows the tool picker once the canvas is actually in a window.
    ///
    /// Doing it from a `DispatchQueue.main.async` inside `makeUIView` looked
    /// equivalent and was not: at that point the view has no window, so the
    /// picker was never attached and the canvas never became first responder.
    /// The symptom is a page you can draw on that stays blank.
    final class CanvasHost: UIView {
        weak var canvas: PKCanvasView?
        /// Owned here: a picker that nobody retains disappears, taking the
        /// tools with it. `PKToolPicker.shared(for:)` is deprecated and can
        /// hand back nothing at all on recent systems.
        private let picker = PKToolPicker()

        override func didMoveToWindow() {
            super.didMoveToWindow()
            guard let canvas, window != nil else { return }
            canvas.becomeFirstResponder()
            picker.addObserver(canvas)
            picker.setVisible(true, forFirstResponder: canvas)
        }
    }

    @MainActor
    final class Coordinator: NSObject, PKCanvasViewDelegate {
        weak var canvas: PKCanvasView?
        private let drawing: Binding<PKDrawing>

        init(drawing: Binding<PKDrawing>) {
            self.drawing = drawing
        }

        nonisolated func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
            let new = canvasView.drawing
            Task { @MainActor [drawing] in drawing.wrappedValue = new }
        }
    }
}

// MARK: - Burning the marks into the document

public enum PDFMarkupBurner {
    /// The name Podbook puts on its own annotations, so a redraw replaces the
    /// previous pass instead of stacking on top of it.
    public static let annotationName = "podbook.markup"

    /// Replaces this page's Podbook annotation with the given image.
    ///
    /// Flattened to an image rather than written as a PDF ink annotation: a
    /// `PKDrawing` carries pressure, tilt and blending that an ink annotation
    /// cannot express, and a stroke that looks different once saved is worse
    /// than one that cannot be edited in another reader.
    /// - Parameter canvasSize: the size the strokes were drawn at. The image
    ///   is cropped from *that* rect, not from the page's: taking the page's
    ///   size cut a region the drawing did not occupy, and the result landed
    ///   several lines lower and stretched past the right margin.
    @MainActor
    public static func apply(
        _ drawing: PKDrawing,
        to page: PDFPage,
        canvasSize: CGSize,
        scale: CGFloat = 2
    ) {
        for existing in page.annotations where existing.contents == annotationName {
            page.removeAnnotation(existing)
        }
        guard !drawing.strokes.isEmpty else { return }

        let bounds = page.bounds(for: .mediaBox)
        let source = canvasSize == .zero ? bounds.size : canvasSize
        let image = drawing.image(from: CGRect(origin: .zero, size: source), scale: scale)
        page.addAnnotation(StampAnnotation(bounds: bounds, image: image, name: annotationName))
    }
}

/// A stamp that draws the image it was given.
///
/// `PDFAnnotation` of type stamp has no public way to carry an image, so the
/// drawing is done by hand.
final class StampAnnotation: PDFAnnotation {
    private let image: UIImage

    init(bounds: CGRect, image: UIImage, name: String) {
        self.image = image
        super.init(bounds: bounds, forType: .stamp, withProperties: nil)
        contents = name
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) { fatalError("not used") }

    override func draw(with box: PDFDisplayBox, in context: CGContext) {
        guard let cgImage = image.cgImage else { return }
        let page = self.page?.bounds(for: box) ?? bounds
        context.saveGState()
        context.draw(cgImage, in: CGRect(origin: .zero, size: page.size))
        context.restoreGState()
    }
}
#endif

/// Presents markup where PencilKit exists, and nothing where it does not.
///
/// Kept as a modifier so the PDF reader itself stays free of `#if`: on macOS
/// the button is simply never offered.
struct PDFMarkupPresentation: ViewModifier {
    @Binding var isPresented: Bool
    let controller: PDFController
    let bookID: Int
    let store: PDFMarkupStore?

    func body(content: Content) -> some View {
        #if canImport(PencilKit) && canImport(UIKit)
        content.fullScreenCover(isPresented: $isPresented) {
            if let store, let document = controller.document {
                PDFMarkupView(
                    document: document,
                    bookID: bookID,
                    store: store,
                    initialPage: controller.currentPage,
                    onCommit: { page, drawing, canvasSize in
                        guard let pdfPage = document.page(at: page) else { return }
                        PDFMarkupBurner.apply(drawing, to: pdfPage, canvasSize: canvasSize)
                        controller.saveDocument()
                    }
                )
            }
        }
        #else
        content
        #endif
    }
}
+111 −0
Changes for Packages/Core/Sources/PodbookUI/Stats/GoalReminder.swift: 111 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation

#if canImport(UserNotifications)
import UserNotifications
#endif

/// The daily nudge, and nothing more.
///
/// One notification, at an hour the reader chooses, and only on a day where
/// the goal is not yet met — a reminder that fires after you have already read
/// teaches you to ignore reminders. It is rescheduled on every change, so the
/// pending request always reflects the current state rather than the state at
/// the time the goal was set.
@MainActor
public struct GoalReminder: Sendable {
    public static let identifier = "podbook.goal.reminder"

    public init() {}

    /// Asks once. Returns false when the reader says no, which is a complete
    /// answer and not an error: the goal still works, it just stays silent.
    public func requestPermission() async -> Bool {
        #if canImport(UserNotifications)
        let centre = UNUserNotificationCenter.current()
        let settings = await centre.notificationSettings()
        switch settings.authorizationStatus {
        case .authorized, .provisional: return true
        case .denied: return false
        default:
            return (try? await centre.requestAuthorization(options: [.alert, .sound])) ?? false
        }
        #else
        return false
        #endif
    }

    public func isAuthorised() async -> Bool {
        #if canImport(UserNotifications)
        let status = await UNUserNotificationCenter.current().notificationSettings()
            .authorizationStatus
        return status == .authorized || status == .provisional
        #else
        return false
        #endif
    }

    /// Puts the pending reminder in line with the goal as it stands now.
    public func reschedule(for goal: ReadingGoal, metToday: Bool) async {
        #if canImport(UserNotifications)
        let centre = UNUserNotificationCenter.current()
        centre.removePendingNotificationRequests(withIdentifiers: [Self.identifier])

        guard goal.isEnabled, goal.hasReminder, await isAuthorised() else { return }

        let content = UNMutableNotificationContent()
        content.title = "Objectif de lecture"
        content.body = "\(goal.minutesPerDay) minutes aujourd'hui. Il est encore temps."
        content.sound = .default

        var when = DateComponents()
        when.hour = goal.reminderHour
        when.minute = goal.reminderMinute

        // Repeating daily, and cancelled for today once the goal is met — so
        // it never congratulates you by asking you to do what you have done.
        let trigger = UNCalendarNotificationTrigger(dateMatching: when, repeats: true)
        try? await centre.add(
            UNNotificationRequest(identifier: Self.identifier, content: content, trigger: trigger)
        )

        if metToday { await suppressForToday(goal: goal) }
        #endif
    }

    /// Removes today's occurrence by replacing the repeating request with one
    /// that starts tomorrow.
    private func suppressForToday(goal: ReadingGoal) async {
        #if canImport(UserNotifications)
        guard let hour = goal.reminderHour, let minute = goal.reminderMinute else { return }
        let calendar = Calendar.current
        let now = Date()
        guard let todaysFiring = calendar.date(
            bySettingHour: hour, minute: minute, second: 0, of: now
        ), todaysFiring > now else { return }

        // The firing is still ahead of us today and the goal is already met:
        // drop it and let the repeating one resume tomorrow.
        let centre = UNUserNotificationCenter.current()
        centre.removePendingNotificationRequests(withIdentifiers: [Self.identifier])

        guard let tomorrow = calendar.date(byAdding: .day, value: 1, to: todaysFiring) else { return }
        let content = UNMutableNotificationContent()
        content.title = "Objectif de lecture"
        content.body = "\(goal.minutesPerDay) minutes aujourd'hui. Il est encore temps."
        content.sound = .default
        let parts = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: tomorrow)
        try? await centre.add(UNNotificationRequest(
            identifier: Self.identifier,
            content: content,
            trigger: UNCalendarNotificationTrigger(dateMatching: parts, repeats: false)
        ))
        #endif
    }

    public func cancel() {
        #if canImport(UserNotifications)
        UNUserNotificationCenter.current()
            .removePendingNotificationRequests(withIdentifiers: [Self.identifier])
        #endif
    }
}
Loading