Commit 6397ef12 authored by Kourser's avatar Kourser
Browse files

feat: file d'attente du mode voiture

Les briques du trajet, sans interface encore. Une file ordonnée d'entrées
écoutables — les résumés déjà produits, du plus court au plus long, puis
le livre repris là où la lecture s'est arrêtée — et un pilote qui
enchaîne tout seul quand une entrée se termine.

Trois minutes de « de quoi parle ce chapitre » valent mieux, au démarrage
d'un trajet, qu'un atterrissage au milieu d'un paragraphe : d'où l'ordre.

La file est un type valeur sans lecture dedans, parce que la partie
pénible d'une file de voiture est la comptabilité — avancer, ne pas
déborder, savoir ce qui suit — et que ça se teste sans produire un son.

Le récapitulatif de disponibilité fait partie de l'interface et non d'un
réglage : la règle des specs est que rien ne se fabrique au moment où on
le consomme, donc avant de partir il faut savoir ce qui est déjà sur
l'appareil. Toutes les entrées proposées le sont.

Les segments d'une entrée sont résolus à la demande : parcourir un EPUB
entier pour chaque entrée dès l'ouverture figerait l'interface.

189 tests au vert.

Co-Authored-By: default avatarClaude Opus 5 <noreply@anthropic.com>
parent 0320995c
Loading
Loading
Loading
Loading
+193 −0
Changes for Packages/Core/Sources/PodbookUI/Driving/DrivingMode.swift: 193 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import Observation

/// Runs the journey: builds the queue, plays it, and moves on by itself.
///
/// The rule from the specs that shapes everything here: **nothing is produced
/// while it is being consumed**. A queue entry that needs the network to exist
/// is not offered; a tunnel must not interrupt the drive. So the readiness
/// check is part of the interface, not an afterthought.
@MainActor
@Observable
public final class DrivingMode {
    public private(set) var queue = DrivingQueue()
    public private(set) var isActive = false
    public private(set) var isPreparing = false

    public var state: NarrationState { player.state }
    public var rate: Double {
        get { player.rate }
        set { player.rate = newValue }
    }

    private let player: NarrationPlayer
    private let locations: ReadingLocationStore
    private let digests: DigestStore

    public init(
        locations: ReadingLocationStore,
        digests: DigestStore,
        player: NarrationPlayer? = nil
    ) {
        self.locations = locations
        self.digests = digests
        self.player = player ?? NarrationPlayer(locations: locations)

        // Auto-advance is the whole point: the car plays the flash, then the
        // chapter, then the next one, without anyone touching the phone.
        self.player.onFinished = { [weak self] in
            Task { @MainActor [weak self] in await self?.playNext() }
        }
    }

    // MARK: - Building the journey

    /// Assembles what is listenable for one book, right now, offline.
    ///
    /// Digests come first and shortest-first: three minutes of « what this
    /// chapter is about » is a better start to a drive than dropping straight
    /// into the middle of a paragraph.
    public func buildQueue(
        for book: LibraryBook,
        bookSegments: (@Sendable (DigestScope) async -> [NarrationSegment])?,
        language: String
    ) {
        digests.load(bookID: book.id)

        var items: [DrivingItem] = digests.scripts
            .filter { $0.bookID == book.id }
            .sorted { $0.estimatedMinutes < $1.estimatedMinutes }
            .map { script in
                DrivingItem(
                    id: "digest-\(script.plan.key)",
                    kind: .digest(script.plan),
                    bookID: book.id,
                    title: script.plan.format.label,
                    subtitle: script.plan.angle.label,
                    estimatedMinutes: script.estimatedMinutes,
                    segments: { script.narrationSegments() }
                )
            }

        if let bookSegments {
            items.append(DrivingItem(
                id: "book",
                kind: .book,
                bookID: book.id,
                title: book.title,
                subtitle: book.authorLine.isEmpty ? "Lecture du livre" : book.authorLine,
                language: language,
                segments: { await bookSegments(.fromCurrentPosition) }
            ))
        }

        queue.replace(with: items)
    }

    /// What someone needs to know before leaving: a queue that only holds the
    /// book means no digest was generated, and generating one needs a model.
    public var readiness: Readiness {
        Readiness(
            itemCount: queue.items.count,
            digestCount: queue.items.filter(\.isDigest).count,
            includesBook: queue.items.contains { !$0.isDigest },
            totalMinutes: queue.totalMinutes
        )
    }

