Commit ddcf408a authored by Kourser's avatar Kourser
Browse files

fix: geste de signature, langue collée, et progression dans la grille

Quatre retours d'usage sur l'iPad.

Le redimensionnement « pas très fluide » était un vrai bug, pas une
question de réglage : `DragGesture.translation` donne le décalage total
depuis le début du geste, pas le pas depuis le dernier appel. En
l'ajoutant chaque fois aux bornes courantes, le mouvement se composait
— la signature accélérait sous le doigt. Les bornes de départ sont
mémorisées au début du geste et la translation s'applique à
celles-là. Le déplacement avait exactement le même défaut.

Une signature posée ne pouvait plus être retirée. Elle a maintenant une
croix sur son cadre.

« Ce livre est déjà en français » sur un livre anglais : la langue était
déduite du livre, ce qui était faux deux fois. Elle n'est connue que
pour un EPUB, donc un PDF gardait celle du livre précédent — le
traducteur est partagé entre les livres — et un livre n'est de toute
façon pas d'une seule langue d'un bout à l'autre. La langue est
maintenant reconnue sur le passage sélectionné, par
NLLanguageRecognizer, et seulement quand il s'engage à plus de 60 % :
deviner de travers sur trois mots refuserait une traduction demandée.
Le traducteur est aussi remis à zéro à l'ouverture d'un livre.

Et la progression de lecture apparaît sous les couvertures, pour les
livres commencés seulement — une barre à zéro sur chaque livre intact
serait du bruit. Verte quand le livre est fini, et prenant le format lu
le plus récemment quand un livre existe en EPUB et en PDF.

Vérifié à l'écran : barres présentes sur trois livres et absentes du
quatrième, signature supprimée par sa croix avec redessin immédiat. La
reconnaissance de langue est couverte par des tests sur de vrais
passages anglais et français — la traduction elle-même attend toujours
un appareil.

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

### Ajouté
- Une barre de progression sous la couverture, dans la bibliothèque, pour les
  livres commencés. Rien pour ceux jamais ouverts : une barre à zéro partout
  serait du bruit, pas une information. Elle devient verte une fois le livre
  fini, et prend le format lu le plus récemment quand un livre existe en
  plusieurs.
- Une signature posée se retire par la croix de son cadre.

### Corrigé
- Déplacer ou retailler une signature s'emballait. `DragGesture.translation`
  est le décalage **total** depuis le début du geste, pas le pas depuis le
  dernier appel ; en l'ajoutant à chaque fois aux bornes courantes, le
  mouvement se composait et la signature filait sous le doigt. Les bornes de
  départ sont maintenant mémorisées au début du geste.
- « Ce livre est déjà en français » sur un livre anglais. La langue était
  déduite du livre, ce qui était faux deux fois : elle n'est connue que pour
  un EPUB, donc un PDF héritait de celle du livre précédent — un PDF anglais
  ouvert après un roman français s'annonçait déjà traduit — et un livre n'est
  de toute façon pas d'une seule langue. Elle est désormais reconnue sur le
  passage sélectionné, et le traducteur est remis à zéro à chaque ouverture.

