SPB Git

Repository Public

SPMusicApp.swift 12.0 KB 269 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Music pour macOS9// File             : App/SPMusicApp.swift10// Description      : App entry point: windows, main layout, menus and keyboard11//                    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 UniformTypeIdentifiers91import SPMusicCore9293@main94struct SPMusicApp: App {95    @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate96    @State private var model = AppModel()9798    var body: some Scene {99        Window("SP Music", id: "main") {100            RootView()101                .environment(model)102                .frame(minWidth: 940, minHeight: 600)103                .task {104                    delegate.model = model105                    await model.start()106                    delegate.flushPendingFiles()107                }108        }109        .defaultSize(width: 1240, height: 800)110        .commands { AppCommands(model: model) }111112        Window("Mini-lecteur", id: "mini") {113            MiniPlayerView().environment(model)114        }115        .windowResizability(.contentSize)116        .windowStyle(.hiddenTitleBar)117        .defaultPosition(.topTrailing)118119        Settings { SettingsView().environment(model) }120    }121}122123struct RootView: View {124    @Environment(AppModel.self) private var model125    var body: some View {126        switch model.phase {127        case .launching: ProgressView().controlSize(.large).frame(maxWidth: .infinity, maxHeight: .infinity)128        case .signedOut: WelcomeView()129        case .ready: MainView()130        }131    }132}133134struct MainView: View {135    @Environment(AppModel.self) private var model136    @State private var newPlaylistName = ""137    private let request = NewPlaylistRequest.shared138139    var body: some View {140        @Bindable var model = model141        @Bindable var settings = model.settings142        NavigationSplitView {143            SidebarView().navigationSplitViewColumnWidth(min: 200, ideal: 230, max: 300)144        } detail: {145            VStack(spacing: 0) {146                StatusBanner()147                NavigationStack(path: $model.path) {148                    Group {149                        if !model.searchText.trimmingCharacters(in: .whitespaces).isEmpty { SearchView() } else { root }150                    }151                    .navigationDestination(for: Route.self) { route in152                        switch route {153                        case .album(let id): AlbumDetailView(albumID: id)154                        case .artist(let id): ArtistDetailView(artistID: id)155                        case .playlist(let id): PlaylistView(playlistID: id)156                        }157                    }158                }159            }160            .toolbar {161                ToolbarItem(placement: .primaryAction) {162                    Toggle(isOn: $settings.downloadedOnly) { Label("Téléchargés seulement", systemImage: "arrow.down.circle") }163                        .toggleStyle(.button).help("N’afficher que la musique présente sur ce Mac").disabled(!model.isOnline)164                }165            }166        }167        .searchable(text: $model.searchText, placement: .toolbar, prompt: model.downloadedOnly ? "Rechercher dans la musique téléchargée" : "Rechercher")168        .safeAreaInset(edge: .bottom, spacing: 0) { PlayerBar() }169        .overlay { if model.showNowPlaying { NowPlayingView().transition(.move(edge: .bottom).combined(with: .opacity)) } }170        // The immersive view takes the whole window: the toolbar (search, filters) steps aside while it is shown.171        .toolbar(model.showNowPlaying ? .hidden : .automatic, for: .windowToolbar)172        .overlay { ToastOverlay() }173        .onDrop(of: [.fileURL], isTargeted: nil) { providers in174            // Audio files dropped on the window are played as they are (nothing is imported or copied).175            Task {176                var urls: [URL] = []177                for p in providers { if let u = try? await p.loadItem(forTypeIdentifier: UTType.fileURL.identifier) as? Data, let url = URL(dataRepresentation: u, relativeTo: nil) { urls.append(url) } }178                model.openFiles(urls)179            }180            return true181        }182        .alert("Nouvelle liste de lecture", isPresented: Binding(get: { request.tracks != nil }, set: { if !$0 { request.tracks = nil } })) {183            TextField("Nom", text: $newPlaylistName)184            Button("Créer") {185                let tracks = request.tracks ?? []186                Task { _ = await model.createPlaylist(name: newPlaylistName, trackIDs: tracks.map(\.id)); newPlaylistName = "" }187            }188            Button("Annuler", role: .cancel) {}189        } message: { Text("\(request.tracks?.count ?? 0) titre(s) y seront ajoutés.") }190    }191192    @ViewBuilder private var root: some View {193        switch model.selection ?? .home {194        case .home: HomeView()195        case .albums: AlbumsView()196        case .artists: ArtistsView()197        case .tracks: TracksView()198        case .favorites: FavoritesView()199        case .history: HistoryView()200        case .downloads: DownloadsView()201        case .admin: AdminView()202        case .playlist(let id): PlaylistView(playlistID: id).id(id)203        }204    }205}206207/// The app's menus. Every shortcut comes from the settings, so the listener can change them.208struct AppCommands: Commands {209    let model: AppModel210    @Environment(\.openWindow) private var openWindow211212    private func item(_ c: AppCommand, _ title: String? = nil, _ action: @escaping () -> Void) -> some View {213        let s = model.settings.shortcut(c)214        return Button(title ?? c.title, action: action).keyboardShortcut(s.keyEquivalent, modifiers: s.modifiers)215    }216217    var body: some Commands {218        CommandGroup(replacing: .newItem) {219            Button("Ouvrir des fichiers audio…") {220                let panel = NSOpenPanel(); panel.allowsMultipleSelection = true; panel.canChooseDirectories = false221                panel.allowedContentTypes = [.audio]222                if panel.runModal() == .OK { model.openFiles(panel.urls) }223            }.keyboardShortcut("o")224            Button("Nouvelle liste de lecture…") { NewPlaylistRequest.shared.tracks = [] }.keyboardShortcut("n").disabled(model.phase != .ready)225        }226        CommandMenu("Lecture") {227            let p = model.playback228            item(.playPause, p.isPlaying ? "Pause" : "Lecture") { p.togglePlay() }229            item(.next) { p.next() }230            item(.previous) { p.previous() }231            Divider()232            item(.seekForward) { p.skip(by: 10) }233            item(.seekBackward) { p.skip(by: -10) }234            Divider()235            item(.volumeUp) { model.settings.volume = min(1, model.settings.volume + 0.06); model.applyAudioSettings() }236            item(.volumeDown) { model.settings.volume = max(0, model.settings.volume - 0.06); model.applyAudioSettings() }237            Divider()238            item(.toggleShuffle, p.queue.shuffle ? "Désactiver la lecture aléatoire" : "Lecture aléatoire") { p.toggleShuffle() }239            item(.cycleRepeat, "Répétition : \(p.queue.repeatMode == .off ? "désactivée" : p.queue.repeatMode == .all ? "toute la file" : "ce titre")") { p.cycleRepeat() }240            Divider()241            item(.toggleFavorite) { if let t = p.currentTrack { model.toggleFavorite(t) } }242            item(.downloadCurrent) { if let t = p.currentTrack { model.download([t]) } }243        }244        CommandGroup(after: .sidebar) {245            item(.showNowPlaying) { if model.playback.currentTrack != nil { withAnimation(.spring(duration: 0.35)) { model.showNowPlaying.toggle() } } }246            item(.showQueue) { model.showQueue.toggle() }247            item(.miniPlayer) { openWindow(id: "mini") }248            Divider()249            item(.find) { NSApp.keyWindow?.makeFirstResponder(nil); NSApp.sendAction(#selector(NSResponder.performTextFinderAction(_:)), to: nil, from: nil); focusSearch() }250            Divider()251        }252        CommandMenu("Bibliothèque") {253            item(.sync) { Task { await model.syncNow() } }254            Button("Tout resynchroniser") { Task { await model.syncNow(full: true) } }255            Divider()256            Toggle("Mode hors ligne", isOn: Binding(get: { model.settings.forcedOffline }, set: { model.setForcedOffline($0) }))257            Toggle("Téléchargés seulement", isOn: Binding(get: { model.settings.downloadedOnly }, set: { model.settings.downloadedOnly = $0 }))258            Divider()259            Button("Téléchargements") { model.select(.downloads) }.keyboardShortcut("j", modifiers: [.command, .option])260        }261    }262263    private func focusSearch() {264        // The toolbar search field is the window's NSSearchToolbarItem.265        guard let toolbar = NSApp.keyWindow?.toolbar else { return }266        for item in toolbar.items { if let s = item as? NSSearchToolbarItem { s.beginSearchInteraction(); return } }267    }268}269
Files main
Menu

Theme