SPB Git

Repository Public

AppSettings.swift 11.4 KB 231 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Music pour macOS9// File             : App/AppSettings.swift10// Description      : Preferences of the app on this Mac (UserDefaults) and the11//                    configurable keyboard shortcuts.12// Module           : App13// Repository       : https://git.spboucher.ai/sp-music-macos14// Created          : 2026-11-1815// Last Modified    : 2026-11-1816//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import SwiftUI90import SPMusicCore9192/// A keyboard shortcut the listener can change. Stored as "modifiers+key".93struct ShortcutSpec: Codable, Hashable {94    var key: String              // one character, or a name: space, left, right, up, down, return95    var command = false, shift = false, option = false, control = false9697    var keyEquivalent: KeyEquivalent {98        switch key {99        case "space": .space100        case "left": .leftArrow101        case "right": .rightArrow102        case "up": .upArrow103        case "down": .downArrow104        case "return": .return105        default: KeyEquivalent(key.first ?? " ")106        }107    }108    var modifiers: EventModifiers {109        var m: EventModifiers = []110        if command { m.insert(.command) }; if shift { m.insert(.shift) }; if option { m.insert(.option) }; if control { m.insert(.control) }111        return m112    }113    var display: String {114        let names = ["space": "Espace", "left": "←", "right": "→", "up": "↑", "down": "↓", "return": "↩"]115        return (control ? "⌃" : "") + (option ? "⌥" : "") + (shift ? "⇧" : "") + (command ? "⌘" : "") + (names[key] ?? key.uppercased())116    }117}118119enum AppCommand: String, CaseIterable, Identifiable {120    case playPause, next, previous, seekForward, seekBackward, volumeUp, volumeDown, toggleShuffle, cycleRepeat, toggleFavorite, showNowPlaying, showQueue, miniPlayer, find, sync, downloadCurrent121    var id: String { rawValue }122    var title: String {123        switch self {124        case .playPause: "Lecture / pause"125        case .next: "Piste suivante"126        case .previous: "Piste précédente"127        case .seekForward: "Avancer de 10 secondes"128        case .seekBackward: "Reculer de 10 secondes"129        case .volumeUp: "Augmenter le volume"130        case .volumeDown: "Baisser le volume"131        case .toggleShuffle: "Lecture aléatoire"132        case .cycleRepeat: "Répétition"133        case .toggleFavorite: "Ajouter aux favoris"134        case .showNowPlaying: "Afficher la lecture en cours"135        case .showQueue: "Afficher la file d’attente"136        case .miniPlayer: "Mini-lecteur"137        case .find: "Rechercher"138        case .sync: "Synchroniser maintenant"139        case .downloadCurrent: "Télécharger le titre en cours"140        }141    }142    var defaultShortcut: ShortcutSpec {143        switch self {144        case .playPause: ShortcutSpec(key: "space")145        case .next: ShortcutSpec(key: "right", command: true)146        case .previous: ShortcutSpec(key: "left", command: true)147        case .seekForward: ShortcutSpec(key: "right", command: true, shift: true)148        case .seekBackward: ShortcutSpec(key: "left", command: true, shift: true)149        case .volumeUp: ShortcutSpec(key: "up", command: true)150        case .volumeDown: ShortcutSpec(key: "down", command: true)151        case .toggleShuffle: ShortcutSpec(key: "s", command: true, option: true)152        case .cycleRepeat: ShortcutSpec(key: "r", command: true, option: true)153        case .toggleFavorite: ShortcutSpec(key: "l", command: true)154        case .showNowPlaying: ShortcutSpec(key: "p", command: true, shift: true)155        case .showQueue: ShortcutSpec(key: "u", command: true, option: true)156        case .miniPlayer: ShortcutSpec(key: "m", command: true, shift: true)157        case .find: ShortcutSpec(key: "f", command: true)158        case .sync: ShortcutSpec(key: "r", command: true)159        case .downloadCurrent: ShortcutSpec(key: "d", command: true)160        }161    }162}163164/// Preferences of the app on this Mac (UserDefaults). Account data lives in the account's database, not here.165@Observable166final class AppSettings {167    @ObservationIgnored private let defaults: UserDefaults168169    var serverURL: URL { didSet { defaults.set(serverURL.absoluteString, forKey: "serverURL") } }170    var volume: Double { didSet { defaults.set(volume, forKey: "volume") } }171    var eqEnabled: Bool { didSet { defaults.set(eqEnabled, forKey: "eqEnabled") } }172    var eqGains: [Double] { didSet { defaults.set(eqGains, forKey: "eqGains") } }173    var preamp: Double { didSet { defaults.set(preamp, forKey: "preamp") } }174    var crossfade: Double { didSet { defaults.set(crossfade, forKey: "crossfade") } }175    var directMode: Bool { didSet { defaults.set(directMode, forKey: "directMode") } }176    var normalize: Bool { didSet { defaults.set(normalize, forKey: "normalize") } }177    var matchSampleRate: Bool { didSet { defaults.set(matchSampleRate, forKey: "matchSampleRate") } }178    var outputDeviceUID: String { didSet { defaults.set(outputDeviceUID, forKey: "outputDeviceUID") } }179    var maxConcurrentDownloads: Int { didSet { defaults.set(maxConcurrentDownloads, forKey: "maxConcurrentDownloads") } }180    var streamCacheLimitGB: Double { didSet { defaults.set(streamCacheLimitGB, forKey: "streamCacheLimitGB") } }181    var downloadedOnly: Bool { didSet { defaults.set(downloadedOnly, forKey: "downloadedOnly") } }182    var forcedOffline: Bool { didSet { defaults.set(forcedOffline, forKey: "forcedOffline") } }183    var notifyDownloads: Bool { didSet { defaults.set(notifyDownloads, forKey: "notifyDownloads") } }184    var shortcuts: [String: ShortcutSpec] { didSet { if let d = try? JSONEncoder().encode(shortcuts) { defaults.set(d, forKey: "shortcuts") } } }185186    static let defaultServer = URL(string: "https://music.spboucher.ai")!187188    init(defaults: UserDefaults = .standard) {189        self.defaults = defaults190        defaults.register(defaults: ["volume": 0.8, "maxConcurrentDownloads": 3, "streamCacheLimitGB": 2.0, "notifyDownloads": true])191        // `-SPMusicServer <url>` on the command line points a development build at another backend.192        serverURL = defaults.string(forKey: "SPMusicServer").flatMap(URL.init(string:)) ?? defaults.string(forKey: "serverURL").flatMap(URL.init(string:)) ?? Self.defaultServer193        volume = defaults.double(forKey: "volume")194        eqEnabled = defaults.bool(forKey: "eqEnabled")195        eqGains = (defaults.array(forKey: "eqGains") as? [Double]).flatMap { $0.count == 10 ? $0 : nil } ?? Array(repeating: 0, count: 10)196        preamp = defaults.double(forKey: "preamp")197        crossfade = defaults.double(forKey: "crossfade")198        directMode = defaults.bool(forKey: "directMode")199        normalize = defaults.bool(forKey: "normalize")200        matchSampleRate = defaults.bool(forKey: "matchSampleRate")201        outputDeviceUID = defaults.string(forKey: "outputDeviceUID") ?? ""202        maxConcurrentDownloads = max(1, min(8, defaults.integer(forKey: "maxConcurrentDownloads")))203        streamCacheLimitGB = defaults.double(forKey: "streamCacheLimitGB")204        downloadedOnly = defaults.bool(forKey: "downloadedOnly")205        forcedOffline = defaults.bool(forKey: "forcedOffline")206        notifyDownloads = defaults.bool(forKey: "notifyDownloads")207        shortcuts = defaults.data(forKey: "shortcuts").flatMap { try? JSONDecoder().decode([String: ShortcutSpec].self, from: $0) } ?? [:]208    }209210    func shortcut(_ c: AppCommand) -> ShortcutSpec { shortcuts[c.rawValue] ?? c.defaultShortcut }211    func setShortcut(_ c: AppCommand, _ s: ShortcutSpec?) { if let s { shortcuts[c.rawValue] = s } else { shortcuts.removeValue(forKey: c.rawValue) } }212213    var engineSettings: EngineSettings {214        var e = EngineSettings()215        // A perceptual curve: the slider's middle sounds like half as loud.216        e.volume = Float(pow(max(0, min(1, volume)), 2))217        e.eqEnabled = eqEnabled; e.eqGains = eqGains.map(Float.init); e.preampDB = Float(preamp)218        e.crossfade = crossfade; e.directMode = directMode219        return e220    }221222    static let eqPresets: [(name: String, gains: [Double])] = [223        ("Plat", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),224        ("Basses", [6, 5, 4, 2, 0, 0, 0, 0, 0, 0]),225        ("Aigus", [0, 0, 0, 0, 0, 1, 2, 4, 5, 6]),226        ("Voix", [-2, -1, 0, 2, 4, 4, 3, 1, 0, -1]),227        ("Loudness", [5, 4, 2, 0, -1, -1, 0, 2, 4, 5]),228        ("Casque", [3, 2, 1, 0, -1, 0, 1, 2, 3, 3]),229    ]230}231
Files main
Menu

Theme