Commit 7f45c10c authored by Kourser's avatar Kourser
Browse files

feat: mode voiture, détection de l'autoradio et commandes Siri

L'écran du mode voiture fait trois cibles, chacune un tiers de la
hauteur, et rien d'autre n'est cliquable. Pas de liste, pas de petit
texte, pas de geste à découvrir : ce qui est affiché est ce qui joue et
ce qui suit. La cible est la surface, pas le pictogramme.

La détection distingue deux cas, et c'est le point. Un autoradio que le
système identifie comme tel est sans ambiguïté, donc le mode voiture
démarre seul. Un Bluetooth inconnu pourrait tout aussi bien être un
casque sur le canapé, donc il se contente de proposer — avec un bouton
« c'est ma voiture » qui retient l'appareil pour la fois suivante. La
classification est une fonction pure sur des types de port, parce qu'on
ne branche pas une voiture dans un banc de tests.

Siri répond à « reprends mon livre », « chapitre suivant », « reviens en
arrière » et « mets Podbook en pause », sans ouvrir l'application :
ouvrir l'app serait l'exact contraire de ce qu'on veut au volant. Les
intentions vivent dans le paquet, donc testables, et le fournisseur de
phrases dans la cible app, parce qu'il n'est découvert que là.

Deux ajustements de concurrence : la closure qui fournit les segments
capture une `Publication` non-Sendable, donc `DrivingItem` et
`DrivingQueue` ne sont pas Sendable — et il ne faut pas les isoler sur
le main actor non plus, ce qui casserait leurs conformances Equatable et
Hashable.

207 tests au vert.

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

### Ajouté
- Mode voiture : écran à trois cibles plein écran, file qui s'enchaîne seule,
  et récapitulatif de ce qui est disponible hors-ligne avant de partir.
- Un autoradio reconnu comme tel lance le mode voiture seul ; un Bluetooth
  inconnu ne fait que proposer, et peut être désigné comme « ma voiture ».
- Siri : reprendre, chapitre suivant, revenir en arrière, mettre en pause,
  sans ouvrir l'application.
- Expérience de lecture à la manière de Books : pages tournées, thèmes clair,
  sépia et nuit, taille de police par paliers, choix de police dont
  OpenDyslexic, et sous un interrupteur l'interligne, l'alignement, l'espace
+124 −0
Changes for Packages/Core/Sources/PodbookUI/Driving/AudioRoute.swift: 124 added lines, 0 removed lines.
Original line number Diff line number Diff line
import AVFoundation
import Foundation
import Observation

/// Why driving mode might start.
///
/// The distinction matters: a car stereo recognised as such can take over the
/// screen on its own, while a Bluetooth device could just as easily be a pair
/// of headphones on the sofa. Taking over the screen there would be rude, so
/// Bluetooth only ever *offers* — unless the person has said that this
/// particular device is their car.
public enum DrivingTrigger: Equatable, Sendable {
    case none
    /// The system identifies the output as car audio. Unambiguous.
    case carAudio(String?)
    /// A Bluetooth device the person designated as their car.
    case designatedDevice(String)
    /// Some other Bluetooth output: offer, and let them designate it.
    case otherBluetooth(String)

    public var startsAutomatically: Bool {
        switch self {
        case .carAudio, .designatedDevice: true
        case .none, .otherBluetooth: false
        }
    }

    public var deviceName: String? {
        switch self {
        case .none: nil
        case .carAudio(let name): name
        case .designatedDevice(let name), .otherBluetooth(let name): name
        }
    }
}

/// Reads the audio output and decides what it means.
///
/// Kept as a pure function over port-type strings so it can be tested: there is
/// no way to plug a car into a test runner.
public enum AudioRouteClassifier {
    /// Raw values of `AVAudioSession.Port`, spelled out because that is what a
    /// route actually carries.
    public static let carAudioPort = "CarAudio"
    public static let bluetoothPorts: Set<String> = [
        "BluetoothA2DPOutput", "BluetoothHFP", "BluetoothLE",
    ]