- 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
+58 −18
Changes for Packages/Core/Sources/PodbookUI/Reader/PDFMarkupView.swift: 58 added lines, 18 removed lines.
Original line number Diff line number Diff line
@@ -47,6 +47,13 @@ struct PDFMarkupView: View {
    /// canvas is a rendered image, and without this it keeps showing the page
    /// as it was — you sign, and nothing appears until you leave.
    @State private var revision = 0
    /// The annotation's bounds when a drag began.
    ///
    /// `DragGesture.translation` is the total offset since the finger went
    /// down, not the step since the last callback. Adding it to the current
    /// bounds each time compounds it, and the signature shoots off under the
    /// finger — « pas très fluide » is exactly what that looks like.
    @State private var dragOrigin: CGRect?

    enum Tool: String, CaseIterable, Identifiable {
        case draw, note, signature
@@ -262,27 +269,57 @@ struct PDFMarkupView: View {
    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) {
            ZStack {
                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)
                                let start = dragOrigin ?? annotation.bounds
                                dragOrigin = start
                                move(
                                    annotation, from: start, by: value.translation,
                                    page: pdfPage, canvas: size
                                )
                            }
                            .onEnded { _ in
                                dragOrigin = nil
                                documentChanged()
                            }
                            .onEnded { _ in documentChanged() }
                    )

                Button {
                    pdfPage.removeAnnotation(annotation)
                    documentChanged()
                } label: {
                    Image(systemName: "xmark.circle.fill")
                        .font(.title3)
                        .symbolRenderingMode(.palette)
                        .foregroundStyle(.white, .red)
                }
                .buttonStyle(.plain)
                .offset(x: -frame.width / 2, y: -frame.height / 2)
                .accessibilityLabel("Retirer cette signature")

                Circle()
                    .fill(.tint)
                    .frame(width: 22, height: 22)
                    .offset(x: 11, y: 11)
                    .frame(width: 24, height: 24)
                    .offset(x: frame.width / 2, y: frame.height / 2)
                    .gesture(
                        DragGesture()
                            .onChanged { value in
                                resize(annotation, by: value.translation, page: pdfPage, canvas: size)
                                let start = dragOrigin ?? annotation.bounds
                                dragOrigin = start
                                resize(
                                    annotation, from: start, by: value.translation,
                                    page: pdfPage, canvas: size
                                )
                            }
                            .onEnded { _ in
                                dragOrigin = nil
                                documentChanged()
                            }
                            .onEnded { _ in documentChanged() }
                    )
                    .accessibilityLabel("Redimensionner la signature")
            }
@@ -298,29 +335,32 @@ struct PDFMarkupView: View {
    /// 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
        _ annotation: PDFAnnotation, from start: CGRect, 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
        var bounds = start
        bounds.origin.x = start.minX + translation.width * scale
        // Canvas down is page up.
        bounds.origin.y -= translation.height * scale
        bounds.origin.y = start.minY - translation.height * scale
        annotation.bounds = clamped(bounds, in: page)
        revision += 1
    }

    private func resize(
        _ annotation: PDFAnnotation, by translation: CGSize, page: PDFPage, canvas: CGSize
        _ annotation: PDFAnnotation, from start: CGRect, 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)
        let ratio = start.height / max(start.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)
        // never stretched out of shape. The top-left stays put, which is what
        // a corner handle is expected to do.
        let width = max(60, start.width + translation.width * scale)
        let height = width * ratio
        bounds.origin.y += bounds.height - height
        bounds.size = CGSize(width: width, height: height)
        let bounds = CGRect(
            x: start.minX, y: start.maxY - height, width: width, height: height
        )
        annotation.bounds = clamped(bounds, in: page)
        revision += 1
    }
+22 −0
Changes for Packages/Core/Sources/PodbookUI/Support/ReadingLocationStore.swift: 22 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -75,6 +75,28 @@ public final class ReadingLocationStore {
        return try? JSONDecoder().decode(ReadingLocation.self, from: data)
    }

    /// How far through this book the reader is, whatever format they opened.
    ///
    /// The grid does not know which format was read — a Calibre book may have
    /// been downloaded as EPUB today and PDF last week — so the most recently
    /// updated position wins. Returns `nil` for a book never opened, which is
    /// what lets the cover stay clean rather than showing a zero bar.
    public func progression(bookID: Int) -> Double? {
        var best: ReadingLocation?
        for (key, location) in pending where key.bookID == bookID {
            if best.map({ location.updatedAt > $0.updatedAt }) ?? true { best = location }
        }
        let names = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []
        for name in names where name.hasPrefix("\(bookID)-") && name.hasSuffix(".json") {
            guard let data = try? Data(contentsOf: root.appendingPathComponent(name)),
                  let location = try? JSONDecoder().decode(ReadingLocation.self, from: data)
            else { continue }
            if best.map({ location.updatedAt > $0.updatedAt }) ?? true { best = location }
        }
        guard let progression = best?.progression, progression > 0.001 else { return nil }
        return min(progression, 1)
    }

    /// Asks the server for a position recorded by another device, and keeps it
    /// only if it is newer than the local one. Calibre tracks positions per
    /// device, so the most recent across devices is the one that matters.