    public struct Readiness: Equatable, Sendable {
        public var itemCount: Int
        public var digestCount: Int
        public var includesBook: Bool
        public var totalMinutes: Int

        public var isReady: Bool { itemCount > 0 }

        /// Everything listed is already on the device — the queue is built from
        /// stored digests and the book's own file.
        public var summary: String {
            guard isReady else {
                return "Rien à écouter hors-ligne pour ce livre."
            }
            var parts: [String] = []
            if digestCount > 0 {
                parts.append("\(digestCount) résumé\(digestCount > 1 ? "s" : "")")
            }
            if includesBook { parts.append("le livre") }
            let duration = totalMinutes > 0 ? ", environ \(totalMinutes) min" : ""
            return parts.joined(separator: " et ") + duration + " — tout est sur l'appareil."
        }
    }

    // MARK: - Driving

    public func start() {
        guard !queue.isEmpty else { return }
        isActive = true
        Task { await playCurrent() }
    }

    public func stop() {
        isActive = false
        player.stop()
    }

    public func toggle() {
        if player.isLoaded { player.toggle() } else { start() }
    }

    public func skipForward() {
        guard queue.advance() else {
            stop()
            return
        }
        Task { await playCurrent() }
    }

    public func skipBackward() {
        // Within a long item, going back a sentence is more useful than
        // jumping to the previous track.
        if case .speaking = player.state, !queue.isEmpty {
            player.previous()
            return
        }
        guard queue.retreat() else { return }
        Task { await playCurrent() }
    }

    public func play(_ item: DrivingItem) {
        queue.jump(to: item)
        isActive = true
        Task { await playCurrent() }
    }

    private func playNext() async {
        guard isActive else { return }
        guard queue.advance() else {
            isActive = false
            return
        }
        await playCurrent()
    }

    private func playCurrent() async {
        guard let item = queue.current else { return }
        isPreparing = true
        let segments = await item.segments()
        isPreparing = false
        guard !segments.isEmpty else {
            // An empty item must not stall the journey.
            await playNext()
            return
        }
        player.load(
            segments: segments,
            bookID: item.bookID,
            format: item.positionFormat,
            title: item.title,
            author: item.subtitle,
            language: item.language
        )
        player.play()
    }
}
+112 −0
Changes for Packages/Core/Sources/PodbookUI/Driving/DrivingQueue.swift: 112 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation

/// One thing to listen to on the way.
public struct DrivingItem: Identifiable, Hashable, Sendable {
    public enum Kind: Hashable, Sendable {
        /// A generated digest: short, and the right thing to open a journey with.
        case digest(DigestPlan)
        /// The book itself, continued from wherever reading or listening stopped.
        case book
    }

    public var id: String
    public var kind: Kind
    public var bookID: Int
    public var title: String
    public var subtitle: String
    /// Minutes, when known.
    public var estimatedMinutes: Int?
    /// Segments are resolved lazily: walking a whole EPUB for every queue entry
    /// up front would stall the moment someone just wants to press play.
    public var segments: @Sendable () async -> [NarrationSegment]
    public var language: String

    public init(
        id: String,
        kind: Kind,
        bookID: Int,
        title: String,
        subtitle: String,
        estimatedMinutes: Int? = nil,
        language: String = "fr-FR",
        segments: @escaping @Sendable () async -> [NarrationSegment]
    ) {
        self.id = id
        self.kind = kind
        self.bookID = bookID
        self.title = title
        self.subtitle = subtitle
        self.estimatedMinutes = estimatedMinutes
        self.language = language
        self.segments = segments
    }

    public static func == (lhs: DrivingItem, rhs: DrivingItem) -> Bool { lhs.id == rhs.id }
    public func hash(into hasher: inout Hasher) { hasher.combine(id) }

    /// Digests are read aloud in French; the book keeps its own language.
    public var isDigest: Bool {
        if case .digest = kind { return true }
        return false
    }

    /// Position keys must not collide: a digest's progress is not the book's
    /// reading position, so it gets its own format key.
    public var positionFormat: String {
        switch kind {
        case .digest(let plan): "digest-\(plan.key)"
        case .book: "book"
        }
    }
}

