Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Music9// File : App/CarPlay/CarPlaySceneDelegate.swift10// Description : CarPlay audio templates over the local library (needs11// Apple's carplay-audio entitlement).12// Module : App13// Repository : https://git.spboucher.ai/sp-music-ios14// Created : 2026-11-1715// Last Modified : 2026-11-1716//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 CarPlay90import SPMusicCore91import UIKit9293/// CarPlay: the library through the system's audio templates (lists and the standard Now Playing screen — CarPlay94/// allows nothing else to an audio app). It reads the same local database, so downloaded music plays in the car95/// without a connection. The scene only connects when the app is signed with Apple's `carplay-audio` entitlement.96@MainActor97final class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate {98 private var controller: CPInterfaceController?99 private let env = AppEnvironment.shared100101 nonisolated func templateApplicationScene(_ scene: CPTemplateApplicationScene, didConnect interfaceController: CPInterfaceController) {102 MainActor.assumeIsolated {103 controller = interfaceController104 Task { await env.start(); await setRoot() }105 }106 }107 nonisolated func templateApplicationScene(_ scene: CPTemplateApplicationScene, didDisconnectInterfaceController interfaceController: CPInterfaceController) {108 MainActor.assumeIsolated { controller = nil }109 }110111 private func setRoot() async {112 let onDevice = await env.db.counts().downloadedTracks113 guard env.auth.canUseLibrary || onDevice > 0 else {114 let t = CPListTemplate(title: "SP Music", sections: [])115 t.emptyViewTitleVariants = ["Non connecté"]; t.emptyViewSubtitleVariants = ["Ouvrez SP Music sur l'iPhone pour vous connecter."]116 _ = try? await controller?.setRootTemplate(t, animated: false); return117 }118 let only = env.downloadedOnly119 let albums = await albumList(title: "Albums", albums: env.db.albums(sort: .artist, downloadedOnly: only), tab: "square.stack")120 let downloaded = await albumList(title: "Téléchargés", albums: env.db.albums(sort: .recent, downloadedOnly: true), tab: "arrow.down.circle")121 let artists = CPListTemplate(title: "Artistes", sections: [CPListSection(items: await env.db.artists(downloadedOnly: only).prefix(CPListTemplate.maximumItemCount).map { a in122 let item = CPListItem(text: a.name, detailText: "\(a.albumCount) album\(a.albumCount > 1 ? "s" : "")")123 item.accessoryType = .disclosureIndicator124 item.handler = { [weak self] _, done in Task { @MainActor in125 if let self { let list = await self.albumList(title: a.name, albums: self.env.db.albums(artistId: a.id, downloadedOnly: self.env.downloadedOnly), tab: nil); _ = try? await self.controller?.pushTemplate(list, animated: true) }126 done()127 } }128 return item129 })])130 artists.tabImage = UIImage(systemName: "music.microphone")131 let lists = CPListTemplate(title: "Listes", sections: [CPListSection(items: await env.db.playlists().prefix(CPListTemplate.maximumItemCount).map { p in132 let item = CPListItem(text: p.name, detailText: "\(p.trackCount) titre\(p.trackCount > 1 ? "s" : "")")133 item.accessoryType = .disclosureIndicator134 item.handler = { [weak self] _, done in Task { @MainActor in135 if let self { let tracks = await self.env.db.playlistTracks(id: p.id, downloadedOnly: self.env.downloadedOnly); _ = try? await self.controller?.pushTemplate(self.trackList(title: p.name, tracks: tracks), animated: true) }136 done()137 } }138 return item139 })])140 lists.tabImage = UIImage(systemName: "music.note.list")141 lists.emptyViewTitleVariants = ["Aucune liste de lecture"]142 _ = try? await controller?.setRootTemplate(CPTabBarTemplate(templates: [albums, artists, lists, downloaded]), animated: false)143 }144145 private func albumList(title: String, albums: [Album], tab: String?) async -> CPListTemplate {146 var items: [CPListItem] = []147 for a in albums.prefix(CPListTemplate.maximumItemCount) {148 let item = CPListItem(text: a.title, detailText: a.artistName)149 if let art = a.artworkId, let image = await env.artwork.image(art, size: 96) { item.setImage(image) }150 item.accessoryType = .disclosureIndicator151 item.handler = { [weak self] _, done in Task { @MainActor in152 if let self { let tracks = await self.env.db.tracks(albumId: a.id, downloadedOnly: self.env.downloadedOnly); _ = try? await self.controller?.pushTemplate(self.trackList(title: a.title, tracks: tracks), animated: true) }153 done()154 } }155 items.append(item)156 }157 let t = CPListTemplate(title: title, sections: [CPListSection(items: items)])158 if let tab { t.tabImage = UIImage(systemName: tab) }159 t.emptyViewTitleVariants = ["Rien à afficher"]160 t.emptyViewSubtitleVariants = [env.downloadedOnly ? "Téléchargez de la musique depuis l'iPhone." : ""]161 return t162 }163164 private func trackList(title: String, tracks: [Track]) -> CPListTemplate {165 let items = tracks.prefix(CPListTemplate.maximumItemCount).enumerated().map { i, t in166 let item = CPListItem(text: t.title, detailText: t.artistName)167 item.isPlaying = env.player.current?.id == t.id168 item.handler = { [weak self] _, done in Task { @MainActor in169 self?.env.play(tracks, startAt: i)170 _ = try? await self?.controller?.pushTemplate(CPNowPlayingTemplate.shared, animated: true)171 done()172 } }173 return item174 }175 let t = CPListTemplate(title: title, sections: [CPListSection(items: items)])176 t.emptyViewTitleVariants = ["Aucun titre disponible"]177 return t178 }179}180