+32 −5
Changes for Packages/Core/Sources/PodbookUI/Translation/SentenceTranslator.swift: 32 added lines, 5 removed lines.
Original line number Diff line number Diff line
import Foundation
import NaturalLanguage
import Observation
import SwiftUI

@@ -119,11 +120,11 @@ public final class SentenceTranslator {
        // a problem with the languages and sends the search in that direction.
        modelStatus = .simulator
        #elseif canImport(Translation)
        let bookLanguage = sourceLanguageCode.map { String($0.prefix(2)) }
        if let bookLanguage, bookLanguage == String(targetLanguageCode.prefix(2)) {
            modelStatus = .sameLanguage
            return
        }
        // The book's language is a hint for « is this pair installed », not a
        // verdict on whether to translate: that is settled per passage.
        let bookLanguage = sourceLanguageCode
            .map { String($0.prefix(2)) }
            .flatMap { $0 == String(targetLanguageCode.prefix(2)) ? nil : $0 }
        let availability = LanguageAvailability()
        let source = Locale.Language(identifier: bookLanguage ?? "en")
        let target = Locale.Language(identifier: targetLanguageCode)
@@ -156,6 +157,18 @@ public final class SentenceTranslator {
            return
        }

        // Decided on the passage in hand, not on the book.
        //
        // The book's language was wrong twice over: it is only known for an
        // EPUB, so a PDF kept whatever the previous book had set — an English
        // PDF opened after a French novel was announced « déjà en français » —
        // and a book is not uniformly one language anyway.
        if let detected = Self.language(of: source),
           detected == String(targetLanguageCode.prefix(2)) {
            phase = .failed(source: source, message: TranslationModelStatus.sameLanguage.label)
            return
        }

        guard modelStatus.isUsable || modelStatus == .unknown else {
            phase = .failed(source: source, message: modelStatus.label)
            return
@@ -171,6 +184,20 @@ public final class SentenceTranslator {
        pending = nil
    }

    /// The dominant language of a passage, as a two-letter code.
    ///
    /// `nil` when the recogniser will not commit — a three-word selection
    /// often leaves it guessing, and guessing wrong here refuses a
    /// translation the reader asked for. Silence means « try anyway ».
    static func language(of text: String) -> String? {
        let recogniser = NLLanguageRecognizer()
        recogniser.processString(text)
        guard let language = recogniser.dominantLanguage else { return nil }
        let hypotheses = recogniser.languageHypotheses(withMaximum: 1)
        guard (hypotheses[language] ?? 0) >= 0.6 else { return nil }
        return String(language.rawValue.prefix(2))
    }

    // MARK: - Fulfilment, called by the SwiftUI modifier

    func complete(_ translation: String, for source: String) async {
+16 −1
Changes for Packages/Core/Sources/PodbookUI/Views/LibraryView.swift: 16 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -124,7 +124,8 @@ public struct LibraryView: View {
                            // tout est sur l'appareil, la pastille n'y
                            // distinguerait rien.
                            isOnDevice: library.source == .calibre
                                && library.isOnDevice(book)
                                && library.isOnDevice(book),
                            progression: services.locations.progression(bookID: book.id)
                        )
                    }
                    .buttonStyle(.plain)
@@ -220,6 +221,9 @@ struct BookCard: View {
    /// Shown in the Calibre tab so the grid says, at a glance, what is already
    /// here — otherwise the only way to find out is to open each book.
    var isOnDevice = false
    /// 0…1 for a book already started, `nil` for one never opened. A bar at
    /// zero on every untouched cover would be noise, not information.
    var progression: Double?

    var body: some View {
        VStack(alignment: .leading, spacing: 6) {
@@ -249,6 +253,17 @@ struct BookCard: View {
                    }
                }

            if let progression {
                ProgressView(value: progression)
                    .progressViewStyle(.linear)
                    .tint(progression >= 0.995 ? .green : .accentColor)
                    .accessibilityLabel(
                        progression >= 0.995
                            ? "Livre terminé"
                            : "Lu à \(Int(progression * 100)) pour cent"
                    )
            }

            Text(book.title)
                .font(.caption.weight(.medium))
                .lineLimit(2)
Loading