/// The order of the journey, and where we are in it.
///
/// Deliberately a plain value type with no playback in it: the awkward part of
/// a car queue is the bookkeeping — advancing, not running off the end, knowing
/// what is next — and that is worth testing without producing a sound.
public struct DrivingQueue: Sendable, Equatable {
    public private(set) var items: [DrivingItem]
    public private(set) var index: Int

    public init(items: [DrivingItem] = [], index: Int = 0) {
        self.items = items
        self.index = items.isEmpty ? 0 : min(max(index, 0), items.count - 1)
    }

    public var isEmpty: Bool { items.isEmpty }
    public var current: DrivingItem? { items.indices.contains(index) ? items[index] : nil }
    public var next: DrivingItem? { items.indices.contains(index + 1) ? items[index + 1] : nil }
    public var previous: DrivingItem? { index > 0 ? items[index - 1] : nil }
    public var hasNext: Bool { next != nil }

    public var totalMinutes: Int {
        items.compactMap(\.estimatedMinutes).reduce(0, +)
    }

    /// `false` when the queue is finished, which is how the player knows to stop
    /// rather than loop.
    @discardableResult
    public mutating func advance() -> Bool {
        guard hasNext else { return false }
        index += 1
        return true
    }

    @discardableResult
    public mutating func retreat() -> Bool {
        guard previous != nil else { return false }
        index -= 1
        return true
    }

    public mutating func jump(to item: DrivingItem) {
        guard let target = items.firstIndex(of: item) else { return }
        index = target
    }

    public mutating func replace(with items: [DrivingItem]) {
        self.items = items
        index = 0
    }
}
+5 −0
Changes for Packages/Core/Sources/PodbookUI/Narration/NarrationPlayer.swift: 5 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -11,6 +11,9 @@ import Observation
public final class NarrationPlayer {
    public private(set) var state: NarrationState = .idle
    public private(set) var voices: [NarrationVoice] = []
    /// Called when a whole item has been read to the end. The driving queue
    /// hangs its auto-advance on this.
    public var onFinished: (() -> Void)?

