Repository Public
1// ORIX DJ2// File: App/Sources/Features/Library/LibraryController.swift3// Description: State and actions of the library screens: the off-main-thread track query, collections, selection,4// import with its failure list, and every edit made from the table, the sidebar and the inspector.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import ORIXDJCore10import SwiftUI1112/// A rule being edited (identity for the editor rows).13struct SmartRuleDraft: Identifiable, Equatable {14 var id = UUID()15 var rule: SmartRule16}1718struct SmartCrateDraft: Equatable {19 /// Nil for a smart crate that is not stored yet.20 var crateID: Int64?21 var name: String22 var match: SmartCrate.Match23 var rules: [SmartRuleDraft]24}2526struct SmartCratePreview: Equatable {27 var count = 028 var sample: [Track] = []29 var error: String?30}3132/// Name prompt for creating or renaming a collection.33struct LibraryNameRequest: Identifiable, Equatable {34 enum Purpose: Equatable { case newCrate, newPlaylist, renameCrate(Int64), renamePlaylist(Int64), renameSmartCrate(Int64) }35 var id = UUID()36 var purpose: Purpose37 var text: String38}3940struct LibraryTagRequest: Identifiable, Equatable {41 var id = UUID()42 var trackIDs: [Int64]43 var text: String44}4546struct LibraryInspectorData: Equatable {47 var trackID: Int6448 var artwork: Data?49 var waveform: WaveformSummary?50 var plays: [HistoryEntry] = []51 var crateNames: [String] = []5253 static func == (a: LibraryInspectorData, b: LibraryInspectorData) -> Bool {54 a.trackID == b.trackID && a.artwork == b.artwork && a.waveform?.peak == b.waveform?.peak && a.plays == b.plays && a.crateNames == b.crateNames55 }56}5758@MainActor @Observable59final class LibraryController {60 // Result of the current query.61 var rows: [LibraryRow] = []62 var loaded = false63 var libraryCount = 064 var selection: Set<Int64> = []65 var sortOrder: [KeyPathComparator<LibraryRow>] = []6667 var crates: [Crate] = []68 var playlists: [Playlist] = []69 var smartCrates: [SmartCrate] = []70 var sessions: [HistorySession] = []7172 // Live deck state, refreshed only when it changes.73 var reference: HarmonicReference?74 var playingDecks = [Bool](repeating: false, count: deckCount)7576 // Import.77 var importProgress: ImportProgress?78 var importScanning = false79 var importFailures: [ImportFailure] = []80 var showImportFailures = false81 var dropTargeted = false8283 // Editors and confirmations.84 var smartDraft: SmartCrateDraft?85 var smartPreview = SmartCratePreview()86 var nameRequest: LibraryNameRequest?87 var tagRequest: LibraryTagRequest?88 var removalRequest: [Int64]?89 var inspector: LibraryInspectorData?90 var showInspector = true9192 @ObservationIgnored private var generation = 093 @ObservationIgnored private var lastQuery: TrackQuery?94 @ObservationIgnored private var lastChangeCount: UInt64?95 @ObservationIgnored private var importTask: Task<Void, Never>?9697 private struct Snapshot: Sendable {98 var rows: [LibraryRow]99 var libraryCount: Int100 var crates: [Crate]101 var playlists: [Playlist]102 var smartCrates: [SmartCrate]103 var sessions: [HistorySession]104 }105106 var sortKey: TrackQuery.SortKey? { TrackQuery.SortKey.from(sortOrder.first) }107108 /// Tracks of the selected rows, in table order, without duplicates.109 var selectedTrackIDs: [Int64] {110 guard !selection.isEmpty else { return [] }111 var seen = Set<Int64>()112 return rows.filter { selection.contains($0.id) }.map(\.track.id).filter { seen.insert($0).inserted }113 }114115 var primaryTrack: Track? {116 guard let id = selection.count == 1 ? selection.first : nil else { return nil }117 return rows.first { $0.id == id }?.track118 }119120 func trackIDs(forRows ids: Set<Int64>) -> [Int64] {121 var seen = Set<Int64>()122 return rows.filter { ids.contains($0.id) }.map(\.track.id).filter { seen.insert($0).inserted }123 }124125 // MARK: Query126127 /// Runs the query on a background task. Skipped when neither the query nor the library changed.128 func reload(library: LibraryStore, scope: TrackQuery.Scope, search: String, force: Bool = false) async {129 let comparator = sortOrder.first130 let query = TrackQuery(search: search, scope: scope, sort: TrackQuery.SortKey.from(comparator), ascending: comparator?.order != .reverse)131 let changeCount = library.changeCount132 if !force, loaded, query == lastQuery, changeCount == lastChangeCount { return }133 generation += 1134 let mine = generation135 let snapshot = await Task.detached(priority: .userInitiated) { () -> Snapshot in136 let tracks = (try? library.tracks(query: query)) ?? []137 return Snapshot(rows: LibraryRow.rows(from: tracks), libraryCount: (try? library.count()) ?? 0,138 crates: (try? library.crates()) ?? [], playlists: (try? library.playlists()) ?? [],139 smartCrates: (try? library.smartCrates()) ?? [], sessions: (try? library.sessions()) ?? [])140 }.value141 guard mine == generation else { return }142 lastQuery = query; lastChangeCount = changeCount143 if snapshot.rows != rows { rows = snapshot.rows }144 libraryCount = snapshot.libraryCount145 if crates != snapshot.crates { crates = snapshot.crates }146 if playlists != snapshot.playlists { playlists = snapshot.playlists }147 if smartCrates != snapshot.smartCrates { smartCrates = snapshot.smartCrates }148 let visible = snapshot.sessions.filter { $0.entryCount > 0 }149 if sessions != visible { sessions = visible }150 let valid = Set(rows.map(\.id))151 if !selection.isSubset(of: valid) { selection.formIntersection(valid) }152 loaded = true153 }154155 func loadInspector(for track: Track?, session: DJSession) async {156 guard let track else { inspector = nil; return }157 let library = session.library158 let data = await Task.detached(priority: .userInitiated) { () -> LibraryInspectorData in159 var d = LibraryInspectorData(trackID: track.id)160 d.artwork = try? library.artwork(for: track.id)161 d.waveform = session.storedAnalysis(for: track)?.waveform.overview(columns: 900)162 d.plays = Array(((try? library.history(limit: 5000)) ?? []).filter { $0.trackID == track.id }.prefix(6))163 let ids = Set((try? library.crateIDs(containing: track.id)) ?? [])164 d.crateNames = ((try? library.crates()) ?? []).filter { ids.contains($0.id) }.map(\.name)165 return d166 }.value167 guard primaryTrack?.id == track.id else { return }168 if inspector != data { inspector = data }169 }170171 // MARK: Decks172173 func load(_ trackID: Int64, deck: Int, model: AppModel) {174 model.load(trackID: trackID, deck: deck)175 }176177 /// Loads on the first visible deck that is not playing.178 func loadOnFreeDeck(_ trackID: Int64, model: AppModel) {179 guard let deck = (0 ..< model.deckCountShown).first(where: { !model.decks[$0].playing }) else {180 model.show(notice: String(localized: "Every deck is playing. Pause one before loading another track."))181 return182 }183 model.load(trackID: trackID, deck: deck)184 }185186 // MARK: Edits187188 private func perform(_ model: AppModel, _ body: () throws -> Void) {189 do { try body(); model.libraryRevision += 1 } catch let e as LibraryError { model.show(notice: e.description) } catch { model.show(notice: error.localizedDescription) }190 }191192 func setRating(_ ids: [Int64], _ rating: Int, model: AppModel) {193 perform(model) { for id in ids { try model.library.setRating(trackID: id, rating: rating) } }194 }195196 func setFavorite(_ ids: [Int64], _ favorite: Bool, model: AppModel) {197 perform(model) { for id in ids { try model.library.setFavorite(trackID: id, favorite: favorite) } }198 }199200 func setTags(_ ids: [Int64], _ tags: [String], model: AppModel) {201 perform(model) { for id in ids { try model.library.setTags(trackID: id, tags: tags) } }202 }203204 static func parseTags(_ text: String) -> [String] {205 var out: [String] = []206 for part in text.split(separator: ",") {207 let t = part.trimmingCharacters(in: .whitespaces)208 if !t.isEmpty, !out.contains(where: { $0.caseInsensitiveCompare(t) == .orderedSame }) { out.append(t) }209 }210 return out211 }212213 func requestTags(_ ids: [Int64]) {214 let tracks = rows.map(\.track).filter { ids.contains($0.id) }215 let common = tracks.first?.tags.filter { tag in tracks.allSatisfy { $0.tags.contains(tag) } } ?? []216 tagRequest = LibraryTagRequest(trackIDs: ids, text: common.joined(separator: ", "))217 }218219 func addToCrate(_ ids: [Int64], crate: Int64, model: AppModel) {220 guard !ids.isEmpty else { return }221 perform(model) { try model.library.addTracks(ids, toCrate: crate) }222 }223224 func addToPlaylist(_ ids: [Int64], playlist: Int64, at index: Int? = nil, model: AppModel) {225 guard !ids.isEmpty else { return }226 perform(model) { try model.library.addTracks(ids, toPlaylist: playlist, at: index) }227 }228229 func removeFromCrate(_ ids: [Int64], crate: Int64, model: AppModel) {230 perform(model) { try model.library.removeTracks(ids, fromCrate: crate) }231 }232233 func removeFromPlaylist(rows ids: Set<Int64>, playlist: Int64, model: AppModel) {234 let positions = IndexSet(rows.filter { ids.contains($0.id) }.map(\.position))235 perform(model) { try model.library.removeFromPlaylist(playlist, atPositions: positions) }236 }237238 /// Moves the given rows of a playlist shown in its own order.239 func movePlaylistRows(_ ids: Set<Int64>, playlist: Int64, to destination: Int, model: AppModel) {240 let offsets = IndexSet(rows.filter { ids.contains($0.id) }.map(\.position))241 guard !offsets.isEmpty else { return }242 perform(model) { try model.library.movePlaylistEntries(playlistID: playlist, fromOffsets: offsets, toOffset: min(max(0, destination), rows.count)) }243 }244245 /// A drop on the table while a playlist is shown in its own order: reorders when the dragged tracks are the246 /// selected rows of this playlist, inserts otherwise.247 func handleTableDrop(_ items: [String], at index: Int, scope: TrackQuery.Scope, model: AppModel) {248 guard case let .playlist(playlist) = scope, sortKey == nil, model.librarySearch.isEmpty else { return }249 let ids = LibraryDrag.trackIDs(from: items)250 guard !ids.isEmpty else { return }251 let draggedRows = rows.filter { selection.contains($0.id) }252 if !draggedRows.isEmpty, Set(draggedRows.map(\.track.id)).isSuperset(of: ids) {253 movePlaylistRows(selection, playlist: playlist, to: index, model: model)254 } else if let row = rows.first(where: { ids.contains($0.track.id) }), ids.count == 1 {255 movePlaylistRows([row.id], playlist: playlist, to: index, model: model)256 } else {257 addToPlaylist(ids, playlist: playlist, at: index, model: model)258 }259 }260261 func showInFinder(_ ids: [Int64]) {262 let urls = rows.map(\.track).filter { ids.contains($0.id) }.map(\.url)263 if !urls.isEmpty { NSWorkspace.shared.activateFileViewerSelecting(Array(Set(urls))) }264 }265266 /// Clears the stored analysis so the background analyser picks the tracks up again.267 func analyseAgain(_ ids: [Int64], model: AppModel) {268 perform(model) { for id in ids { try model.library.setAnalysis(trackID: id, TrackAnalysis(analysisVersion: 0)) } }269 model.session.analyzePending()270 }271272 func confirmRemoval(model: AppModel) {273 guard let ids = removalRequest else { return }274 removalRequest = nil275 perform(model) { try model.library.removeTracks(ids: ids) }276 selection.removeAll()277 }278279 // MARK: Collections280281 func commitName(model: AppModel) {282 guard let request = nameRequest else { return }283 nameRequest = nil284 let name = request.text.trimmingCharacters(in: .whitespaces)285 guard !name.isEmpty else { return }286 perform(model) {287 switch request.purpose {288 case .newCrate: model.libraryScope = .crate(try model.library.createCrate(name: name).id)289 case .newPlaylist: model.libraryScope = .playlist(try model.library.createPlaylist(name: name).id)290 case let .renameCrate(id): try model.library.renameCrate(id: id, to: name)291 case let .renamePlaylist(id): try model.library.renamePlaylist(id: id, to: name)292 case let .renameSmartCrate(id):293 if var crate = try model.library.smartCrate(id: id) { crate.name = name; try model.library.updateSmartCrate(crate) }294 }295 }296 }297298 func delete(_ source: LibrarySource, model: AppModel) {299 perform(model) {300 switch source {301 case let .crate(id): try model.library.deleteCrate(id: id)302 case let .playlist(id): try model.library.deletePlaylist(id: id)303 case let .smartCrate(id): try model.library.deleteSmartCrate(id: id)304 case let .history(id?): try model.library.deleteSession(id: id)305 default: break306 }307 }308 if LibrarySource(scope: model.libraryScope) == source { model.libraryScope = .all }309 }310311 // MARK: Smart crates312313 func newSmartCrate() {314 smartPreview = SmartCratePreview()315 smartDraft = SmartCrateDraft(crateID: nil, name: String(localized: "New Smart Crate"), match: .all,316 rules: [SmartRuleDraft(rule: SmartRule(field: .bpm, comparison: .between, value: "120", upperValue: "128"))])317 }318319 func editSmartCrate(_ crate: SmartCrate) {320 smartPreview = SmartCratePreview()321 smartDraft = SmartCrateDraft(crateID: crate.id, name: crate.name, match: crate.match, rules: crate.rules.map { SmartRuleDraft(rule: $0) })322 }323324 func refreshSmartPreview(library: LibraryStore) async {325 guard let draft = smartDraft else { return }326 let rules = draft.rules.map(\.rule), match = draft.match327 let preview = await Task.detached(priority: .userInitiated) { () -> SmartCratePreview in328 do {329 let tracks = try library.tracks(matching: rules, match: match, limit: nil)330 return SmartCratePreview(count: tracks.count, sample: Array(tracks.prefix(200)), error: nil)331 } catch let e as LibraryError { return SmartCratePreview(error: e.description) } catch { return SmartCratePreview(error: error.localizedDescription) }332 }.value333 guard smartDraft == draft else { return }334 smartPreview = preview335 }336337 func saveSmartDraft(model: AppModel) {338 guard let draft = smartDraft else { return }339 let name = draft.name.trimmingCharacters(in: .whitespaces)340 guard !name.isEmpty else { model.show(notice: String(localized: "Give the smart crate a name.")); return }341 do {342 let rules = draft.rules.map(\.rule)343 if let id = draft.crateID {344 guard var crate = try model.library.smartCrate(id: id) else { throw LibraryError.notFound("smart crate") }345 crate.name = name; crate.match = draft.match; crate.rules = rules346 try model.library.updateSmartCrate(crate)347 model.libraryScope = .smartCrate(id)348 } else {349 model.libraryScope = .smartCrate(try model.library.createSmartCrate(name: name, match: draft.match, rules: rules).id)350 }351 smartDraft = nil352 model.libraryRevision += 1353 } catch let e as LibraryError { model.show(notice: e.description) } catch { model.show(notice: error.localizedDescription) }354 }355356 // MARK: Import357358 var isImporting: Bool { importTask != nil }359360 func chooseFiles(model: AppModel) {361 let panel = NSOpenPanel()362 panel.canChooseDirectories = true; panel.canChooseFiles = true; panel.allowsMultipleSelection = true363 panel.message = String(localized: "Choose audio files or folders. ORIX DJ reads them where they are; nothing is copied.")364 if panel.runModal() == .OK { importURLs(panel.urls, model: model) }365 }366367 /// Imports through the session (so analysis follows) and keeps the list of files that could not be read.368 func importURLs(_ urls: [URL], model: AppModel) {369 guard !urls.isEmpty, importTask == nil else { return }370 importScanning = true371 importProgress = nil372 let session = model.session373 importTask = Task { [weak self] in374 let summary = await session.importURLs(urls) { progress in375 Task { @MainActor in self?.importScanning = false; self?.importProgress = progress }376 }377 guard let self else { return }378 self.importTask = nil; self.importProgress = nil; self.importScanning = false379 self.importFailures = summary.failures380 let n = summary.imported.count381 var text = n == 1 ? String(localized: "Imported 1 track") : String(localized: "Imported \(n) tracks")382 if summary.cancelled { text += String(localized: " (cancelled)") }383 if !summary.failures.isEmpty { text += String(localized: ", \(summary.failures.count) could not be read") }384 model.show(notice: text)385 model.libraryRevision += 1386 }387 }388389 func cancelImport() { importTask?.cancel() }390391 func handleFileDrop(_ providers: [NSItemProvider], model: AppModel) -> Bool {392 let group = DispatchGroup()393 let box = URLBox()394 for p in providers where p.canLoadObject(ofClass: URL.self) {395 group.enter()396 _ = p.loadObject(ofClass: URL.self) { url, _ in397 if let url { box.append(url) }398 group.leave()399 }400 }401 group.notify(queue: .main) { [weak self] in402 let urls = box.urls403 MainActor.assumeIsolated { self?.importURLs(urls, model: model) }404 }405 return true406 }407}408409/// Collects dropped URLs from item-provider callbacks.410private final class URLBox: @unchecked Sendable {411 private let lock = NSLock()412 private var storage: [URL] = []413 func append(_ url: URL) { lock.withLock { storage.append(url) } }414 var urls: [URL] { lock.withLock { storage } }415}416