Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Settings/SettingsView.swift3// Description: Settings: audio, downloads, storage, shortcuts, account.4import SwiftUI5import SPMusicCore67struct SettingsView: View {8 var body: some View {9 TabView {10 AudioSettings().tabItem { Label("Audio", systemImage: "hifispeaker") }11 DownloadSettings().tabItem { Label("Téléchargements", systemImage: "arrow.down.circle") }12 StorageSettings().tabItem { Label("Stockage", systemImage: "internaldrive") }13 ShortcutSettings().tabItem { Label("Raccourcis", systemImage: "keyboard") }14 AccountSettings().tabItem { Label("Compte", systemImage: "person.crop.circle") }15 }16 .frame(width: 640, height: 520)17 }18}1920struct AudioSettings: View {21 @Environment(AppModel.self) private var model22 var body: some View {23 @Bindable var s = model.settings24 Form {25 Section("Sortie") {26 Picker("Périphérique", selection: Binding(get: { s.outputDeviceUID }, set: { model.selectOutput(uid: $0) })) {27 Text("Sortie du système" + (model.outputDevices.first { $0.isDefault }.map { " (\($0.name))" } ?? "")).tag("")28 Divider()29 ForEach(model.outputDevices) { d in Text(d.name + (d.transport.isEmpty ? "" : " — \(d.transport)")).tag(d.uid) }30 }31 if let d = model.currentOutput {32 LabeledContent("Fréquence actuelle", value: Format.sampleRate(Int(d.sampleRate)))33 LabeledContent("Fréquences offertes", value: d.availableSampleRates.isEmpty ? "—" : d.availableSampleRates.map { Format.sampleRate(Int($0)) }.joined(separator: ", "))34 }35 Toggle("Adapter la fréquence du périphérique à celle du titre", isOn: $s.matchSampleRate)36 Text("Quand le périphérique l’offre, sa fréquence est réglée sur celle du fichier (44,1 kHz, 96 kHz…), ce qui évite la conversion par macOS. Le réglage vaut pour tout le Mac tant que le titre joue.").font(.caption).foregroundStyle(.secondary)37 }38 Section("Fidélité") {39 Toggle("Mode direct (aucun traitement)", isOn: $s.directMode)40 Text("Désactive l’égaliseur, la normalisation et le fondu : les échantillons décodés vont au mélangeur de Core Audio tels quels. Les fichiers ne sont jamais transcodés. L’app n’annonce pas de lecture « bit-perfect » : ce que reçoit le périphérique dépend aussi de macOS.").font(.caption).foregroundStyle(.secondary)41 Toggle("Normaliser le volume entre les titres", isOn: $s.normalize).disabled(s.directMode)42 Text("Niveau mesuré selon ITU-R BS.1770 sur les fichiers téléchargés, cible −14 LUFS, sans jamais dépasser la crête du titre. Un titre pas encore mesuré joue à son niveau d’origine.").font(.caption).foregroundStyle(.secondary)43 }44 Section("Enchaînement") {45 LabeledContent("Fondu enchaîné") {46 HStack { Slider(value: $s.crossfade, in: 0...12, step: 1).frame(width: 220); Text(s.crossfade == 0 ? "aucun" : "\(Int(s.crossfade)) s").monospacedDigit().frame(width: 50, alignment: .trailing) }47 }48 .disabled(s.directMode)49 Text("Sans fondu, chaque titre démarre sur l’échantillon exact où le précédent se termine (albums live, enchaînés). Les MP3 gardent le court silence propre à leur encodage.").font(.caption).foregroundStyle(.secondary)50 }51 Section("Égaliseur") {52 Toggle("Activer l’égaliseur", isOn: $s.eqEnabled).disabled(s.directMode)53 HStack(alignment: .bottom, spacing: 10) {54 eqSlider("Préampli", $s.preamp)55 Divider().frame(height: 110)56 ForEach(0..<10, id: \.self) { i in57 eqSlider(label(EngineSettings.eqFrequencies[i]), Binding(get: { s.eqGains[i] }, set: { s.eqGains[i] = $0 }))58 }59 }60 .disabled(!s.eqEnabled || s.directMode).opacity(s.eqEnabled && !s.directMode ? 1 : 0.45)61 HStack {62 Text("Préréglages").foregroundStyle(.secondary)63 ForEach(AppSettings.eqPresets, id: \.name) { p in Button(p.name) { s.eqGains = p.gains; s.preamp = p.name == "Plat" ? 0 : -3 }.controlSize(.small) }64 }65 .disabled(!s.eqEnabled || s.directMode)66 }67 }68 .formStyle(.grouped)69 .onChange(of: s.eqEnabled) { model.applyAudioSettings() }.onChange(of: s.eqGains) { model.applyAudioSettings() }.onChange(of: s.preamp) { model.applyAudioSettings() }70 .onChange(of: s.crossfade) { model.applyAudioSettings() }.onChange(of: s.directMode) { model.applyAudioSettings() }71 .onChange(of: s.normalize) { if s.normalize, let session = model.session { Task.detached(priority: .background) { await session.analyzeLoudness(limit: 500) } } }72 .onAppear { model.outputDevices = AudioOutputManager.outputDevices() }73 }7475 private func label(_ hz: Float) -> String { hz >= 1000 ? "\(Int(hz / 1000)) k" : "\(Int(hz))" }76 private func eqSlider(_ title: String, _ value: Binding<Double>) -> some View {77 VStack(spacing: 4) {78 Text(String(format: "%+.0f", value.wrappedValue)).font(.system(size: 9).monospacedDigit()).foregroundStyle(.secondary)79 VerticalSlider(value: value, range: -12...12).frame(width: 22, height: 96)80 Text(title).font(.system(size: 9)).foregroundStyle(.secondary).lineLimit(1).fixedSize()81 }82 .accessibilityElement(children: .ignore).accessibilityLabel("Bande \(title)").accessibilityValue("\(Int(value.wrappedValue)) décibels")83 .accessibilityAdjustableAction { d in value.wrappedValue = max(-12, min(12, value.wrappedValue + (d == .increment ? 1 : -1))) }84 }85}8687struct VerticalSlider: View {88 @Binding var value: Double89 let range: ClosedRange<Double>90 var body: some View {91 GeometryReader { geo in92 let h = geo.size.height93 let frac = (value - range.lowerBound) / (range.upperBound - range.lowerBound)94 ZStack(alignment: .bottom) {95 Capsule().fill(.quaternary).frame(width: 4)96 Capsule().fill(Color.accentColor.opacity(0.8)).frame(width: 4, height: max(0, h * frac))97 Circle().fill(.white).shadow(radius: 1, y: 0.5).frame(width: 13, height: 13).offset(y: -(h - 13) * frac)98 }99 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)100 .contentShape(Rectangle())101 .gesture(DragGesture(minimumDistance: 0).onChanged { g in102 let f = 1 - max(0, min(1, g.location.y / h))103 let v = range.lowerBound + f * (range.upperBound - range.lowerBound)104 value = abs(v) < 0.6 ? 0 : (v * 2).rounded() / 2 // snaps to zero, steps of 0.5 dB105 })106 .onTapGesture(count: 2) { value = 0 }107 }108 }109}110111struct DownloadSettings: View {112 @Environment(AppModel.self) private var model113 var body: some View {114 @Bindable var s = model.settings115 Form {116 Section("Téléchargements") {117 Picker("Téléchargements simultanés", selection: Binding(get: { s.maxConcurrentDownloads }, set: { model.setMaxConcurrentDownloads($0) })) {118 ForEach(1...8, id: \.self) { Text("\($0)").tag($0) }119 }120 Toggle("Prévenir quand un lot de téléchargements est terminé", isOn: $s.notifyDownloads)121 Text("Chaque fichier est l’original du cluster, vérifié par son empreinte SHA-256 avant d’être rangé. Un téléchargement interrompu (réseau, fermeture de l’app) reprend à l’octet où il s’est arrêté.").font(.caption).foregroundStyle(.secondary)122 }123 Section("Connexion") {124 Toggle("Mode hors ligne", isOn: Binding(get: { s.forcedOffline }, set: { model.setForcedOffline($0) }))125 Text("En mode hors ligne, l’app n’envoie aucune requête : seule la musique téléchargée est lue, et vos modifications sont envoyées plus tard.").font(.caption).foregroundStyle(.secondary)126 Toggle("N’afficher que la musique téléchargée", isOn: $s.downloadedOnly)127 }128 Section("Lecture en continu") {129 LabeledContent("Taille maximale du cache") {130 HStack { Slider(value: $s.streamCacheLimitGB, in: 0.5...20, step: 0.5).frame(width: 200); Text(String(format: "%.1f Go", s.streamCacheLimitGB)).monospacedDigit().frame(width: 60, alignment: .trailing) }131 }132 Text("Les titres écoutés en continu sont gardés un moment sur ce Mac : les réécouter ou les télécharger ensuite ne refait pas le transfert.").font(.caption).foregroundStyle(.secondary)133 }134 }135 .formStyle(.grouped)136 }137}138139struct StorageSettings: View {140 @Environment(AppModel.self) private var model141 @State private var usage: StorageUsage?142 @State private var stats = LibraryStats()143 @State private var confirmClearCache = false144145 var body: some View {146 Form {147 if let u = usage {148 Section("Bibliothèque sur ce Mac") {149 LabeledContent("Emplacement") {150 HStack {151 Text(u.libraryRoot.path.replacingOccurrences(of: NSHomeDirectory(), with: "~")).lineLimit(1).truncationMode(.middle).textSelection(.enabled)152 Button("Afficher") { NSWorkspace.shared.open(u.libraryRoot) }.controlSize(.small).disabled(!u.rootAvailable)153 }154 }155 if !u.rootAvailable { Label("Ce dossier est introuvable (disque externe débranché ?). Rien n’a été supprimé : rebranchez le disque.", systemImage: "exclamationmark.triangle.fill").foregroundStyle(.orange) }156 LabeledContent("Titres téléchargés", value: "\(stats.downloadedTracks) (\(stats.downloadedAlbums) albums)")157 LabeledContent("Espace utilisé", value: Format.bytes(u.downloadedBytes))158 if u.partialBytes > 0 { LabeledContent("Téléchargements en cours", value: Format.bytes(u.partialBytes)) }159 LabeledContent("Espace libre", value: Format.bytes(u.freeBytes) + (u.volumeName.isEmpty ? "" : " sur « \(u.volumeName) »"))160 HStack {161 Button("Changer de dossier…") { chooseFolder() }.disabled(model.moveProgress != nil || !u.rootAvailable)162 if let p = model.moveProgress { ProgressView(value: p).frame(width: 160); Text("Déplacement… \(Int(p * 100)) %").font(.caption).foregroundStyle(.secondary) }163 }164 Text("Les fichiers sont déplacés vers le nouveau dossier (un disque externe convient), vérifiés, puis retirés de l’ancien. Ce sont des fichiers audio ordinaires, rangés par artiste et par album : n’importe quel lecteur peut les ouvrir.").font(.caption).foregroundStyle(.secondary)165 }166 Section("Caches") {167 LabeledContent("Cache de lecture en continu") { HStack { Text(Format.bytes(u.streamCacheBytes)); Button("Vider") { confirmClearCache = true }.controlSize(.small).disabled(u.streamCacheBytes == 0) } }168 LabeledContent("Pochettes") { HStack { Text(Format.bytes(u.artworkBytes)); Button("Vider") { model.session?.storage.clearArtworkCache(); refresh() }.controlSize(.small).disabled(u.artworkBytes == 0 || !model.isOnline) } }169 Text("Vider un cache ne supprime aucun téléchargement. Les pochettes sont récupérées de nouveau à la prochaine synchronisation (indisponible hors ligne, pour ne pas les perdre).").font(.caption).foregroundStyle(.secondary)170 }171 Section("Sur le cluster") {172 LabeledContent("Bibliothèque complète", value: "\(stats.tracks) titres · \(Format.bytes(stats.totalBytes))")173 }174 } else { Text("Connectez-vous pour gérer le stockage.").foregroundStyle(.secondary) }175 }176 .formStyle(.grouped)177 .task(id: "\(model.libraryRevision)-\(model.moveProgress == nil)") { refresh() }178 .confirmationDialog("Vider le cache de lecture en continu ?", isPresented: $confirmClearCache) {179 Button("Vider le cache", role: .destructive) { model.playback.stop(); model.session?.storage.clearStreamCache(); refresh() }180 } message: { Text("La lecture en cours s’arrête. Les téléchargements ne sont pas touchés.") }181 }182183 private func refresh() {184 guard let s = model.session else { usage = nil; return }185 Task { stats = await s.store.stats(); usage = s.storage.usage(downloadedBytes: stats.downloadedBytes) }186 }187 private func chooseFolder() {188 let panel = NSOpenPanel()189 panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true; panel.allowsMultipleSelection = false190 panel.prompt = "Déplacer ici"; panel.message = "Choisissez un dossier vide pour la bibliothèque SP Music (un disque externe convient)."191 guard panel.runModal() == .OK, let url = panel.url else { return }192 // A folder of its own inside the chosen place, so nothing of the listener's is ever mixed with the library.193 let target = ((try? FileManager.default.contentsOfDirectory(atPath: url.path)) ?? []).filter { $0 != ".DS_Store" }.isEmpty ? url : url.appendingPathComponent("SP Music", isDirectory: true)194 Task { await model.moveLibrary(to: target); refresh() }195 }196}197198struct ShortcutSettings: View {199 @Environment(AppModel.self) private var model200 @State private var recording: AppCommand?201 @State private var monitor: Any?202203 var body: some View {204 Form {205 Section {206 ForEach(AppCommand.allCases) { c in207 LabeledContent(c.title) {208 HStack(spacing: 6) {209 Button(recording == c ? "Tapez le raccourci…" : model.settings.shortcut(c).display) { record(c) }210 .frame(minWidth: 130).foregroundStyle(recording == c ? Color.accentColor : .primary)211 Button { model.settings.setShortcut(c, nil) } label: { Image(systemName: "arrow.uturn.backward") }.buttonStyle(.borderless)212 .disabled(model.settings.shortcuts[c.rawValue] == nil).help("Rétablir le raccourci d’origine")213 }214 }215 }216 } footer: {217 Text("Cliquez sur un raccourci puis tapez la nouvelle combinaison (Échap pour annuler). Les touches multimédias du clavier, des AirPods et du centre de contrôle fonctionnent toujours, sans réglage.").font(.caption).foregroundStyle(.secondary)218 }219 }220 .formStyle(.grouped)221 .onDisappear { stop() }222 }223224 private func stop() { if let monitor { NSEvent.removeMonitor(monitor) }; monitor = nil; recording = nil }225 private func record(_ c: AppCommand) {226 stop(); recording = c227 monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in228 defer { stop() }229 if event.keyCode == 53 { return nil } // Escape230 let named: [UInt16: String] = [49: "space", 123: "left", 124: "right", 125: "down", 126: "up", 36: "return"]231 guard let key = named[event.keyCode] ?? event.charactersIgnoringModifiers?.lowercased().first.map(String.init), !key.isEmpty else { return nil }232 let m = event.modifierFlags233 let spec = ShortcutSpec(key: key, command: m.contains(.command), shift: m.contains(.shift), option: m.contains(.option), control: m.contains(.control))234 // A bare letter would hijack typing in the search field: letters need at least one modifier.235 if named[event.keyCode] == nil, !(spec.command || spec.option || spec.control) { NSSound.beep(); return nil }236 if let clash = AppCommand.allCases.first(where: { $0 != c && model.settings.shortcut($0) == spec }) { model.toast("Ce raccourci est déjà utilisé par « \(clash.title) ».", error: true); return nil }237 model.settings.setShortcut(c, spec)238 return nil239 }240 }241}242243struct AccountSettings: View {244 @Environment(AppModel.self) private var model245 @State private var confirmSignOut = false246 @State private var sessions: [SessionRow] = []247 struct SessionRow: Decodable, Identifiable { var id: String; var method: String; var userAgent: String; var lastSeenAt: Date; var current: Bool }248249 var body: some View {250 Form {251 if let a = model.account {252 Section("Compte") {253 LabeledContent("Nom", value: a.displayName)254 LabeledContent("Courriel", value: a.email)255 LabeledContent("Rôle", value: a.isOwner ? "Propriétaire" : a.isAdmin ? "Administrateur" : "Auditeur")256 LabeledContent("Serveur", value: model.settings.serverURL.absoluteString)257 LabeledContent("État", value: model.sessionExpired ? "Session expirée" : model.isOnline ? "Connecté" : "Hors ligne")258 if model.sessionExpired {259 HStack {260 Button("Se reconnecter avec une clé d’accès") { Task { await model.signInWithPasskey() } }261 Button("Associer avec le navigateur") { Task { await model.beginDeviceLink() } }262 }263 if let link = model.deviceLink { Text("Code à approuver dans le navigateur : \(link.userCode)").font(.callout.monospaced()) }264 if let e = model.signInError { Text(e).font(.caption).foregroundStyle(.orange) }265 }266 }267 if !sessions.isEmpty {268 Section("Sessions ouvertes sur ce compte") {269 ForEach(sessions) { s in270 LabeledContent(describe(s)) { Text(s.current ? "cette session" : s.lastSeenAt.formatted(date: .abbreviated, time: .shortened)).foregroundStyle(.secondary) }271 }272 Text("Les sessions se ferment depuis « Compte » sur le site.").font(.caption).foregroundStyle(.secondary)273 }274 }275 Section {276 Button("Se déconnecter…", role: .destructive) { confirmSignOut = true }277 Text("La session de ce Mac est fermée sur le cluster et effacée du trousseau. La musique téléchargée reste sur le disque et redevient disponible en vous reconnectant avec le même compte.").font(.caption).foregroundStyle(.secondary)278 }279 } else { Text("Non connecté.").foregroundStyle(.secondary) }280 Section("À propos") {281 LabeledContent("SP Music", value: "version \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "?") (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "?"))")282 Text("Application native (Swift, SwiftUI, AVAudioEngine). Aucune donnée d’écoute n’est transmise à un tiers : l’app ne parle qu’à votre cluster.").font(.caption).foregroundStyle(.secondary)283 }284 }285 .formStyle(.grouped)286 .task(id: model.isOnline) {287 struct Page: Decodable { var items: [SessionRow] }288 if model.isOnline, !model.sessionExpired, let p: Page = try? await model.api.get("me/sessions") { sessions = p.items }289 }290 .confirmationDialog("Se déconnecter de SP Music ?", isPresented: $confirmSignOut) {291 Button("Se déconnecter", role: .destructive) { Task { await model.signOut() } }292 } message: { Text("Vos téléchargements restent sur ce Mac.") }293 }294 private func describe(_ s: SessionRow) -> String {295 if s.userAgent.hasPrefix("SPMusic/") { return "SP Music — " + (s.userAgent.split(separator: "(").last?.split(separator: ";").first.map(String.init) ?? "Mac") }296 let ua = s.userAgent297 let os = ua.contains("iPhone") ? "iPhone" : ua.contains("iPad") ? "iPad" : ua.contains("Macintosh") ? "Mac" : ua.contains("Android") ? "Android" : ua.contains("Windows") ? "Windows" : "Navigateur"298 let br = ua.contains("Edg/") ? "Edge" : ua.contains("Firefox/") ? "Firefox" : ua.contains("Chrome/") ? "Chrome" : ua.contains("Safari/") ? "Safari" : ""299 return [br, os].filter { !$0.isEmpty }.joined(separator: " · ")300 }301}302