    public static func trigger(
        portTypes: [String],
        outputName: String?,
        designatedDeviceName: String?
    ) -> DrivingTrigger {
        if portTypes.contains(carAudioPort) {
            return .carAudio(outputName)
        }
        guard portTypes.contains(where: bluetoothPorts.contains), let outputName else {
            return .none
        }
        if let designatedDeviceName,
           outputName.compare(designatedDeviceName, options: .caseInsensitive) == .orderedSame {
            return .designatedDevice(outputName)
        }
        return .otherBluetooth(outputName)
    }
}

/// Watches the audio output and reports when it looks like a car.
///
/// iOS only: `AVAudioSession` does not exist on macOS, and neither does the
/// commute.
@MainActor
@Observable
public final class DrivingRouteMonitor {
    public private(set) var trigger: DrivingTrigger = .none
    /// Set once the offer has been shown, so a reconnection does not nag.
    public private(set) var hasOfferedForCurrentRoute = false

    private let designatedDeviceName: () -> String?
    private var observer: NSObjectProtocol?

    public init(designatedDeviceName: @escaping () -> String?) {
        self.designatedDeviceName = designatedDeviceName
    }

    public func start() {
        #if canImport(UIKit)
        guard observer == nil else { return }
        refresh()
        observer = NotificationCenter.default.addObserver(
            forName: AVAudioSession.routeChangeNotification,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            MainActor.assumeIsolated { self?.refresh() }
        }
        #endif
    }

    public func stop() {
        if let observer { NotificationCenter.default.removeObserver(observer) }
        observer = nil
    }

    public func acknowledgeOffer() {
        hasOfferedForCurrentRoute = true
    }

