SPB Git

Repository Public

NowPlayingView.swift 17.0 KB 283 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/NowPlaying/NowPlayingView.swift3// Description: Immersive Now Playing view with queue, synchronised lyrics and technical details.4import SwiftUI5import SPMusicCore67/// The immersive view: large cover over a backdrop drawn from it, transport, and a side panel for the queue, the8/// lyrics or the technical details of what is really playing.9struct NowPlayingView: View {10    @Environment(AppModel.self) private var model11    @AppStorage("nowPlayingPanel") private var panel = "queue"1213    var body: some View {14        let p = model.playback15        ZStack {16            backdrop(p.currentTrack)17            HStack(spacing: 0) {18                VStack(spacing: 18) {19                    Spacer(minLength: 10)20                    GeometryReader { geo in21                        let side = min(geo.size.width, geo.size.height, 520)22                        ArtworkView(artworkID: p.currentTrack?.artworkID, size: side, cornerRadius: 14, externalKey: p.currentTrack?.externalFileURL != nil ? p.currentTrack?.id : nil)23                            .shadow(color: .black.opacity(0.45), radius: 30, y: 16)24                            .scaleEffect(p.isPlaying ? 1 : 0.94).animation(.spring(duration: 0.5), value: p.isPlaying)25                            .frame(maxWidth: .infinity, maxHeight: .infinity)26                    }27                    .frame(minHeight: 200)28                    VStack(spacing: 4) {29                        Text(p.currentTrack?.title ?? "").font(.system(size: 24, weight: .bold)).lineLimit(2).multilineTextAlignment(.center)30                        if let t = p.currentTrack {31                            HStack(spacing: 5) {32                                Button(t.artistName) { if t.externalFileURL == nil { model.show(.artist(t.artistID)) } }.buttonStyle(.plain)33                                if !t.albumTitle.isEmpty { Text("—"); Button(t.albumTitle) { if t.externalFileURL == nil { model.show(.album(t.albumID)) } }.buttonStyle(.plain) }34                            }35                            .font(.title3).foregroundStyle(.white.opacity(0.75)).lineLimit(1)36                        }37                    }38                    VStack(spacing: 4) {39                        SeekBar(height: 5)40                        HStack {41                            Text(Format.duration(seconds: p.position)); Spacer()42                            HStack(spacing: 8) { QualityLabel(); SourceLabel() }43                            Spacer(); Text("-" + Format.duration(seconds: max(0, p.duration - p.position)))44                        }45                        .font(.caption.monospacedDigit()).foregroundStyle(.white.opacity(0.7))46                    }47                    .frame(maxWidth: 520)48                    TransportButtons(large: true)49                    HStack(spacing: 18) {50                        if let t = p.currentTrack, t.externalFileURL == nil { CurrentDownloadButton(trackID: t.id) }51                        VolumeSlider(width: 160)52                    }53                    if let m = p.message { Text(m).font(.callout).foregroundStyle(.orange) }54                    Spacer(minLength: 10)55                }56                .padding(.horizontal, 40).padding(.top, 36).padding(.bottom, 24).frame(maxWidth: .infinity)5758                VStack(spacing: 0) {59                    Picker("", selection: $panel) { Text("File d’attente").tag("queue"); Text("Paroles").tag("lyrics"); Text("Audio").tag("info") }60                        .pickerStyle(.segmented).labelsHidden().padding(.horizontal, 12).padding(.top, 34).padding(.bottom, 10)61                    Group {62                        switch panel {63                        case "lyrics": LyricsView()64                        case "info": TechnicalInfoView()65                        default: QueueView(embedded: true)66                        }67                    }68                    .frame(maxWidth: .infinity, maxHeight: .infinity)69                }70                .frame(width: 380)71                .background(.ultraThinMaterial)72            }73            .environment(\.colorScheme, .dark)74        }75        .ignoresSafeArea()76        .overlay(alignment: .topLeading) {77            Button { withAnimation(.spring(duration: 0.35)) { model.showNowPlaying = false } } label: { Image(systemName: "chevron.down").font(.system(size: 15, weight: .semibold)).padding(9).background(.ultraThinMaterial, in: Circle()) }78                .buttonStyle(.plain).padding(.leading, 16).padding(.top, 40).keyboardShortcut(.cancelAction).help("Fermer").accessibilityLabel("Fermer la lecture en cours")79        }80        .foregroundStyle(.white)81    }8283    @ViewBuilder private func backdrop(_ track: Track?) -> some View {84        ZStack {85            Color.black86            // The cover itself, enlarged and blurred: the view takes the colours of what is playing.87            ArtworkView(artworkID: track?.artworkID, size: 900, cornerRadius: 0, externalKey: track?.externalFileURL != nil ? track?.id : nil)88                .scaledToFill().blur(radius: 90).saturation(1.4).opacity(0.75)89                .frame(maxWidth: .infinity, maxHeight: .infinity).clipped()90            LinearGradient(colors: [.black.opacity(0.15), .black.opacity(0.55)], startPoint: .top, endPoint: .bottom)91        }92        .ignoresSafeArea()93        .animation(.easeInOut(duration: 0.8), value: track?.artworkID)94    }95}9697struct QueueView: View {98    @Environment(AppModel.self) private var model99    var embedded = false100101    var body: some View {102        let p = model.playback103        VStack(spacing: 0) {104            if !embedded {105                HStack { Text("File d’attente").font(.headline); Spacer(); Button("Vider la suite") { p.clearUpcoming() }.controlSize(.small).disabled(p.queue.upcoming.isEmpty) }.padding(12)106                Divider()107            }108            if p.queue.isEmpty {109                EmptyState(symbol: "list.bullet", title: "File d’attente vide", message: "Lancez un album ou une liste : ce qui suit apparaît ici.")110            } else {111                ScrollViewReader { proxy in112                    List {113                        ForEach(Array(p.queue.items.enumerated()), id: \.element.id) { i, item in114                            HStack(spacing: 9) {115                                ArtworkView(artworkID: item.track.artworkID, size: 34, cornerRadius: 4, externalKey: item.track.externalFileURL != nil ? item.track.id : nil)116                                VStack(alignment: .leading, spacing: 1) {117                                    Text(item.track.title).lineLimit(1).foregroundStyle(i == p.queue.index ? Color.accentColor : .primary)118                                    Text(item.track.artistName).font(.caption).foregroundStyle(.secondary).lineLimit(1)119                                }120                                Spacer(minLength: 4)121                                if i == p.queue.index { Image(systemName: p.isPlaying ? "speaker.wave.2.fill" : "speaker.fill").font(.caption).foregroundStyle(Color.accentColor) }122                                else if !model.isOnline, !(model.session?.isAvailableOffline(item.track) ?? false) { Image(systemName: "icloud.slash").font(.caption).foregroundStyle(.tertiary).help("Non téléchargé : sera passé hors ligne") }123                                Text(Format.duration(ms: item.track.durationMs)).font(.caption.monospacedDigit()).foregroundStyle(.secondary)124                            }125                            .opacity(i < p.queue.index ? 0.45 : 1)126                            .contentShape(Rectangle())127                            .onTapGesture(count: 2) { p.jump(to: item.id) }128                            .contextMenu {129                                Button("Lire maintenant") { p.jump(to: item.id) }130                                if i != p.queue.index { Button("Retirer de la file", role: .destructive) { p.removeFromQueue(item.id) } }131                            }132                            .id(item.id).listRowBackground(Color.clear)133                        }134                        .onMove { from, to in if let f = from.first { p.moveInQueue(from: f, to: to) } }135                    }136                    .listStyle(.plain).scrollContentBackground(.hidden)137                    .onAppear { if let c = p.queue.current { proxy.scrollTo(c.id, anchor: .center) } }138                    .onChange(of: p.queue.current?.id) { if let c = p.queue.current { withAnimation { proxy.scrollTo(c.id, anchor: .center) } } }139                }140                if embedded {141                    Divider()142                    HStack { Text("\(max(0, p.queue.items.count - p.queue.index - 1)) à suivre").font(.caption).foregroundStyle(.secondary); Spacer(); Button("Vider la suite") { p.clearUpcoming() }.controlSize(.small).disabled(p.queue.upcoming.isEmpty) }.padding(10)143                }144            }145        }146    }147}148149/// Synchronised lyrics (generated on the cluster from the track's own audio, or typed by an administrator). The150/// current line is highlighted from the player's clock; a click on a line seeks to it. Cached for offline use.151struct LyricsView: View {152    @Environment(AppModel.self) private var model153    @State private var lyrics: Lyrics?154    @State private var loading = false155156    var body: some View {157        let p = model.playback158        Group {159            if loading { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }160            else if let lyrics, lyrics.state == "ready", !lyrics.lines.isEmpty {161                let ms = Int(p.position * 1000)162                let current = lyrics.lines.lastIndex { $0.t <= ms + 150 }163                ScrollViewReader { proxy in164                    ScrollView {165                        VStack(alignment: .leading, spacing: 12) {166                            ForEach(Array(lyrics.lines.enumerated()), id: \.offset) { i, line in167                                Text(line.text).font(.system(size: 19, weight: .semibold)).fixedSize(horizontal: false, vertical: true)168                                    .foregroundStyle(i == current ? .white : .white.opacity(i < (current ?? -1) ? 0.35 : 0.55))169                                    .scaleEffect(i == current ? 1.03 : 1, anchor: .leading).animation(.easeOut(duration: 0.25), value: current)170                                    .contentShape(Rectangle()).onTapGesture { p.seek(to: Double(line.t) / 1000) }171                                    .id(i)172                            }173                        }174                        .padding(18).frame(maxWidth: .infinity, alignment: .leading)175                    }176                    .onChange(of: current) { if let current { withAnimation(.easeInOut(duration: 0.4)) { proxy.scrollTo(current, anchor: .center) } } }177                }178            } else {179                EmptyState(symbol: "quote.bubble", title: message.0, message: message.1)180            }181        }182        .task(id: p.currentTrack?.id) {183            guard let t = p.currentTrack, let s = model.session else { lyrics = nil; return }184            loading = lyrics == nil185            lyrics = await s.lyrics(for: t)186            loading = false187        }188    }189190    private var message: (String, String) {191        switch lyrics?.state {192        case "empty": ("Instrumental", "Aucune parole n’a été trouvée dans ce titre.")193        case "queued", "working": ("Paroles en préparation", "Le cluster transcrit ce titre ; revenez dans un instant.")194        case "error": ("Paroles indisponibles", "La transcription a échoué sur le cluster.")195        default: ("Pas de paroles", model.isOnline ? "Ce titre n’a pas de paroles sur le cluster." : "Les paroles de ce titre n’ont pas été mises en cache avant de passer hors ligne.")196        }197    }198}199200/// What is actually happening to the sound, stated without embellishment.201struct TechnicalInfoView: View {202    @Environment(AppModel.self) private var model203204    var body: some View {205        let p = model.playback206        ScrollView {207            VStack(alignment: .leading, spacing: 16) {208                if let t = p.currentTrack {209                    group("Fichier") {210                        row("Format", Format.codecName(t.codec, container: t.container) + (p.isRendition ? " (lu via un rendu AAC du cluster)" : ""))211                        if let i = p.info {212                            row("Fréquence d’échantillonnage", Format.sampleRate(Int(i.sampleRate)))213                            row("Profondeur", i.bitDepth.map { "\($0) bits" } ?? "sans objet (codec avec perte)")214                            row("Canaux", i.channels == 1 ? "Mono" : i.channels == 2 ? "Stéréo" : "\(i.channels) canaux")215                        } else if let r = t.sampleRate { row("Fréquence d’échantillonnage", Format.sampleRate(r)) }216                        if let b = t.bitrate, b > 0 { row("Débit", "\(Int((Double(b) / 1000).rounded())) kb/s") }217                        if t.sizeBytes > 0 { row("Taille", Format.bytes(t.sizeBytes)) }218                    }219                    group("Source") {220                        row("Provenance", sourceText(p.sourceKind))221                        if p.sourceKind == .stream { row("Reçu", "\(Int(p.bufferedFraction * 100)) %") }222                        if let u = model.session?.storage.localFile(for: t) { row("Emplacement", u.path.replacingOccurrences(of: NSHomeDirectory(), with: "~")) }223                    }224                    group("Sortie") {225                        row("Périphérique", model.currentOutput?.name ?? "Sortie du système")226                        if let d = model.currentOutput, !d.transport.isEmpty { row("Connexion", d.transport) }227                        row("Fréquence du périphérique", p.outputSampleRate > 0 ? Format.sampleRate(Int(p.outputSampleRate)) : "—")228                        if let i = p.info, p.outputSampleRate > 0 {229                            row("Conversion de fréquence", i.sampleRate == p.outputSampleRate ? "aucune" : "\(Format.sampleRate(Int(i.sampleRate))) → \(Format.sampleRate(Int(p.outputSampleRate)))")230                        }231                    }232                    group("Traitement") {233                        row("Égaliseur", p.settings.eqEnabled && !p.settings.directMode ? "activé" : "désactivé")234                        row("Normalisation du volume", model.settings.normalize && !p.settings.directMode ? "activée" : "désactivée")235                        row("Fondu enchaîné", p.settings.crossfade > 0 && !p.settings.directMode ? "\(Int(p.settings.crossfade)) s" : "aucun (enchaînement sans blanc)")236                        row("Volume de l’app", "\(Int(model.settings.volume * 100)) %")237                    }238                    Text(pathSummary(p)).font(.caption).foregroundStyle(.white.opacity(0.6)).fixedSize(horizontal: false, vertical: true)239                } else {240                    EmptyState(symbol: "waveform", title: "Rien en lecture")241                }242            }243            .padding(16).frame(maxWidth: .infinity, alignment: .leading)244        }245    }246247    private func sourceText(_ k: SourceKind?) -> String {248        switch k {249        case .local: "Fichier téléchargé sur ce Mac"250        case .cache: "Copie complète en cache sur ce Mac"251        case .stream: "Cluster MacLustr (lecture en continu)"252        case .file: "Fichier ouvert depuis le disque"253        case nil: "—"254        }255    }256257    /// An honest account of the signal path. The word "bit-perfect" is never used: the samples go through Core258    /// Audio's mixer in 32-bit float, and what the device finally receives is not something the app can verify.259    private func pathSummary(_ p: PlaybackController) -> String {260        guard let i = p.info, p.outputSampleRate > 0 else { return "" }261        var parts: [String] = []262        parts.append(Format.isLossless(p.currentTrack!) && !p.isRendition ? "Décodage sans perte du fichier original." : "Décodage d’un format compressé avec perte.")263        if p.settings.directMode { parts.append("Mode direct : ni égaliseur, ni normalisation, ni fondu.") }264        parts.append(i.sampleRate == p.outputSampleRate ? "Pas de conversion de fréquence entre le fichier et le périphérique." : "La fréquence est convertie par Core Audio pour correspondre au périphérique (activez « Adapter la fréquence du périphérique » dans les réglages audio pour l’éviter quand le périphérique le permet).")265        parts.append("Le mixage se fait en virgule flottante 32 bits ; le volume de l’app à 100 % n’atténue rien. Ce que le périphérique reçoit ensuite dépend de macOS et du matériel : l’app ne peut pas le vérifier et n’annonce donc pas de lecture « bit-perfect ».")266        return parts.joined(separator: " ")267    }268269    private func group<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {270        VStack(alignment: .leading, spacing: 6) {271            Text(title.uppercased()).font(.caption2.weight(.bold)).foregroundStyle(.white.opacity(0.5))272            VStack(spacing: 5) { content() }273        }274    }275    private func row(_ k: String, _ v: String) -> some View {276        HStack(alignment: .firstTextBaseline) {277            Text(k).foregroundStyle(.white.opacity(0.65)); Spacer(minLength: 12)278            Text(v).multilineTextAlignment(.trailing).textSelection(.enabled)279        }280        .font(.callout)281    }282}283
Files main
Menu

Theme