    public var rate: Double = 1.0 {
        didSet {
@@ -124,6 +127,8 @@ public final class NarrationPlayer {
        self.state = state
        publishNowPlaying()

        if state == .finished { onFinished?() }

        guard let book, let utterance = state.utterance, let locator = utterance.locator else { return }
        guard locator != lastSavedLocator else { return }
        lastSavedLocator = locator
+155 −0
Changes for Packages/Core/Tests/PodbookUITests/DrivingTests.swift: 155 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import Testing
@testable import PodbookUI

private func item(_ id: String, minutes: Int? = nil, digest: Bool = false) -> DrivingItem {
    DrivingItem(
        id: id,
        kind: digest ? .digest(DigestPlan(format: .flash)) : .book,
        bookID: 42,
        title: id,
        subtitle: "",
        estimatedMinutes: minutes,
        segments: { [] }
    )
}

@Suite("File d'attente du trajet")
struct DrivingQueueTests {
    @Test("Une file vide n'a ni courant ni suivant")
    func empty() {
        let queue = DrivingQueue()
        #expect(queue.isEmpty)
        #expect(queue.current == nil)
        #expect(queue.hasNext == false)
    }

    @Test("On avance jusqu'au bout, puis plus")
    func advancesToTheEnd() {
        var queue = DrivingQueue(items: [item("a"), item("b")])
        #expect(queue.current?.id == "a")

        let movedForward = queue.advance()
        #expect(movedForward)
        #expect(queue.current?.id == "b")

        // Ne pas boucler : la fin du trajet doit arrêter la lecture, pas
        // repartir au début.
        let movedPastEnd = queue.advance()
        #expect(movedPastEnd == false)
        #expect(queue.current?.id == "b")
    }

    @Test("On recule, et pas en dessous du premier")
    func retreats() {
        var queue = DrivingQueue(items: [item("a"), item("b")], index: 1)
        let movedBack = queue.retreat()
        #expect(movedBack)
        #expect(queue.current?.id == "a")
        let movedBeforeStart = queue.retreat()
        #expect(movedBeforeStart == false)
        #expect(queue.current?.id == "a")
    }

    @Test("Un index hors bornes est ramené dans la file")
    func clampsIndex() {
        #expect(DrivingQueue(items: [item("a")], index: 99).current?.id == "a")
        #expect(DrivingQueue(items: [item("a")], index: -5).current?.id == "a")
    }

    @Test("On saute directement à une entrée")
    func jumps() {
        var queue = DrivingQueue(items: [item("a"), item("b"), item("c")])
        queue.jump(to: item("c"))
        #expect(queue.current?.id == "c")

        // Une entrée absente ne doit pas déplacer la file.
        queue.jump(to: item("inconnue"))
        #expect(queue.current?.id == "c")
    }

    @Test("La durée totale additionne ce qui est connu")
    func sumsDuration() {
        let queue = DrivingQueue(items: [item("a", minutes: 3), item("b", minutes: 30), item("c")])
        #expect(queue.totalMinutes == 33)
    }

    @Test("Un résumé et le livre n'écrivent pas la même position")
    func separatePositionKeys() {
        let digest = item("d", digest: true)
        let book = item("b")
        #expect(digest.positionFormat != book.positionFormat)
        #expect(book.positionFormat == "book")
        #expect(digest.positionFormat.hasPrefix("digest-"))
    }
}

@Suite("Pilote du mode voiture")
@MainActor
struct DrivingModeTests {
    private func make() -> DrivingMode {
        let root = FileManager.default.temporaryDirectory
            .appendingPathComponent("podbook-tests-" + UUID().uuidString, isDirectory: true)
        return DrivingMode(
            locations: ReadingLocationStore(root: root),
            digests: DigestStore(root: root)
        )
    }

    private var book: LibraryBook {
        LibraryBook(id: 42, origin: .calibre, title: "Un livre", authors: ["Auteur"])
    }

    @Test("Sans résumé et sans livre, il n'y a rien à écouter")
    func nothingToPlay() {
        let mode = make()
        mode.buildQueue(for: book, bookSegments: nil, language: "en-US")

        #expect(mode.queue.isEmpty)
        #expect(mode.readiness.isReady == false)
        #expect(mode.readiness.summary.contains("Rien à écouter"))
    }

    @Test("Le livre seul suffit à partir")
    func bookOnly() {
        let mode = make()
        mode.buildQueue(for: book, bookSegments: { _ in [] }, language: "en-US")

        #expect(mode.queue.items.count == 1)
        #expect(mode.readiness.isReady)
        #expect(mode.readiness.includesBook)
        #expect(mode.readiness.digestCount == 0)
    }

    @Test("Les résumés passent avant le livre, du plus court au plus long")
    func digestsFirstShortestFirst() {
        let root = FileManager.default.temporaryDirectory
            .appendingPathComponent("podbook-tests-" + UUID().uuidString, isDirectory: true)
        let digests = DigestStore(root: root)
        let long = Array(repeating: "mot", count: 3300).joined(separator: " ")
        let short = Array(repeating: "mot", count: 500).joined(separator: " ")
        digests.save(DigestScript(bookID: 42, plan: DigestPlan(format: .bookInTwenty),
                                  text: long, model: "m"))
        digests.save(DigestScript(bookID: 42, plan: DigestPlan(format: .flash),
                                  text: short, model: "m"))

        let mode = DrivingMode(locations: ReadingLocationStore(root: root), digests: digests)
        mode.buildQueue(for: book, bookSegments: { _ in [] }, language: "en-US")

        // Trois minutes de « de quoi parle ce chapitre » valent mieux, au
        // démarrage, qu'un atterrissage au milieu d'un paragraphe.
        #expect(mode.queue.items.map(\.id) == ["digest-wholeBook-flash-faithful",
                                               "digest-wholeBook-bookInTwenty-faithful",
                                               "book"])
        #expect(mode.readiness.digestCount == 2)
        #expect(mode.readiness.includesBook)
    }

    @Test("Le récapitulatif dit que tout est déjà sur l'appareil")
    func readinessMentionsOffline() {
        let mode = make()
        mode.buildQueue(for: book, bookSegments: { _ in [] }, language: "en-US")
        #expect(mode.readiness.summary.contains("sur l'appareil"),
                "c'est l'information qui compte avant de partir")
    }
}