    private func refresh() {
        #if canImport(UIKit)
        let outputs = AVAudioSession.sharedInstance().currentRoute.outputs
        let next = AudioRouteClassifier.trigger(
            portTypes: outputs.map(\.portType.rawValue),
            outputName: outputs.first?.portName,
            designatedDeviceName: designatedDeviceName()
        )
        if next != trigger {
            trigger = next
            // A new route deserves a fresh offer; the same one does not.
            hasOfferedForCurrentRoute = false
        }
        #endif
    }
}
+1 −1
Changes for Packages/Core/Sources/PodbookUI/Driving/DrivingMode.swift: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -49,7 +49,7 @@ public final class DrivingMode {
    /// into the middle of a paragraph.
    public func buildQueue(
        for book: LibraryBook,
        bookSegments: (@Sendable (DigestScope) async -> [NarrationSegment])?,
        bookSegments: ((DigestScope) async -> [NarrationSegment])?,
        language: String
    ) {
        digests.load(bookID: book.id)
+171 −0
Changes for Packages/Core/Sources/PodbookUI/Driving/DrivingModeView.swift: 171 added lines, 0 removed lines.
Original line number Diff line number Diff line
import SwiftUI

/// The screen for when the phone is in a cradle and the car is moving.
///
/// Three targets, each a third of the screen, and nothing else tappable. No
/// lists, no small text, no gesture to discover. What is on screen is what is
/// playing and what comes next — everything else is in the way.
public struct DrivingModeView: View {
    let mode: DrivingMode
    let onExit: () -> Void

    @Environment(\.dismiss) private var dismiss

    public init(mode: DrivingMode, onExit: @escaping () -> Void = {}) {
        self.mode = mode
        self.onExit = onExit
    }

    public var body: some View {
        GeometryReader { geometry in
            VStack(spacing: 0) {
                header
                    .frame(height: max(96, geometry.size.height * 0.24))

                HStack(spacing: 2) {
                    control(systemImage: "backward.fill", label: "Précédent") {
                        mode.skipBackward()
                    }
                    control(
                        systemImage: mode.state.isSpeaking ? "pause.fill" : "play.fill",
                        label: mode.state.isSpeaking ? "Pause" : "Lire",
                        isPrimary: true
                    ) {
                        mode.toggle()
                    }
                    control(systemImage: "forward.fill", label: "Suivant") {
                        mode.skipForward()
                    }
                }

                footer
                    .frame(height: 72)
            }
        }
        .background(.black)
        .foregroundStyle(.white)
        .ignoresSafeArea(edges: .bottom)
        #if canImport(UIKit)
        .statusBarHidden()
        .persistentSystemOverlays(.hidden)
        #endif
        .preferredColorScheme(.dark)
    }

    private var header: some View {
        VStack(spacing: 6) {
            if mode.isPreparing {
                ProgressView().controlSize(.large).tint(.white)
            }
            Text(mode.queue.current?.title ?? "Rien en file")
                .font(.title2.weight(.semibold))
                .multilineTextAlignment(.center)
                .lineLimit(2)
            if let subtitle = mode.queue.current?.subtitle, !subtitle.isEmpty {
                Text(subtitle)
                    .font(.headline)
                    .foregroundStyle(.secondary)
                    .lineLimit(1)
            }
        }
        .padding(.horizontal, 24)
        .frame(maxWidth: .infinity)
    }

    /// Each control fills its third: the target is the area, not the glyph.
    private func control(
        systemImage: String,
        label: String,
        isPrimary: Bool = false,
        action: @escaping () -> Void
    ) -> some View {
        Button(action: action) {
            VStack(spacing: 10) {
                Image(systemName: systemImage)
                    .font(.system(size: isPrimary ? 72 : 48, weight: .bold))
                Text(label)
                    .font(.headline)
                    .foregroundStyle(.secondary)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(isPrimary ? Color.white.opacity(0.12) : Color.white.opacity(0.05))
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
        .accessibilityLabel(label)
    }

    private var footer: some View {
        HStack {
            Button {
                mode.stop()
                onExit()
                dismiss()
            } label: {
                Label("Quitter", systemImage: "xmark")
                    .font(.headline)
                    .padding(.horizontal, 20)
                    .padding(.vertical, 12)
                    .background(Color.white.opacity(0.1), in: Capsule())
            }
            .buttonStyle(.plain)

            Spacer()

            if let next = mode.queue.next {
                VStack(alignment: .trailing, spacing: 2) {
                    Text("Ensuite").font(.caption).foregroundStyle(.secondary)
                    Text(next.title).font(.subheadline).lineLimit(1)
                }
            } else {
                Text("Dernier de la file")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
        }
        .padding(.horizontal, 24)
    }
}

/// The banner that offers driving mode when a Bluetooth device shows up.
///
/// An offer rather than a takeover: that Bluetooth output could be headphones.
struct DrivingOfferBanner: View {
    let deviceName: String
    let readiness: DrivingMode.Readiness
    let onAccept: () -> Void
    let onDesignate: () -> Void
    let onDismiss: () -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            HStack {
                Label("Connecté à \(deviceName)", systemImage: "car.fill")
                    .font(.subheadline.weight(.medium))
                Spacer()
                Button {
                    onDismiss()
                } label: {
                    Image(systemName: "xmark").font(.caption)
                }
                .buttonStyle(.plain)
                .foregroundStyle(.secondary)
            }

            Text(readiness.summary)
                .font(.footnote)
                .foregroundStyle(.secondary)

            HStack {
                Button("Mode voiture", action: onAccept)
                    .buttonStyle(.borderedProminent)
                    .disabled(!readiness.isReady)
                Button("C'est ma voiture", action: onDesignate)
                    .buttonStyle(.bordered)
            }
        }
        .padding(14)
        .background(.bar, in: RoundedRectangle(cornerRadius: 12))
        .padding(.horizontal)
    }
}
+5 −5
Changes for Packages/Core/Sources/PodbookUI/Driving/DrivingQueue.swift: 5 added lines, 5 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 {
public struct DrivingItem: Identifiable, Hashable {
    public enum Kind: Hashable {
        /// 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.
@@ -18,7 +18,7 @@ public struct DrivingItem: Identifiable, Hashable, Sendable {
    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 segments: () async -> [NarrationSegment]
    public var language: String

    public init(
@@ -29,7 +29,7 @@ public struct DrivingItem: Identifiable, Hashable, Sendable {
        subtitle: String,
        estimatedMinutes: Int? = nil,
        language: String = "fr-FR",
        segments: @escaping @Sendable () async -> [NarrationSegment]
        segments: @escaping () async -> [NarrationSegment]
    ) {
        self.id = id
        self.kind = kind
@@ -65,7 +65,7 @@ public struct DrivingItem: Identifiable, Hashable, Sendable {
/// 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 struct DrivingQueue: Equatable {
    public private(set) var items: [DrivingItem]
    public private(set) var index: Int

Loading